@thg-agentic/hyper-personalisation-web 3.17.1 → 3.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hp.min.js CHANGED
@@ -1,3 +1,3 @@
1
- (()=>{var xt=e=>{throw TypeError(e)};var Xn=(e,t,n)=>t.has(e)||xt("Cannot "+n);var It=(e,t,n)=>t.has(e)?xt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n);var O=(e,t,n)=>(Xn(e,t,"access private method"),n);var pe=[];for(let e=2;pe.length<64;e++)pe.every(t=>e%t!==0)&&pe.push(e);var At=e=>(e-Math.floor(e))*2**32>>>0,Ho=pe.slice(0,8).map(e=>At(Math.sqrt(e))),Ko=pe.map(e=>At(Math.cbrt(e)));var Ve=(e,t)=>e<<t|e>>>32-t;function vt(e){let t=new Uint32Array((e.length+8>>6)*16+16);e.forEach((s,i)=>{t[i>>2]|=s<<24-i%4*8}),t[e.length>>2]|=128<<24-e.length%4*8,t[t.length-2]=Math.floor(e.length/2**29),t[t.length-1]=e.length*8;let n=Uint32Array.of(1732584193,4023233417,2562383102,271733878,3285377520),r=new Uint32Array(80);for(let s=0;s<t.length;s+=16){for(let f=0;f<80;f++)r[f]=f<16?t[s+f]:Ve(r[f-3]^r[f-8]^r[f-14]^r[f-16],1);let[i,c,l,d,m]=n;for(let f=0;f<80;f++){let g,b;f<20?(g=c&l|~c&d,b=1518500249):f<40?(g=c^l^d,b=1859775393):f<60?(g=c&l|c&d|l&d,b=2400959708):(g=c^l^d,b=3395469782);let A=Ve(i,5)+g+m+b+r[f]|0;[m,d,l,c,i]=[d,l,Ve(c,30),i,A]}[i,c,l,d,m].forEach((f,g)=>{n[g]+=f})}let o=new Uint8Array(20);return n.forEach((s,i)=>{o[i*4]=s>>>24,o[i*4+1]=s>>>16,o[i*4+2]=s>>>8,o[i*4+3]=s}),o}var Yn="e28e8ada-5b76-4209-bba9-79b823a0af75",Zn=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");function kt(e,t){let n=Uint8Array.from(e.replace(/-/g,"").match(/../g),c=>Number.parseInt(c,16)),r=new TextEncoder().encode(t),o=new Uint8Array(16+r.length);o.set(n),o.set(r,16);let s=vt(o).slice(0,16);s[6]=s[6]&15|80,s[8]=s[8]&63|128;let i=Zn(s);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}var J=(e,t)=>typeof e=="string"&&e!==""&&e.length<=t?e:null;function we(e,t){return J(e,64)??J(t,256)}function Et({sessionId:e,slot:t,arm:n}={}){let r=J(e,256);return!r||!J(t,256)||!J(n,256)?null:kt(Yn,`${r}:${t}:${n}`)}var Qn="4b1f2c7e-9a3d-4e58-b6c1-2d7f0a9e8c53";function Ct({sessionId:e,surface:t}={}){let n=J(e,256);return!n||!J(t,64)?null:kt(Qn,`${n}:${t}`)}var er=Array.from({length:11},(e,t)=>t/10);function tr(e,t){if(!e.isIntersecting)return!1;let{intersectionRect:n,boundingClientRect:r,rootBounds:o}=e;if(!n||!r)return!0;let s=n.width*n.height,i=r.width*r.height,c=o?Math.min(i,o.width*o.height):i;return c>0&&s/c>=t}function z(e){let{selector:t,onViewable:n,visibleRatio:r=.5,dwellMs:o=1e3,root:s=document}=e,i=new Map,c=new WeakSet,l=new Set,d=h=>{i.has(h)||i.set(h,setTimeout(()=>{i.delete(h),n(h)&&(f?.unobserve(h),l.delete(h))},o))},m=h=>{clearTimeout(i.get(h)),i.delete(h)},f=typeof IntersectionObserver>"u"?null:new IntersectionObserver(h=>{for(let x of h){let p=x.target;if(!tr(x,r)){l.delete(p),m(p);continue}l.add(p),g()&&d(p)}},{threshold:er}),g=()=>typeof document>"u"||document.visibilityState!=="hidden",b=()=>{if(g())for(let h of l)d(h);else for(let h of l)m(h)};document.addEventListener("visibilitychange",b);let A=()=>{for(let h of s.querySelectorAll(t))c.has(h)||(c.add(h),f?.observe(h))},k=typeof MutationObserver>"u"?null:new MutationObserver(()=>A()),w=()=>{A(),k?.observe(s===document?document.body:s,{childList:!0,subtree:!0})},L=s===document&&!document.body;return L?document.addEventListener("DOMContentLoaded",w,{once:!0}):w(),()=>{L&&document.removeEventListener("DOMContentLoaded",w),document.removeEventListener("visibilitychange",b),f?.disconnect(),k?.disconnect();for(let h of i.values())clearTimeout(h);i.clear(),l.clear()}}function je(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-exposure]",visibleRatio:r=.5,dwellMs:o=1e3,root:s=document}=t;return z({selector:n,root:s,visibleRatio:r,dwellMs:o,onViewable(i){let c=i.dataset?.hpExposure?.trim();return c&&e.surfaceViewed({surface:c}),!0}})}var Pt=e=>{try{return new URL(e,document.baseURI).toString()}catch{return e}};function qe(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-list]",tileSelector:r="[data-hp-product]",visibleRatio:o=.5,dwellMs:s=1e3,root:i=document}=t,c=new Set,l=A=>A.closest?.(n)??null,d=A=>{let k=A.dataset.hpList?.trim();return k?{list_id:k,category:A.dataset.hpListCategory?.trim()||null}:null},m=A=>Array.from(A.querySelectorAll(r)).filter(k=>l(k)===A),f=(A,k)=>{try{let w=JSON.parse(A.dataset.hpProduct??"");return!w||typeof w!="object"||!w.product_id?null:{...w,position:w.position??k+1,...w.url?{url:Pt(w.url)}:{},...w.image_url?{image_url:Pt(w.image_url)}:{}}}catch{return null}},g=z({selector:`${n} ${r}`,root:i,visibleRatio:o,dwellMs:s,onViewable(A){let k=l(A);if(!k||k.dataset.hpListView==="manual")return!0;let w=d(k);if(!w||c.has(w.list_id))return!0;let L=new Set,h=m(k).map(f).filter(x=>!x||L.has(x.product_id)?!1:(L.add(x.product_id),!0));return h.length===0||(c.add(w.list_id),e.productListViewed({...w,products:h})),!0}}),b=A=>{let w=A.target?.closest?.("a[href]")?.closest(r);if(!w)return;let L=l(w),h=f(w,L?m(L).indexOf(w):0);h&&e.productClicked({list_id:L?d(L)?.list_id??null:null,products:[h]})};return document.addEventListener("click",b,!0),()=>{document.removeEventListener("click",b,!0),g()}}function T(e,...t){let n=e.dataset??{};for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim()!=="")return o.trim()}return null}function Se(e,...t){let n=T(e,...t);if(n===null)return null;let r=Number(n);return Number.isFinite(r)?Math.trunc(r):null}function nr(e,t){let n=T(e,"hpPromotion");return n?{promotion_id:n,name:T(e,"hpPromotionName"),creative:T(e,"hpPromotionCreative"),position:T(e,"hpPromotionSlot")??String(t+1)}:null}function Be(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-promotion]",resolve:r=nr,visibleRatio:o=.5,dwellMs:s=1e3,root:i=document}=t,c=new Set,l=f=>{let g=Array.from(i.querySelectorAll(n)),b=g.indexOf(f);try{return r(f,b<0?g.length:b)}catch{return null}},d=z({selector:n,root:i,visibleRatio:o,dwellMs:s,onViewable(f){let g=l(f);return!g||c.has(g.promotion_id)?!1:(c.add(g.promotion_id),e.promotionViewed(g),!0)}}),m=f=>{let g=f.target;if(!g||typeof g.closest!="function")return;let b=g.closest(n),A=g.closest("a[href]");if(!b||!A||!b.contains(A)&&!A.contains(b))return;let k=l(b);k&&e.promotionClicked({...k,href:A.getAttribute("href")})};return document.addEventListener("click",m,!0),()=>{document.removeEventListener("click",m,!0),d()}}function rr(e){let t=T(e,"hpRecoRequest"),n=T(e,"hpRecoPlacement"),r=T(e,"hpRecoStrategy");if(!t||!n||!r)return null;let o=T(e,"hpRecoHoldout");return{recommendation_request_id:t,placement:n,strategy:r,recipe:T(e,"hpRecoRecipe"),algorithm_version:T(e,"hpRecoAlgorithmVersion"),experiment:T(e,"hpRecoExperiment"),variant:T(e,"hpRecoVariant"),holdout:o===null?null:o==="true",assignment_bucket:Se(e,"hpRecoBucket"),assignment_unit_kind:T(e,"hpRecoUnitKind"),candidate_set_fingerprint:T(e,"hpRecoFingerprint"),candidate_set_size:Se(e,"hpRecoCandidates"),ranked_by:T(e,"hpRecoRankedBy"),served_at:T(e,"hpRecoServedAt")}}function or(e,t){let n=T(e,"hpRecoProduct");if(!n)return null;let r=T(e,"hpRecoPrice");return{product_id:n,sku:T(e,"hpRecoSku"),name:T(e,"hpRecoName"),brand:T(e,"hpRecoBrand"),price:r===null||Number.isNaN(Number(r))?null:Number(r),position:Se(e,"hpRecoPosition")??t+1}}function Fe(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-reco-request]",tileSelector:r="[data-hp-reco-product]",resolveRail:o=rr,resolveTile:s=or,visibleRatio:i=.5,dwellMs:c=1e3,root:l=document}=t,d=new Set,m=new Map,f=new Map,g=(h,...x)=>{try{return h(...x)}catch{return null}},b=h=>typeof h.closest=="function"?h.closest(n):null,A=h=>Array.from(h.querySelectorAll(r)),k=(h,x)=>{if(f.delete(x.recommendation_request_id),d.has(x.recommendation_request_id))return;let p=A(h).map((S,P)=>g(s,S,P)).filter(S=>S?.product_id);if(p.length===0)return;d.add(x.recommendation_request_id);let _=[...m.get(x.recommendation_request_id)?.values()??[]].sort((S,P)=>S.position-P.position);e.recommendationsViewed({...x,products:p,viewable:_})},w=z({selector:`${n} ${r}`,root:l,visibleRatio:i,dwellMs:c,onViewable(h){let x=b(h);if(!x)return!0;let p=g(o,x);if(!p)return!0;let _=p.recommendation_request_id,S=g(s,h,A(x).indexOf(h));if(S?.product_id){m.has(_)||m.set(_,new Map);let P=m.get(_);P.has(S.position)||P.set(S.position,{position:S.position,product_id:S.product_id,viewable_at:new Date().toISOString()})}return!d.has(_)&&!f.has(_)&&f.set(_,setTimeout(()=>k(x,p),0)),!0}}),L=h=>{let x=h.target;if(!x||typeof x.closest!="function")return;let p=x.closest(r);if(!p)return;let _=x.closest("[data-hp-reco-interaction]"),S=x.closest("a[href]"),P=S&&(p.contains(S)||S.contains(p));if(!(_&&p.contains(_))&&!P)return;let M=b(p);if(!M)return;let B=g(o,M);if(!B)return;let y=g(s,p,A(M).indexOf(p));if(!y?.product_id)return;let V=B.recommendation_request_id;d.has(V)||(clearTimeout(f.get(V)),k(M,B)),e.productClicked({recommendation_request_id:B.recommendation_request_id,interaction:T(_??p,"hpRecoInteraction")??"navigate",products:[y]})};return document.addEventListener("click",L,!0),()=>{document.removeEventListener("click",L,!0);for(let h of f.values())clearTimeout(h);f.clear(),w()}}var ne=new Set(["home","list","product","search","basket","checkout","order_confirmation","login","register","account","info","blog","other"]),sr=new Set(["products"]),Lt=e=>e==null;function He(e){if(Array.isArray(e))return e.map(He);if(e===null||typeof e!="object")return e;let t={};for(let[n,r]of Object.entries(e))Lt(r)||(t[n]=He(r));return t}function Ke(e){if(!e)return e;let t=He(e);for(let n of sr)n in e&&Lt(e[n])&&(t[n]=e[n]);return t}function Ot(){try{let e=performance.getEntriesByType("navigation")[0];return e?["navigate","reload","back_forward","prerender"].includes(e.type)?e.type:"navigate":null}catch{return null}}var ir=new Set(["","unknown","undefined","null","none","nil","nan","anonymous","guest","0","-1"]);function q(e){if(e==null)return null;let t=String(e).trim();return ir.has(t.toLowerCase())?null:t}function re(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function R(e){if(typeof document>"u")return null;try{let t=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith(`${e}=`));return t&&decodeURIComponent(t.slice(e.length+1))||null}catch{return null}}var ar={gclid:"gclid",fbclid:"fbclid",ttclid:"ttclid"},cr=/[a-z0-9._%+-]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}/i,ur=/\d(?:[ -]?\d){12,}/,lr=new Set(["gclid","fbclid","ttclid","msclkid"]);function Tt(e,t=""){if(typeof e!="string"||e==="")return!1;let n=[e];try{let o=decodeURIComponent(e.replace(/\+/g," "));o!==e&&n.push(o)}catch{}let r=!lr.has(String(t).toLowerCase());return n.some(o=>cr.test(o)||r&&ur.test(o))}function dr(e){if(!e)return null;let t=new URLSearchParams(e),n={},r={utm_source:"source",utm_medium:"medium",utm_campaign:"name",utm_term:"term",utm_content:"content"};for(let[o,s]of[...Object.entries(r),...Object.entries(ar)]){let i=t.get(o);i&&!Tt(i,o)&&(n[s]=i)}return Object.keys(n).length?n:null}var fr=["email","e-mail","password","pass","pwd","token","auth","code","uid","customer_id","postcode","zip","phone","applyCode"],pr=["email","password","passwd","pwd","token","secret","auth","session","phone","postcode","zip","address","birth","card","cvv","iban","ssn","customerid","userid"],mr=["tel","uid","dob"],hr=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid","ttclid","msclkid"],gr=new Set(fr.map(e=>e.toLowerCase()));function yr(e){let t=String(e).toLowerCase();if(gr.has(t))return!0;let n=t.replace(/[-_.]/g,"");return pr.some(o=>n.includes(o))?!0:String(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).some(o=>mr.includes(o))}function Ge(e){return(e??[]).map(t=>{try{return new RegExp(`^${t}$`,"i")}catch{return{test:n=>n.toLowerCase()===String(t).toLowerCase()}}})}function Rt(e,t={}){if(!e)return null;try{let n=new URLSearchParams(e),r=t.queryParamAllowlist?Ge([...t.queryParamAllowlist,...hr]):null,o=Ge(t.queryParamBlocklist),s=Ge(t.sensitiveParamAllowlist);for(let c of new Set(n.keys()))(yr(c)&&!s.some(d=>d.test(c))||n.getAll(c).some(d=>Tt(d,c))||(r?!r.some(d=>d.test(c)):o.some(d=>d.test(c))))&&n.delete(c);let i=n.toString();return i?`?${i}`:""}catch{return""}}function wr(e,t,n={}){if(!e)return null;try{let r=new URL(e);return t&&r.origin===t?r.origin+r.pathname+(Rt(r.search,n)??""):r.origin+r.pathname}catch{return null}}function ze(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();return/^[A-Z]{3}$/.test(t)?t:null}function Nt(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();return/^[A-Z]{2}$/.test(t)?t:null}function Sr(e){if(typeof e!="string")return null;let t=e.trim().replace(/_/g,"-");if(!/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(t))return null;try{return Intl.getCanonicalLocales(t)[0]}catch{return null}}function $(e,t){if(typeof e=="function")try{let n=e();if(n!=null)return n}catch{}return t}function _r(e){return{property_id:String(e.propertyId),channel:e.channel??null,market:e.market??null,environment:e.environment??null}}function br(e){let t=typeof window<"u"?window.location:null,n=t?Rt(t.search,e):null;return{url:t?t.origin+t.pathname+(n??""):e.pageUrl??null,path:t?t.pathname:e.pagePath??null,search:n??null,referrer:typeof document<"u"?wr(document.referrer,t?.origin,e):null,title:typeof document<"u"&&document.title||null,type:e.pageType??null}}function Dt(e,t={}){let n=typeof window<"u"?window.location:null,r={library:{name:e.libraryName,version:e.libraryVersion},spec:{version:"1.8"},source:_r(e),session_id:$(e.getSessionId,null),render_id:$(e.getRenderId,null),identity_trust:q($(e.getAnonymousId,null))?"device":"none",page:br(e),campaign:n?dr(n.search):null,device:{user_agent:typeof navigator<"u"?navigator.userAgent:null,type:null,viewport_width:typeof window<"u"?window.innerWidth:null,viewport_height:typeof window<"u"?window.innerHeight:null},currency:ze($(e.getCurrency,e.currency)),locale:Sr($(e.getLocale,e.locale)),timezone:(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}})(),country:Nt(e.country),ship_to_country:Nt($(e.getShipToCountry,e.shipToCountry)),ip:null,bot:null,consent:e.getConsent?.()??null,experiments:$(e.getExperiments,null),audiences:$(e.getAudiences,null),decisions:$(e.getDecisions,null),recommendations:$(e.getRecommendations,null),extensions:$(e.getExtensions,null)};return Mt(r,t)}function Mt(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&!Array.isArray(o)&&e[r]&&typeof e[r]=="object"&&!Array.isArray(e[r])?n[r]=Mt(e[r],o):o!==void 0&&(n[r]=o);return n}var Z=Object.freeze({consent:"thg_hp_consent",retry:"thg_hp_retry",sessionSignals:"thg_hp_session_signals",identified:"thg_hp_identified",previousPage:"thg_hp_prev_page",decisions:"thg_hp_decisions",settings:"thg_hp_settings",held:"thg_hp_held",carried:"thg_hp_carried",recommendationContext:"thg_hp_recommendation_context",anonymousId:"thg_hp_anonymous_id",session:"thg_hp_session",preview:"thg_hp_preview"}),xr={retry:"cdp.retry",sessionSignals:"cdp_session_signals",identified:"cdp_identified",previousPage:"cdp_prev_page_message_id"},We={...Z},$t=!1;function _e(e){let t={...Z};for(let[n,r]of Object.entries(e??{})){if(!(n in Z))throw new Error(`storageNames: unknown kind "${n}"`);if(typeof r!="string"||!/^[\w.-]+$/.test(r))throw new Error(`storageNames.${n} must be a non-empty cookie-safe name`);t[n]=r}We=t}function N(e){return We[e]}var Ir="_",Ut=e=>e==null||e===""?Ir:String(e);function j(e,t,n){let r=`${e}:${Ut(t)}`;return n==null||n===""?r:`${r}:${n}`}function Vt(e,t){return`${e}:${Ut(t)}:`}function be(){if(!$t){$t=!0;for(let e of[()=>localStorage,()=>sessionStorage]){let t;try{if(t=e(),!t)continue;for(let n of Object.keys(t))for(let[r,o]of Object.entries(xr)){if(n!==o&&!n.startsWith(`${o}:`))continue;let s=We[r]+n.slice(o.length);t.getItem(s)===null&&t.setItem(s,t.getItem(n)),t.removeItem(n)}}catch{}}}}var Xe=1800*1e3,xe=()=>{try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}},Je=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};function jt(e,t=()=>Date.now()){return{read(){try{let n=xe()?.getItem(e),r=n?JSON.parse(n):null;return!r||t()-r.savedAt>Xe?(r&&xe()?.removeItem(e),{items:[],anonymousId:null}):{items:Array.isArray(r.items)?r.items:[],anonymousId:typeof r.anonymousId=="string"?r.anonymousId:null}}catch{return{items:[],anonymousId:null}}},write(n,r=null){try{n.length===0?xe()?.removeItem(e):xe()?.setItem(e,JSON.stringify({savedAt:t(),items:n,anonymousId:r}))}catch{}}}}var Ar=400*24*60*60;function W(e,t,n,r){if(typeof document>"u")return!1;try{let o=typeof location<"u"&&location.protocol==="https:"?"; Secure":"",s=r?`; Domain=${r}`:"",i=n===null?"":`; Max-Age=${n}`;return document.cookie=`${e}=${encodeURIComponent(t)}; Path=/${i}; SameSite=Lax`+s+o,!0}catch{return!1}}function vr({name:e,domain:t=null,legacyKey:n,read:r,mint:o,mayStore:s,carried:i=null}){let c=null;try{c=Je()?.getItem(n)||null}catch{c=null}let l=r(e)??c??i,d=!1,m=()=>{if(!(d||l===null||!s())&&(d=W(e,l,Ar,t),!(!d||c===null)))try{Je()?.removeItem(n),c=null}catch{}};return{get(){return l??(l=o()),m(),l},peek:()=>l,persist:m,forget(){W(e,"",0,t),d=!1;try{Je()?.removeItem(n)}catch{}c=null}}}function qt(e,{carried:t,mayStore:n}){let r=e.anonymousIdSource;if(r?.source==="site_cookie"&&r.cookie){let i=r.cookie;return e.getAnonymousId=()=>R(i),null}if(r?.source!=="hp_cookie")return null;let o=N("anonymousId"),s=vr({name:o,domain:e.consentCookieDomain??null,legacyKey:j(o,e.propertyId),read:R,mint:re,mayStore:n,carried:t});return e.getAnonymousId=()=>s.get(),s}var kr=200;function Bt(e,t,n=()=>Date.now()){let r=()=>j(N("carried"),e),o=!1;function s(){try{let i=JSON.parse(sessionStorage.getItem(r())??"null");return!i||!(n()-i.savedAt<=Xe)?[]:Array.isArray(i.calls)?i.calls:[]}catch{return[]}}return{take(){let i=s();try{sessionStorage.removeItem(r())}catch{}return i},save(i){try{return o||!t()?!1:(sessionStorage.setItem(r(),JSON.stringify({savedAt:n(),calls:[...s(),...i].slice(-kr)})),!0)}catch{return!1}},close(){o=!0}}}var ks=Z.consent,Ie=Object.freeze({visitor:"visitor",host:"host"}),Ft=()=>({basis:Ie.host}),Er="hp-consent",Q=["analytics","marketing","personalisation","ad_user_data","ad_personalization"],Ht={analytics:"a",marketing:"m",personalisation:"p",ad_user_data:"aud",ad_personalization:"adp"},K=()=>typeof window<"u",Kt=()=>K()&&typeof window.cookieStore?.addEventListener=="function",Cr=e=>e===!0?!0:e===!1?!1:null;function oe(e){if(!e||typeof e!="object")return null;let t={};for(let n of Q)t[n]=Cr(e[n]);return t}function Ze(e,t){return!e||!t?e===t:Q.every(n=>e[n]===t[n])}function Qe(e){if(!e)return"";let t=[];for(let n of Q){let r=e[n];(r===!0||r===!1)&&t.push(`${Ht[n]}=${r?1:0}`)}return t.join("&")}function Gt(e){return{[Er]:Qe(oe(e))}}function me(e){let t=oe({});if(e==null)return t;let n=String(e).trim();if(n.length>=2&&n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1)),n.includes("%"))try{n=decodeURIComponent(n.replace(/\+/g," "))}catch{return t}let r=Object.fromEntries(Object.entries(Ht).map(([s,i])=>[i,s])),o=new Set;for(let s of n.split("&")){let i=s.indexOf("=");if(i<=0)continue;let c=r[s.slice(0,i).trim()],l={1:!0,0:!1}[s.slice(i+1).trim()]??null;!c||l===null||o.has(c)||(t[c]===null?t[c]=l:t[c]!==l&&(t[c]=null,o.add(c)))}return t}function et(e,t){if(!t)return e;let n=r=>{if(!r)return r;let o={...r};for(let s of Q)s!=="analytics"&&t[s]!==!0&&(o[s]=null);return o};return{name:e.name,basis:e.basis,read:()=>n(e.read()),subscribe:r=>e.subscribe(o=>r(n(o))),get observesChanges(){return e.observesChanges}}}function tt(e,t={}){return{...e,ad_user_data:t.ad_user_data??e.marketing,ad_personalization:t.ad_personalization??e.marketing}}function Ae(e,t){let n=!0;return{notify:()=>{if(n)try{let o=e();o&&t(o)}catch{}},stop:()=>n=!1}}var Pr={analytics:["analytics","measure_content_performance","audience_measurement"],marketing:["marketing","targeting","advertising","select_personalized_ads","create_ads_profile"],personalisation:["personalisation","personalization","select_personalized_content","create_content_profile"]};function Lr(e,t){if(!t?.length)return null;let n=!1;for(let[r,o]of Object.entries(e)){let s=String(o?.id??r).toLowerCase();if(t.some(c=>{let l=String(c).toLowerCase();return s===l||s.startsWith(`${l}-`)})&&(n=!0,o?.enabled===!0))return!0}return n?!1:null}function zt(e={}){let t={...Pr,...e.purposes};function n(){let r=K()?window.Didomi:void 0;if(!r?.getCurrentUserStatus||r.shouldUserStatusBeCollected?.()!==!1||r.isUserStatusPartial?.()===!0)return null;let o=r.getCurrentUserStatus()?.purposes;if(!o||typeof o!="object")return null;let s=i=>Lr(o,t[i]);return tt({analytics:s("analytics"),marketing:s("marketing"),personalisation:s("personalisation")},{ad_user_data:s("ad_user_data"),ad_personalization:s("ad_personalization")})}return{name:"didomi",read:n,observesChanges:!0,subscribe(r){if(!K())return()=>{};let o=Ae(n,r),s={event:"consent.changed",listener:o.notify};return window.didomiEventListeners=window.didomiEventListeners||[],window.didomiEventListeners.push(s),window.didomiOnReady=window.didomiOnReady||[],window.didomiOnReady.push(i=>{o.notify(),(i??window.Didomi)?.on?.("consent.changed",o.notify)}),window.Didomi?.on?.("consent.changed",o.notify),o.stop}}}function Ye(e){let t={};if(!e)return t;for(let n of String(e).split("&")){let r=n.indexOf("=");if(r<=0)continue;let o=n.slice(r+1).replace(/\+/g," ");try{o=decodeURIComponent(o)}catch{}t[n.slice(0,r)]=o}return t}function Wt(e={}){let t={analytics:"C0002",personalisation:"C0003",marketing:"C0004",...e.groups},n=e.impliedConsent===!0;function r(){let i=K()?window.OnetrustActiveGroups:void 0;if(typeof i=="string"&&i.length){let d=new Set(i.split(",").map(m=>m.trim()).filter(Boolean));return m=>d.has(m)}let c=Ye(R("OptanonConsent"));if(!c.groups)return null;let l={};for(let d of c.groups.split(",")){let[m,f]=d.split(":");m?.trim()&&(l[m.trim()]=f==="1"?!0:f==="0"?!1:null)}return d=>l[d]??null}function o(){if(R("OptanonAlertBoxClosed"))return!0;try{if(K()&&window.OneTrust?.IsAlertBoxClosed?.()===!0)return!0}catch{}return Number.parseInt(Ye(R("OptanonConsent")).interactionCount,10)>0?!0:n&&K()&&(!!window.OneTrust||typeof window.OnetrustActiveGroups=="string")}function s(){if(!o())return null;let i=r();if(!i)return null;let c=f=>t[f]?i(t[f]):null,l=tt({analytics:c("analytics"),marketing:c("marketing"),personalisation:c("personalisation")},{ad_user_data:c("ad_user_data"),ad_personalization:c("ad_personalization")}),d=Ye(R("OptanonConsent"));return(typeof navigator<"u"&&navigator.globalPrivacyControl===!0||d.isGpcEnabled==="1")&&(l.marketing=!1,l.ad_user_data=!1,l.ad_personalization=!1),l}return{name:"onetrust",read:s,observesChanges:!0,subscribe(i){if(!K())return()=>{};let c=Ae(s,i),l=!1,d=()=>{l||!window.OneTrust?.OnConsentChanged||(l=!0,window.OneTrust.OnConsentChanged(c.notify))};window.addEventListener("OneTrustGroupsUpdated",c.notify);let m=window.OptanonWrapper;return window.OptanonWrapper=function(...g){try{typeof m=="function"&&m.apply(this,g)}finally{d(),c.notify()}},d(),()=>{c.stop(),window.removeEventListener("OneTrustGroupsUpdated",c.notify)}}}}function Or(e){let t=String(e).split(",").map(n=>n.trim()).filter(Boolean);return t.length?new Set(t):null}function Jt(e){let{name:t,categories:n,parse:r=Or,refusedValue:o,source:s="native",changeEvent:i="thg_hp_consent_change"}=e??{};if(typeof t!="string"||t==="")throw new Error("cookieConsent: `name` (the cookie your banner writes) is required");if(!n||typeof n.analytics!="string")throw new Error("cookieConsent: `categories.analytics` (the category id that grants analytics) is required");function c(){let l=R(t);if(l==null)return null;let d;if(o!==void 0&&l===o)d=new Set;else try{d=r(l)}catch{d=null}if(!(d instanceof Set))return null;let m=f=>n[f]?d.has(n[f]):null;return tt({analytics:m("analytics"),marketing:m("marketing"),personalisation:m("personalisation")},{ad_user_data:m("ad_user_data"),ad_personalization:m("ad_personalization")})}return{name:s,read:c,get observesChanges(){return Kt()},subscribe(l){if(!K())return()=>{};let d=Ae(c,l),m=f=>{[...f.changed??[],...f.deleted??[]].some(b=>b?.name===t)&&d.notify()};return window.addEventListener(i,d.notify),window.cookieStore?.addEventListener?.("change",m),()=>{d.stop(),window.removeEventListener(i,d.notify),window.cookieStore?.removeEventListener?.("change",m)}}}}function Xt(e={}){let t=e.name??N("consent"),n=()=>{let r=R(t);if(r==null)return null;let o=me(r);return o.analytics==null?null:o};return{name:"forwarded",read:n,get observesChanges(){return Kt()},subscribe(r){if(!K())return()=>{};let o=Ae(n,r),s=i=>{[...i.changed??[],...i.deleted??[]].some(l=>l?.name===t)&&o.notify()};return window.cookieStore?.addEventListener?.("change",s),()=>{o.stop(),window.cookieStore?.removeEventListener?.("change",s)}}}}function Yt(e){let t=oe(e);return{name:"static",basis:Ie.host,read:()=>t?{...t}:null,observesChanges:!0,subscribe:()=>()=>{}}}function Zt(e){if(e==null)return null;let t=String(e).split("/").map(n=>n.trim()).filter(Boolean).join("/");return t===""?null:t}function Nr(e){let t=e.item_category;if(t!=null&&String(t).includes("/"))return Zt(t);let n=[t,e.item_category2,e.item_category3,e.item_category4,e.item_category5].map(r=>r==null?"":String(r).trim()).filter(Boolean);return Zt(n.join("/"))}var Tr=e=>{if(e==null||typeof e=="object")return null;let t=String(e).trim();return t===""?null:t};function Rr(...e){for(let t of e){if(typeof t=="number"&&Number.isFinite(t))return String(t);if(typeof t=="string"&&t.trim()!=="")return t.trim()}return null}var ve=e=>Rr(e.item_group_id,e.item_id);function Dr(e,t=ve){if(!e)return null;let n=c=>c==null||c===""||Number.isNaN(Number(c))?null:Number(c),r=c=>{let l=n(c);return l==null?null:Math.round(l*1e6)/1e6},o=c=>{let l=r(c);return l!=null&&l>=0?l:null},s=c=>{let l=n(c);return Number.isInteger(l)&&l>=0?l:null},i=Tr;return{product_id:i(t(e)),sku:i(e.item_id),name:i(e.item_name),brand:i(e.item_brand),variant:i(e.item_variant)??i(e.variant),category:Nr(e),price:r(e.price),discount:o(e.discount),quantity:s(e.quantity),coupon:i(e.coupon),position:s(e.index)!=null?s(e.index)+1:null,url:i(e.url)??i(e.item_url)??null,image_url:i(e.image_url)??i(e.image_link)??null,displayed_sku:i(e.displayed_sku)??i(e.displayed_variant_sku)}}function nt(e,t=ve){return(e??[]).map(n=>Dr(n,t)).filter(n=>n?.product_id)}var Mr=1e3,$r={shipping:2,payment:3},Ur=new Set(["password","google","apple","facebook","magic_link","sso","passkey","other"]),D=e=>{if(e==null||typeof e=="object")return null;let t=String(e).trim();return t===""?null:t},Vr=e=>{if(e==null||e===""||typeof e=="object")return null;let t=Number(e);return Number.isFinite(t)&&t>=0?t:null},ke=e=>e!==null&&typeof e=="object";function jr(e){return Array.isArray(e.items)?e.items.filter(ke):null}function Qt(e){let t=D(e)?.toLowerCase().replace(/[\s-]+/g,"_");return t?Ur.has(t)?t:t==="email"||t==="email_password"?"password":"other":null}function qr({ecommerce:e,items:t}){let n=s=>({promotion_id:D(s.promotion_id),name:D(s.promotion_name),creative:D(s.creative_name),position:D(s.creative_slot)}),r=new Set,o=[];for(let s of[n(e),...t.map(n)])!s.promotion_id||r.has(s.promotion_id)||(r.add(s.promotion_id),o.push(s));return o}var en=({ecommerce:e,items:t})=>D(e.item_list_id)??D(e.item_list_name)??D(t[0]?.item_list_id)??D(t[0]?.item_list_name),ee=(e,t)=>t.products?.length?{event:e,properties:t}:null,Br=new Set(["product","products","item","items"]);function Fr({ecommerce:e}){let t=D(e.item_id),n=D(e.content_type)?.toLowerCase();return!t||n&&!Br.has(n)?null:{event:"Product Shared",properties:{share_via:D(e.method),products:[{product_id:t}]}}}function Hr(e){let t=o=>ee("Product List Viewed",{list_id:en(o),products:o.products}),n=o=>{let s=D(o.ecommerce.search_term);return s?{event:"Products Searched",properties:{query:s,...o.products.length?{products:o.products}:{}}}:null},r=o=>s=>s.promotions.map(i=>({event:o,properties:i}));return{view_item:o=>ee("Product Viewed",{currency:o.currency,value:o.value,products:o.products.slice(0,1)}),view_item_list:t,view_search_results:o=>n(o)??t(o),search:n,select_item:o=>ee("Product Clicked",{list_id:en(o),products:o.products.slice(0,1)}),add_to_cart:o=>ee("Product Added",{cart_id:D(o.ecommerce.cart_id),products:o.products}),remove_from_cart:o=>ee("Product Removed",{cart_id:D(o.ecommerce.cart_id),products:o.products}),view_cart:o=>({event:"Cart Viewed",properties:{cart_id:D(o.ecommerce.cart_id),value:o.value,currency:o.currency,coupon:D(o.ecommerce.coupon),...o.itemsListed?{products:o.products}:{}}}),begin_checkout:o=>ee("Checkout Started",{value:o.value,currency:o.currency,coupon:D(o.ecommerce.coupon),products:o.products}),add_shipping_info:o=>({event:"Checkout Step Completed",properties:{step:e.shipping,step_name:"shipping",shipping_method:D(o.ecommerce.shipping_tier)}}),add_payment_info:o=>({event:"Payment Info Entered",properties:{step:e.payment,step_name:"payment",payment_method:D(o.ecommerce.payment_type)}}),view_promotion:r("Promotion Viewed"),select_promotion:r("Promotion Clicked"),add_to_wishlist:o=>ee("Product Added to Wishlist",{products:o.products}),share:Fr,login:o=>({event:"Signed In",properties:{method:Qt(o.ecommerce.method)}}),sign_up:o=>({event:"Signed Up",properties:{method:Qt(o.ecommerce.method)}})}}var Kr=e=>e.event;function Gr(e,t){if(!ke(e))return null;if(typeof e.length=="number"&&e[0]==="event"&&typeof e[1]=="string"){let r=ke(e[2])?e[2]:{};return{name:e[1],entry:r,ecommerce:r}}let n=D(t(e));return n?{name:n,entry:e,ecommerce:ke(e.ecommerce)?e.ecommerce:e}:null}function rt(e){return Array.isArray(e)?`[${e.map(rt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${rt(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function tn(e,t={}){if(!e||typeof e.track!="function")throw new Error("connectDataLayer: analytics must have a track(event, properties, options) method");let n=t.dataLayer??(typeof window<"u"?window.dataLayer=window.dataLayer||[]:null);if(!Array.isArray(n))return()=>{};let r=Hr({...$r,...t.steps}),o=t.map??{},s=t.eventName??Kr,i=t.productId??ve,c=new Set(["purchase","refund",...t.ignore??[]]),l=t.dedupeMs??Mr,d=new Map,m=!0;function f(p,_,S){if(l<=0)return!1;let P=`${p}|${S??""}|${rt(_)}`,M=Date.now();for(let[B,y]of d)M-y>l&&d.delete(B);return d.has(P)?!0:(d.set(P,M),!1)}let g=null,b=new Set;function A(p,_){if(p!=="Product Viewed")return!1;let S=typeof location>"u"?"":location.pathname;S!==g&&(g=S,b.clear());let P=_.products?.[0]?.product_id;return P?b.has(P)?!0:(b.add(P),!1):!1}function k({event:p,properties:_={}},S){if(!p||f(p,_,S)||A(p,_))return;let P=S?{context:{currency:S}}:void 0;if(p==="Signed Out"&&typeof e.signedOut=="function"){e.signedOut(P);return}e.track(p,_,P)}function w(p){let _=t.transform?t.transform(p):p,S=Gr(_,s);if(!S||c.has(S.name))return;let P=Object.hasOwn(o,S.name),M=P?o[S.name]:r[S.name];if(typeof M!="function")return;let B=jr(S.ecommerce),y=B??[],V={...S,items:y,itemsListed:B!==null,products:nt(y,i),currency:ze(S.ecommerce.currency),value:Vr(S.ecommerce.value)};V.promotions=qr(V);let le=P?M(_,{...V,toProducts:F=>nt(F,i)}):M(V);for(let F of[le].flat())F&&k(F,V.currency)}function L(p){if(m)try{w(p)}catch(_){try{t.onError?.(_,p)}catch{}}}for(let p of n.slice())L(p);let h=n.push;function x(...p){let _=h.apply(this,p);for(let S of p)L(S);return _}return n.push=x,()=>{m=!1,n.push===x&&(n.push=h)}}var zr=4320*60*60,Wr=100,Jr=1e3,Xr=2e3,nn=500,Ee=e=>(e?.unref?.(),e);function Yr(e,t){if(t?.analytics===!0&&e.analytics===!1)return"withdrawn";let n=Q.map(r=>e[r]).filter(r=>r!==null);return n.length&&n.every(Boolean)?"accept_all":n.length&&n.every(r=>!r)?"reject_all":"custom"}function Zr(e,t,n=N("consent")){if(!(typeof document>"u"))try{let r=typeof location<"u"&&location.protocol==="https:"?"; Secure":"",o=t?`; Domain=${t}`:"";document.cookie=`${n}=${Qe(e)}; Path=/; Max-Age=${zr}; SameSite=Lax`+o+r}catch{}}function Qr(e){let t=me(R(e));return Q.some(n=>t[n]!==null)?t:null}function rn(e){let{adapter:t,timeoutMs:n=5e3,cookieDomain:r=null,cookieName:o=N("consent"),release:s,announce:i}=e,c=e.discard??(()=>{}),l="pending",d=null,m=null,f=null,g=null,b=!1,A=null,k=[],w=a=>{l=a,e.onStatus?.(a)};function L(){try{return oe(t.read())}catch{return null}}function h(){m&&clearInterval(m),f&&clearTimeout(f),m=null,f=null}let x=()=>typeof window<"u"&&typeof document<"u",p=()=>{try{return typeof t.subscribe=="function"&&t.observesChanges===!0}catch{return!1}};function _(){g&&clearInterval(g),g=null}function S(){b||g||d===null||p()||x()&&document.visibilityState==="hidden"||(g=Ee(setInterval(()=>V(L()),Xr)))}let P=()=>l==="pending"||l==="unknown",M=e.store??null,B=()=>{let a=k.splice(0);M?.write([]);for(let u of a)s(u)},y=()=>{let a=k.splice(0);M?.write([]);for(let u of a)c(u)};function V(a){let u=oe(a);if(!u||u.analytics===null)return;let v=d===null,C=v?Qr(o):d;if(!v&&Ze(C,u))return;h(),d=u,S(),Zr(u,r,o);let E=!Ze(C,u);if(u.analytics){w("granted"),B(),E&&i({action:Yr(u,C),state:u,withdrawal:!1});return}y(),C?.analytics===!0&&i({action:"withdrawn",state:u,withdrawal:!0}),w("denied")}function le(){f=null,l==="pending"&&(w("unknown"),m&&clearInterval(m),m=Ee(setInterval(()=>V(L()),Jr)))}function F(a){P()&&(M||a?.type!=="visibilitychange"&&!a?.persisted&&y())}let de=a=>{document.visibilityState==="hidden"?(_(),F(a)):S()},ge=a=>{_(),F(a)},fe=()=>S();return{get status(){return l},get state(){return d?{...d}:null},stamp(){return d?{...d,source:t.name??null,basis:t.basis??Ie.visitor}:null},admits(){return l==="granted"},hold(a){return!P()||k.length>=nn?(c(a),!1):(k.push(a),M?.write(k),!0)},onHidden:F,start(){b=!1;try{A=t.subscribe?.(a=>V(a))??null}catch(a){e.debug&&console.warn("[hp] consent adapter subscribe failed",a)}x()&&(window.addEventListener("pagehide",ge),window.addEventListener("pageshow",fe),document.addEventListener("visibilitychange",de)),M&&k.length===0&&k.push(...M.read().slice(-nn)),V(L()),!d&&(m=Ee(setInterval(()=>V(L()),Wr)),f=Ee(setTimeout(le,n)))},stop(){b=!0,h(),_(),typeof A=="function"&&A(),x()&&(window.removeEventListener("pagehide",ge),window.removeEventListener("pageshow",fe),document.removeEventListener("visibilitychange",de))}}}var eo=["recommendation","search_rank","banner","offer","layout","copy","price","other"],Ce=e=>typeof e=="string"&&e!=="";function on(e){return(Array.isArray(e?.decisions)?e.decisions:[]).filter(t=>Ce(t?.slot)&&Ce(t.decision_id)&&t.holdout!==!0).map(({decision_id:t,slot:n,arm:r,kind:o})=>({decision_id:t,slot:n,...Ce(r)&&{arm:r},...eo.includes(o)&&{kind:o}}))}function sn({key:e,mayStore:t}){let n,r=()=>{if(n)return n;try{let s=JSON.parse(sessionStorage.getItem(e));n=Array.isArray(s)?s.filter(i=>Ce(i?.slot)):[]}catch{n=[]}return n},o=()=>{try{n?.length&&t()&&sessionStorage.setItem(e,JSON.stringify(n))}catch{}};return{persist:o,current:()=>r().length?n.map(s=>({...s})):null,remember(s){if(!s.length)return;let i=new Set(s.map(c=>c.slot));n=[...r().filter(c=>!i.has(c.slot)),...s],o()},forget(){n=[];try{sessionStorage.removeItem(e)}catch{}}}}function to(e){let t=2166136261,n=String(e);for(let r=0;r<n.length;r+=1)t^=n.charCodeAt(r),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t^=t>>>16,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t>>>0}function an(e,t,n=1e4){return to(`${t}\0${e}`)%n}function ot(e){let t=o=>Math.min(Math.max(Number(o)||0,0),1),n=t(e.share),r=1-n;return{holdout_share:n,personalised_share:e.ramp==null?r:Math.min(t(e.ramp),r)}}function st(e,t){if(!e||typeof e.salt!="string")return{holdout:!1,bucket:null,group:"personalised"};let n=e.ramp!=null;if(t==null||t==="")return{holdout:!1,bucket:null,group:n?"excluded":"personalised"};let{holdout_share:r,personalised_share:o}=ot(e),s=an(t,e.salt),i=l=>Math.round(l*1e4),c=r>0&&s<i(r)?"holdout":!n||s<i(r+o)?"personalised":"excluded";return{holdout:c==="holdout",bucket:s,group:c}}function cn(e,t){return typeof e!="string"||e===""||t==null||t===""?null:an(t,`bandit-vs-default:${e}`)<1e4/2?"default":"bandit"}var no="hp_preview",ro=256;function un(e,t=null){if(typeof location>"u")return R(e);let n=null;try{n=new URLSearchParams(location.search).get(no)}catch{n=null}if(n===null)return R(e);let r=n.trim();return r===""||r.length>ro?(W(e,"",0,t),null):(W(e,r,null,t),r)}var oo=40,so=128,io=5,ao=60,dn=e=>typeof e=="string"&&e!==""&&e.length<=so&&!e.includes(","),ln=e=>Array.isArray(e)?e.filter(dn).slice(0,oo):[],co=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.replaceAll(","," ").trim()).filter(t=>t!=="").slice(0,io):[],uo=e=>Object.entries(e&&typeof e=="object"?e:{}).filter(([t,n])=>dn(t)&&Number.isFinite(n)&&n>=1).sort(([,t],[,n])=>n-t).slice(0,ao).map(([t,n])=>`${t}:${Math.floor(n)}`);function it(e){let t={},n={viewed:ln(e?.recentProducts),basket:ln(e?.basketProducts),q:co(e?.recentSearches),impressed:uo(e?.impressions)};for(let[r,o]of Object.entries(n))o.length>0&&(t[r]=o.join(","));return t}var lo=1800*1e3;function fn(e,t=Date.now()){try{localStorage.setItem(N("recommendationContext"),JSON.stringify({context:e,until:t+lo}))}catch{}}function pn(){try{localStorage.removeItem(N("recommendationContext"))}catch{}}function at(e){return e.trim().toLowerCase().replace(/\s*\/\s*/g,"/").replace(/^\/+|\/+$/g,"")}var fo=2,po=12;function mo(e,t=fo){return e.split("/").slice(0,t).join("/")}function se(e,t){if(typeof t!="string"||!t.trim())return null;let n=mo(at(t));return n?(e.unshift(n),e.length=Math.min(e.length,po),n):null}var te=()=>N("sessionSignals"),ie=null,ct=()=>ie??te();function mn(){try{return ie?localStorage:sessionStorage}catch{return}}function hn(e,t){let n=t==null?null:String(t),r=e?j(te(),n,e):null;if(r===ie)return;let o=ie===null?ho():null;if(ie=r,!!ie)try{let s=ct(),i=Vt(te(),n);for(let c of Object.keys(localStorage))c.startsWith(i)&&c!==s&&localStorage.removeItem(c);o&&!localStorage.getItem(s)&&(localStorage.setItem(s,JSON.stringify(o)),sessionStorage.removeItem(te()))}catch{}}function ho(){try{let e=sessionStorage.getItem(te());if(!e)return null;let t=JSON.parse(e);return t&&(t.productViews>0||t.listViews>0||t.recentProducts?.length||t.recentBrowse?.length)?t:null}catch{return null}}function Pe(){return{productViews:0,listViews:0,cartAdds:0,searches:0,recentProducts:[],recentCategories:[],recentBrowse:[],basketProducts:[],recentSearches:[],impressions:{},browsingCategory:null,startedAt:0}}function ut(){let e=mn();if(!e)return Pe();try{let t=e.getItem(ct());return t?{...Pe(),...JSON.parse(t)}:{...Pe(),startedAt:Date.now()}}catch{return{...Pe(),startedAt:Date.now()}}}function gn(e){let t=mn();if(t)try{t.setItem(ct(),JSON.stringify(e))}catch{}}function yn(){return ut()}function wn(){for(let e of[()=>sessionStorage,()=>localStorage])try{let t=e();t.removeItem(te());for(let n of Object.keys(t))n.startsWith(`${te()}:`)&&t.removeItem(n)}catch{}}var Sn=20,_n=200,go=new Set(["Product Viewed","Product Clicked","Product Added","Product Added to Wishlist"]),yo=new Set(["Product Clicked","Product Added to Wishlist"]);function bn(e,t){let n=ut();n.startedAt||(n.startedAt=Date.now());let r=Array.isArray(t?.products)?t.products:[];switch(e){case"Product Viewed":n.productViews+=1,se(n.recentBrowse,n.browsingCategory);break;case"Product List Viewed":n.listViews+=1;{let i=t?.list_id;typeof i=="string"&&i.includes("/")&&!i.startsWith("cdp-")&&(n.browsingCategory=se(n.recentBrowse,i)??n.browsingCategory)}break;case"Product List Filtered":{let i=t?.change,c=typeof t?.list_id=="string"?t.list_id:"",l=typeof i?.value=="string"?i.value:"";l&&i?.action!=="removed"&&(n.browsingCategory=se(n.recentBrowse,`${c}/${l}`)??n.browsingCategory);break}case"Product Added":{n.cartAdds+=1,se(n.recentBrowse,n.browsingCategory);for(let i of r){let c=i.product_id;typeof c!="string"||!c||(n.basketProducts=[c,...n.basketProducts.filter(l=>l!==c)].slice(0,Sn))}break}case"Product Removed":{for(let i of r){let c=i.product_id;typeof c=="string"&&c&&(n.basketProducts=n.basketProducts.filter(l=>l!==c))}break}case"Products Searched":{n.searches+=1;let i=t?.query;if(typeof i=="string"&&i.trim()){let c=i.trim().toLowerCase().slice(0,64);n.recentSearches=[c,...n.recentSearches.filter(l=>l!==c)].slice(0,5)}break}case"Product Clicked":case"Product Added to Wishlist":break;default:return n}let o=go.has(e);if(o)for(let i of r)typeof i.product_id=="string"&&i.product_id&&delete n.impressions[i.product_id];else{for(let c of r){let l=c.product_id;typeof l!="string"||!l||(n.impressions[l]=(n.impressions[l]??0)+1)}let i=Object.keys(n.impressions);if(i.length>_n){let c={};for(let l of i.sort((d,m)=>n.impressions[m]-n.impressions[d]).slice(0,_n))c[l]=n.impressions[l];n.impressions=c}}let s=new Set;for(let i of r){let c=i.product_id;if(o&&typeof c=="string"&&c&&(n.recentProducts=[c,...n.recentProducts.filter(l=>l!==c)].slice(0,Sn)),!yo.has(e)&&typeof i.category=="string"&&i.category){let l=at(i.category);l&&!s.has(l)&&(s.add(l),se(n.recentCategories,l))}}return gn(n),n}var xn=1800*1e3;function In({name:e,domain:t=null,mayStore:n,now:r=()=>Date.now(),mint:o=re}){let s=null,i=0,c=()=>{s!==null&&n()&&W(e,s,xn/1e3,t)};return{get(){let l=r(),d=R(e);return d?s=d:(s===null||l-i>=xn)&&(s=o()),i=l,c(),s},persist:c,forget(){W(e,"",0,t),s=null}}}var G=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),vn=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),lt=Object.freeze({enabled:!1});function kn(e,t){let n=e?.track;return G(n)?(Object.hasOwn(n,t)?n[t]:n.__default)?.enabled!==!1:!0}function wo(e,t){return`${ae(e)}/v1/projects/${encodeURIComponent(t)}/settings`}var So="https://hp.uat.thgingenuity.com";function ae(e){return e==null||e===""?So:En(e)}function En(e){if(typeof e!="string")return null;let t=e.trim().replace(/\/+$/,"");return/^https?:\/\/[^/\s]+$/i.test(t)?t:/^[a-z0-9.-]+(:\d+)?$/i.test(t)?`https://${t}`:null}function _o(e){if(!G(e))return null;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>typeof n=="boolean"));return Object.keys(t).length?t:null}var An=e=>typeof e=="number"&&e>=0&&e<=1;function bo(e){if(!G(e))return null;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>G(n)&&An(n.share)&&(n.ramp==null||An(n.ramp))&&typeof n.salt=="string"&&n.salt!=="").map(([n,r])=>[n,{share:r.share,ramp:r.ramp??null,salt:r.salt,...vn(r.readoutSlots)&&r.readoutSlots.length>0&&{readoutSlots:r.readoutSlots}}]));return Object.keys(t).length?t:null}var xo=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;function Io(e){return G(e)?e.source==="hp_cookie"?{source:"hp_cookie"}:e.source!=="site_cookie"?null:e.cookie==null?{source:"site_cookie",cookie:null}:typeof e.cookie=="string"&&xo.test(e.cookie)?{source:"site_cookie",cookie:e.cookie}:null:null}function dt(e){let t=G(e)?e.hp:null;return!G(t)||t.enabled!==!0?lt:{enabled:!0,propertyId:typeof t.propertyId=="string"&&t.propertyId!==""?t.propertyId:null,environment:typeof t.environment=="string"?t.environment:null,consentPurposes:_o(t.consent?.purposes),queryParamAllowlist:vn(t.queryParamAllowlist)?t.queryParamAllowlist:null,anonymousId:Io(t.anonymousId),apiHost:En(t.apiHost),holdouts:bo(t.holdouts),plan:G(e.plan)&&G(e.plan.track)?{track:e.plan.track}:null}}async function Cn(e,t,n=globalThis.fetch){try{let r=await n(wo(e,t),{credentials:"omit",headers:{accept:"application/json"}});return r.ok?dt(await r.json()):null}catch{return null}}var Le=e=>j(N("settings"),e);function Pn(e){try{let t=localStorage.getItem(Le(e));if(!t)return null;let n=JSON.parse(t);return n?.enabled===!0?n:null}catch{return null}}function Ln(e,t){try{t?.enabled===!0?localStorage.setItem(Le(e),JSON.stringify(t)):localStorage.removeItem(Le(e))}catch{}}function ft(e){try{localStorage.removeItem(Le(e))}catch{}}var Ao={flushAt:20,flushIntervalMs:1e4,maxQueue:500,maxRetryAgeMs:1440*60*1e3,maxRetries:5,maxPersistedBatches:20,maxPersistedBytes:1024*1024,storageKey:Z.retry,beaconSafeBytes:56*1024,maxBatchEvents:100,maxBatchBytes:500*1024},pt=()=>Date.now(),ce=e=>typeof TextEncoder<"u"?new TextEncoder().encode(e).length:Buffer.byteLength(e),mt=()=>typeof window<"u"&&typeof document<"u";function vo(){try{return!mt()||!window.localStorage?null:(window.localStorage.getItem("thg_hp_probe"),window.localStorage)}catch{return null}}var I,ht,On,Oe,gt,yt,Nn,he,wt,Ne,Tn,St,Rn,Te,Re=class{constructor(t){It(this,I);this.o={...Ao,...t},this.queue=[],this.timer=null,this.storage=vo(),this.inflight=null,this.sending=new Set,this.replayAllowed=!this.o.deferReplay,this.draining=null,mt()&&(window.addEventListener("pagehide",()=>this.flush({beacon:!0})),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush()}),O(this,I,Te).call(this))}replayPersisted(){return this.replayAllowed=!0,O(this,I,Te).call(this)}clearPersisted(){if(this.replayAllowed=!1,!!this.storage)try{this.storage.removeItem(this.o.storageKey)}catch{}}enqueue(t){this.queue.push(t),this.queue.length>this.o.maxQueue&&this.queue.splice(0,this.queue.length-this.o.maxQueue),this.queue.length>=this.o.flushAt?this.flush():O(this,I,ht).call(this)}flush(t={}){if(O(this,I,On).call(this),this.queue.length===0)return Promise.resolve();if(t.beacon&&mt()&&typeof navigator<"u"&&navigator.sendBeacon)return O(this,I,Nn).call(this),Promise.resolve();if(this.inflight)return this.inflight;let n=O(this,I,yt).call(this,this.queue,this.o.maxBatchEvents,this.o.maxBatchBytes).map(r=>{let o=O(this,I,St).call(this,r);return o&&this.sending.add(o),{batch:r,id:o}});return this.queue=[],this.inflight=(async()=>{for(let{batch:r,id:o}of n)await O(this,I,he).call(this,r,0,o)})().finally(()=>{this.inflight=null,this.queue.length>=this.o.flushAt?this.flush():this.queue.length&&O(this,I,ht).call(this)}),this.inflight}};I=new WeakSet,ht=function(){this.timer||(this.timer=setTimeout(()=>this.flush(),this.o.flushIntervalMs),this.timer?.unref?.())},On=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},Oe=function(t){return JSON.stringify({batch:t,writeKey:this.o.writeKey,sentAt:new Date().toISOString()})},gt=function(){return`${this.o.apiHost.replace(/\/$/,"")}/v1/batch`},yt=function(t,n,r){let o=ce(O(this,I,Oe).call(this,[])),s=[],i=[],c=o;for(let l of t){let d=ce(JSON.stringify(l))+1;i.length&&(i.length>=n||c+d>r)&&(s.push(i),i=[],c=o),i.push(l),c+=d}return i.length&&s.push(i),s},Nn=function(){let t=this.queue;this.queue=[];let n=O(this,I,gt).call(this);for(let r of O(this,I,yt).call(this,t,this.o.maxBatchEvents,this.o.beaconSafeBytes)){let o=O(this,I,Oe).call(this,r);if(ce(o)<=this.o.beaconSafeBytes){let s=!1;try{s=navigator.sendBeacon(n,new Blob([o],{type:"text/plain"}))}catch{s=!1}if(s)continue}O(this,I,he).call(this,r,0,O(this,I,St).call(this,r))}},he=async function(t,n,r=null){r&&this.sending.add(r);let o=O(this,I,Oe).call(this,t);try{let s=await fetch(O(this,I,gt).call(this),{method:"POST",headers:{"Content-Type":"text/plain"},body:o,keepalive:ce(o)<=this.o.beaconSafeBytes});if(s.ok)return O(this,I,wt).call(this,r),O(this,I,Te).call(this),!0;if(!(s.status===429||s.status>=500))return O(this,I,wt).call(this,r),this.o.onError?.(`CDP ingest rejected batch (${s.status}); dropping ${t.length} events`),!0;throw new Error(`retryable ${s.status}`)}catch(s){if(n>=this.o.maxRetries){r&&this.sending.delete(r);let c=r?"kept for the next page":"dropped";return this.o.onError?.(`CDP ingest unreachable after ${n} attempts; ${c}: ${t.length} events`,s),!1}let i=Math.min(1e3*2**n,3e4)*(.5+Math.random());return await new Promise(c=>setTimeout(c,i)),O(this,I,he).call(this,t,n+1,r)}},wt=function(t){t&&(this.sending.delete(t),O(this,I,Rn).call(this,t))},Ne=function(){let t=JSON.parse(this.storage.getItem(this.o.storageKey)||"[]");return Array.isArray(t)?t:[]},Tn=function(t,n){let r=i=>ce(JSON.stringify(i))+1,o=[...t,n].slice(-this.o.maxPersistedBatches),s=o.reduce((i,c)=>i+r(c),2);for(;o.length>1&&s>this.o.maxPersistedBytes;)s-=r(o[0]),o=o.slice(1);for(;o.length;)try{return this.storage.setItem(this.o.storageKey,JSON.stringify(o)),!0}catch{o=o.slice(1)}return!1},St=function(t){if(!this.storage||this.o.mayPersist&&!this.o.mayPersist())return null;try{let n={at:pt(),id:`${pt()}-${Math.random().toString(36).slice(2)}`,batch:t};return ce(JSON.stringify(n))+3>this.o.maxPersistedBytes?null:O(this,I,Tn).call(this,O(this,I,Ne).call(this),n)?n.id:null}catch{return null}},Rn=function(t){if(!(!t||!this.storage))try{let n=O(this,I,Ne).call(this).filter(r=>r.id!==t);n.length?this.storage.setItem(this.o.storageKey,JSON.stringify(n)):this.storage.removeItem(this.o.storageKey)}catch{}},Te=function(){if(!this.storage||!this.replayAllowed)return this.draining??Promise.resolve();if(this.draining)return this.draining;let t;try{let r=O(this,I,Ne).call(this);t=r.filter(o=>Array.isArray(o?.batch)&&pt()-o.at<this.o.maxRetryAgeMs).map(o=>o.id?o:{...o,id:`${o.at}-${Math.random().toString(36).slice(2)}`}),(t.length!==r.length||t.some((o,s)=>o!==r[s]))&&(t.length?this.storage.setItem(this.o.storageKey,JSON.stringify(t)):this.storage.removeItem(this.o.storageKey))}catch{return Promise.resolve()}let n=t.filter(r=>!this.sending.has(r.id));return n.length?(this.draining=(async()=>{for(let r of n)if(!this.replayAllowed||!await O(this,I,he).call(this,r.batch,0,r.id))return})().finally(()=>{this.draining=null}),this.draining):Promise.resolve()};var Dn="3.17.1",Mn="@thg-agentic/hyper-personalisation-web";var ko=new Set(["audiences","decisions","recommendations"]);var Eo=Symbol.for("@thg-agentic/hyper-personalisation-web.replay");function Co(e){let t={...e??{}},n=Array.isArray(t.products)?t.products:null;if(t.item_count==null&&n){let r=n.map(o=>o?.quantity);r.every(Number.isInteger)&&(t.item_count=r.reduce((o,s)=>o+s,0))}return t}var Po="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";function Lo(e){if(/^[0-9a-fA-F]{64}$/.test(e))return e.toLowerCase();if(!/^[A-Za-z0-9+/_-]{43}=?$/.test(e))return null;try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(44,"="));return t.length!==32?null:Array.from(t,n=>n.charCodeAt(0).toString(16).padStart(2,"0")).join("")}catch{return null}}function De(e){if(typeof e!="string")return null;let t=Lo(e.trim());return t===Po?null:t}var $n=!1;function Oo(e){!e||$n||($n=!0,console.warn("[hp] mintAnonymousId is ignored since 3.6: where device ids come from is set per source in the console (the site\u2019s own cookie, or Hyper-Personalisation\u2019s)."))}function Un(e){return e&&typeof e.context=="object"&&e.context!==null?e.context:e}function Vn(e){let t=ae(e?.apiHost);if(!t)throw new Error("createAnalytics: apiHost, when given, must be a host or an http(s) origin");if(!e?.propertyId)throw new Error("createAnalytics: propertyId is required");let n={libraryName:Mn,libraryVersion:Dn,writeKey:"web",queryParamBlocklist:[],debug:!1,validate:null,consentTimeoutMs:5e3,...e,apiHost:t};_e(n.storageNames),be();let r=!!n.consent,o=null;n.getConsent=()=>o?o.stamp():Ft();let s=()=>!r||o?.status==="granted",i=r&&n.holdAcrossPages?jt(j(N("held"),n.propertyId)):null,c=i?.read()??{items:[],anonymousId:null};n.mintAnonymousId!==void 0&&Oo(n.debug);let l=qt(n,{carried:c.anonymousId,mayStore:s}),d=n.getSessionId==null?In({name:N("session"),domain:n.consentCookieDomain??null,mayStore:s}):null;d&&(n.getSessionId=()=>d.get());let m=un(N("preview"),n.consentCookieDomain??null),f=n.transport??new Re({apiHost:n.apiHost,writeKey:n.writeKey,storageKey:j(N("retry"),n.propertyId),mayPersist:r?()=>o?.status==="granted":void 0,deferReplay:r,onError:(a,u)=>n.debug&&console.warn("[hp]",a,u??"")}),g=j(N("previousPage"),n.propertyId),b=null,A=()=>{if(b)return b;try{return sessionStorage.getItem(g)||null}catch{return null}},k=a=>{if(b=a||null,!(r&&o.status!=="granted"))try{sessionStorage.setItem(g,a)}catch{}},w=sn({key:j(N("decisions"),n.propertyId),mayStore:s});n.getDecisions??(n.getDecisions=w.current);let L=q($(n.getUserId,null)),h=null;function x(a,u,v=!1){let C=h;h=null;let E={messageId:C?.messageId??re(),timestamp:C?.timestamp??new Date().toISOString(),anonymousId:q($(n.getAnonymousId,null)),userId:L??null,...a,context:Dt(n,Un(u))};if(E.properties&&(E.properties=Ke(E.properties)),n.beforeSend){let H;try{H=n.beforeSend(E)}catch(Jn){return console.warn("[hp] beforeSend failed; the event was not sent",Jn),null}if(!H)return null;let{type:ye,event:bt,messageId:zn,timestamp:Wn}=E;E={...H,type:ye,messageId:zn,timestamp:Wn,...bt?{event:bt}:{}}}if(n.validate){let H=n.validate(E,{producer:"web"});if(!H.valid){let ye=`[hp] invalid ${E.event??E.type}:
2
- ${H.errors.join(`
3
- `)}`;if(n.throwOnInvalid)throw new Error(ye);console.error(ye)}}return n.debug&&console.debug("[hp]",E.event??E.type,E),B(E,v),E}function p(a){if(a.type==="track"&&M(a),n.onEvent)try{n.onEvent(a)}catch(u){console.warn("[hp] onEvent observer failed",u)}}let _=()=>r&&o?.state?.personalisation===!0,S=()=>hn($(n.getSessionId,null),n.propertyId),P=!1;function M(a){try{_()?(S(),fn(it(bn(a.event,a.properties))),P=!0):(pn(),P&&wn(),P=!1)}catch(u){n.debug&&console.warn("[hp] the visit was not recorded",u)}}function B(a,u){!r||u||o.admits()?(p(a),f.enqueue(a)):o.hold(a)}let y=(a,u,v)=>kn(n.plan,a)?x({type:"track",event:a,properties:u??{}},v):null,V=new Set,le=(a,u,v)=>a==="audiences"?{audiences:u?null:v.audiences??[]}:a==="decisions"?{decisions:(v.decisions??[]).map(C=>({slot:C.slot,decision_id:C.decision_id??null,arm:C.arm??null,...C.variant&&{variant:C.variant}}))}:{recommendation_request_id:v.recommendation_request_id??null};r&&(o=rn({adapter:n.consent,timeoutMs:n.consentTimeoutMs,cookieDomain:n.consentCookieDomain,debug:n.debug,store:i&&{read:()=>c.items,write:a=>i.write(a,l?.peek()??null)},release(a){a.context&&(a.context.consent=o.stamp()),p(a),f.enqueue(a)},onStatus(a){if(a==="granted"&&(l?.persist(),d?.persist(),b&&k(b),w.persist(),f.replayPersisted?.()),a==="denied"){f.clearPersisted?.(),l?.forget(),d?.forget();try{sessionStorage.removeItem(g)}catch{}w.forget()}try{n.onConsentStatus?.(a)}catch(u){console.warn("[hp] onConsentStatus observer failed",u)}},announce({action:a,state:u,withdrawal:v}){x({type:"track",event:"Consent Updated",properties:{action:a,state:u}},void 0,v),v&&f.flush()}}),o.start());let F=()=>n.holdout?ot(n.holdout):null,de=()=>st(n.holdout,q($(n.getAnonymousId,null))).group;function ge(a,u){if(!Array.isArray(a?.decisions))return a;let v=n.holdout?.readoutSlots??[],C=q($(n.getAnonymousId,null));return{...a,decisions:a.decisions.map(E=>{let H=E?.variant==="bandit"||E?.variant==="default"?E.variant:!u&&E?.holdout!==!0&&v.includes(E?.slot)?cn(E.slot,C):null;return H?H==="default"?{...E,variant:H,decision_id:null}:{...E,variant:H}:E})}}function fe(a,u){if(m)return null;let v=a?.exposure,C=v?.holdout===!0,E=ge(a,C);return w.remember(on(E)),!v?.token||V.has(v.token)?null:(V.add(v.token),y("Personalisation Exposed",{exposure_token:v.token,surface:v.surface,holdout:C,holdout_share:v.holdout_share??F()?.holdout_share??null,personalised_share:v.personalised_share??F()?.personalised_share??null,...le(v.surface,C,E)},u))}return{track:y,page(a={},u){let v=n.pageType??null;a.type&&(ne.has(a.type)?(v=a.type,n.pageType=a.type):n.debug&&console.warn(`[hp] ignoring unknown page.type "${a.type}". Allowed: ${[...ne].join(", ")}`));let C=x({type:"page",properties:{name:a.name??null,navigation_trigger:a.navigation_trigger??Ot(),previous_message_id:A()}},{page:{type:v},...Un(u)??{}});return C&&k(C.messageId),C},identify(a,u){let{userId:v,...C}=a&&typeof a=="object"?a:{};if(v!==void 0&&(L=q(v)),typeof C.email_sha256=="string"){let E=De(C.email_sha256);E?C.email_sha256=E:delete C.email_sha256}return x({type:"identify",traits:C},u)},reset(){L=null,k("")},productViewed:(a,u)=>y("Product Viewed",a,u),productListViewed:(a,u)=>y("Product List Viewed",a,u),recommendationsViewed:(a,u)=>y("Recommendations Viewed",a,u),personalisationExposed:(a,u)=>y("Personalisation Exposed",a,u),recordExposure:fe,surfaceViewed({surface:a}={},u){if(!ko.has(a)||!n.holdout||a!=="decisions"&&!_())return null;let v=q($(n.getAnonymousId,null)),C=st(n.holdout,v).group;if(C==="excluded")return null;let E=Ct({sessionId:we($(n.getSessionId,null),v),surface:a});return E?fe({exposure:{token:E,surface:a,holdout:C==="holdout"}},u):null},inHoldout:()=>de()!=="personalised",personalisationGroup:de,productClicked:(a,u)=>y("Product Clicked",a,u),productListFiltered:(a,u)=>y("Product List Filtered",a,u),productsSearched:(a,u)=>y("Products Searched",a,u),productAdded:(a,u)=>y("Product Added",a,u),productRemoved:(a,u)=>y("Product Removed",a,u),cartUpdated:(a,u)=>y("Cart Updated",Co(a),u),identityLinked:(a,u)=>y("Identity Linked",a,u),slotEngaged:(a,u)=>m?null:y("Slot Engaged",a,u),productVariantSelected:(a,u)=>y("Product Variant Selected",a,u),cartViewed:(a,u)=>y("Cart Viewed",a,u),productAddedToWishlist:(a,u)=>y("Product Added to Wishlist",a,u),productRemovedFromWishlist:(a,u)=>y("Product Removed from Wishlist",a,u),wishlistProductAddedToCart:(a,u)=>y("Wishlist Product Added to Cart",a,u),productShared:(a,u)=>y("Product Shared",a,u),cartShared:(a,u)=>y("Cart Shared",a,u),couponEntered:(a,u)=>y("Coupon Entered",a,u),couponApplied:(a,u)=>y("Coupon Applied",a,u),couponDenied:(a,u)=>y("Coupon Denied",a,u),couponRemoved:(a,u)=>y("Coupon Removed",a,u),checkoutStarted:(a,u)=>y("Checkout Started",a,u),promotionViewed:(a,u)=>y("Promotion Viewed",a,u),promotionClicked:(a,u)=>y("Promotion Clicked",a,u),checkoutStepViewed:(a,u)=>y("Checkout Step Viewed",a,u),checkoutStepCompleted:(a,u)=>y("Checkout Step Completed",a,u),paymentInfoEntered:(a,u)=>y("Payment Info Entered",a,u),checkoutFailed:(a,u)=>y("Checkout Failed",a,u),signedIn:(a,u)=>y("Signed In",a,u),signedUp:(a,u)=>y("Signed Up",a,u),signedOut(a){let u=y("Signed Out",{},a);return L=null,u},newsletterSubscribed:(a,u)=>y("Newsletter Subscribed",a,u),newsletterUnsubscribed:(a,u)=>y("Newsletter Unsubscribed",a,u),backInStockSubscribed:(a,u)=>y("Back In Stock Subscribed",a,u),productReviewed:(a,u)=>y("Product Reviewed",a,u),consentUpdated:(a,u)=>y("Consent Updated",a,u),flush:a=>f.flush(a),recommendationContext(){if(!_())return{};try{return S(),it(yn())}catch{return{}}},get consent(){return o?o.state:null},servingHeaders:()=>Gt(o?.state??null),get lastPageMessageId(){return A()},get anonymousId(){return q($(n.getAnonymousId,null))},[Eo](a,u,v){if(typeof this[a]=="function"){h=typeof v?.messageId=="string"&&typeof v?.timestamp=="string"?{messageId:v.messageId,timestamp:v.timestamp}:null;try{this[a](...Array.isArray(u)?u:[])}finally{h=null}}}}}var _t=Symbol.for("@thg-agentic/hyper-personalisation-web.bootstrap"),No=Symbol.for("@thg-agentic/hyper-personalisation-web.drain"),To=Symbol.for("@thg-agentic/hyper-personalisation-web.carry"),Ro=Symbol.for("@thg-agentic/hyper-personalisation-web.replay"),Do=Symbol.for("@thg-agentic/hyper-personalisation-web.assignment"),Mo=Symbol.for("@thg-agentic/hyper-personalisation-web.recommendation-context"),Ue=e=>e?()=>R(e):()=>null,Bn={didomi:e=>zt({purposes:e.purposes}),onetrust:e=>Wt({groups:e.groups,impliedConsent:e.impliedConsent}),cookie:e=>Jt({name:e.name,categories:e.categories,refusedValue:e.refusedValue,source:e.source,changeEvent:e.changeEvent}),forwarded:e=>Xt({name:e.name}),static:e=>{if(!e.state||typeof e.state!="object")throw new Error('consent.state is required for provider "static"');return Yt(e.state)}},jn=Object.keys(Bn),ue=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Me=e=>typeof e=="string"&&e!=="",$o=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),Fn=e=>ue(e)&&typeof e.read=="function";function Uo(e,t={}){let n=[];if(!ue(e))return["config must be { writeKey, apiHost? }"];Me(e.writeKey)||n.push("writeKey is required"),ae(e.apiHost)||n.push("apiHost, when given, must be a host or an http(s) origin"),t.propertyId!==void 0&&!Me(t.propertyId)&&n.push("propertyId must be a string");let{consent:r}=t;if(!Fn(r)&&!(ue(r)&&jn.includes(r.provider))&&n.push(`consent must be a consent adapter or { provider: ${jn.join(" | ")} }`),t.autocapture!==void 0&&t.autocapture!==!1&&!ue(t.autocapture)&&n.push("autocapture must be false or { promotions, productLists, recommendations }"),t.beforeSend!==void 0&&typeof t.beforeSend!="function"&&n.push("beforeSend must be a function"),t.identityCookies!==void 0)if(!ue(t.identityCookies))n.push("identityCookies must be an object");else for(let o of["anonymousId","sessionId"]){let s=t.identityCookies[o];s!==void 0&&!Me(s)&&n.push(`identityCookies.${o} must be a cookie name`)}for(let o of["getCurrency","getShipToCountry","getLocale"])t[o]!==void 0&&typeof t[o]!="function"&&n.push(`${o} must be a function`);return t.dataLayer!==void 0&&(ue(t.dataLayer)?(t.dataLayer.name!==void 0&&!Me(t.dataLayer.name)&&n.push("dataLayer.name must be a string"),t.dataLayer.ignore!==void 0&&!$o(t.dataLayer.ignore)&&n.push("dataLayer.ignore must be an array of strings")):n.push("dataLayer must be an object")),n}function Vo(e,t,n){if(Fn(e))return et(e,t.consentPurposes);let{provider:r,...o}=e,s=n?.consent?.[r]??Bn[r];return et(s(o),t.consentPurposes)}var Hn=(e,t)=>`${e??""}|${t??""}`;function jo(e,t){let n=q(t?.userId),r=De(t?.emailSha256);if(!n&&!r)return null;try{let o=j(N("identified"),e);if(sessionStorage.getItem(o)===Hn(n,r))return null}catch{}return{...n?{userId:n}:{},...r?{email_sha256:r}:{}}}async function qo({writeKey:e,apiHost:t},n){if(n.settings!==void 0)return{settings:dt(n.settings),revalidated:null};let r=Cn(t,e),o=Pn(e);if(o)return{settings:o,revalidated:r};let s=await r,i=s??lt;return{settings:i,revalidated:Promise.resolve(i),unreachable:s===null}}function Kn(e,t={}){let n=typeof window<"u"?window:null;if(n?.[_t])return n[_t];let r=Bt(e?.writeKey,()=>{let{analytics:s}=me(R(N("consent")));return s===!0||s===null&&t.holdAcrossPages===!0}),o=Bo(e,t,r);if(n){let s=t.extend?.getSessionId??Ue(t.identityCookies?.sessionId),i=Ue(t.identityCookies?.anonymousId);n[Do]=({slot:c,arm:l}={})=>Et({sessionId:we(s(),i()),slot:c,arm:l}),n[_t]=o,n[To]=r,n[No]?.(o)}return o}function qn(e,t){if(t===!1)return()=>{};let n={promotions:!0,productLists:!0,recommendations:!0,exposures:!0,...t},r=s=>s&&typeof s=="object"?s:{},o=[];try{n.promotions&&o.push(Be(e,r(n.promotions))),n.productLists&&o.push(qe(e,r(n.productLists))),n.recommendations&&o.push(Fe(e,r(n.recommendations))),n.exposures&&o.push(je(e,r(n.exposures)))}catch(s){console.warn("[hp] autocapture not started:",s?.message??s)}return()=>{for(let s of o)s()}}function $e(e){return e.close(),null}async function Bo(e,t,n){try{let r=Uo(e,t);if(r.length)return console.warn(`[hp] not started, the configuration is invalid: ${r.join("; ")}`),$e(n);_e(t.storageNames),be();let{writeKey:o}=e,[{settings:s,revalidated:i,unreachable:c},l]=await Promise.all([qo(e,t),Promise.resolve(t.identity).catch(()=>null)]),d=i?s:null,m=!1,f=()=>m&&d&&Ln(o,d);if(i?.then(p=>{p&&(d=p,p.enabled?f():ft(o))}),c)return null;if(!s.enabled)return t.debug&&console.info("[hp] off: the settings for this write key do not enable it"),$e(n);let g=s.propertyId??t.propertyId;if(!g)return console.warn("[hp] not started: this write key covers several properties, so propertyId is required"),$e(n);let{preset:b}=t,A=jo(g,l),k=q(l?.userId),w=Vn({apiHost:s.apiHost??ae(e.apiHost),writeKey:o,propertyId:g,pageType:ne.has(t.pageType)?t.pageType:void 0,environment:s.environment,queryParamAllowlist:s.queryParamAllowlist??void 0,plan:s.plan,holdout:s.holdouts?.[g],getCurrency:t.getCurrency,getShipToCountry:t.getShipToCountry,getLocale:t.getLocale,consent:Vo(t.consent,s,b),consentCookieDomain:t.consentCookieDomain,storageNames:t.storageNames,holdAcrossPages:t.holdAcrossPages===!0,mintAnonymousId:t.mintAnonymousId,debug:t.debug===!0,anonymousIdSource:s.anonymousId??void 0,getAnonymousId:Ue(t.identityCookies?.anonymousId),getSessionId:t.identityCookies?.sessionId?Ue(t.identityCookies.sessionId):void 0,getUserId:()=>k,beforeSend:t.beforeSend,...t.extend,onConsentStatus(p){if(p==="granted"&&(m=!0,f()),p==="denied"){ft(o);try{sessionStorage.removeItem(j(N("identified"),g))}catch{}}t.extend?.onConsentStatus?.(p)},onEvent(p){if(p.type==="identify"){let _=Hn(q(p.userId),De(p.traits?.email_sha256));try{sessionStorage.setItem(j(N("identified"),g),_)}catch{}}t.extend?.onEvent?.(p)}});typeof window<"u"&&(window[Mo]=()=>w.recommendationContext());for(let[p,_,S]of n.take())try{w[Ro](p,_,S)}catch(P){console.warn(`[hp] carried ${p} failed`,P)}w.page(t.pageType?{type:t.pageType}:{});let L=qn(w,t.autocapture),h=w.page;w.page=(...p)=>{let _=h(...p);return L(),L=qn(w,t.autocapture),_};let x=typeof window<"u"?window:null;if(t.dataLayer&&x){let p=t.dataLayer.name??"dataLayer";x[p]=x[p]||[],tn(w,{...b,dataLayer:x[p],ignore:[...b?.ignore??[],...t.dataLayer.ignore??[]],onError:_=>t.debug&&console.warn("[hp] dataLayer mapping failed",_)})}return A&&w.identify(A),w}catch(r){return console.warn("[hp] not started:",r?.message??r),$e(n)}}function Gn(e){e.initialized=!0,Kn(e._config,e._options).then(t=>{let n=e.splice(0);if(!t){for(let r of e.methods??[])e[r]=()=>e;return}e.client=t;for(let[r,o]of Object.entries(t))typeof o=="function"&&(e[r]=o);for(let[r,...o]of n)try{t[r]?.(...o)}catch(s){console.warn(`[hp] queued ${r} failed`,s)}})}var U=window.hp=window.hp||[];U.servingHeaders??(U.servingHeaders=()=>({}));U.inHoldout??(U.inHoldout=()=>!0);U.personalisationGroup??(U.personalisationGroup=()=>"excluded");U.recommendationContext??(U.recommendationContext=()=>({}));U.initialized||(U._config?Gn(U):U.load=(e,t)=>{U._config=e,U._options=t??{},Gn(U)});})();
1
+ (()=>{var $t=e=>{throw TypeError(e)};var Sr=(e,t,n)=>t.has(e)||$t("Cannot "+n);var Ut=(e,t,n)=>t.has(e)?$t("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n);var N=(e,t,n)=>(Sr(e,t,"access private method"),n);var we=[];for(let e=2;we.length<64;e++)we.every(t=>e%t!==0)&&we.push(e);var Vt=e=>(e-Math.floor(e))*2**32>>>0,wr=we.slice(0,8).map(e=>Vt(Math.sqrt(e))),_r=we.map(e=>Vt(Math.cbrt(e))),z=(e,t)=>e>>>t|e<<32-t;function Bt(e){let t=new TextEncoder().encode(String(e)),n=new Uint32Array((t.length+8>>6)*16+16);t.forEach((i,s)=>{n[s>>2]|=i<<24-s%4*8}),n[t.length>>2]|=128<<24-t.length%4*8,n[n.length-2]=Math.floor(t.length/2**29),n[n.length-1]=t.length*8;let r=Uint32Array.from(wr),o=new Uint32Array(64);for(let i=0;i<n.length;i+=16){for(let S=0;S<64;S++){if(S<16){o[S]=n[i+S];continue}let b=o[S-15],I=o[S-2],k=z(b,7)^z(b,18)^b>>>3,h=z(I,17)^z(I,19)^I>>>10;o[S]=o[S-16]+k+o[S-7]+h}let[s,a,u,d,p,f,y,x]=r;for(let S=0;S<64;S++){let b=z(p,6)^z(p,11)^z(p,25),I=x+b+(p&f^~p&y)+_r[S]+o[S]|0,h=(z(s,2)^z(s,13)^z(s,22))+(s&a^s&u^a&u)|0;[x,y,f,p,d,u,a,s]=[y,f,p,d+I|0,u,a,s,I+h|0]}[s,a,u,d,p,f,y,x].forEach((S,b)=>{r[b]+=S})}return Array.from(r,i=>i.toString(16).padStart(8,"0")).join("")}var Ye=(e,t)=>e<<t|e>>>32-t;function jt(e){let t=new Uint32Array((e.length+8>>6)*16+16);e.forEach((i,s)=>{t[s>>2]|=i<<24-s%4*8}),t[e.length>>2]|=128<<24-e.length%4*8,t[t.length-2]=Math.floor(e.length/2**29),t[t.length-1]=e.length*8;let n=Uint32Array.of(1732584193,4023233417,2562383102,271733878,3285377520),r=new Uint32Array(80);for(let i=0;i<t.length;i+=16){for(let f=0;f<80;f++)r[f]=f<16?t[i+f]:Ye(r[f-3]^r[f-8]^r[f-14]^r[f-16],1);let[s,a,u,d,p]=n;for(let f=0;f<80;f++){let y,x;f<20?(y=a&u|~a&d,x=1518500249):f<40?(y=a^u^d,x=1859775393):f<60?(y=a&u|a&d|u&d,x=2400959708):(y=a^u^d,x=3395469782);let S=Ye(s,5)+y+p+x+r[f]|0;[p,d,u,a,s]=[d,u,Ye(a,30),s,S]}[s,a,u,d,p].forEach((f,y)=>{n[y]+=f})}let o=new Uint8Array(20);return n.forEach((i,s)=>{o[s*4]=i>>>24,o[s*4+1]=i>>>16,o[s*4+2]=i>>>8,o[s*4+3]=i}),o}var br="e28e8ada-5b76-4209-bba9-79b823a0af75",xr=e=>Array.from(e,t=>t.toString(16).padStart(2,"0")).join("");function qt(e,t){let n=Uint8Array.from(e.replace(/-/g,"").match(/../g),a=>Number.parseInt(a,16)),r=new TextEncoder().encode(t),o=new Uint8Array(16+r.length);o.set(n),o.set(r,16);let i=jt(o).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=xr(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}var re=(e,t)=>typeof e=="string"&&e!==""&&e.length<=t?e:null;function ke(e,t){return re(e,64)??re(t,256)}function Ft({sessionId:e,slot:t,arm:n}={}){let r=re(e,256);return!r||!re(t,256)||!re(n,256)?null:qt(br,`${r}:${t}:${n}`)}var Ir="4b1f2c7e-9a3d-4e58-b6c1-2d7f0a9e8c53";function Ht({sessionId:e,surface:t}={}){let n=re(e,256);return!n||!re(t,64)?null:qt(Ir,`${n}:${t}`)}var Ar=Array.from({length:11},(e,t)=>t/10);function vr(e,t){if(!e.isIntersecting)return!1;let{intersectionRect:n,boundingClientRect:r,rootBounds:o}=e;if(!n||!r)return!0;let i=n.width*n.height,s=r.width*r.height,a=o?Math.min(s,o.width*o.height):s;return a>0&&i/a>=t}function X(e){let{selector:t,onViewable:n,visibleRatio:r=.5,dwellMs:o=1e3,root:i=document}=e,s=new Map,a=new WeakSet,u=new Set,d=h=>{s.has(h)||s.set(h,setTimeout(()=>{s.delete(h),n(h)&&(f?.unobserve(h),u.delete(h))},o))},p=h=>{clearTimeout(s.get(h)),s.delete(h)},f=typeof IntersectionObserver>"u"?null:new IntersectionObserver(h=>{for(let v of h){let w=v.target;if(!vr(v,r)){u.delete(w),p(w);continue}u.add(w),y()&&d(w)}},{threshold:Ar}),y=()=>typeof document>"u"||document.visibilityState!=="hidden",x=()=>{if(y())for(let h of u)d(h);else for(let h of u)p(h)};document.addEventListener("visibilitychange",x);let S=()=>{for(let h of i.querySelectorAll(t))a.has(h)||(a.add(h),f?.observe(h))},b=typeof MutationObserver>"u"?null:new MutationObserver(()=>S()),I=()=>{S(),b?.observe(i===document?document.body:i,{childList:!0,subtree:!0})},k=i===document&&!document.body;return k?document.addEventListener("DOMContentLoaded",I,{once:!0}):I(),()=>{k&&document.removeEventListener("DOMContentLoaded",I),document.removeEventListener("visibilitychange",x),f?.disconnect(),b?.disconnect();for(let h of s.values())clearTimeout(h);s.clear(),u.clear()}}function Xe(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-exposure]",visibleRatio:r=.5,dwellMs:o=1e3,root:i=document}=t;return X({selector:n,root:i,visibleRatio:r,dwellMs:o,onViewable(s){let a=s.dataset?.hpExposure?.trim();return a&&e.surfaceViewed({surface:a}),!0}})}var Kt=e=>{try{return new URL(e,document.baseURI).toString()}catch{return e}};function Ze(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-list]",tileSelector:r="[data-hp-product]",visibleRatio:o=.5,dwellMs:i=1e3,root:s=document}=t,a=new Set,u=S=>S.closest?.(n)??null,d=S=>{let b=S.dataset.hpList?.trim();return b?{list_id:b,category:S.dataset.hpListCategory?.trim()||null}:null},p=S=>Array.from(S.querySelectorAll(r)).filter(b=>u(b)===S),f=(S,b)=>{try{let I=JSON.parse(S.dataset.hpProduct??"");return!I||typeof I!="object"||!I.product_id?null:{...I,position:I.position??b+1,...I.url?{url:Kt(I.url)}:{},...I.image_url?{image_url:Kt(I.image_url)}:{}}}catch{return null}},y=X({selector:`${n} ${r}`,root:s,visibleRatio:o,dwellMs:i,onViewable(S){let b=u(S);if(!b||b.dataset.hpListView==="manual")return!0;let I=d(b);if(!I||a.has(I.list_id))return!0;let k=new Set,h=p(b).map(f).filter(v=>!v||k.has(v.product_id)?!1:(k.add(v.product_id),!0));return h.length===0||(a.add(I.list_id),e.productListViewed({...I,products:h})),!0}}),x=S=>{let I=S.target?.closest?.("a[href]")?.closest(r);if(!I)return;let k=u(I),h=f(I,k?p(k).indexOf(I):0);h&&e.productClicked({list_id:k?d(k)?.list_id??null:null,products:[h]})};return document.addEventListener("click",x,!0),()=>{document.removeEventListener("click",x,!0),y()}}function T(e,...t){let n=e.dataset??{};for(let r of t){let o=n[r];if(typeof o=="string"&&o.trim()!=="")return o.trim()}return null}function Ce(e,...t){let n=T(e,...t);if(n===null)return null;let r=Number(n);return Number.isFinite(r)?Math.trunc(r):null}function Er(e,t){let n=T(e,"hpPromotion");return n?{promotion_id:n,name:T(e,"hpPromotionName"),creative:T(e,"hpPromotionCreative"),position:T(e,"hpPromotionSlot")??String(t+1)}:null}function Qe(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-promotion]",resolve:r=Er,visibleRatio:o=.5,dwellMs:i=1e3,root:s=document}=t,a=new Set,u=f=>{let y=Array.from(s.querySelectorAll(n)),x=y.indexOf(f);try{return r(f,x<0?y.length:x)}catch{return null}},d=X({selector:n,root:s,visibleRatio:o,dwellMs:i,onViewable(f){let y=u(f);return!y||a.has(y.promotion_id)?!1:(a.add(y.promotion_id),e.promotionViewed(y),!0)}}),p=f=>{let y=f.target;if(!y||typeof y.closest!="function")return;let x=y.closest(n),S=y.closest("a[href]");if(!x||!S||!x.contains(S)&&!S.contains(x))return;let b=u(x);b&&e.promotionClicked({...b,href:S.getAttribute("href")})};return document.addEventListener("click",p,!0),()=>{document.removeEventListener("click",p,!0),d()}}function kr(e){let t=T(e,"hpRecoRequest"),n=T(e,"hpRecoPlacement"),r=T(e,"hpRecoStrategy");if(!t||!n||!r)return null;let o=T(e,"hpRecoHoldout");return{recommendation_request_id:t,placement:n,strategy:r,recipe:T(e,"hpRecoRecipe"),algorithm_version:T(e,"hpRecoAlgorithmVersion"),experiment:T(e,"hpRecoExperiment"),variant:T(e,"hpRecoVariant"),holdout:o===null?null:o==="true",assignment_bucket:Ce(e,"hpRecoBucket"),assignment_unit_kind:T(e,"hpRecoUnitKind"),candidate_set_fingerprint:T(e,"hpRecoFingerprint"),candidate_set_size:Ce(e,"hpRecoCandidates"),ranked_by:T(e,"hpRecoRankedBy"),served_at:T(e,"hpRecoServedAt")}}function Cr(e,t){let n=T(e,"hpRecoProduct");if(!n)return null;let r=T(e,"hpRecoPrice");return{product_id:n,sku:T(e,"hpRecoSku"),name:T(e,"hpRecoName"),brand:T(e,"hpRecoBrand"),price:r===null||Number.isNaN(Number(r))?null:Number(r),position:Ce(e,"hpRecoPosition")??t+1}}function et(e,t={}){if(typeof window>"u"||typeof document>"u")return()=>{};let{selector:n="[data-hp-reco-request]",tileSelector:r="[data-hp-reco-product]",resolveRail:o=kr,resolveTile:i=Cr,visibleRatio:s=.5,dwellMs:a=1e3,root:u=document}=t,d=new Set,p=new Map,f=new Map,y=(h,...v)=>{try{return h(...v)}catch{return null}},x=h=>typeof h.closest=="function"?h.closest(n):null,S=h=>Array.from(h.querySelectorAll(r)),b=(h,v)=>{if(f.delete(v.recommendation_request_id),d.has(v.recommendation_request_id))return;let w=S(h).map((_,P)=>y(i,_,P)).filter(_=>_?.product_id);if(w.length===0)return;d.add(v.recommendation_request_id);let g=[...p.get(v.recommendation_request_id)?.values()??[]].sort((_,P)=>_.position-P.position);e.recommendationsViewed({...v,products:w,viewable:g})},I=X({selector:`${n} ${r}`,root:u,visibleRatio:s,dwellMs:a,onViewable(h){let v=x(h);if(!v)return!0;let w=y(o,v);if(!w)return!0;let g=w.recommendation_request_id,_=y(i,h,S(v).indexOf(h));if(_?.product_id){p.has(g)||p.set(g,new Map);let P=p.get(g);P.has(_.position)||P.set(_.position,{position:_.position,product_id:_.product_id,viewable_at:new Date().toISOString()})}return!d.has(g)&&!f.has(g)&&f.set(g,setTimeout(()=>b(v,w),0)),!0}}),k=h=>{let v=h.target;if(!v||typeof v.closest!="function")return;let w=v.closest(r);if(!w)return;let g=v.closest("[data-hp-reco-interaction]"),_=v.closest("a[href]"),P=_&&(w.contains(_)||_.contains(w));if(!(g&&w.contains(g))&&!P)return;let M=x(w);if(!M)return;let H=y(o,M);if(!H)return;let K=y(i,w,S(M).indexOf(w));if(!K?.product_id)return;let j=H.recommendation_request_id;d.has(j)||(clearTimeout(f.get(j)),b(M,H)),e.productClicked({recommendation_request_id:H.recommendation_request_id,interaction:T(g??w,"hpRecoInteraction")??"navigate",products:[K]})};return document.addEventListener("click",k,!0),()=>{document.removeEventListener("click",k,!0);for(let h of f.values())clearTimeout(h);f.clear(),I()}}var fe=new Set(["home","list","product","search","basket","checkout","order_confirmation","login","register","account","info","blog","other"]),Pr=new Set(["products"]),Gt=e=>e==null;function tt(e,t=new WeakSet){if(e instanceof Date)return e.toJSON();if(e===null||typeof e!="object"||t.has(e))return e;t.add(e);let n=Array.isArray(e)?e.map(r=>tt(r,t)):Object.fromEntries(Object.entries(e).filter(([,r])=>!Gt(r)).map(([r,o])=>[r,tt(o,t)]));return t.delete(e),n}function nt(e){if(!e)return e;let t=tt(e);for(let n of Pr)n in e&&Gt(e[n])&&(t[n]=e[n]);return t}function zt(){try{let e=performance.getEntriesByType("navigation")[0];return e?["navigate","reload","back_forward","prerender"].includes(e.type)?e.type:"navigate":null}catch{return null}}var Or=new Set(["","unknown","undefined","null","none","nil","nan","anonymous","guest","0","-1"]);function q(e){if(e==null)return null;let t=String(e).trim();return Or.has(t.toLowerCase())?null:t}function Z(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}var Wt="1.12";function D(e){if(typeof document>"u")return null;try{let t=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith(`${e}=`));return t&&decodeURIComponent(t.slice(e.length+1))||null}catch{return null}}var Lr={gclid:"gclid",fbclid:"fbclid",ttclid:"ttclid"},Nr=/[a-z0-9._%+-]+@[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,}/i,Tr=/\d(?:[ -]?\d){12,}/,Rr=new Set(["gclid","fbclid","ttclid","msclkid"]);function Yt(e,t=""){if(typeof e!="string"||e==="")return!1;let n=[e];try{let o=decodeURIComponent(e.replace(/\+/g," "));o!==e&&n.push(o)}catch{}let r=!Rr.has(String(t).toLowerCase());return n.some(o=>Nr.test(o)||r&&Tr.test(o))}function Mr(e){if(!e)return null;let t=new URLSearchParams(e),n={},r={utm_source:"source",utm_medium:"medium",utm_campaign:"name",utm_term:"term",utm_content:"content"};for(let[o,i]of[...Object.entries(r),...Object.entries(Lr)]){let s=t.get(o);s&&!Yt(s,o)&&(n[i]=s)}return Object.keys(n).length?n:null}var Dr=["email","e-mail","password","pass","pwd","token","auth","code","uid","customer_id","postcode","zip","phone","applyCode"],$r=["email","password","passwd","pwd","token","secret","auth","session","phone","postcode","zip","address","birth","card","cvv","iban","ssn","customerid","userid"],Ur=["tel","uid","dob"],Vr=["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","fbclid","ttclid","msclkid"],Br=new Set(Dr.map(e=>e.toLowerCase()));function jr(e){let t=String(e).toLowerCase();if(Br.has(t))return!0;let n=t.replace(/[-_.]/g,"");return $r.some(o=>n.includes(o))?!0:String(e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).some(o=>Ur.includes(o))}function rt(e){return(e??[]).map(t=>{try{return new RegExp(`^${t}$`,"i")}catch{return{test:n=>n.toLowerCase()===String(t).toLowerCase()}}})}function Xt(e,t={}){if(!e)return null;try{let n=new URLSearchParams(e),r=t.queryParamAllowlist?rt([...t.queryParamAllowlist,...Vr]):null,o=rt(t.queryParamBlocklist),i=rt(t.sensitiveParamAllowlist);for(let a of new Set(n.keys()))(jr(a)&&!i.some(d=>d.test(a))||n.getAll(a).some(d=>Yt(d,a))||(r?!r.some(d=>d.test(a)):o.some(d=>d.test(a))))&&n.delete(a);let s=n.toString();return s?`?${s}`:""}catch{return""}}function qr(e,t,n={}){if(!e)return null;try{let r=new URL(e);return t&&r.origin===t?r.origin+r.pathname+(Xt(r.search,n)??""):r.origin+r.pathname}catch{return null}}function ot(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();return/^[A-Z]{3}$/.test(t)?t:null}function Jt(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();return/^[A-Z]{2}$/.test(t)?t:null}function Fr(e){if(typeof e!="string")return null;let t=e.trim().replace(/_/g,"-");if(!/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(t))return null;try{return Intl.getCanonicalLocales(t)[0]}catch{return null}}function R(e,t){if(typeof e=="function")try{let n=e();if(n!=null)return n}catch{}return t}function Hr(e){return{property_id:String(e.propertyId),channel:e.channel??null,market:e.market??null,environment:e.environment??null}}function Kr(e){let t=typeof window<"u"?window.location:null,n=t?Xt(t.search,e):null;return{url:t?t.origin+t.pathname+(n??""):e.pageUrl??null,path:t?t.pathname:e.pagePath??null,search:n??null,referrer:typeof document<"u"?qr(document.referrer,t?.origin,e):null,title:typeof document<"u"&&document.title||null,type:e.pageType??null}}function Zt(e,t={}){let n=typeof window<"u"?window.location:null,r={library:{name:e.libraryName,version:e.libraryVersion},spec:{version:Wt},source:Hr(e),session_id:R(e.getSessionId,null),render_id:R(e.getRenderId,null),identity_trust:q(R(e.getAnonymousId,null))?"device":"none",page:Kr(e),campaign:n?Mr(n.search):null,device:{user_agent:typeof navigator<"u"?navigator.userAgent:null,type:null,viewport_width:typeof window<"u"?window.innerWidth:null,viewport_height:typeof window<"u"?window.innerHeight:null},currency:ot(R(e.getCurrency,e.currency)),locale:Fr(R(e.getLocale,e.locale)),timezone:(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}})(),country:Jt(e.country),ship_to_country:Jt(R(e.getShipToCountry,e.shipToCountry)),ip:null,bot:null,consent:e.getConsent?.()??null,experiments:R(e.getExperiments,null),audiences:R(e.getAudiences,null),decisions:R(e.getDecisions,null),recommendations:R(e.getRecommendations,null),extensions:R(e.getExtensions,null)};return Qt(r,t)}function Qt(e,t){if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t))o&&typeof o=="object"&&!Array.isArray(o)&&e[r]&&typeof e[r]=="object"&&!Array.isArray(e[r])?n[r]=Qt(e[r],o):o!==void 0&&(n[r]=o);return n}var ie=Object.freeze({consent:"thg_hp_consent",retry:"thg_hp_retry",sessionSignals:"thg_hp_session_signals",identified:"thg_hp_identified",previousPage:"thg_hp_prev_page",decisions:"thg_hp_decisions",settings:"thg_hp_settings",held:"thg_hp_held",carried:"thg_hp_carried",recommendationContext:"thg_hp_recommendation_context",anonymousId:"thg_hp_anonymous_id",session:"thg_hp_session",preview:"thg_hp_preview",debug:"thg_hp_debug"}),Gr={retry:"cdp.retry",sessionSignals:"cdp_session_signals",identified:"cdp_identified",previousPage:"cdp_prev_page_message_id"},st={...ie},en=!1;function Pe(e){let t={...ie};for(let[n,r]of Object.entries(e??{})){if(!(n in ie))throw new Error(`storageNames: unknown kind "${n}"`);if(typeof r!="string"||!/^[\w.-]+$/.test(r))throw new Error(`storageNames.${n} must be a non-empty cookie-safe name`);t[n]=r}st=t}function L(e){return st[e]}var zr="_",tn=e=>e==null||e===""?zr:String(e);function F(e,t,n){let r=`${e}:${tn(t)}`;return n==null||n===""?r:`${r}:${n}`}function nn(e,t){return`${e}:${tn(t)}:`}function Oe(){if(!en){en=!0;for(let e of[()=>localStorage,()=>sessionStorage]){let t;try{if(t=e(),!t)continue;for(let n of Object.keys(t))for(let[r,o]of Object.entries(Gr)){if(n!==o&&!n.startsWith(`${o}:`))continue;let i=st[r]+n.slice(o.length);t.getItem(i)===null&&t.setItem(i,t.getItem(n)),t.removeItem(n)}}catch{}}}}var at=1800*1e3,Le=()=>{try{return typeof sessionStorage>"u"?null:sessionStorage}catch{return null}},it=()=>{try{return typeof localStorage>"u"?null:localStorage}catch{return null}};function rn(e,t=()=>Date.now()){return{read(){try{let n=Le()?.getItem(e),r=n?JSON.parse(n):null;return!r||t()-r.savedAt>at?(r&&Le()?.removeItem(e),{items:[],anonymousId:null}):{items:Array.isArray(r.items)?r.items:[],anonymousId:typeof r.anonymousId=="string"?r.anonymousId:null}}catch{return{items:[],anonymousId:null}}},write(n,r=null){try{n.length===0?Le()?.removeItem(e):Le()?.setItem(e,JSON.stringify({savedAt:t(),items:n,anonymousId:r}))}catch{}}}}var Wr=400*24*60*60;function Q(e,t,n,r){if(typeof document>"u")return!1;try{let o=typeof location<"u"&&location.protocol==="https:"?"; Secure":"",i=r?`; Domain=${r}`:"",s=n===null?"":`; Max-Age=${n}`;return document.cookie=`${e}=${encodeURIComponent(t)}; Path=/${s}; SameSite=Lax`+i+o,!0}catch{return!1}}function Jr({name:e,domain:t=null,legacyKey:n,read:r,mint:o,mayStore:i,carried:s=null}){let a=null;try{a=it()?.getItem(n)||null}catch{a=null}let u=r(e)??a??s,d=!1,p=()=>{if(!(d||u===null||!i())&&(d=Q(e,u,Wr,t),!(!d||a===null)))try{it()?.removeItem(n),a=null}catch{}};return{get(){return u??(u=o()),p(),u},peek:()=>u,persist:p,forget(){Q(e,"",0,t),u=null,d=!1;try{it()?.removeItem(n)}catch{}a=null}}}function on(e,{carried:t=null,mayStore:n,orOwn:r=!1}){let o=e.anonymousIdSource,i=()=>Jr({name:L("anonymousId"),domain:e.consentCookieDomain??null,legacyKey:F(L("anonymousId"),e.propertyId),read:D,mint:Z,mayStore:n,carried:t});if(o?.source==="hp_cookie"){let u=i();return e.getAnonymousId=()=>u.get(),u}if(o?.source==="site_cookie"&&o.cookie){let u=o.cookie;e.getAnonymousId=()=>D(u)}if(!r)return null;let s=e.getAnonymousId,a=i();return e.getAnonymousId=()=>q(R(s,null))??a.get(),a}var Yr=200;function sn(e,t,n=()=>Date.now()){let r=()=>F(L("carried"),e),o=!1;function i(){try{let s=JSON.parse(sessionStorage.getItem(r())??"null");return!s||!(n()-s.savedAt<=at)?[]:Array.isArray(s.calls)?s.calls:[]}catch{return[]}}return{take(){let s=i();try{sessionStorage.removeItem(r())}catch{}return s},save(s){try{return o||!t()?!1:(sessionStorage.setItem(r(),JSON.stringify({savedAt:n(),calls:[...i(),...s].slice(-Yr)})),!0)}catch{return!1}},close(){o=!0}}}var si=ie.consent,Ne=Object.freeze({visitor:"visitor",host:"host"}),an=()=>({basis:Ne.host}),Xr="hp-consent",ae=["analytics","marketing","personalisation","ad_user_data","ad_personalization"],cn={analytics:"a",marketing:"m",personalisation:"p",ad_user_data:"aud",ad_personalization:"adp"},Y=()=>typeof window<"u",un=()=>Y()&&typeof window.cookieStore?.addEventListener=="function",Zr=e=>e===!0?!0:e===!1?!1:null;function pe(e){if(!e||typeof e!="object")return null;let t={};for(let n of ae)t[n]=Zr(e[n]);return t}function ut(e,t){return!e||!t?e===t:ae.every(n=>e[n]===t[n])}function lt(e){if(!e)return"";let t=[];for(let n of ae){let r=e[n];(r===!0||r===!1)&&t.push(`${cn[n]}=${r?1:0}`)}return t.join("&")}function ln(e){return{[Xr]:lt(pe(e))}}function _e(e){let t=pe({});if(e==null)return t;let n=String(e).trim();if(n.length>=2&&n.startsWith('"')&&n.endsWith('"')&&(n=n.slice(1,-1)),n.includes("%"))try{n=decodeURIComponent(n.replace(/\+/g," "))}catch{return t}let r=Object.fromEntries(Object.entries(cn).map(([i,s])=>[s,i])),o=new Set;for(let i of n.split("&")){let s=i.indexOf("=");if(s<=0)continue;let a=r[i.slice(0,s).trim()],u={1:!0,0:!1}[i.slice(s+1).trim()]??null;!a||u===null||o.has(a)||(t[a]===null?t[a]=u:t[a]!==u&&(t[a]=null,o.add(a)))}return t}function dt(e,t){if(!t)return e;let n=r=>{if(!r)return r;let o={...r};for(let i of ae)i!=="analytics"&&t[i]!==!0&&(o[i]=null);return o};return{name:e.name,basis:e.basis,read:()=>n(e.read()),subscribe:r=>e.subscribe(o=>r(n(o))),get observesChanges(){return e.observesChanges}}}function ft(e,t={}){return{...e,ad_user_data:t.ad_user_data??e.marketing,ad_personalization:t.ad_personalization??e.marketing}}function Te(e,t){let n=!0;return{notify:()=>{if(n)try{let o=e();o&&t(o)}catch{}},stop:()=>n=!1}}var Qr={analytics:["analytics","measure_content_performance","audience_measurement"],marketing:["marketing","targeting","advertising","select_personalized_ads","create_ads_profile"],personalisation:["personalisation","personalization","select_personalized_content","create_content_profile"]};function eo(e,t){if(!t?.length)return null;let n=!1;for(let[r,o]of Object.entries(e)){let i=String(o?.id??r).toLowerCase();if(t.some(a=>{let u=String(a).toLowerCase();return i===u||i.startsWith(`${u}-`)})&&(n=!0,o?.enabled===!0))return!0}return n?!1:null}function dn(e={}){let t={...Qr,...e.purposes};function n(){let r=Y()?window.Didomi:void 0;if(!r?.getCurrentUserStatus||r.shouldUserStatusBeCollected?.()!==!1||r.isUserStatusPartial?.()===!0)return null;let o=r.getCurrentUserStatus()?.purposes;if(!o||typeof o!="object")return null;let i=s=>eo(o,t[s]);return ft({analytics:i("analytics"),marketing:i("marketing"),personalisation:i("personalisation")},{ad_user_data:i("ad_user_data"),ad_personalization:i("ad_personalization")})}return{name:"didomi",read:n,observesChanges:!0,subscribe(r){if(!Y())return()=>{};let o=Te(n,r),i={event:"consent.changed",listener:o.notify};return window.didomiEventListeners=window.didomiEventListeners||[],window.didomiEventListeners.push(i),window.didomiOnReady=window.didomiOnReady||[],window.didomiOnReady.push(s=>{o.notify(),(s??window.Didomi)?.on?.("consent.changed",o.notify)}),window.Didomi?.on?.("consent.changed",o.notify),o.stop}}}function ct(e){let t={};if(!e)return t;for(let n of String(e).split("&")){let r=n.indexOf("=");if(r<=0)continue;let o=n.slice(r+1).replace(/\+/g," ");try{o=decodeURIComponent(o)}catch{}t[n.slice(0,r)]=o}return t}function fn(e={}){let t={analytics:"C0002",personalisation:"C0003",marketing:"C0004",...e.groups},n=e.impliedConsent===!0;function r(){let s=Y()?window.OnetrustActiveGroups:void 0;if(typeof s=="string"&&s.length){let d=new Set(s.split(",").map(p=>p.trim()).filter(Boolean));return p=>d.has(p)}let a=ct(D("OptanonConsent"));if(!a.groups)return null;let u={};for(let d of a.groups.split(",")){let[p,f]=d.split(":");p?.trim()&&(u[p.trim()]=f==="1"?!0:f==="0"?!1:null)}return d=>u[d]??null}function o(){if(D("OptanonAlertBoxClosed"))return!0;try{if(Y()&&window.OneTrust?.IsAlertBoxClosed?.()===!0)return!0}catch{}return Number.parseInt(ct(D("OptanonConsent")).interactionCount,10)>0?!0:n&&Y()&&(!!window.OneTrust||typeof window.OnetrustActiveGroups=="string")}function i(){if(!o())return null;let s=r();if(!s)return null;let a=f=>t[f]?s(t[f]):null,u=ft({analytics:a("analytics"),marketing:a("marketing"),personalisation:a("personalisation")},{ad_user_data:a("ad_user_data"),ad_personalization:a("ad_personalization")}),d=ct(D("OptanonConsent"));return(typeof navigator<"u"&&navigator.globalPrivacyControl===!0||d.isGpcEnabled==="1")&&(u.marketing=!1,u.ad_user_data=!1,u.ad_personalization=!1),u}return{name:"onetrust",read:i,observesChanges:!0,subscribe(s){if(!Y())return()=>{};let a=Te(i,s),u=!1,d=()=>{u||!window.OneTrust?.OnConsentChanged||(u=!0,window.OneTrust.OnConsentChanged(a.notify))};window.addEventListener("OneTrustGroupsUpdated",a.notify);let p=window.OptanonWrapper;return window.OptanonWrapper=function(...y){try{typeof p=="function"&&p.apply(this,y)}finally{d(),a.notify()}},d(),()=>{a.stop(),window.removeEventListener("OneTrustGroupsUpdated",a.notify)}}}}function to(e){let t=String(e).split(",").map(n=>n.trim()).filter(Boolean);return t.length?new Set(t):null}function pn(e){let{name:t,categories:n,parse:r=to,refusedValue:o,source:i="native",changeEvent:s="thg_hp_consent_change"}=e??{};if(typeof t!="string"||t==="")throw new Error("cookieConsent: `name` (the cookie your banner writes) is required");if(!n||typeof n.analytics!="string")throw new Error("cookieConsent: `categories.analytics` (the category id that grants analytics) is required");function a(){let u=D(t);if(u==null)return null;let d;if(o!==void 0&&u===o)d=new Set;else try{d=r(u)}catch{d=null}if(!(d instanceof Set))return null;let p=f=>n[f]?d.has(n[f]):null;return ft({analytics:p("analytics"),marketing:p("marketing"),personalisation:p("personalisation")},{ad_user_data:p("ad_user_data"),ad_personalization:p("ad_personalization")})}return{name:i,read:a,get observesChanges(){return un()},subscribe(u){if(!Y())return()=>{};let d=Te(a,u),p=f=>{[...f.changed??[],...f.deleted??[]].some(x=>x?.name===t)&&d.notify()};return window.addEventListener(s,d.notify),window.cookieStore?.addEventListener?.("change",p),()=>{d.stop(),window.removeEventListener(s,d.notify),window.cookieStore?.removeEventListener?.("change",p)}}}}function mn(e={}){let t=e.name??L("consent"),n=()=>{let r=D(t);if(r==null)return null;let o=_e(r);return o.analytics==null?null:o};return{name:"forwarded",read:n,get observesChanges(){return un()},subscribe(r){if(!Y())return()=>{};let o=Te(n,r),i=s=>{[...s.changed??[],...s.deleted??[]].some(u=>u?.name===t)&&o.notify()};return window.cookieStore?.addEventListener?.("change",i),()=>{o.stop(),window.cookieStore?.removeEventListener?.("change",i)}}}}function hn(e){let t=pe(e);return{name:"static",basis:Ne.host,read:()=>t?{...t}:null,observesChanges:!0,subscribe:()=>()=>{}}}function gn(e){if(e==null)return null;let t=String(e).split("/").map(n=>n.trim()).filter(Boolean).join("/");return t===""?null:t}function no(e){let t=e.item_category;if(t!=null&&String(t).includes("/"))return gn(t);let n=[t,e.item_category2,e.item_category3,e.item_category4,e.item_category5].map(r=>r==null?"":String(r).trim()).filter(Boolean);return gn(n.join("/"))}var ro=e=>{if(e==null||typeof e=="object")return null;let t=String(e).trim();return t===""?null:t};function oo(...e){for(let t of e){if(typeof t=="number"&&Number.isFinite(t))return String(t);if(typeof t=="string"&&t.trim()!=="")return t.trim()}return null}var Re=e=>oo(e.item_group_id,e.item_id);function so(e,t=Re){if(!e)return null;let n=a=>a==null||a===""||Number.isNaN(Number(a))?null:Number(a),r=a=>{let u=n(a);return u==null?null:Math.round(u*1e6)/1e6},o=a=>{let u=r(a);return u!=null&&u>=0?u:null},i=a=>{let u=n(a);return Number.isInteger(u)&&u>=0?u:null},s=ro;return{product_id:s(t(e)),sku:s(e.item_id),name:s(e.item_name),brand:s(e.item_brand),variant:s(e.item_variant)??s(e.variant),category:no(e),price:r(e.price),discount:o(e.discount),quantity:i(e.quantity),coupon:s(e.coupon),position:i(e.index)!=null?i(e.index)+1:null,url:s(e.url)??s(e.item_url)??null,image_url:s(e.image_url)??s(e.image_link)??null,displayed_sku:s(e.displayed_sku)??s(e.displayed_variant_sku)}}function pt(e,t=Re){return(e??[]).map(n=>so(n,t)).filter(n=>n?.product_id)}var io=1e3,ao={shipping:2,payment:3},co=new Set(["password","google","apple","facebook","magic_link","sso","passkey","other"]),$=e=>{if(e==null||typeof e=="object")return null;let t=String(e).trim();return t===""?null:t},uo=e=>{if(e==null||e===""||typeof e=="object")return null;let t=Number(e);return Number.isFinite(t)&&t>=0?t:null},Me=e=>e!==null&&typeof e=="object";function lo(e){return Array.isArray(e.items)?e.items.filter(Me):null}function yn(e){let t=$(e)?.toLowerCase().replace(/[\s-]+/g,"_");return t?co.has(t)?t:t==="email"||t==="email_password"?"password":"other":null}function fo({ecommerce:e,items:t}){let n=i=>({promotion_id:$(i.promotion_id),name:$(i.promotion_name),creative:$(i.creative_name),position:$(i.creative_slot)}),r=new Set,o=[];for(let i of[n(e),...t.map(n)])!i.promotion_id||r.has(i.promotion_id)||(r.add(i.promotion_id),o.push(i));return o}var Sn=({ecommerce:e,items:t})=>$(e.item_list_id)??$(e.item_list_name)??$(t[0]?.item_list_id)??$(t[0]?.item_list_name),ce=(e,t)=>t.products?.length?{event:e,properties:t}:null,po=new Set(["product","products","item","items"]);function mo({ecommerce:e}){let t=$(e.item_id),n=$(e.content_type)?.toLowerCase();return!t||n&&!po.has(n)?null:{event:"Product Shared",properties:{share_via:$(e.method),products:[{product_id:t}]}}}function ho(e){let t=o=>ce("Product List Viewed",{list_id:Sn(o),products:o.products}),n=o=>{let i=$(o.ecommerce.search_term);return i?{event:"Products Searched",properties:{query:i,...o.products.length?{products:o.products}:{}}}:null},r=o=>i=>i.promotions.map(s=>({event:o,properties:s}));return{view_item:o=>ce("Product Viewed",{currency:o.currency,value:o.value,products:o.products.slice(0,1)}),view_item_list:t,view_search_results:o=>n(o)??t(o),search:n,select_item:o=>ce("Product Clicked",{list_id:Sn(o),products:o.products.slice(0,1)}),add_to_cart:o=>ce("Product Added",{cart_id:$(o.ecommerce.cart_id),products:o.products}),remove_from_cart:o=>ce("Product Removed",{cart_id:$(o.ecommerce.cart_id),products:o.products}),view_cart:o=>({event:"Cart Viewed",properties:{cart_id:$(o.ecommerce.cart_id),value:o.value,currency:o.currency,coupon:$(o.ecommerce.coupon),...o.itemsListed?{products:o.products}:{}}}),begin_checkout:o=>ce("Checkout Started",{value:o.value,currency:o.currency,coupon:$(o.ecommerce.coupon),products:o.products}),add_shipping_info:o=>({event:"Checkout Step Completed",properties:{step:e.shipping,step_name:"shipping",shipping_method:$(o.ecommerce.shipping_tier)}}),add_payment_info:o=>({event:"Payment Info Entered",properties:{step:e.payment,step_name:"payment",payment_method:$(o.ecommerce.payment_type)}}),view_promotion:r("Promotion Viewed"),select_promotion:r("Promotion Clicked"),add_to_wishlist:o=>ce("Product Added to Wishlist",{products:o.products}),share:mo,login:o=>({event:"Signed In",properties:{method:yn(o.ecommerce.method)}}),sign_up:o=>({event:"Signed Up",properties:{method:yn(o.ecommerce.method)}})}}var go=e=>e.event;function yo(e,t){if(!Me(e))return null;if(typeof e.length=="number"&&e[0]==="event"&&typeof e[1]=="string"){let r=Me(e[2])?e[2]:{};return{name:e[1],entry:r,ecommerce:r}}let n=$(t(e));return n?{name:n,entry:e,ecommerce:Me(e.ecommerce)?e.ecommerce:e}:null}function mt(e){return Array.isArray(e)?`[${e.map(mt).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${mt(e[t])}`).join(",")}}`:JSON.stringify(e??null)}function wn(e,t={}){if(!e||typeof e.track!="function")throw new Error("connectDataLayer: analytics must have a track(event, properties, options) method");let n=t.dataLayer??(typeof window<"u"?window.dataLayer=window.dataLayer||[]:null);if(!Array.isArray(n))return()=>{};let r=ho({...ao,...t.steps}),o=t.map??{},i=t.eventName??go,s=t.productId??Re,a=new Set(["purchase","refund",...t.ignore??[]]),u=t.dedupeMs??io,d=new Map,p=!0;function f(w,g,_){if(u<=0)return!1;let P=`${w}|${_??""}|${mt(g)}`,M=Date.now();for(let[H,K]of d)M-K>u&&d.delete(H);return d.has(P)?!0:(d.set(P,M),!1)}let y=null,x=new Set;function S(w,g){if(w!=="Product Viewed")return!1;let _=typeof location>"u"?"":location.pathname;_!==y&&(y=_,x.clear());let P=g.products?.[0]?.product_id;return P?x.has(P)?!0:(x.add(P),!1):!1}function b({event:w,properties:g={}},_){if(!w||f(w,g,_)||S(w,g))return;let P=_?{context:{currency:_}}:void 0;if(w==="Signed Out"&&typeof e.signedOut=="function"){e.signedOut(P);return}e.track(w,g,P)}function I(w){let g=t.transform?t.transform(w):w,_=yo(g,i);if(!_||a.has(_.name))return;let P=Object.hasOwn(o,_.name),M=P?o[_.name]:r[_.name];if(typeof M!="function")return;let H=lo(_.ecommerce),K=H??[],j={..._,items:K,itemsListed:H!==null,products:pt(K,s),currency:ot(_.ecommerce.currency),value:uo(_.ecommerce.value)};j.promotions=fo(j);let te=P?M(g,{...j,toProducts:G=>pt(G,s)}):M(j);for(let G of[te].flat())G&&b(G,j.currency)}function k(w){if(p)try{I(w)}catch(g){try{t.onError?.(g,w)}catch{}}}for(let w of n.slice())k(w);let h=n.push;function v(...w){let g=h.apply(this,w);for(let _ of w)k(_);return g}return n.push=v,()=>{p=!1,n.push===v&&(n.push=h)}}var So="hp_debug",wo=256;function _o(){try{return new URLSearchParams(location.search).get(So)}catch{return null}}function _n(e,t){if(typeof location>"u")return!1;try{let n=_o();if(n!==null){let o=n.trim();o===""||o.length>wo?sessionStorage.removeItem(t):sessionStorage.setItem(t,o)}let r=sessionStorage.getItem(t);return!!(e&&r&&Bt(r)===e)}catch{return!1}}var me=class extends Error{},bo={inHoldout:()=>!0,personalisationGroup:()=>"excluded",servingHeaders:()=>({}),recommendationContext:()=>({}),flush:()=>Promise.resolve(),reset:()=>{}};function ht(e,t){let n=bo[e]??(()=>null),r=o=>(console.warn(`[hp] ${String(e)} failed; nothing was sent`,o),n());return function(...i){try{let s=t.apply(this,i);return typeof s?.then=="function"?Promise.resolve(s).catch(r):s}catch(s){if(s instanceof me)throw s;return r(s)}}}function bn(e){for(let t of Reflect.ownKeys(e)){let{value:n}=Object.getOwnPropertyDescriptor(e,t)??{};typeof n=="function"&&(e[t]=ht(t,n))}return e}var be=Symbol("hp.identityOption");var xo=4320*60*60,Io=100,Ao=1e3,vo=2e3,xn=500,De=e=>(e?.unref?.(),e);function Eo(e,t){if(t?.analytics===!0&&e.analytics===!1)return"withdrawn";let n=ae.map(r=>e[r]).filter(r=>r!==null);return n.length&&n.every(Boolean)?"accept_all":n.length&&n.every(r=>!r)?"reject_all":"custom"}function ko(e,t,n=L("consent")){if(!(typeof document>"u"))try{let r=typeof location<"u"&&location.protocol==="https:"?"; Secure":"",o=t?`; Domain=${t}`:"";document.cookie=`${n}=${lt(e)}; Path=/; Max-Age=${xo}; SameSite=Lax`+o+r}catch{}}function Co(e){let t=_e(D(e));return ae.some(n=>t[n]!==null)?t:null}function In(e){let{adapter:t,timeoutMs:n=5e3,cookieDomain:r=null,cookieName:o=L("consent"),release:i,announce:s}=e,a=e.discard??(()=>{}),u="pending",d=null,p=null,f=null,y=null,x=!1,S=null,b=[],I=m=>{u=m,e.onStatus?.(m)};function k(){try{return pe(t.read())}catch{return null}}function h(){p&&clearInterval(p),f&&clearTimeout(f),p=null,f=null}let v=()=>typeof window<"u"&&typeof document<"u",w=()=>{try{return typeof t.subscribe=="function"&&t.observesChanges===!0}catch{return!1}};function g(){y&&clearInterval(y),y=null}function _(){x||y||d===null||w()||v()&&document.visibilityState==="hidden"||(y=De(setInterval(()=>j(k()),vo)))}let P=()=>u==="pending"||u==="unknown",M=e.store??null,H=()=>{let m=b.splice(0);M?.write([]);for(let B of m)i(B)},K=()=>{let m=b.splice(0);M?.write([]);for(let B of m)a(B)};function j(m){let B=pe(m);if(!B||B.analytics===null)return;let Ae=d===null,J=Ae?Co(o):d;if(!Ae&&ut(J,B))return;h(),d=B,_(),ko(B,r,o);let ve=!ut(J,B);if(B.analytics){I("granted"),H(),ve&&s({action:Eo(B,J),state:B,previous:J,withdrawal:!1});return}K(),J?.analytics===!0&&s({action:"withdrawn",state:B,previous:J,withdrawal:!0}),I("denied")}function te(){f=null,u==="pending"&&(I("unknown"),p&&clearInterval(p),p=De(setInterval(()=>j(k()),Ao)))}function G(m){P()&&(M||m?.type!=="visibilitychange"&&!m?.persisted&&K())}let ne=m=>{document.visibilityState==="hidden"?(g(),G(m)):_()},le=m=>{g(),G(m)},Ie=()=>_();return{get status(){return u},get state(){return d?{...d}:null},stamp(){return d?{...d,source:t.name??null,basis:t.basis??Ne.visitor}:null},admits(){return u==="granted"},hold(m){return!P()||b.length>=xn?(a(m),!1):(b.push(m),M?.write(b),!0)},onHidden:G,start(){x=!1;try{S=t.subscribe?.(m=>j(m))??null}catch(m){e.debug&&console.warn("[hp] consent adapter subscribe failed",m)}v()&&(window.addEventListener("pagehide",le),window.addEventListener("pageshow",Ie),document.addEventListener("visibilitychange",ne)),M&&b.length===0&&b.push(...M.read().slice(-xn)),j(k()),!d&&(p=De(setInterval(()=>j(k()),Io)),f=De(setTimeout(te,n)))},stop(){x=!0,h(),g(),typeof S=="function"&&S(),v()&&(window.removeEventListener("pagehide",le),window.removeEventListener("pageshow",Ie),document.removeEventListener("visibilitychange",ne))}}}var Po=["recommendation","search_rank","banner","offer","layout","copy","price","other"],$e=e=>typeof e=="string"&&e!=="";function An(e){return(Array.isArray(e?.decisions)?e.decisions:[]).filter(t=>$e(t?.slot)&&$e(t.decision_id)&&t.holdout!==!0).map(({decision_id:t,slot:n,arm:r,kind:o})=>({decision_id:t,slot:n,...$e(r)&&{arm:r},...Po.includes(o)&&{kind:o}}))}function vn({key:e,mayStore:t}){let n,r=()=>{if(n)return n;try{let i=JSON.parse(sessionStorage.getItem(e));n=Array.isArray(i)?i.filter(s=>$e(s?.slot)):[]}catch{n=[]}return n},o=()=>{try{n?.length&&t()&&sessionStorage.setItem(e,JSON.stringify(n))}catch{}};return{persist:o,current:()=>r().length?n.map(i=>({...i})):null,remember(i){if(!i.length)return;let s=new Set(i.map(a=>a.slot));n=[...r().filter(a=>!s.has(a.slot)),...i],o()},forget(){n=[];try{sessionStorage.removeItem(e)}catch{}}}}function Oo(e){let t=2166136261,n=String(e);for(let r=0;r<n.length;r+=1)t^=n.charCodeAt(r),t=t+((t<<1)+(t<<4)+(t<<7)+(t<<8)+(t<<24))>>>0;return t^=t>>>16,t=Math.imul(t,2246822507)>>>0,t^=t>>>13,t=Math.imul(t,3266489909)>>>0,t^=t>>>16,t>>>0}function Ue(e,t,n=1e4){return Oo(`${t}\0${e}`)%n}function gt(e){let t=o=>Math.min(Math.max(Number(o)||0,0),1),n=t(e.share),r=1-n;return{holdout_share:n,personalised_share:e.ramp==null?r:Math.min(t(e.ramp),r)}}function yt(e,t){if(!e||typeof e.salt!="string")return{holdout:!1,bucket:null,group:"personalised"};let n=e.ramp!=null;if(t==null||t==="")return{holdout:!1,bucket:null,group:n?"excluded":"personalised"};let{holdout_share:r,personalised_share:o}=gt(e),i=Ue(t,e.salt),s=u=>Math.round(u*1e4),a=r>0&&i<s(r)?"holdout":!n||i<s(r+o)?"personalised":"excluded";return{holdout:a==="holdout",bucket:i,group:a}}function En(e,t){return typeof e!="string"||e===""||t==null||t===""?null:Ue(t,`bandit-vs-default:${e}`)<1e4/2?"default":"bandit"}var Lo="hp_preview",No=256;function kn(e,t=null){if(typeof location>"u")return D(e);let n=null;try{n=new URLSearchParams(location.search).get(Lo)}catch{n=null}if(n===null)return D(e);let r=n.trim();return r===""||r.length>No?(Q(e,"",0,t),null):(Q(e,r,null,t),r)}var To=40,Ro=128,Mo=5,Do=60,Pn=e=>typeof e=="string"&&e!==""&&e.length<=Ro&&!e.includes(","),Cn=e=>Array.isArray(e)?e.filter(Pn).slice(0,To):[],$o=e=>Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.replaceAll(","," ").trim()).filter(t=>t!=="").slice(0,Mo):[],Uo=e=>Object.entries(e&&typeof e=="object"?e:{}).filter(([t,n])=>Pn(t)&&Number.isFinite(n)&&n>=1).sort(([,t],[,n])=>n-t).slice(0,Do).map(([t,n])=>`${t}:${Math.floor(n)}`);function St(e){let t={},n={viewed:Cn(e?.recentProducts),basket:Cn(e?.basketProducts),q:$o(e?.recentSearches),impressed:Uo(e?.impressions)};for(let[r,o]of Object.entries(n))o.length>0&&(t[r]=o.join(","));return t}var Vo=1800*1e3;function On(e,t=Date.now()){try{localStorage.setItem(L("recommendationContext"),JSON.stringify({context:e,until:t+Vo}))}catch{}}function Ln(){try{localStorage.removeItem(L("recommendationContext"))}catch{}}var Bo="hp_sample",Nn=1e4;function Tn(e,t){return!(typeof t=="number"&&t<1)||e==null||e===""?!0:Ue(e,Bo,Nn)<Math.round(t*Nn)}function wt(e){return e.trim().toLowerCase().replace(/\s*\/\s*/g,"/").replace(/^\/+|\/+$/g,"")}var jo=2,qo=12;function Fo(e,t=jo){return e.split("/").slice(0,t).join("/")}function he(e,t){if(typeof t!="string"||!t.trim())return null;let n=Fo(wt(t));return n?(e.unshift(n),e.length=Math.min(e.length,qo),n):null}var ue=()=>L("sessionSignals"),ge=null,_t=()=>ge??ue();function Rn(){try{return ge?localStorage:sessionStorage}catch{return}}function Mn(e,t){let n=t==null?null:String(t),r=e?F(ue(),n,e):null;if(r===ge)return;let o=ge===null?Ho():null;if(ge=r,!!ge)try{let i=_t(),s=nn(ue(),n);for(let a of Object.keys(localStorage))a.startsWith(s)&&a!==i&&localStorage.removeItem(a);o&&!localStorage.getItem(i)&&(localStorage.setItem(i,JSON.stringify(o)),sessionStorage.removeItem(ue()))}catch{}}function Ho(){try{let e=sessionStorage.getItem(ue());if(!e)return null;let t=JSON.parse(e);return t&&(t.productViews>0||t.listViews>0||t.basketValue!=null||t.recentProducts?.length||t.recentBrowse?.length)?t:null}catch{return null}}function Ve(){return{productViews:0,listViews:0,cartAdds:0,searches:0,recentProducts:[],recentCategories:[],recentBrowse:[],basketProducts:[],basketValue:null,recentSearches:[],impressions:{},browsingCategory:null,startedAt:0}}function bt(){let e=Rn();if(!e)return Ve();try{let t=e.getItem(_t());return t?{...Ve(),...JSON.parse(t)}:{...Ve(),startedAt:Date.now()}}catch{return{...Ve(),startedAt:Date.now()}}}function xt(e){let t=Rn();if(t)try{t.setItem(_t(),JSON.stringify(e))}catch{}}function Dn(){return bt()}function $n(){for(let e of[()=>sessionStorage,()=>localStorage])try{let t=e();t.removeItem(ue());for(let n of Object.keys(t))n.startsWith(`${ue()}:`)&&t.removeItem(n)}catch{}}var Un=20,Vn=200,Ko=new Set(["Product Viewed","Product Clicked","Product Added","Product Added to Wishlist"]),Go=new Set(["Product Viewed","Product Added"]);function Bn(e,t){let n=bt();n.startedAt||(n.startedAt=Date.now());let r=Array.isArray(t?.products)?t.products:[];switch(e){case"Product Viewed":n.productViews+=1,he(n.recentBrowse,n.browsingCategory);break;case"Product List Viewed":{let s=t?.list_id;typeof s=="string"&&s.includes("/")&&!s.startsWith("cdp-")&&(n.listViews+=1,n.browsingCategory=he(n.recentBrowse,s)??n.browsingCategory)}break;case"Product List Filtered":{let s=t?.change,a=typeof t?.list_id=="string"?t.list_id:"",u=typeof s?.value=="string"?s.value:"";u&&s?.action!=="removed"&&(n.browsingCategory=he(n.recentBrowse,`${a}/${u}`)??n.browsingCategory);break}case"Product Added":{n.cartAdds+=1,he(n.recentBrowse,n.browsingCategory);for(let s of r){let a=s.product_id;typeof a!="string"||!a||(n.basketProducts=[a,...n.basketProducts.filter(u=>u!==a)].slice(0,Un))}break}case"Product Removed":{for(let s of r){let a=s.product_id;typeof a=="string"&&a&&(n.basketProducts=n.basketProducts.filter(u=>u!==a))}break}case"Products Searched":{n.searches+=1;let s=t?.query;if(typeof s=="string"&&s.trim()){let a=s.trim().toLowerCase().slice(0,64);n.recentSearches=[a,...n.recentSearches.filter(u=>u!==a)].slice(0,5)}break}case"Product Clicked":case"Product Added to Wishlist":break;case"Cart Updated":{let s=t?.value;return n.basketValue=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:null,xt(n),n}default:return n}let o=Ko.has(e);if(o)for(let s of r)typeof s.product_id=="string"&&s.product_id&&delete n.impressions[s.product_id];else{for(let a of r){let u=a.product_id;typeof u!="string"||!u||(n.impressions[u]=(n.impressions[u]??0)+1)}let s=Object.keys(n.impressions);if(s.length>Vn){let a={};for(let u of s.sort((d,p)=>n.impressions[p]-n.impressions[d]).slice(0,Vn))a[u]=n.impressions[u];n.impressions=a}}let i=new Set;for(let s of r){let a=s.product_id;if(o&&typeof a=="string"&&a&&(n.recentProducts=[a,...n.recentProducts.filter(u=>u!==a)].slice(0,Un)),Go.has(e)&&typeof s.category=="string"&&s.category){let u=wt(s.category);u&&!i.has(u)&&(i.add(u),he(n.recentCategories,u))}}return xt(n),n}var jn=1800*1e3;function qn({name:e,domain:t=null,mayStore:n,now:r=()=>Date.now(),mint:o=Z}){let i=null,s=0,a=()=>{i!==null&&n()&&Q(e,i,jn/1e3,t)};return{get(){let u=r(),d=D(e);return d?i=d:(i===null||u-s>=jn)&&(i=o()),s=u,a(),i},persist:a,forget(){Q(e,"",0,t),i=null}}}var W=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Fn=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),At=Object.freeze({enabled:!1});function Hn(e,t){let n=e?.track;return W(n)?(Object.hasOwn(n,t)?n[t]:n.__default)?.enabled!==!1:!0}function zo(e,t){return`${ye(e)}/v1/projects/${encodeURIComponent(t)}/settings`}var Wo="https://hp.thgingenuity.com";function ye(e){return e==null||e===""?Wo:Kn(e)}function Kn(e){if(typeof e!="string")return null;let t=e.trim().replace(/\/+$/,"");return/^https?:\/\/[^/\s]+$/i.test(t)?t:/^[a-z0-9.-]+(:\d+)?$/i.test(t)?`https://${t}`:null}function Jo(e){if(!W(e))return null;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>typeof n=="boolean"));return Object.keys(t).length?t:null}var It=e=>typeof e=="number"&&e>=0&&e<=1,Yo=/^[0-9a-f]{64}$/;function Xo(e){return W(e)?{enabled:e.enabled===!0,tokenSha256:typeof e.tokenSha256=="string"&&Yo.test(e.tokenSha256)?e.tokenSha256:null}:{enabled:!1,tokenSha256:null}}function Zo(e){if(!W(e))return null;let t=Object.fromEntries(Object.entries(e).filter(([,n])=>W(n)&&It(n.share)&&(n.ramp==null||It(n.ramp))&&typeof n.salt=="string"&&n.salt!=="").map(([n,r])=>[n,{share:r.share,ramp:r.ramp??null,salt:r.salt,...Fn(r.readoutSlots)&&r.readoutSlots.length>0&&{readoutSlots:r.readoutSlots}}]));return Object.keys(t).length?t:null}var Qo=/^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;function es(e){return W(e)?e.source==="hp_cookie"?{source:"hp_cookie"}:e.source!=="site_cookie"?null:e.cookie==null?{source:"site_cookie",cookie:null}:typeof e.cookie=="string"&&Qo.test(e.cookie)?{source:"site_cookie",cookie:e.cookie}:null:null}function vt(e){let t=W(e)?e.hp:null;return!W(t)||t.enabled!==!0?At:{enabled:!0,propertyId:typeof t.propertyId=="string"&&t.propertyId!==""?t.propertyId:null,environment:typeof t.environment=="string"?t.environment:null,consentPurposes:Jo(t.consent?.purposes),queryParamAllowlist:Fn(t.queryParamAllowlist)?t.queryParamAllowlist:null,anonymousId:es(t.anonymousId),apiHost:Kn(t.apiHost),holdouts:Zo(t.holdouts),sampleRate:It(t.sampleRate)?t.sampleRate:1,debug:Xo(t.debug),plan:W(e.plan)&&W(e.plan.track)?{track:e.plan.track}:null}}async function Gn(e,t,n=globalThis.fetch){try{let r=await n(zo(e,t),{credentials:"omit",headers:{accept:"application/json"}});return r.ok?vt(await r.json()):null}catch{return null}}var Be=e=>F(L("settings"),e);function zn(e){try{let t=localStorage.getItem(Be(e));if(!t)return null;let n=JSON.parse(t);return n?.enabled===!0?n:null}catch{return null}}function Wn(e,t){try{t?.enabled===!0?localStorage.setItem(Be(e),JSON.stringify(t)):localStorage.removeItem(Be(e))}catch{}}function Et(e){try{localStorage.removeItem(Be(e))}catch{}}var ts={flushAt:20,flushIntervalMs:1e4,maxQueue:500,maxRetryAgeMs:1440*60*1e3,maxRetries:5,maxPersistedBatches:20,maxPersistedBytes:1024*1024,storageKey:ie.retry,beaconSafeBytes:56*1024,maxBatchEvents:100,maxBatchBytes:500*1024},je=()=>Date.now(),Jn=3e4,Tt=55*1024;function ns(e,t=je()){if(typeof e!="string")return 0;let n=e.trim();if(/^\d+$/.test(n))return Number(n)*1e3;if(n==="")return 0;let r=Date.parse(n);return Number.isNaN(r)?0:Math.max(0,r-t)}var ee=e=>typeof TextEncoder<"u"?new TextEncoder().encode(e).length:Buffer.byteLength(e),kt=()=>typeof window<"u"&&typeof document<"u";function rs(){try{return!kt()||!window.localStorage?null:(window.localStorage.getItem("thg_hp_probe"),window.localStorage)}catch{return null}}var A,Ct,Yn,qe,Pt,Ot,Xn,xe,Lt,Fe,Zn,Nt,Qn,He,Ke=class{constructor(t){Ut(this,A);this.o={...ts,...t},this.queue=[],this.timer=null,this.storage=rs(),this.inflight=null,this.sending=new Set,this.replayAllowed=!this.o.deferReplay,this.draining=null,kt()&&(window.addEventListener("pagehide",()=>this.flush({beacon:!0})),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.flush()}),N(this,A,He).call(this))}replayPersisted(){return this.replayAllowed=!0,N(this,A,He).call(this)}clearPersisted(){if(this.replayAllowed=!1,!!this.storage)try{this.storage.removeItem(this.o.storageKey)}catch{}}enqueue(t){let n;try{n=JSON.parse(JSON.stringify(t))}catch(r){this.o.onError?.(`event ${t?.messageId??""} cannot be serialised; dropped`,r);return}this.queue.push(n),this.queue.length>this.o.maxQueue&&this.queue.splice(0,this.queue.length-this.o.maxQueue),this.queue.length>=this.o.flushAt?this.flush():N(this,A,Ct).call(this)}flush(t={}){if(N(this,A,Yn).call(this),this.queue.length===0)return Promise.resolve();if(t.beacon&&kt()&&typeof navigator<"u"&&navigator.sendBeacon)return N(this,A,Xn).call(this),Promise.resolve();if(this.inflight)return this.inflight;let n=N(this,A,Ot).call(this,this.queue,this.o.maxBatchEvents,this.o.maxBatchBytes).map(r=>{let o=N(this,A,Nt).call(this,r);return o&&this.sending.add(o),{batch:r,id:o}});return this.queue=[],this.inflight=(async()=>{for(let{batch:r,id:o}of n)await N(this,A,xe).call(this,r,0,o)})().finally(()=>{this.inflight=null,this.queue.length>=this.o.flushAt?this.flush():this.queue.length&&N(this,A,Ct).call(this)}),this.inflight}};A=new WeakSet,Ct=function(){this.timer||(this.timer=setTimeout(()=>this.flush(),this.o.flushIntervalMs),this.timer?.unref?.())},Yn=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},qe=function(t){return JSON.stringify({batch:t,writeKey:this.o.writeKey,sentAt:new Date().toISOString()})},Pt=function(){return`${this.o.apiHost.replace(/\/$/,"")}/v1/batch`},Ot=function(t,n,r){let o=ee(N(this,A,qe).call(this,[])),i=[],s=[],a=o;for(let u of t){let d=ee(JSON.stringify(u))+1;s.length&&(s.length>=n||a+d>r)&&(i.push(s),s=[],a=o),s.push(u),a+=d}return s.length&&i.push(s),i},Xn=function(){let t=this.queue;this.queue=[];let n=N(this,A,Pt).call(this);for(let r of N(this,A,Ot).call(this,t,this.o.maxBatchEvents,this.o.beaconSafeBytes)){let o=N(this,A,qe).call(this,r);if(ee(o)<=this.o.beaconSafeBytes){let i=!1;try{i=navigator.sendBeacon(n,new Blob([o],{type:"text/plain"}))}catch{i=!1}if(i)continue}N(this,A,xe).call(this,r,0,N(this,A,Nt).call(this,r))}},xe=async function(t,n,r=null){r&&this.sending.add(r);let o=N(this,A,qe).call(this,t),i=0;try{let s=await fetch(N(this,A,Pt).call(this),{method:"POST",headers:{"Content-Type":"text/plain"},body:o,keepalive:ee(o)<=this.o.beaconSafeBytes});if(s.ok)return N(this,A,Lt).call(this,r),N(this,A,He).call(this),!0;let a=s.status===429||s.status>=500;if(a&&(i=ns(s.headers?.get?.("retry-after"))),!a)return N(this,A,Lt).call(this,r),this.o.onError?.(`CDP ingest rejected batch (${s.status}); dropping ${t.length} events`),!0;throw new Error(`retryable ${s.status}`)}catch(s){if(n>=this.o.maxRetries){r&&this.sending.delete(r);let u=r?"kept for the next page":"dropped";return this.o.onError?.(`CDP ingest unreachable after ${n} attempts; ${u}: ${t.length} events`,s),!1}let a=Math.max(Math.min(1e3*2**n,Jn)*(.5+Math.random()),Math.min(i,Jn));return await new Promise(u=>setTimeout(u,a)),N(this,A,xe).call(this,t,n+1,r)}},Lt=function(t){t&&(this.sending.delete(t),N(this,A,Qn).call(this,t))},Fe=function(){let t=JSON.parse(this.storage.getItem(this.o.storageKey)||"[]");return Array.isArray(t)?t:[]},Zn=function(t,n){let r=s=>ee(JSON.stringify(s))+1,o=[...t,n].slice(-this.o.maxPersistedBatches),i=o.reduce((s,a)=>s+r(a),2);for(;o.length>1&&i>this.o.maxPersistedBytes;)i-=r(o[0]),o=o.slice(1);for(;o.length;)try{return this.storage.setItem(this.o.storageKey,JSON.stringify(o)),!0}catch{o=o.slice(1)}return!1},Nt=function(t){if(!this.storage||this.o.mayPersist&&!this.o.mayPersist())return null;try{let n={at:je(),id:`${je()}-${Math.random().toString(36).slice(2)}`,batch:t};return ee(JSON.stringify(n))+3>this.o.maxPersistedBytes?null:N(this,A,Zn).call(this,N(this,A,Fe).call(this),n)?n.id:null}catch{return null}},Qn=function(t){if(!(!t||!this.storage))try{let n=N(this,A,Fe).call(this).filter(r=>r.id!==t);n.length?this.storage.setItem(this.o.storageKey,JSON.stringify(n)):this.storage.removeItem(this.o.storageKey)}catch{}},He=function(){if(!this.storage||!this.replayAllowed)return this.draining??Promise.resolve();if(this.draining)return this.draining;let t;try{let r=N(this,A,Fe).call(this);t=r.filter(o=>Array.isArray(o?.batch)&&je()-o.at<this.o.maxRetryAgeMs).map(o=>o.id?o:{...o,id:`${o.at}-${Math.random().toString(36).slice(2)}`}),(t.length!==r.length||t.some((o,i)=>o!==r[i]))&&(t.length?this.storage.setItem(this.o.storageKey,JSON.stringify(t)):this.storage.removeItem(this.o.storageKey))}catch{return Promise.resolve()}let n=t.filter(r=>!this.sending.has(r.id));return n.length?(this.draining=(async()=>{for(let r of n)if(!this.replayAllowed||!await N(this,A,xe).call(this,r.batch,0,r.id))return})().finally(()=>{this.draining=null}),this.draining):Promise.resolve()};var er="3.19.0",tr="@thg-agentic/hyper-personalisation-web";var os=new Set(["audiences","decisions","recommendations"]);var ss=Symbol.for("@thg-agentic/hyper-personalisation-web.replay");function is(e){let t={...e??{}},n=Array.isArray(t.products)?t.products:null;if(t.item_count==null&&n){let r=n.map(o=>o?.quantity);r.every(Number.isInteger)&&(t.item_count=r.reduce((o,i)=>o+i,0))}return t}var as="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";function cs(e){if(/^[0-9a-fA-F]{64}$/.test(e))return e.toLowerCase();if(!/^[A-Za-z0-9+/_-]{43}=?$/.test(e))return null;try{let t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(44,"="));return t.length!==32?null:Array.from(t,n=>n.charCodeAt(0).toString(16).padStart(2,"0")).join("")}catch{return null}}function Ge(e){if(typeof e!="string")return null;let t=cs(e.trim());return t===as?null:t}var nr=!1,rr=!1;function us(){rr||(rr=!0,console.warn("[hp] no consent adapter: events are sent under the host's lawful basis (basis 'host'). Pass `consent` to send only once the visitor allows analytics."))}function ls(e){!e||nr||(nr=!0,console.warn("[hp] mintAnonymousId is ignored since 3.6: where device ids come from is set per source in the console (the site\u2019s own cookie, or Hyper-Personalisation\u2019s)."))}function ds(e){try{return ee(JSON.stringify(e))}catch{return 0}}function or(e){return e&&typeof e.context=="object"&&e.context!==null?e.context:e}function sr(e){let t=ye(e?.apiHost);if(!t)throw new Error("createAnalytics: apiHost, when given, must be a host or an http(s) origin");if(!e?.propertyId)throw new Error("createAnalytics: propertyId is required");let n={libraryName:tr,libraryVersion:er,writeKey:"web",queryParamBlocklist:[],debug:!1,validate:null,consentTimeoutMs:5e3,...e,apiHost:t};Pe(n.storageNames),Oe();let r=!!n.consent;r||us();let o=null;n.getConsent=()=>o?o.stamp():an();let i=()=>!r||o?.status==="granted",s=r&&n.holdAcrossPages?rn(F(L("held"),n.propertyId)):null,a=s?.read()??{items:[],anonymousId:null};n.mintAnonymousId!==void 0&&ls(n.debug);let u=on(n,{carried:a.anonymousId,mayStore:i,orOwn:!0}),d=qn({name:L("session"),domain:n.consentCookieDomain??null,mayStore:i}),p=n.getSessionId;n.getSessionId=()=>q(R(p,null))??d.get();let f=kn(L("preview"),n.consentCookieDomain??null),y=(c,l)=>n.debug&&console.warn("[hp]",c,l??""),x=n.transport??new Ke({apiHost:n.apiHost,writeKey:n.writeKey,storageKey:F(L("retry"),n.propertyId),mayPersist:r?()=>o?.status==="granted":void 0,deferReplay:r,onError:y}),S=F(L("previousPage"),n.propertyId),b=null,I=()=>{if(b)return b;try{return sessionStorage.getItem(S)||null}catch{return null}},k=c=>{if(b=c||null,!(r&&o.status!=="granted"))try{sessionStorage.setItem(S,c)}catch{}},h=vn({key:F(L("decisions"),n.propertyId),mayStore:i});n.getDecisions??(n.getDecisions=h.current);let v=q(R(n.getUserId,null)),w=null,g=null,_=null;function P(c,l,C=!1){try{return M(c,l,C)}catch(O){if(O instanceof me)throw O;return console.warn("[hp] the event was not sent",O),null}}function M(c,l,C){let O=_;_=null;let E={messageId:O?.messageId??Z(),timestamp:O?.timestamp??new Date().toISOString(),anonymousId:q(R(n.getAnonymousId,null)),userId:v??null,...c,context:Zt(n,or(l))};if(E.properties&&(E.properties=nt(E.properties)),!C&&!Tn(E.anonymousId,n.sampleRate))return n.debug&&console.debug("[hp] not sent: outside the sample",E),null;if(n.beforeSend){let de;try{de=n.beforeSend(E)}catch(yr){return console.warn("[hp] beforeSend failed; the event was not sent",yr),null}if(!de)return null;let{type:Ee,event:Dt,messageId:hr,timestamp:gr}=E;E={...de,type:Ee,messageId:hr,timestamp:gr,...Dt?{event:Dt}:{}}}if(n.validate){let de=n.validate(E,{producer:"web"});if(!de.valid){let Ee=`[hp] invalid ${E.event??E.type}:
2
+ ${de.errors.join(`
3
+ `)}`;if(n.throwOnInvalid)throw new me(Ee);console.error(Ee)}}n.debug&&console.debug("[hp]",E.event??E.type,E);let U=ds(E);return U>Tt?(y(`${E.event??E.type} not sent: ${U} bytes, over the ${Tt}-byte limit for one event`),null):(Ie(E,C),E)}function H(c){if(c.type==="track"&&G(c),n.onEvent)try{n.onEvent(c)}catch(l){console.warn("[hp] onEvent observer failed",l)}}let K=()=>r&&o?.state?.personalisation===!0,j=()=>Mn(R(n.getSessionId,null),n.propertyId),te=!1;function G(c){try{K()?(j(),On(St(Bn(c.event,c.properties))),te=!0):ne()}catch(l){n.debug&&console.warn("[hp] the visit was not recorded",l)}}function ne(c=!1){Ln(),(c||te)&&$n(),te=!1}function le(){d.forget(),h.forget(),B.clear(),u?.forget(),ne(!0)}function Ie(c,l){!r||l||o.admits()?(H(c),x.enqueue(c)):o.hold(c)}let m=(c,l,C)=>Hn(n.plan,c)?P({type:"track",event:c,properties:l??{}},C):null,B=new Set,Ae=(c,l,C)=>c==="audiences"?{audiences:l?null:C.audiences??[]}:c==="decisions"?{decisions:(C.decisions??[]).map(O=>({slot:O.slot,decision_id:O.decision_id??null,arm:O.arm??null,...O.variant&&{variant:O.variant}}))}:{recommendation_request_id:C.recommendation_request_id??null};r&&(o=In({adapter:n.consent,timeoutMs:n.consentTimeoutMs,cookieDomain:n.consentCookieDomain,debug:n.debug,store:s&&{read:()=>a.items,write:c=>s.write(c,u?.peek()??null)},release(c){c.context&&(c.context.consent=o.stamp()),H(c),x.enqueue(c)},onStatus(c){if(c==="granted"&&(u?.persist(),d.persist(),b&&k(b),h.persist(),x.replayPersisted?.()),c==="denied"){x.clearPersisted?.(),u?.forget(),d.forget();try{sessionStorage.removeItem(S)}catch{}h.forget(),ne(!0)}try{n.onConsentStatus?.(c)}catch(l){console.warn("[hp] onConsentStatus observer failed",l)}},announce({action:c,state:l,previous:C,withdrawal:O}){l?.personalisation!==!0&&ne(C?.personalisation===!0),P({type:"track",event:"Consent Updated",properties:{action:c,state:l}},void 0,O),O&&x.flush()}}),o.start());let J=()=>n.holdout?gt(n.holdout):null,ve=()=>yt(n.holdout,q(R(n.getAnonymousId,null))).group;function mr(c,l){if(!Array.isArray(c?.decisions))return c;let C=n.holdout?.readoutSlots??[],O=q(R(n.getAnonymousId,null));return{...c,decisions:c.decisions.map(E=>{let U=E?.variant==="bandit"||E?.variant==="default"?E.variant:!l&&E?.holdout!==!0&&C.includes(E?.slot)?En(E.slot,O):null;return U?U==="default"?{...E,variant:U,decision_id:null}:{...E,variant:U}:E})}}function Mt(c,l){if(f)return null;let C=c?.exposure,O=C?.holdout===!0,E=mr(c,O);return h.remember(An(E)),!C?.token||B.has(C.token)?null:(B.add(C.token),m("Personalisation Exposed",{exposure_token:C.token,surface:C.surface,holdout:O,holdout_share:C.holdout_share??J()?.holdout_share??null,personalised_share:C.personalised_share??J()?.personalised_share??null,...Ae(C.surface,O,E)},l))}return bn({track:m,page(c,l){c??(c={});let C=n.pageType??null;c.type&&(fe.has(c.type)?(C=c.type,n.pageType=c.type):n.debug&&console.warn(`[hp] ignoring unknown page.type "${c.type}". Allowed: ${[...fe].join(", ")}`));let O=P({type:"page",properties:{name:c.name??null,navigation_trigger:c.navigation_trigger??zt(),previous_message_id:I()}},{page:{type:C},...or(l)??{}});return O&&k(O.messageId),O},identify(c,l,C){let{userId:O,...E}=c&&typeof c=="object"?c:{};if(O!==void 0){let U=q(O);C===be?g=U:w&&U&&U!==w?le():n.debug&&g&&U&&U!==g&&console.warn("[hp] identify names another userId than the identity option; using the new one"),v=U,U&&C!==be&&(w=U)}if(typeof E.email_sha256=="string"){let U=Ge(E.email_sha256);U?E.email_sha256=U:delete E.email_sha256}return P({type:"identify",traits:E},l)},reset(){v&&le(),v=null,w=null,g=null,k("")},productViewed:(c,l)=>m("Product Viewed",c,l),productListViewed:(c,l)=>m("Product List Viewed",c,l),recommendationsViewed:(c,l)=>m("Recommendations Viewed",c,l),personalisationExposed:(c,l)=>m("Personalisation Exposed",c,l),recordExposure:Mt,surfaceViewed({surface:c}={},l){if(!os.has(c)||!n.holdout||c!=="decisions"&&!K())return null;let C=q(R(n.getAnonymousId,null)),O=yt(n.holdout,C).group;if(O==="excluded")return null;let E=Ht({sessionId:ke(R(n.getSessionId,null),C),surface:c});return E?Mt({exposure:{token:E,surface:c,holdout:O==="holdout"}},l):null},inHoldout:()=>ve()!=="personalised",personalisationGroup:ve,productClicked:(c,l)=>m("Product Clicked",c,l),productListFiltered:(c,l)=>m("Product List Filtered",c,l),productsSearched:(c,l)=>m("Products Searched",c,l),searchSuggestionsViewed:(c,l)=>m("Search Suggestions Viewed",c,l),productAdded:(c,l)=>m("Product Added",c,l),productRemoved:(c,l)=>m("Product Removed",c,l),cartUpdated:(c,l)=>m("Cart Updated",is(c),l),identityLinked:(c,l)=>m("Identity Linked",c,l),slotEngaged:(c,l)=>f?null:m("Slot Engaged",c,l),productVariantSelected:(c,l)=>m("Product Variant Selected",c,l),cartViewed:(c,l)=>m("Cart Viewed",c,l),productAddedToWishlist:(c,l)=>m("Product Added to Wishlist",c,l),productRemovedFromWishlist:(c,l)=>m("Product Removed from Wishlist",c,l),wishlistProductAddedToCart:(c,l)=>m("Wishlist Product Added to Cart",c,l),productShared:(c,l)=>m("Product Shared",c,l),cartShared:(c,l)=>m("Cart Shared",c,l),couponEntered:(c,l)=>m("Coupon Entered",c,l),couponApplied:(c,l)=>m("Coupon Applied",c,l),couponDenied:(c,l)=>m("Coupon Denied",c,l),couponRemoved:(c,l)=>m("Coupon Removed",c,l),checkoutStarted:(c,l)=>m("Checkout Started",c,l),promotionViewed:(c,l)=>m("Promotion Viewed",c,l),promotionClicked:(c,l)=>m("Promotion Clicked",c,l),checkoutStepViewed:(c,l)=>m("Checkout Step Viewed",c,l),checkoutStepCompleted:(c,l)=>m("Checkout Step Completed",c,l),paymentInfoEntered:(c,l)=>m("Payment Info Entered",c,l),checkoutFailed:(c,l)=>m("Checkout Failed",c,l),signedIn:(c,l)=>m("Signed In",c,l),signedUp:(c,l)=>m("Signed Up",c,l),signedOut(c){let l=m("Signed Out",{},c);return v&&le(),v=null,w=null,g=null,l},newsletterSubscribed:(c,l)=>m("Newsletter Subscribed",c,l),newsletterUnsubscribed:(c,l)=>m("Newsletter Unsubscribed",c,l),backInStockSubscribed:(c,l)=>m("Back In Stock Subscribed",c,l),productReviewed:(c,l)=>m("Product Reviewed",c,l),consentUpdated:(c,l)=>m("Consent Updated",c,l),flush:c=>x.flush(c),recommendationContext(){if(!K())return{};try{return j(),St(Dn())}catch{return{}}},get consent(){return o?o.state:null},servingHeaders:()=>ln(o?.state??null),get lastPageMessageId(){return I()},get anonymousId(){return q(R(n.getAnonymousId,null))},[ss](c,l,C){if(typeof this[c]=="function"){_=typeof C?.messageId=="string"&&typeof C?.timestamp=="string"?{messageId:C.messageId,timestamp:C.timestamp}:null;try{this[c](...Array.isArray(l)?l:[])}finally{_=null}}}})}var Rt=Symbol.for("@thg-agentic/hyper-personalisation-web.bootstrap"),fs=Symbol.for("@thg-agentic/hyper-personalisation-web.drain"),ps=Symbol.for("@thg-agentic/hyper-personalisation-web.carry"),ir=Symbol.for("@thg-agentic/hyper-personalisation-web.replay"),ms=Symbol.for("@thg-agentic/hyper-personalisation-web.assignment"),hs=Symbol.for("@thg-agentic/hyper-personalisation-web.recommendation-context"),Je=e=>e?()=>D(e):()=>null,ur={didomi:e=>dn({purposes:e.purposes}),onetrust:e=>fn({groups:e.groups,impliedConsent:e.impliedConsent}),cookie:e=>pn({name:e.name,categories:e.categories,refusedValue:e.refusedValue,source:e.source,changeEvent:e.changeEvent}),forwarded:e=>mn({name:e.name}),static:e=>{if(!e.state||typeof e.state!="object")throw new Error('consent.state is required for provider "static"');return hn(e.state)}},ar=Object.keys(ur),Se=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),ze=e=>typeof e=="string"&&e!=="",gs=e=>Array.isArray(e)&&e.every(t=>typeof t=="string"),lr=e=>Se(e)&&typeof e.read=="function";function ys(e,t={}){let n=[];if(!Se(e))return["config must be { writeKey, apiHost? }"];ze(e.writeKey)||n.push("writeKey is required"),ye(e.apiHost)||n.push("apiHost, when given, must be a host or an http(s) origin"),t.propertyId!==void 0&&!ze(t.propertyId)&&n.push("propertyId must be a string");let{consent:r}=t;if(!lr(r)&&!(Se(r)&&ar.includes(r.provider))&&n.push(`consent must be a consent adapter or { provider: ${ar.join(" | ")} }`),t.autocapture!==void 0&&t.autocapture!==!1&&!Se(t.autocapture)&&n.push("autocapture must be false or { promotions, productLists, recommendations }"),t.beforeSend!==void 0&&typeof t.beforeSend!="function"&&n.push("beforeSend must be a function"),t.identityCookies!==void 0)if(!Se(t.identityCookies))n.push("identityCookies must be an object");else for(let o of["anonymousId","sessionId"]){let i=t.identityCookies[o];i!==void 0&&!ze(i)&&n.push(`identityCookies.${o} must be a cookie name`)}for(let o of["getCurrency","getShipToCountry","getLocale"])t[o]!==void 0&&typeof t[o]!="function"&&n.push(`${o} must be a function`);return t.dataLayer!==void 0&&(Se(t.dataLayer)?(t.dataLayer.name!==void 0&&!ze(t.dataLayer.name)&&n.push("dataLayer.name must be a string"),t.dataLayer.ignore!==void 0&&!gs(t.dataLayer.ignore)&&n.push("dataLayer.ignore must be an array of strings")):n.push("dataLayer must be an object")),n}function Ss(e,t,n){if(lr(e))return dt(e,t.consentPurposes);let{provider:r,...o}=e,i=n?.consent?.[r]??ur[r];return dt(i(o),t.consentPurposes)}var dr=(e,t)=>`${e??""}|${t??""}`;function ws(e,t){let n=q(t?.userId),r=Ge(t?.emailSha256);if(!n&&!r)return null;try{let o=F(L("identified"),e);if(sessionStorage.getItem(o)===dr(n,r))return null}catch{}return{...n?{userId:n}:{},...r?{email_sha256:r}:{}}}async function _s({writeKey:e,apiHost:t},n){if(n.settings!==void 0)return{settings:vt(n.settings),revalidated:null};let r=Gn(t,e),o=zn(e);if(o)return{settings:o,revalidated:r};let i=await r,s=i??At;return{settings:s,revalidated:Promise.resolve(s),unreachable:i===null}}function fr(e,t){let n=t??{},r=typeof window<"u"?window:null;if(r?.[Rt])return r[Rt];let o=sn(e?.writeKey,()=>{let{analytics:s}=_e(D(L("consent")));return s===!0||s===null&&n.holdAcrossPages===!0}),i=xs(e,n,o);if(r){let s=n.extend?.getSessionId??Je(n.identityCookies?.sessionId),a=Je(n.identityCookies?.anonymousId);r[ms]=({slot:u,arm:d}={})=>Ft({sessionId:ke(s(),a()),slot:u,arm:d}),r[Rt]=i,r[ps]=o,r[fs]?.(i)}return i}function bs(){let e=globalThis.performance?.now?.();return new Date(Date.now()-(Number.isFinite(e)?e:0)).toISOString()}function cr(e,t){if(t===!1)return()=>{};let n={promotions:!0,productLists:!0,recommendations:!0,exposures:!0,...t},r=i=>i&&typeof i=="object"?i:{},o=[];try{n.promotions&&o.push(Qe(e,r(n.promotions))),n.productLists&&o.push(Ze(e,r(n.productLists))),n.recommendations&&o.push(et(e,r(n.recommendations))),n.exposures&&o.push(Xe(e,r(n.exposures)))}catch(i){console.warn("[hp] autocapture not started:",i?.message??i)}return()=>{for(let i of o)i()}}function We(e){return e.close(),null}async function xs(e,t,n){try{let r=ys(e,t);if(r.length)return console.warn(`[hp] not started, the configuration is invalid: ${r.join("; ")}`),We(n);Pe(t.storageNames),Oe();let{writeKey:o}=e,[{settings:i,revalidated:s,unreachable:a},u]=await Promise.all([_s(e,t),Promise.resolve(t.identity).catch(()=>null)]),d=s?i:null,p=!1,f=()=>p&&d&&Wn(o,d);if(s?.then(g=>{g&&(d=g,g.enabled?f():Et(o))}),a)return null;if(!i.enabled)return t.debug&&console.info("[hp] off: the settings for this write key do not enable it"),We(n);let y=i.propertyId??t.propertyId;if(!y)return console.warn("[hp] not started: this write key covers several properties, so propertyId is required"),We(n);let{preset:x}=t,S=ws(y,u),b=t.debug===!0||i.debug?.enabled===!0||_n(i.debug?.tokenSha256??null,L("debug")),I=q(u?.userId),k=sr({apiHost:i.apiHost??ye(e.apiHost),writeKey:o,propertyId:y,pageType:fe.has(t.pageType)?t.pageType:void 0,environment:i.environment,queryParamAllowlist:i.queryParamAllowlist??void 0,plan:i.plan,sampleRate:i.sampleRate??1,holdout:i.holdouts?.[y],getCurrency:t.getCurrency,getShipToCountry:t.getShipToCountry,getLocale:t.getLocale,consent:Ss(t.consent,i,x),consentCookieDomain:t.consentCookieDomain,storageNames:t.storageNames,holdAcrossPages:t.holdAcrossPages===!0,mintAnonymousId:t.mintAnonymousId,debug:b,anonymousIdSource:i.anonymousId??void 0,getAnonymousId:Je(t.identityCookies?.anonymousId),getSessionId:t.identityCookies?.sessionId?Je(t.identityCookies.sessionId):void 0,getUserId:()=>I,beforeSend:t.beforeSend,...t.extend,onConsentStatus(g){if(g==="granted"&&(p=!0,f()),g==="denied"){Et(o);try{sessionStorage.removeItem(F(L("identified"),y))}catch{}}t.extend?.onConsentStatus?.(g)},onEvent(g){if(g.type==="identify"){let _=dr(q(g.userId),Ge(g.traits?.email_sha256));try{sessionStorage.setItem(F(L("identified"),y),_)}catch{}}t.extend?.onEvent?.(g)}});typeof window<"u"&&(window[hs]=()=>k.recommendationContext());for(let[g,_,P]of n.take())try{k[ir](g,_,P)}catch(M){console.warn(`[hp] carried ${g} failed`,M)}k[ir]("page",[t.pageType?{type:t.pageType}:{}],{messageId:Z(),timestamp:bs()});let h=cr(k,t.autocapture),v=k.page;k.page=ht("page",(...g)=>{let _=v(...g);return h(),h=cr(k,t.autocapture),_});let w=typeof window<"u"?window:null;if(t.dataLayer&&w){let g=t.dataLayer.name??"dataLayer";w[g]=w[g]||[],wn(k,{...x,dataLayer:w[g],ignore:[...x?.ignore??[],...t.dataLayer.ignore??[]],onError:_=>b&&console.warn("[hp] dataLayer mapping failed",_)})}return S&&k.identify(S,void 0,be),k}catch(r){return console.warn("[hp] not started:",r?.message??r),We(n)}}function pr(e){e.initialized=!0,fr(e._config,e._options).then(t=>{let n=e.splice(0);if(!t){for(let r of e.methods??[])e[r]=()=>e;return}e.client=t;for(let[r,o]of Object.entries(t))typeof o=="function"&&(e[r]=o);for(let[r,...o]of n)try{t[r]?.(...o)}catch(i){console.warn(`[hp] queued ${r} failed`,i)}})}var V=window.hp=window.hp||[];V.servingHeaders??(V.servingHeaders=()=>({}));V.inHoldout??(V.inHoldout=()=>!0);V.personalisationGroup??(V.personalisationGroup=()=>"excluded");V.recommendationContext??(V.recommendationContext=()=>({}));V.initialized||(V._config?pr(V):V.load=(e,t)=>{V._config=e,V._options=t??{},pr(V)});})();
@@ -1 +1 @@
1
- (()=>{(()=>{let e=window.hp=window.hp||[];if(!(e.initialized||e.invoked)){e.invoked=!0,e.methods=["track","page","identify","reset","flush","productViewed","productListViewed","recommendationsViewed","personalisationExposed","recordExposure","surfaceViewed","productClicked","productListFiltered","productsSearched","productAdded","productRemoved","cartUpdated","identityLinked","slotEngaged","productVariantSelected","cartViewed","productAddedToWishlist","productRemovedFromWishlist","wishlistProductAddedToCart","productShared","cartShared","couponEntered","couponApplied","couponDenied","couponRemoved","checkoutStarted","promotionViewed","promotionClicked","checkoutStepViewed","checkoutStepCompleted","paymentInfoEntered","checkoutFailed","signedIn","signedUp","signedOut","newsletterSubscribed","newsletterUnsubscribed","backInStockSubscribed","productReviewed","consentUpdated"],e.factory=t=>(...o)=>(e.push([t,...o]),e);for(let t of e.methods)e[t]=e.factory(t);e.servingHeaders=()=>({}),e.inHoldout=()=>!0,e.personalisationGroup=()=>"excluded",e.recommendationContext=()=>({}),e.load=(t,o,r)=>{e._config=t,e._options=o||{};let d=document.createElement("script");d.async=!0,d.src=r;let i=document.getElementsByTagName("script")[0];i.parentNode.insertBefore(d,i)},e.SNIPPET_VERSION="1",e.load({writeKey:"hp_pk_live_REPLACE_ME",apiHost:"https://api.example.com"},{consent:{provider:"onetrust"},identityCookies:{sessionId:"session_id"}},"https://cdn.jsdelivr.net/npm/@thg-agentic/hyper-personalisation-web@3/dist/hp.min.js")}})();})();
1
+ (()=>{(()=>{let e=window.hp=window.hp||[];if(!(e.initialized||e.invoked)){e.invoked=!0,e.methods=["track","page","identify","reset","flush","productViewed","productListViewed","recommendationsViewed","personalisationExposed","recordExposure","surfaceViewed","productClicked","productListFiltered","productsSearched","searchSuggestionsViewed","productAdded","productRemoved","cartUpdated","identityLinked","slotEngaged","productVariantSelected","cartViewed","productAddedToWishlist","productRemovedFromWishlist","wishlistProductAddedToCart","productShared","cartShared","couponEntered","couponApplied","couponDenied","couponRemoved","checkoutStarted","promotionViewed","promotionClicked","checkoutStepViewed","checkoutStepCompleted","paymentInfoEntered","checkoutFailed","signedIn","signedUp","signedOut","newsletterSubscribed","newsletterUnsubscribed","backInStockSubscribed","productReviewed","consentUpdated"],e.factory=t=>(...o)=>(e.push([t,...o]),e);for(let t of e.methods)e[t]=e.factory(t);e.servingHeaders=()=>({}),e.inHoldout=()=>!0,e.personalisationGroup=()=>"excluded",e.recommendationContext=()=>({}),e.load=(t,o,r)=>{e._config=t,e._options=o||{};let d=document.createElement("script");d.async=!0,d.src=r;let i=document.getElementsByTagName("script")[0];i.parentNode.insertBefore(d,i)},e.SNIPPET_VERSION="1",e.load({writeKey:"hp_pk_live_REPLACE_ME",apiHost:"https://api.example.com"},{consent:{provider:"onetrust"},identityCookies:{sessionId:"session_id"}},"https://cdn.jsdelivr.net/npm/@thg-agentic/hyper-personalisation-web@3/dist/hp.min.js")}})();})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thg-agentic/hyper-personalisation-web",
3
- "version": "3.17.1",
3
+ "version": "3.19.0",
4
4
  "description": "Browser SDK for the THG Hyper-Personalisation event specification: event tracking from a write key and remote settings, strict CMP-agnostic consent, a GA4 dataLayer bridge and in-session audience evaluation. Dependency-free ESM on the Segment wire protocol, a CDN script (dist/hp.min.js), and an optional @segment/analytics-next plugin path.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -74,7 +74,7 @@
74
74
  "esbuild": "^0.28.2",
75
75
  "jsdom": "^30.1.1",
76
76
  "typescript": "^7.0.2",
77
- "@thg-agentic/hyper-personalisation-spec": "1.8.1"
77
+ "@thg-agentic/hyper-personalisation-spec": "1.12.0"
78
78
  },
79
79
  "scripts": {
80
80
  "test": "node --test tests/*.test.mjs",
package/src/bootstrap.js CHANGED
@@ -10,7 +10,8 @@
10
10
  * The key is the whole config: `apiHost` is optional, for a first-party proxy (DEFAULT_API_HOST
11
11
  * otherwise). Everything tenant-level comes from `GET {apiHost}/v1/projects/{writeKey}/settings`: whether the
12
12
  * SDK is on, the property, the environment, the reported consent purposes, the query-param
13
- * allowlist, where device ids come from, and the tracking plan. What only the page can know stays
13
+ * allowlist, where device ids come from, the tracking plan (which events are blocked), the sampling
14
+ * rate and debug logging. What only the page can know stays
14
15
  * in code: the CMP, the session cookie's name (and, for a source whose settings name no device
15
16
  * cookie, the device cookie's), the per-request currency / ship-to / locale getters, the preset,
16
17
  * the page type, debug, and which property this page is for a key scoped to several.
@@ -39,6 +40,9 @@ import {
39
40
  } from './consent.js';
40
41
  import { getCookie } from './context.js';
41
42
  import { connectDataLayer } from './datalayer.js';
43
+ import { sessionDebug } from './debug.js';
44
+ import { guard } from './guard.js';
45
+ import { IDENTITY_OPTION } from './identity-option.js';
42
46
  import { createAnalytics, normaliseSha256, PAGE_TYPES } from './index.js';
43
47
  import {
44
48
  cachedSettings,
@@ -49,7 +53,7 @@ import {
49
53
  readSettings,
50
54
  resolveApiHost,
51
55
  } from './settings.js';
52
- import { realId } from './shape.js';
56
+ import { realId, uuid } from './shape.js';
53
57
  import {
54
58
  configureStorageNames,
55
59
  migrateLegacyStorage,
@@ -227,7 +231,8 @@ async function resolveSettings({ writeKey, apiHost }, options) {
227
231
  * @param {import('../types/bootstrap').BootstrapOptions} options See types/bootstrap.d.ts.
228
232
  * @returns {Promise<object|null>} the client, or null when it is off.
229
233
  */
230
- export function bootstrap(config, options = {}) {
234
+ export function bootstrap(config, maybeOptions) {
235
+ const options = maybeOptions ?? {};
231
236
  const host = typeof window !== 'undefined' ? window : null;
232
237
  if (host?.[INSTANCE]) return host[INSTANCE];
233
238
  // What `hp` queued on an earlier page that navigated before its client started. Carried only as
@@ -261,6 +266,17 @@ export function bootstrap(config, options = {}) {
261
266
  return started;
262
267
  }
263
268
 
269
+ /**
270
+ * When this document was navigated to: the wall clock less the time since, not `timeOrigin`, which
271
+ * browsers derive from a monotonic clock that drifts from the wall clock after a sleep.
272
+ */
273
+ function navigatedAt() {
274
+ const since = globalThis.performance?.now?.();
275
+ return new Date(
276
+ Date.now() - (Number.isFinite(since) ? since : 0),
277
+ ).toISOString();
278
+ }
279
+
264
280
  /**
265
281
  * The declarative trackers: they report only what the page tags (`data-hp-promotion`,
266
282
  * `data-hp-list` / `data-hp-product`, `data-hp-reco-request`, `data-hp-exposure`), so they are on
@@ -353,6 +369,11 @@ async function start(config, options, carry) {
353
369
 
354
370
  const { preset } = options;
355
371
  const identified = pendingIdentify(propertyId, identity);
372
+ // Settings from before 3.18, cached or served, have none of these: nothing sampled, no logging.
373
+ const debug =
374
+ options.debug === true ||
375
+ settings.debug?.enabled === true ||
376
+ sessionDebug(settings.debug?.tokenSha256 ?? null, storageName('debug'));
356
377
  const userId = realId(identity?.userId);
357
378
 
358
379
  const client = createAnalytics({
@@ -365,6 +386,7 @@ async function start(config, options, carry) {
365
386
  environment: settings.environment,
366
387
  queryParamAllowlist: settings.queryParamAllowlist ?? undefined,
367
388
  plan: settings.plan,
389
+ sampleRate: settings.sampleRate ?? 1,
368
390
  holdout: settings.holdouts?.[propertyId],
369
391
  // Per request, never per tenant: a site can trade in several currencies and ship anywhere.
370
392
  getCurrency: options.getCurrency,
@@ -376,7 +398,7 @@ async function start(config, options, carry) {
376
398
  holdAcrossPages: options.holdAcrossPages === true,
377
399
  // Deprecated in 3.6 and ignored; passed on only so debug can say so.
378
400
  mintAnonymousId: options.mintAnonymousId,
379
- debug: options.debug === true,
401
+ debug,
380
402
  // Where device ids come from is the source's: with no setting (settings from before 3.6),
381
403
  // the cookie named here, as before.
382
404
  anonymousIdSource: settings.anonymousId ?? undefined,
@@ -440,16 +462,25 @@ async function start(config, options, carry) {
440
462
  }
441
463
  }
442
464
 
443
- client.page(options.pageType ? { type: options.pageType } : {});
465
+ // Stamped when the document was navigated to, not when the settings came back: the page view
466
+ // is the page's first event, ahead of what the page queued through `hp` meanwhile (#527).
467
+ client[REPLAY](
468
+ 'page',
469
+ [options.pageType ? { type: options.pageType } : {}],
470
+ {
471
+ messageId: uuid(),
472
+ timestamp: navigatedAt(),
473
+ },
474
+ );
444
475
  let stopAutocapture = startAutocapture(client, options.autocapture);
445
476
  // Impressions count once per page view, so a single-page app's next route reports afresh.
446
477
  const page = client.page;
447
- client.page = (...args) => {
478
+ client.page = guard('page', (...args) => {
448
479
  const event = page(...args);
449
480
  stopAutocapture();
450
481
  stopAutocapture = startAutocapture(client, options.autocapture);
451
482
  return event;
452
- };
483
+ });
453
484
 
454
485
  const host = typeof window !== 'undefined' ? window : null;
455
486
  if (options.dataLayer && host) {
@@ -463,11 +494,11 @@ async function start(config, options, carry) {
463
494
  ...(options.dataLayer.ignore ?? []),
464
495
  ],
465
496
  onError: (err) =>
466
- options.debug && console.warn('[hp] dataLayer mapping failed', err),
497
+ debug && console.warn('[hp] dataLayer mapping failed', err),
467
498
  });
468
499
  }
469
500
 
470
- if (identified) client.identify(identified);
501
+ if (identified) client.identify(identified, undefined, IDENTITY_OPTION);
471
502
  return client;
472
503
  } catch (err) {
473
504
  console.warn('[hp] not started:', err?.message ?? err);
@@ -92,7 +92,7 @@ function previousFromCookie(name) {
92
92
  * @param {string} [options.cookieName] Defaults to storageName('consent'), `thg_hp_consent`.
93
93
  * @param {(item: any) => void} options.release A held item may now be sent.
94
94
  * @param {(item: any) => void} [options.discard] A held item will never be sent.
95
- * @param {(update: { action: string, state: object, withdrawal: boolean }) => void} options.announce
95
+ * @param {(update: { action: string, state: object, previous: object|null, withdrawal: boolean }) => void} options.announce
96
96
  * Record a Consent Updated. Called only when analytics is granted, or for the withdrawal itself.
97
97
  * @param {(status: string) => void} [options.onStatus]
98
98
  * @param {boolean} [options.debug]
@@ -201,6 +201,7 @@ export function createConsentGate(options) {
201
201
  announce({
202
202
  action: consentAction(next, previous),
203
203
  state: next,
204
+ previous,
204
205
  withdrawal: false,
205
206
  });
206
207
  return;
@@ -210,7 +211,12 @@ export function createConsentGate(options) {
210
211
  // A withdrawal is recorded, then nothing more: the raw table is where a refusal is proven to
211
212
  // have been received, and the warehouse's consent filter keeps it out of every model.
212
213
  if (previous?.analytics === true)
213
- announce({ action: 'withdrawn', state: next, withdrawal: true });
214
+ announce({
215
+ action: 'withdrawn',
216
+ state: next,
217
+ previous,
218
+ withdrawal: true,
219
+ });
214
220
  setStatus('denied');
215
221
  }
216
222
 
package/src/debug.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Session debug (3.18): `?hp_debug=<token>` turns console logging on for the rest of the browser
3
+ * session, but only when the token hashes to the one the source's settings name, so a shopper who
4
+ * guesses the parameter turns nothing on. `?hp_debug=` with no value ends it. The token is kept in
5
+ * sessionStorage and checked on every page against the settings that page starts from, so a token
6
+ * cleared in the console stops working once the browser has read the new settings.
7
+ */
8
+
9
+ import { sha256Hex } from './hash.js';
10
+
11
+ export const DEBUG_PARAM = 'hp_debug';
12
+
13
+ const MAX_TOKEN_LENGTH = 256;
14
+
15
+ function readParam() {
16
+ try {
17
+ return new URLSearchParams(location.search).get(DEBUG_PARAM);
18
+ } catch {
19
+ return null;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Whether this session has debug on: apply the page URL's `hp_debug` to sessionStorage under
25
+ * `name`, then check what is kept against `tokenSha256`.
26
+ *
27
+ * @param {string|null} tokenSha256 The settings' `hp.debug.tokenSha256`.
28
+ * @param {string} name The sessionStorage key, storageName('debug').
29
+ */
30
+ export function sessionDebug(tokenSha256, name) {
31
+ if (typeof location === 'undefined') return false;
32
+ try {
33
+ const given = readParam();
34
+ if (given !== null) {
35
+ const token = given.trim();
36
+ if (token === '' || token.length > MAX_TOKEN_LENGTH)
37
+ sessionStorage.removeItem(name);
38
+ else sessionStorage.setItem(name, token);
39
+ }
40
+ const kept = sessionStorage.getItem(name);
41
+ return Boolean(tokenSha256 && kept && sha256Hex(kept) === tokenSha256);
42
+ } catch {
43
+ return false;
44
+ }
45
+ }