@grainql/analytics-web 3.2.0 → 3.2.1

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.
@@ -1,4 +1,4 @@
1
- /* Grain Analytics Web SDK v3.2.0 | MIT License */
1
+ /* Grain Analytics Web SDK v3.2.1 | MIT License */
2
2
  "use strict";var Grain=(()=>{var Ze=Object.defineProperty;var Ur=Object.getOwnPropertyDescriptor;var $r=Object.getOwnPropertyNames;var Hr=Object.prototype.hasOwnProperty;var $=(n,e)=>()=>(n&&(e=n(n=0)),e);var z=(n,e)=>{for(var t in e)Ze(n,t,{get:e[t],enumerable:!0})},Br=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $r(e))!Hr.call(n,r)&&r!==t&&Ze(n,r,{get:()=>e[r],enumerable:!(i=Ur(e,r))||i.enumerable});return n};var Fr=n=>Br(Ze({},"__esModule",{value:!0}),n);var Yr,W,it=$(()=>{"use strict";Yr={maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4},W=class{constructor(e,t={}){this.isDestroyed=!1;this.isPageVisible=!0;this.visibilityChangeHandler=null;this.sectionStates=new Map;this.lastFilterReason=null;this.activityDetector=e,this.options={...Yr,...t,debug:t.debug??!1},this.setupPageVisibilityTracking()}setupPageVisibilityTracking(){typeof document>"u"||(this.isPageVisible=document.visibilityState==="visible",this.visibilityChangeHandler=()=>{let e=this.isPageVisible;this.isPageVisible=document.visibilityState==="visible",!this.isPageVisible&&e?this.log("Page hidden - tracking paused"):this.isPageVisible&&!e&&(this.log("Page visible - tracking resumed"),this.resetAllSections())},document.addEventListener("visibilitychange",this.visibilityChangeHandler))}shouldTrack(){return this.isPageVisible?this.activityDetector.isActive(this.options.idleThreshold)?(this.lastFilterReason=null,!0):(this.lastFilterReason="user_idle",!1):(this.lastFilterReason="page_hidden",!1)}shouldTrackSection(e,t){if(!this.shouldTrack())return{shouldTrack:!1,reason:this.lastFilterReason||"global_policy"};let i=this.sectionStates.get(e);i||(i={sectionName:e,currentDuration:0,lastScrollPosition:t,lastResetTime:Date.now()},this.sectionStates.set(e,i));let r=Math.abs(t-i.lastScrollPosition);return r>=this.options.minScrollDistance?(this.log(`Section "${e}": Attention reset due to ${Math.round(r)}px scroll`),i.currentDuration=0,i.lastScrollPosition=t,i.lastResetTime=Date.now(),{shouldTrack:!0,resetAttention:!0}):i.currentDuration>=this.options.maxSectionDuration?{shouldTrack:!1,reason:"max_duration_reached"}:{shouldTrack:!0}}updateSectionDuration(e,t){let i=this.sectionStates.get(e);i&&(i.currentDuration+=t,i.currentDuration>=this.options.maxSectionDuration&&this.log(`Section "${e}": Max duration cap reached (${i.currentDuration}ms)`))}resetSection(e){let t=this.sectionStates.get(e);t&&(this.log(`Section "${e}": Attention reset (section exit)`),t.currentDuration=0,t.lastResetTime=Date.now())}resetAllSections(){this.log("Resetting all section attention states");for(let e of this.sectionStates.values())e.currentDuration=0,e.lastResetTime=Date.now()}getSectionState(e){return this.sectionStates.get(e)}getLastFilterReason(){return this.lastFilterReason}shouldTrackScroll(e,t){return this.shouldTrack()?Math.abs(t-e)<10?{shouldTrack:!1,reason:"scroll_too_small"}:{shouldTrack:!0}:{shouldTrack:!1,reason:this.lastFilterReason||"global_policy"}}getPolicies(){return{maxSectionDuration:this.options.maxSectionDuration,minScrollDistance:this.options.minScrollDistance,idleThreshold:this.options.idleThreshold}}getTrackingState(){return{isPageVisible:this.isPageVisible,isUserActive:this.activityDetector.isActive(this.options.idleThreshold),timeSinceLastActivity:this.activityDetector.getTimeSinceLastActivity(),activeSections:this.sectionStates.size}}log(...e){this.options.debug&&console.log("[AttentionQuality]",...e)}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.visibilityChangeHandler&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=null),this.sectionStates.clear())}}});function Jr(n){if(n)return n.replace(/[\u{1F300}-\u{1F9FF}]/gu,"").replace(/[\u{1F600}-\u{1F64F}]/gu,"").replace(/[\u{1F680}-\u{1F6FF}]/gu,"").replace(/[\u{2600}-\u{26FF}]/gu,"").replace(/[\u{2700}-\u{27BF}]/gu,"").replace(/[\u{1F900}-\u{1F9FF}]/gu,"").replace(/[\u{1F1E0}-\u{1F1FF}]/gu,"").replace(/[\u{200D}]/gu,"").replace(/[\u{FE0F}]/gu,"").replace(/[\u{20E3}]/gu,"").trim()}function Ae(n,e=100){if(!n)return;let t=Jr(n);if(t)return t.substring(0,e)||void 0}var rt=$(()=>{"use strict"});var kr={};z(kr,{IGNORED_NODE:()=>ut,Mirror:()=>J,absolutifyURLs:()=>ae,adaptCssForReplay:()=>Ye,buildNodeWithSN:()=>Ht,classMatchesRegex:()=>$e,cleanupSnapshot:()=>Nn,createCache:()=>Ia,createMirror:()=>pn,escapeImportStatement:()=>Mi,extractFileExtension:()=>xt,fixSafariColons:()=>Ii,genId:()=>Bi,getInputType:()=>Ni,ignoreAttribute:()=>Gi,is2DCanvasBlank:()=>Li,isCSSImportRule:()=>_i,isCSSStyleRule:()=>Ri,isElement:()=>ze,isNativeShadowDom:()=>De,isNodeMetaEqual:()=>Oi,isShadowRoot:()=>xi,markCssSplits:()=>$i,maskInputValue:()=>Di,needMaskingText:()=>zi,normalizeCssString:()=>Le,rebuild:()=>Na,serializeNodeWithId:()=>Y,snapshot:()=>Ln,splitCssText:()=>Ui,stringifyRule:()=>Pi,stringifyStylesheet:()=>Ue,toLowerCase:()=>he,transformAttribute:()=>Fi,visitSnapshot:()=>On});function kt(n){if(Ee[n])return Ee[n];let e=globalThis[n],t=e.prototype,i=n in ri?ri[n]:void 0,r=!!(i&&i.every(o=>{var c,l;return!!((l=(c=Object.getOwnPropertyDescriptor(t,o))==null?void 0:c.get)!=null&&l.toString().includes("[native code]"))})),s=n in ni?ni[n]:void 0,a=!!(s&&s.every(o=>{var c;return typeof t[o]=="function"&&((c=t[o])==null?void 0:c.toString().includes("[native code]"))}));if(r&&a&&!Zr())return Ee[n]=e.prototype,e.prototype;try{let o=document.createElement("iframe");document.body.appendChild(o);let c=o.contentWindow;if(!c)return e.prototype;let l=c[n].prototype;return document.body.removeChild(o),l?Ee[n]=l:t}catch{return t}}function U(n,e,t){var i;let r=`${n}.${String(t)}`;if(nt[r])return nt[r].call(e);let s=kt(n),a=(i=Object.getOwnPropertyDescriptor(s,t))==null?void 0:i.get;return a?(nt[r]=a,a.call(e)):e[t]}function ki(n,e,t){let i=`${n}.${String(t)}`;if(st[i])return st[i].bind(e);let s=kt(n)[t];return typeof s!="function"?e[t]:(st[i]=s,s.bind(e))}function en(n){return U("Node",n,"childNodes")}function tn(n){return U("Node",n,"parentNode")}function rn(n){return U("Node",n,"parentElement")}function nn(n){return U("Node",n,"textContent")}function sn(n,e){return ki("Node",n,"contains")(e)}function an(n){return ki("Node",n,"getRootNode")()}function on(n){return!n||!("host"in n)?null:U("ShadowRoot",n,"host")}function cn(n){return n.styleSheets}function ln(n){return!n||!("shadowRoot"in n)?null:U("Element",n,"shadowRoot")}function un(n,e){return U("Element",n,"querySelector")(e)}function hn(n,e){return U("Element",n,"querySelectorAll")(e)}function dn(){return kt("MutationObserver").constructor}function ze(n){return n.nodeType===n.ELEMENT_NODE}function xi(n){let e=n&&"host"in n&&"mode"in n&&k.host(n)||null;return!!(e&&"shadowRoot"in e&&k.shadowRoot(e)===n)}function De(n){return Object.prototype.toString.call(n)==="[object ShadowRoot]"}function fn(n){return n.includes(" background-clip: text;")&&!n.includes(" -webkit-background-clip: text;")&&(n=n.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),n}function Mi(n){let{cssText:e}=n;if(e.split('"').length<3)return e;let t=["@import",`url(${JSON.stringify(n.href)})`];return n.layerName===""?t.push("layer"):n.layerName&&t.push(`layer(${n.layerName})`),n.supportsText&&t.push(`supports(${n.supportsText})`),n.media.length&&t.push(n.media.mediaText),t.join(" ")+";"}function Ue(n){try{let e=n.rules||n.cssRules;if(!e)return null;let t=n.href;!t&&n.ownerNode&&n.ownerNode.ownerDocument&&(t=n.ownerNode.ownerDocument.location.href);let i=Array.from(e,r=>Pi(r,t)).join("");return fn(i)}catch{return null}}function Pi(n,e){if(_i(n)){let t;try{t=Ue(n.styleSheet)||Mi(n)}catch{t=n.cssText}return n.styleSheet.href?ae(t,n.styleSheet.href):t}else{let t=n.cssText;return Ri(n)&&n.selectorText.includes(":")&&(t=Ii(t)),e?ae(t,e):t}}function Ii(n){let e=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return n.replace(e,"$1\\$2")}function _i(n){return"styleSheet"in n}function Ri(n){return"selectorText"in n}function pn(){return new J}function Di({element:n,maskInputOptions:e,tagName:t,type:i,value:r,maskInputFn:s}){let a=r||"",o=i&&he(i);return(e[t.toLowerCase()]||o&&e[o])&&(s?a=s(a,n):a="*".repeat(a.length)),a}function he(n){return n.toLowerCase()}function Li(n){let e=n.getContext("2d");if(!e)return!0;let t=50;for(let i=0;i<n.width;i+=t)for(let r=0;r<n.height;r+=t){let s=e.getImageData,a=si in s?s[si]:s;if(new Uint32Array(a.call(e,i,r,Math.min(t,n.width-i),Math.min(t,n.height-r)).data.buffer).some(c=>c!==0))return!1}return!0}function Oi(n,e){return!n||!e||n.type!==e.type?!1:n.type===m.Document?n.compatMode===e.compatMode:n.type===m.DocumentType?n.name===e.name&&n.publicId===e.publicId&&n.systemId===e.systemId:n.type===m.Comment||n.type===m.Text||n.type===m.CDATA?n.textContent===e.textContent:n.type===m.Element?n.tagName===e.tagName&&JSON.stringify(n.attributes)===JSON.stringify(e.attributes)&&n.isSVG===e.isSVG&&n.needBlock===e.needBlock:!1}function Ni(n){let e=n.type;return n.hasAttribute("data-rr-is-password")?"password":e?he(e):null}function xt(n,e){let t;try{t=new URL(n,e??window.location.href)}catch{return null}let i=/\.([0-9a-z]+)(?:$)/i,r=t.pathname.match(i);return r?.[1]??null}function gn(n){let e="";return n.indexOf("//")>-1?e=n.split("/").slice(0,3).join("/"):e=n.split("/")[0],e=e.split("?")[0],e}function ae(n,e){return(n||"").replace(mn,(t,i,r,s,a,o)=>{let c=r||a||o,l=i||s||"";if(!c)return t;if(yn.test(c)||vn.test(c))return`url(${l}${c}${l})`;if(bn.test(c))return`url(${l}${c}${l})`;if(c[0]==="/")return`url(${l}${gn(e)+c}${l})`;let u=e.split("/"),d=c.split("/");u.pop();for(let f of d)f!=="."&&(f===".."?u.pop():u.push(f));return`url(${l}${u.join("/")}${l})`})}function Le(n){return n.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"")}function Ui(n,e){let t=Array.from(e.childNodes),i=[];if(t.length>1&&n&&typeof n=="string"){let r=Le(n);for(let s=1;s<t.length;s++)if(t[s].textContent&&typeof t[s].textContent=="string"){let a=Le(t[s].textContent);for(let o=3;o<a.length;o++){let c=a.substring(0,o);if(r.split(c).length===2){let l=r.indexOf(c);for(let u=l;u<n.length;u++)if(Le(n.substring(0,u)).length===l){i.push(n.substring(0,u)),n=n.substring(u);break}break}}}}return i.push(n),i}function $i(n,e){return Ui(n,e).join("/* rr_split */")}function Bi(){return Hi++}function Sn(n){if(n instanceof HTMLFormElement)return"form";let e=he(n.tagName);return wn.test(e)?"div":e}function Cn(n,e){if(e.trim()==="")return e;let t=0;function i(s){let a,o=s.exec(e.substring(t));return o?(a=o[0],t+=a.length,a):""}let r=[];for(;i(En),!(t>=e.length);){let s=i(An);if(s.slice(-1)===",")s=Q(n,s.substring(0,s.length-1)),r.push(s);else{let a="";s=Q(n,s);let o=!1;for(;;){let c=e.charAt(t);if(c===""){r.push((s+a).trim());break}else if(o)c===")"&&(o=!1);else if(c===","){t+=1,r.push((s+a).trim());break}else c==="("&&(o=!0);a+=c,t+=1}}}return r.join(", ")}function Q(n,e){return!e||e.trim()===""?e:Mt(n,e)}function Tn(n){return!!(n.tagName==="svg"||n.ownerSVGElement)}function Mt(n,e){let t=oi.get(n);if(t||(t=n.createElement("a"),oi.set(n,t)),!e)e="";else if(e.startsWith("blob:")||e.startsWith("data:"))return e;return t.setAttribute("href",e),t.href}function Fi(n,e,t,i){return i&&(t==="src"||t==="href"&&!(e==="use"&&i[0]==="#")||t==="xlink:href"&&i[0]!=="#"||t==="background"&&(e==="table"||e==="td"||e==="th")?Q(n,i):t==="srcset"?Cn(n,i):t==="style"?ae(i,Mt(n)):e==="object"&&t==="data"?Q(n,i):i)}function Gi(n,e,t){return(n==="video"||n==="audio")&&e==="autoplay"}function kn(n,e,t){try{if(typeof e=="string"){if(n.classList.contains(e))return!0}else for(let i=n.classList.length;i--;){let r=n.classList[i];if(e.test(r))return!0}if(t)return n.matches(t)}catch{}return!1}function $e(n,e,t){if(!n)return!1;if(n.nodeType!==n.ELEMENT_NODE)return t?$e(k.parentNode(n),e,t):!1;for(let i=n.classList.length;i--;){let r=n.classList[i];if(e.test(r))return!0}return t?$e(k.parentNode(n),e,t):!1}function zi(n,e,t,i){let r;if(ze(n)){if(r=n,!k.childNodes(r).length)return!1}else{if(k.parentElement(n)===null)return!1;r=k.parentElement(n)}try{if(typeof e=="string"){if(i){if(r.closest(`.${e}`))return!0}else if(r.classList.contains(e))return!0}else if($e(r,e,i))return!0;if(t){if(i){if(r.closest(t))return!0}else if(r.matches(t))return!0}}catch{}return!1}function xn(n,e,t){let i=n.contentWindow;if(!i)return;let r=!1,s;try{s=i.document.readyState}catch{return}if(s!=="complete"){let o=setTimeout(()=>{r||(e(),r=!0)},t);n.addEventListener("load",()=>{clearTimeout(o),r=!0,e()});return}let a="about:blank";if(i.location.href!==a||n.src===a||n.src==="")return setTimeout(e,0),n.addEventListener("load",e);n.addEventListener("load",e)}function Mn(n,e,t){let i=!1,r;try{r=n.sheet}catch{return}if(r)return;let s=setTimeout(()=>{i||(e(),i=!0)},t);n.addEventListener("load",()=>{clearTimeout(s),i=!0,e()})}function Pn(n,e){let{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:a,inlineStylesheet:o,maskInputOptions:c={},maskTextFn:l,maskInputFn:u,dataURLOptions:d={},inlineImages:f,recordCanvas:y,keepIframeSrcFn:g,newlyAddedElement:v=!1,cssCaptured:h=!1}=e,T=In(t,i);switch(n.nodeType){case n.DOCUMENT_NODE:return n.compatMode!=="CSS1Compat"?{type:m.Document,childNodes:[],compatMode:n.compatMode}:{type:m.Document,childNodes:[]};case n.DOCUMENT_TYPE_NODE:return{type:m.DocumentType,name:n.name,publicId:n.publicId,systemId:n.systemId,rootId:T};case n.ELEMENT_NODE:return Rn(n,{doc:t,blockClass:r,blockSelector:s,inlineStylesheet:o,maskInputOptions:c,maskInputFn:u,dataURLOptions:d,inlineImages:f,recordCanvas:y,keepIframeSrcFn:g,newlyAddedElement:v,rootId:T});case n.TEXT_NODE:return _n(n,{doc:t,needsMask:a,maskTextFn:l,rootId:T,cssCaptured:h});case n.CDATA_SECTION_NODE:return{type:m.CDATA,textContent:"",rootId:T};case n.COMMENT_NODE:return{type:m.Comment,textContent:k.textContent(n)||"",rootId:T};default:return!1}}function In(n,e){if(!e.hasNode(n))return;let t=e.getId(n);return t===1?void 0:t}function _n(n,e){let{needsMask:t,maskTextFn:i,rootId:r,cssCaptured:s}=e,a=k.parentNode(n),o=a&&a.tagName,c="",l=o==="STYLE"?!0:void 0,u=o==="SCRIPT"?!0:void 0;return u?c="SCRIPT_PLACEHOLDER":s||(c=k.textContent(n),l&&c&&(c=ae(c,Mt(e.doc)))),!l&&!u&&c&&t&&(c=i?i(c,k.parentElement(n)):c.replace(/[\S]/g,"*")),{type:m.Text,textContent:c||"",rootId:r}}function Rn(n,e){let{doc:t,blockClass:i,blockSelector:r,inlineStylesheet:s,maskInputOptions:a={},maskInputFn:o,dataURLOptions:c={},inlineImages:l,recordCanvas:u,keepIframeSrcFn:d,newlyAddedElement:f=!1,rootId:y}=e,g=kn(n,i,r),v=Sn(n),h={},T=n.attributes.length;for(let p=0;p<T;p++){let b=n.attributes[p];Gi(v,b.name,b.value)||(h[b.name]=Fi(t,v,he(b.name),b.value))}if(v==="link"&&s){let p=Array.from(t.styleSheets).find(M=>M.href===n.href),b=null;p&&(b=Ue(p)),b&&(delete h.rel,delete h.href,h._cssText=b)}if(v==="style"&&n.sheet){let p=Ue(n.sheet);p&&(n.childNodes.length>1&&(p=$i(p,n)),h._cssText=p)}if(v==="input"||v==="textarea"||v==="select"){let p=n.value,b=n.checked;h.type!=="radio"&&h.type!=="checkbox"&&h.type!=="submit"&&h.type!=="button"&&p?h.value=Di({element:n,type:Ni(n),tagName:v,value:p,maskInputOptions:a,maskInputFn:o}):b&&(h.checked=b)}if(v==="option"&&(n.selected&&!a.select?h.selected=!0:delete h.selected),v==="dialog"&&n.open&&(h.rr_open_mode=n.matches("dialog:modal")?"modal":"non-modal"),v==="canvas"&&u){if(n.__context==="2d")Li(n)||(h.rr_dataURL=n.toDataURL(c.type,c.quality));else if(!("__context"in n)){let p=n.toDataURL(c.type,c.quality),b=t.createElement("canvas");b.width=n.width,b.height=n.height;let M=b.toDataURL(c.type,c.quality);p!==M&&(h.rr_dataURL=p)}}if(v==="img"&&l){j||(j=t.createElement("canvas"),ai=j.getContext("2d"));let p=n,b=p.currentSrc||p.getAttribute("src")||"<unknown-src>",M=p.crossOrigin,I=()=>{p.removeEventListener("load",I);try{j.width=p.naturalWidth,j.height=p.naturalHeight,ai.drawImage(p,0,0),h.rr_dataURL=j.toDataURL(c.type,c.quality)}catch(B){if(p.crossOrigin!=="anonymous"){p.crossOrigin="anonymous",p.complete&&p.naturalWidth!==0?I():p.addEventListener("load",I);return}else console.warn(`Cannot inline img src=${b}! Error: ${B}`)}p.crossOrigin==="anonymous"&&(M?h.crossOrigin=M:p.removeAttribute("crossorigin"))};p.complete&&p.naturalWidth!==0?I():p.addEventListener("load",I)}if(v==="audio"||v==="video"){let p=h;p.rr_mediaState=n.paused?"paused":"played",p.rr_mediaCurrentTime=n.currentTime,p.rr_mediaPlaybackRate=n.playbackRate,p.rr_mediaMuted=n.muted,p.rr_mediaLoop=n.loop,p.rr_mediaVolume=n.volume}if(f||(n.scrollLeft&&(h.rr_scrollLeft=n.scrollLeft),n.scrollTop&&(h.rr_scrollTop=n.scrollTop)),g){let{width:p,height:b}=n.getBoundingClientRect();h={class:h.class,rr_width:`${p}px`,rr_height:`${b}px`}}v==="iframe"&&!d(h.src)&&(n.contentDocument||(h.rr_src=h.src),delete h.src);let x;try{customElements.get(v)&&(x=!0)}catch{}return{type:m.Element,tagName:v,attributes:h,childNodes:[],isSVG:Tn(n)||void 0,needBlock:g,rootId:y,isCustom:x}}function A(n){return n==null?"":n.toLowerCase()}function Dn(n,e){if(e.comment&&n.type===m.Comment)return!0;if(n.type===m.Element){if(e.script&&(n.tagName==="script"||n.tagName==="link"&&(n.attributes.rel==="preload"||n.attributes.rel==="modulepreload")&&n.attributes.as==="script"||n.tagName==="link"&&n.attributes.rel==="prefetch"&&typeof n.attributes.href=="string"&&xt(n.attributes.href)==="js"))return!0;if(e.headFavicon&&(n.tagName==="link"&&n.attributes.rel==="shortcut icon"||n.tagName==="meta"&&(A(n.attributes.name).match(/^msapplication-tile(image|color)$/)||A(n.attributes.name)==="application-name"||A(n.attributes.rel)==="icon"||A(n.attributes.rel)==="apple-touch-icon"||A(n.attributes.rel)==="shortcut icon")))return!0;if(n.tagName==="meta"){if(e.headMetaDescKeywords&&A(n.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(A(n.attributes.property).match(/^(og|twitter|fb):/)||A(n.attributes.name).match(/^(og|twitter):/)||A(n.attributes.name)==="pinterest"))return!0;if(e.headMetaRobots&&(A(n.attributes.name)==="robots"||A(n.attributes.name)==="googlebot"||A(n.attributes.name)==="bingbot"))return!0;if(e.headMetaHttpEquiv&&n.attributes["http-equiv"]!==void 0)return!0;if(e.headMetaAuthorship&&(A(n.attributes.name)==="author"||A(n.attributes.name)==="generator"||A(n.attributes.name)==="framework"||A(n.attributes.name)==="publisher"||A(n.attributes.name)==="progid"||A(n.attributes.property).match(/^article:/)||A(n.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(A(n.attributes.name)==="google-site-verification"||A(n.attributes.name)==="yandex-verification"||A(n.attributes.name)==="csrf-token"||A(n.attributes.name)==="p:domain_verify"||A(n.attributes.name)==="verify-v1"||A(n.attributes.name)==="verification"||A(n.attributes.name)==="shopify-checkout-api-token"))return!0}}return!1}function Y(n,e){let{doc:t,mirror:i,blockClass:r,blockSelector:s,maskTextClass:a,maskTextSelector:o,skipChild:c=!1,inlineStylesheet:l=!0,maskInputOptions:u={},maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g={},inlineImages:v=!1,recordCanvas:h=!1,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p=5e3,onStylesheetLoad:b,stylesheetLoadTimeout:M=5e3,keepIframeSrcFn:I=()=>!1,newlyAddedElement:B=!1,cssCaptured:O=!1}=e,{needsMask:_}=e,{preserveWhiteSpace:N=!0}=e;_||(_=zi(n,a,o,_===void 0));let te=Pn(n,{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:_,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,dataURLOptions:g,inlineImages:v,recordCanvas:h,keepIframeSrcFn:I,newlyAddedElement:B,cssCaptured:O});if(!te)return console.warn(n,"not serialized"),null;let ie;i.hasNode(n)?ie=i.getId(n):Dn(te,y)||!N&&te.type===m.Text&&!te.textContent.replace(/^\s+|\s+$/gm,"").length?ie=ut:ie=Bi();let S=Object.assign(te,{id:ie});if(i.add(n,S),ie===ut)return null;T&&T(n);let Je=!c;if(S.type===m.Element){Je=Je&&!S.needBlock,delete S.needBlock;let P=k.shadowRoot(n);P&&De(P)&&(S.isShadowHost=!0)}if((S.type===m.Document||S.type===m.Element)&&Je){y.headWhitespace&&S.type===m.Element&&S.tagName==="head"&&(N=!1);let P={doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:_,maskTextClass:a,maskTextSelector:o,skipChild:c,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g,inlineImages:v,recordCanvas:h,preserveWhiteSpace:N,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:I,cssCaptured:!1};if(!(S.type===m.Element&&S.tagName==="textarea"&&S.attributes.value!==void 0)){S.type===m.Element&&S.attributes._cssText!==void 0&&typeof S.attributes._cssText=="string"&&(P.cssCaptured=!0);for(let Xe of Array.from(k.childNodes(n))){let G=Y(Xe,P);G&&S.childNodes.push(G)}}let F=null;if(ze(n)&&(F=k.shadowRoot(n)))for(let Xe of Array.from(k.childNodes(F))){let G=Y(Xe,P);G&&(De(F)&&(G.isShadow=!0),S.childNodes.push(G))}}let qe=k.parentNode(n);return qe&&xi(qe)&&De(qe)&&(S.isShadow=!0),S.type===m.Element&&S.tagName==="iframe"&&xn(n,()=>{let P=n.contentDocument;if(P&&x){let F=Y(P,{doc:P,mirror:i,blockClass:r,blockSelector:s,needsMask:_,maskTextClass:a,maskTextSelector:o,skipChild:!1,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g,inlineImages:v,recordCanvas:h,preserveWhiteSpace:N,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:I});F&&x(n,F)}},p),S.type===m.Element&&S.tagName==="link"&&typeof S.attributes.rel=="string"&&(S.attributes.rel==="stylesheet"||S.attributes.rel==="preload"&&typeof S.attributes.href=="string"&&xt(S.attributes.href)==="css")&&Mn(n,()=>{if(b){let P=Y(n,{doc:t,mirror:i,blockClass:r,blockSelector:s,needsMask:_,maskTextClass:a,maskTextSelector:o,skipChild:!1,inlineStylesheet:l,maskInputOptions:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y,dataURLOptions:g,inlineImages:v,recordCanvas:h,preserveWhiteSpace:N,onSerialize:T,onIframeLoad:x,iframeLoadTimeout:p,onStylesheetLoad:b,stylesheetLoadTimeout:M,keepIframeSrcFn:I});P&&b(n,P)}},M),S}function Ln(n,e){let{mirror:t=new J,blockClass:i="rr-block",blockSelector:r=null,maskTextClass:s="rr-mask",maskTextSelector:a=null,inlineStylesheet:o=!0,inlineImages:c=!1,recordCanvas:l=!1,maskAllInputs:u=!1,maskTextFn:d,maskInputFn:f,slimDOM:y=!1,dataURLOptions:g,preserveWhiteSpace:v,onSerialize:h,onIframeLoad:T,iframeLoadTimeout:x,onStylesheetLoad:p,stylesheetLoadTimeout:b,keepIframeSrcFn:M=()=>!1}=e||{};return Y(n,{doc:n,mirror:t,blockClass:i,blockSelector:r,maskTextClass:s,maskTextSelector:a,skipChild:!1,inlineStylesheet:o,maskInputOptions:u===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:u===!1?{password:!0}:u,maskTextFn:d,maskInputFn:f,slimDOMOptions:y===!0||y==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:y==="all",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:y===!1?{}:y,dataURLOptions:g,inlineImages:c,recordCanvas:l,preserveWhiteSpace:v,onSerialize:h,onIframeLoad:T,iframeLoadTimeout:x,onStylesheetLoad:p,stylesheetLoadTimeout:b,keepIframeSrcFn:M,newlyAddedElement:!1})}function On(n,e){function t(i){e(i),(i.type===m.Document||i.type===m.Element)&&i.childNodes.forEach(t)}t(n)}function Nn(){Hi=1}function Bn(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function Fn(n){if(n.__esModule)return n;var e=n.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(n).forEach(function(i){var r=Object.getOwnPropertyDescriptor(n,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return n[i]}})}),t}function Kn(n){return n[0].toUpperCase()+n.slice(1)}function ft(n,e){new Wn(e).stringify(n)}function pt(n,e){let t=new n.constructor;for(let i in n){if(!Object.prototype.hasOwnProperty.call(n,i)||i==="proxyCache")continue;let r=n[i],s=typeof r;i==="parent"&&s==="object"?e&&(t[i]=e):i==="source"?t[i]=r:Array.isArray(r)?t[i]=r.map(a=>pt(a,t)):(s==="object"&&r!==null&&(r=pt(r)),t[i]=r)}return t}function ss(n){return Buffer?Buffer.from(n,"base64").toString():window.atob(n)}function sr(n){return n.map(e=>(e.nodes&&(e.nodes=sr(e.nodes)),delete e.source,e))}function ar(n){if(n[Zi]=!1,n.proxyOf.nodes)for(let e of n.proxyOf.nodes)ar(e)}function Us(n){for(let e=n.length-1;e>=0;e--){let t=n[e],i=t[3]||t[2];if(i)return i}}function Ge(n,e){let t=new Gs(n,e),i=new Fs(t);try{i.parse()}catch(r){throw r}return i.root}function se(n){return typeof n=="object"&&typeof n.then=="function"}function yr(n){let e=!1,t=Js[n.type];return n.type==="decl"?e=n.prop.toLowerCase():n.type==="atrule"&&(e=n.name.toLowerCase()),e&&n.append?[t,t+"-"+e,X,t+"Exit",t+"Exit-"+e]:e?[t,t+"-"+e,t+"Exit",t+"Exit-"+e]:n.append?[t,X,t+"Exit"]:[t,t+"Exit"]}function Ci(n){let e;return n.type==="document"?e=["Document",X,"DocumentExit"]:n.type==="root"?e=["Root",X,"RootExit"]:e=yr(n),{eventIndex:0,events:e,iterator:0,node:n,visitorIndex:0,visitors:[]}}function Et(n){return n[D]=!1,n.nodes&&n.nodes.forEach(e=>Et(e)),n}function ue(n,e){if(Array.isArray(n))return n.map(r=>ue(r));let{inputs:t,...i}=n;if(t){e=[];for(let r of t){let s={...r,__proto__:fa.prototype};s.map&&(s.map={...s.map,__proto__:ua.prototype}),e.push(s)}}if(i.nodes&&(i.nodes=n.nodes.map(r=>ue(r,e))),i.source){let{inputId:r,...s}=i.source;i.source=s,r!=null&&(i.source.input=e[r])}if(i.type==="root")return new pa(i);if(i.type==="decl")return new la(i);if(i.type==="rule")return new ga(i);if(i.type==="comment")return new ha(i);if(i.type==="atrule")return new da(i);throw new Error("Unknown node type: "+n.type)}function w(...n){return n.length===1&&Array.isArray(n[0])&&(n=n[0]),new $t(n)}function Pa(n){let e=Ti[n.tagName]?Ti[n.tagName]:n.tagName;return e==="link"&&n.attributes._cssText&&(e="style"),e}function Ye(n,e){let t=e?.stylesWithHoverClass.get(n);if(t)return t;let r=C([$n,Hn]).process(n).css;return e?.stylesWithHoverClass.set(n,r),r}function Ia(){return{stylesWithHoverClass:new Map}}function _a(n,e,t,i){let r=[];for(let a of n.childNodes)a.type===m.Text&&r.push(a);let s=e.split("/* rr_split */");for(;s.length>1&&s.length>r.length;)s.splice(-2,2,s.slice(-2).join(""));for(let a=0;a<r.length;a++){let o=r[a],c=s[a];o&&c&&(o.textContent=t?Ye(c,i):c)}}function Ra(n,e,t,i){let{doc:r,hackCss:s,cache:a}=i;n.childNodes.length?_a(n,t,s,a):(s&&(t=Ye(t,a)),e.appendChild(r.createTextNode(t)))}function Da(n,e){var t;let{doc:i,hackCss:r,cache:s}=e;switch(n.type){case m.Document:return i.implementation.createDocument(null,"",null);case m.DocumentType:return i.implementation.createDocumentType(n.name||"html",n.publicId,n.systemId);case m.Element:{let a=Pa(n),o;n.isSVG?o=i.createElementNS("http://www.w3.org/2000/svg",a):(n.isCustom&&((t=i.defaultView)!=null&&t.customElements)&&!i.defaultView.customElements.get(n.tagName)&&i.defaultView.customElements.define(n.tagName,class extends i.defaultView.HTMLElement{}),o=i.createElement(a));let c={};for(let l in n.attributes){if(!Object.prototype.hasOwnProperty.call(n.attributes,l))continue;let u=n.attributes[l];if(!(a==="option"&&l==="selected"&&u===!1)&&u!==null){if(u===!0&&(u=""),l.startsWith("rr_")){c[l]=u;continue}if(typeof u=="string"){if(a==="style"&&l==="_cssText"){Ra(n,o,u,e);continue}else if(a==="textarea"&&l==="value"){o.appendChild(i.createTextNode(u)),n.childNodes=[];continue}}try{if(n.isSVG&&l==="xlink:href")o.setAttributeNS("http://www.w3.org/1999/xlink",l,u.toString());else if(l==="onload"||l==="onclick"||l.substring(0,7)==="onmouse")o.setAttribute("_"+l,u.toString());else if(a==="meta"&&n.attributes["http-equiv"]==="Content-Security-Policy"&&l==="content"){o.setAttribute("csp-content",u.toString());continue}else a==="link"&&(n.attributes.rel==="preload"||n.attributes.rel==="modulepreload")&&n.attributes.as==="script"||a==="link"&&n.attributes.rel==="prefetch"&&typeof n.attributes.href=="string"&&n.attributes.href.endsWith(".js")||(a==="img"&&n.attributes.srcset&&n.attributes.rr_dataURL?o.setAttribute("rrweb-original-srcset",n.attributes.srcset):o.setAttribute(l,u.toString()))}catch{}}}for(let l in c){let u=c[l];if(a==="canvas"&&l==="rr_dataURL"){let d=i.createElement("img");d.onload=()=>{let f=o.getContext("2d");f&&f.drawImage(d,0,0,d.width,d.height)},d.src=u.toString(),o.RRNodeType&&(o.rr_dataURL=u.toString())}else if(a==="img"&&l==="rr_dataURL"){let d=o;d.currentSrc.startsWith("data:")||(d.setAttribute("rrweb-original-src",n.attributes.src),d.src=u.toString())}if(l==="rr_width")o.style.setProperty("width",u.toString());else if(l==="rr_height")o.style.setProperty("height",u.toString());else if(l==="rr_mediaCurrentTime"&&typeof u=="number")o.currentTime=u;else if(l==="rr_mediaState")switch(u){case"played":o.play().catch(d=>console.warn("media playback error",d));break;case"paused":o.pause();break}else l==="rr_mediaPlaybackRate"&&typeof u=="number"?o.playbackRate=u:l==="rr_mediaMuted"&&typeof u=="boolean"?o.muted=u:l==="rr_mediaLoop"&&typeof u=="boolean"?o.loop=u:l==="rr_mediaVolume"&&typeof u=="number"?o.volume=u:l==="rr_open_mode"&&o.setAttribute("rr_open_mode",u)}if(n.isShadowHost)if(!o.shadowRoot)o.attachShadow({mode:"open"});else for(;o.shadowRoot.firstChild;)o.shadowRoot.removeChild(o.shadowRoot.firstChild);return o}case m.Text:return n.isStyle&&r?i.createTextNode(Ye(n.textContent,s)):i.createTextNode(n.textContent);case m.CDATA:return i.createCDATASection(n.textContent);case m.Comment:return i.createComment(n.textContent);default:return null}}function Ht(n,e){let{doc:t,mirror:i,skipChild:r=!1,hackCss:s=!0,afterAppend:a,cache:o}=e;if(i.has(n.id)){let l=i.getNode(n.id),u=i.getMeta(l);if(Oi(u,n))return i.getNode(n.id)}let c=Da(n,{doc:t,hackCss:s,cache:o});if(!c)return null;if(n.rootId&&i.getNode(n.rootId)!==t&&i.replace(n.rootId,t),n.type===m.Document&&(t.close(),t.open(),n.compatMode==="BackCompat"&&n.childNodes&&n.childNodes[0].type!==m.DocumentType&&(n.childNodes[0].type===m.Element&&"xmlns"in n.childNodes[0].attributes&&n.childNodes[0].attributes.xmlns==="http://www.w3.org/1999/xhtml"?t.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">'):t.write('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "">')),c=t),i.add(c,n),(n.type===m.Document||n.type===m.Element)&&!r)for(let l of n.childNodes){let u=Ht(l,{doc:t,mirror:i,skipChild:!1,hackCss:s,afterAppend:a,cache:o});if(!u){console.warn("Failed to rebuild",l);continue}if(l.isShadow&&ze(c)&&c.shadowRoot)c.shadowRoot.appendChild(u);else if(n.type===m.Document&&l.type==m.Element){let d=u,f=null;d.childNodes.forEach(y=>{y.nodeName==="BODY"&&(f=y)}),f?(d.removeChild(f),c.appendChild(u),d.appendChild(f)):c.appendChild(u)}else c.appendChild(u);a&&a(u,l.id)}return c}function La(n,e){function t(i){e(i)}for(let i of n.getIds())n.has(i)&&t(n.getNode(i))}function Oa(n,e){let t=e.getMeta(n);if(t?.type!==m.Element)return;let i=n;for(let r in t.attributes){if(!(Object.prototype.hasOwnProperty.call(t.attributes,r)&&r.startsWith("rr_")))continue;let s=t.attributes[r];r==="rr_scrollLeft"&&(i.scrollLeft=s),r==="rr_scrollTop"&&(i.scrollTop=s)}}function Na(n,e){let{doc:t,onVisit:i,hackCss:r=!0,afterAppend:s,cache:a,mirror:o=new J}=e,c=Ht(n,{doc:t,mirror:o,skipChild:!1,hackCss:r,afterAppend:s,cache:a});return La(o,l=>{i&&i(l),Oa(l,o)}),c}var qr,Xr,ii,m,ri,ni,Ee,Zr,nt,st,k,J,si,mn,yn,vn,bn,Hi,wn,ut,j,ai,An,En,oi,Un,ci,$n,Hn,Pt,E,Vi,Gn,zn,Vn,R,li,ui,ht,It,de,hi,dt,Wi,Wn,Ve,Ce,jn,Qn,Yn,Jn,gt,Ke,qn,mt,We,Xn,Zn,es,ts,di,fi,is,rs,at,ns,yt,ji,as,os,pi,Te,vt,bt,cs,ot,gi,ls,ct,us,mi,He,je,Qi,Oe,Ne,Yi,Ji,qi,yi,hs,ds,fs,ps,Xi,gs,wt,Qe,Zi,er,tr,ir,ms,rr,_t,Rt,nr,L,H,ys,cr,lr,oe,Dt,St,ur,vs,At,Lt,lt,vi,ke,bi,xe,ne,Me,Pe,Ie,bs,ws,Ss,As,Es,Cs,Ts,ks,xs,Ms,_e,Re,Ps,wi,Is,hr,Be,Ot,dr,fr,pr,q,fe,ce,gr,mr,_s,Fe,Nt,Rs,Ds,Ls,Os,Ns,Si,Ai,$s,Hs,Bs,Fs,Gs,Ut,D,zs,Vs,Ks,Ws,js,Ei,Qs,Ys,Js,qs,Xs,X,Ct,Z,br,Zs,ea,ta,ia,Tt,ra,na,sa,aa,oa,le,ca,la,ua,ha,da,fa,pa,ga,ma,ya,wr,va,ba,$t,wa,Sa,Sr,Aa,Ar,Er,Ea,Ca,Ta,ka,Cr,Tr,xa,Ma,C,Ti,xr=$(()=>{qr=Object.defineProperty,Xr=(n,e,t)=>e in n?qr(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ii=(n,e,t)=>Xr(n,typeof e!="symbol"?e+"":e,t),m=(n=>(n[n.Document=0]="Document",n[n.DocumentType=1]="DocumentType",n[n.Element=2]="Element",n[n.Text=3]="Text",n[n.CDATA=4]="CDATA",n[n.Comment=5]="Comment",n))(m||{}),ri={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},ni={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Ee={},Zr=()=>!!globalThis.Zone;nt={};st={};k={childNodes:en,parentNode:tn,parentElement:rn,textContent:nn,contains:sn,getRootNode:an,host:on,styleSheets:cn,shadowRoot:ln,querySelector:un,querySelectorAll:hn,mutationObserver:dn};J=class{constructor(){ii(this,"idNodeMap",new Map),ii(this,"nodeMetaMap",new WeakMap)}getId(e){var t;return e?((t=this.getMeta(e))==null?void 0:t.id)??-1:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){let t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(i=>this.removeNodeFromMap(i))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){let i=t.id;this.idNodeMap.set(i,e),this.nodeMetaMap.set(e,t)}replace(e,t){let i=this.getNode(e);if(i){let r=this.nodeMetaMap.get(i);r&&this.nodeMetaMap.set(t,r)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}};si="__rrweb_original__";mn=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,yn=/^(?:[a-z+]+:)?\/\//i,vn=/^www\..*/i,bn=/^(data:)([^,]*),(.*)/i;Hi=1,wn=new RegExp("[^a-z0-9-_:]"),ut=-2;An=/^[^ \t\n\r\u000c]+/,En=/^[, \t\n\r\u000c]+/;oi=new WeakMap;Un=/(max|min)-device-(width|height)/,ci=new RegExp(Un.source,"g"),$n={postcssPlugin:"postcss-custom-selectors",prepare(){return{postcssPlugin:"postcss-custom-selectors",AtRule:function(n){n.params.match(ci)&&(n.params=n.params.replace(ci,"$1-$2"))}}}},Hn={postcssPlugin:"postcss-hover-classes",prepare:function(){let n=[];return{Rule:function(e){n.indexOf(e)===-1&&(n.push(e),e.selectors.forEach(function(t){t.includes(":hover")&&(e.selector+=`,
3
3
  `+t.replace(/:hover/g,".\\:hover"))}))}}}};Pt={exports:{}},E=String,Vi=function(){return{isColorSupported:!1,reset:E,bold:E,dim:E,italic:E,underline:E,inverse:E,hidden:E,strikethrough:E,black:E,red:E,green:E,yellow:E,blue:E,magenta:E,cyan:E,white:E,gray:E,bgBlack:E,bgRed:E,bgGreen:E,bgYellow:E,bgBlue:E,bgMagenta:E,bgCyan:E,bgWhite:E}};Pt.exports=Vi();Pt.exports.createColors=Vi;Gn=Pt.exports,zn={},Vn=Object.freeze(Object.defineProperty({__proto__:null,default:zn},Symbol.toStringTag,{value:"Module"})),R=Fn(Vn),li=Gn,ui=R,ht=class Ki extends Error{constructor(e,t,i,r,s,a){super(e),this.name="CssSyntaxError",this.reason=e,s&&(this.file=s),r&&(this.source=r),a&&(this.plugin=a),typeof t<"u"&&typeof i<"u"&&(typeof t=="number"?(this.line=t,this.column=i):(this.line=t.line,this.column=t.column,this.endLine=i.line,this.endColumn=i.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,Ki)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"<css input>",typeof this.line<"u"&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;e==null&&(e=li.isColorSupported),ui&&e&&(t=ui(t));let i=t.split(/\r?\n/),r=Math.max(this.line-3,0),s=Math.min(this.line+2,i.length),a=String(s).length,o,c;if(e){let{bold:l,gray:u,red:d}=li.createColors(!0);o=f=>l(d(f)),c=f=>u(f)}else o=c=l=>l;return i.slice(r,s).map((l,u)=>{let d=r+1+u,f=" "+(" "+d).slice(-a)+" | ";if(d===this.line){let y=c(f.replace(/\d/g," "))+l.slice(0,this.column-1).replace(/[^\t]/g," ");return o(">")+c(f)+l+`
4
4
  `+y+o("^")}return" "+c(f)+l}).join(`
@@ -25,7 +25,7 @@
25
25
  `),t=o.length-a):t+=o.length,c&&l!=="start"){let u=c.parent||{raws:{}};(!(c.type==="decl"||c.type==="atrule"&&!c.nodes)||c!==u.last||u.raws.semicolon)&&(c.source&&c.source.end?(r.source=this.sourcePath(c),r.original.line=c.source.end.line,r.original.column=c.source.end.column-1,r.generated.line=e,r.generated.column=t-2,this.map.addMapping(r)):(r.source=i,r.original.line=1,r.original.column=0,r.generated.line=e,r.generated.column=t-1,this.map.addMapping(r)))}})}isAnnotation(){return this.isInline()?!0:typeof this.mapOpts.annotation<"u"?this.mapOpts.annotation:this.previous().length?this.previous().some(e=>e.annotation):!0}isInline(){if(typeof this.mapOpts.inline<"u")return this.mapOpts.inline;let e=this.mapOpts.annotation;return typeof e<"u"&&e!==!0?!1:this.previous().length?this.previous().some(t=>t.inline):!0}isMap(){return typeof this.opts.map<"u"?!!this.opts.map:this.previous().length>0}isSourcesContent(){return typeof this.mapOpts.sourcesContent<"u"?this.mapOpts.sourcesContent:this.previous().length?this.previous().some(e=>e.withContent()):!0}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute||e.charCodeAt(0)===60||/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let i=this.opts.to?Ne(this.opts.to):".";typeof this.mapOpts.annotation=="string"&&(i=Ne(Ji(i,this.mapOpts.annotation)));let r=Yi(i,e);return this.memoizedPaths.set(e,r),r}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new hs(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let i=t.source.input.from;if(i&&!e[i]){e[i]=!0;let r=this.usesFileUrls?this.toFileUrl(i):this.toUrl(this.path(i));this.map.setSourceContent(r,t.source.input.css)}}});else if(this.css){let t=this.opts.from?this.toUrl(this.path(this.opts.from)):"<no source>";this.map.setSourceContent(t,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(yi){let i=yi(e).toString();return this.memoizedFileURLs.set(e,i),i}else throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;qi==="\\"&&(e=e.replace(/\\/g,"/"));let i=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,i),i}},Xi=ps,gs=Ke,wt=class extends gs{constructor(e){super(e),this.type="comment"}},Qe=wt;wt.default=wt;({isClean:Zi,my:er}=de),tr=We,ir=Qe,ms=Ke;L=class or extends ms{append(...e){for(let t of e){let i=this.normalize(t,this.last);for(let r of i)this.proxyOf.nodes.push(r)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t=this.getIterator(),i,r;for(;this.indexes[t]<this.proxyOf.nodes.length&&(i=this.indexes[t],r=e(this.proxyOf.nodes[i],i),r!==!1);)this.indexes[t]+=1;return delete this.indexes[t],r}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,t){return t==="proxyOf"?e:e[t]?t==="each"||typeof t=="string"&&t.startsWith("walk")?(...i)=>e[t](...i.map(r=>typeof r=="function"?(s,a)=>r(s.toProxy(),a):r)):t==="every"||t==="some"?i=>e[t]((r,...s)=>i(r.toProxy(),...s)):t==="root"?()=>e.root().toProxy():t==="nodes"?e.nodes.map(i=>i.toProxy()):t==="first"||t==="last"?e[t].toProxy():e[t]:e[t]},set(e,t,i){return e[t]===i||(e[t]=i,(t==="name"||t==="params"||t==="selector")&&e.markDirty()),!0}}}index(e){return typeof e=="number"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let i=this.index(e),r=this.normalize(t,this.proxyOf.nodes[i]).reverse();i=this.index(e);for(let a of r)this.proxyOf.nodes.splice(i+1,0,a);let s;for(let a in this.indexes)s=this.indexes[a],i<s&&(this.indexes[a]=s+r.length);return this.markDirty(),this}insertBefore(e,t){let i=this.index(e),r=i===0?"prepend":!1,s=this.normalize(t,this.proxyOf.nodes[i],r).reverse();i=this.index(e);for(let o of s)this.proxyOf.nodes.splice(i,0,o);let a;for(let o in this.indexes)a=this.indexes[o],i<=a&&(this.indexes[o]=a+s.length);return this.markDirty(),this}normalize(e,t){if(typeof e=="string")e=sr(rr(e).nodes);else if(typeof e>"u")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let r of e)r.parent&&r.parent.removeChild(r,"ignore")}else if(e.type==="root"&&this.type!=="document"){e=e.nodes.slice(0);for(let r of e)r.parent&&r.parent.removeChild(r,"ignore")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value>"u")throw new Error("Value field is missed in node creation");typeof e.value!="string"&&(e.value=String(e.value)),e=[new tr(e)]}else if(e.selector)e=[new _t(e)];else if(e.name)e=[new Rt(e)];else if(e.text)e=[new ir(e)];else throw new Error("Unknown node type in node creation");return e.map(r=>(r[er]||or.rebuild(r),r=r.proxyOf,r.parent&&r.parent.removeChild(r),r[Zi]&&ar(r),typeof r.raws.before>"u"&&t&&typeof t.raws.before<"u"&&(r.raws.before=t.raws.before.replace(/\S/g,"")),r.parent=this.proxyOf,r))}prepend(...e){e=e.reverse();for(let t of e){let i=this.normalize(t,this.first,"prepend").reverse();for(let r of i)this.proxyOf.nodes.unshift(r);for(let r in this.indexes)this.indexes[r]=this.indexes[r]+i.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let t;for(let i in this.indexes)t=this.indexes[i],t>=e&&(this.indexes[i]=t-1);return this.markDirty(),this}replaceValues(e,t,i){return i||(i=t,t={}),this.walkDecls(r=>{t.props&&!t.props.includes(r.prop)||t.fast&&!r.value.includes(t.fast)||(r.value=r.value.replace(e,i))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,i)=>{let r;try{r=e(t,i)}catch(s){throw t.addToError(s)}return r!==!1&&t.walk&&(r=t.walk(e)),r})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((i,r)=>{if(i.type==="atrule"&&e.test(i.name))return t(i,r)}):this.walk((i,r)=>{if(i.type==="atrule"&&i.name===e)return t(i,r)}):(t=e,this.walk((i,r)=>{if(i.type==="atrule")return t(i,r)}))}walkComments(e){return this.walk((t,i)=>{if(t.type==="comment")return e(t,i)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((i,r)=>{if(i.type==="decl"&&e.test(i.prop))return t(i,r)}):this.walk((i,r)=>{if(i.type==="decl"&&i.prop===e)return t(i,r)}):(t=e,this.walk((i,r)=>{if(i.type==="decl")return t(i,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((i,r)=>{if(i.type==="rule"&&e.test(i.selector))return t(i,r)}):this.walk((i,r)=>{if(i.type==="rule"&&i.selector===e)return t(i,r)}):(t=e,this.walk((i,r)=>{if(i.type==="rule")return t(i,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};L.registerParse=n=>{rr=n};L.registerRule=n=>{_t=n};L.registerAtRule=n=>{Rt=n};L.registerRoot=n=>{nr=n};H=L;L.default=L;L.rebuild=n=>{n.type==="atrule"?Object.setPrototypeOf(n,Rt.prototype):n.type==="rule"?Object.setPrototypeOf(n,_t.prototype):n.type==="decl"?Object.setPrototypeOf(n,tr.prototype):n.type==="comment"?Object.setPrototypeOf(n,ir.prototype):n.type==="root"&&Object.setPrototypeOf(n,nr.prototype),n[er]=!0,n.nodes&&n.nodes.forEach(e=>{L.rebuild(e)})};ys=H,oe=class extends ys{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new cr(new lr,this,e).stringify()}};oe.registerLazyResult=n=>{cr=n};oe.registerProcessor=n=>{lr=n};Dt=oe;oe.default=oe;St=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let i=t.node.rangeBy(t);this.line=i.start.line,this.column=i.start.column,this.endLine=i.end.line,this.endColumn=i.end.column}for(let i in t)this[i]=t[i]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}},ur=St;St.default=St;vs=ur,At=class{constructor(e,t,i){this.processor=e,this.messages=[],this.root=t,this.opts=i,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let i=new vs(e,t);return this.messages.push(i),i}warnings(){return this.messages.filter(e=>e.type==="warning")}get content(){return this.css}},Lt=At;At.default=At;lt=39,vi=34,ke=92,bi=47,xe=10,ne=32,Me=12,Pe=9,Ie=13,bs=91,ws=93,Ss=40,As=41,Es=123,Cs=125,Ts=59,ks=42,xs=58,Ms=64,_e=/[\t\n\f\r "#'()/;[\\\]{}]/g,Re=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Ps=/.[\r\n"'(/\\]/,wi=/[\da-f]/i,Is=function(e,t={}){let i=e.css.valueOf(),r=t.ignoreErrors,s,a,o,c,l,u,d,f,y,g,v=i.length,h=0,T=[],x=[];function p(){return h}function b(O){throw e.error("Unclosed "+O,h)}function M(){return x.length===0&&h>=v}function I(O){if(x.length)return x.pop();if(h>=v)return;let _=O?O.ignoreUnclosed:!1;switch(s=i.charCodeAt(h),s){case xe:case ne:case Pe:case Ie:case Me:{a=h;do a+=1,s=i.charCodeAt(a);while(s===ne||s===xe||s===Pe||s===Ie||s===Me);g=["space",i.slice(h,a)],h=a-1;break}case bs:case ws:case Es:case Cs:case xs:case Ts:case As:{let N=String.fromCharCode(s);g=[N,N,h];break}case Ss:{if(f=T.length?T.pop()[1]:"",y=i.charCodeAt(h+1),f==="url"&&y!==lt&&y!==vi&&y!==ne&&y!==xe&&y!==Pe&&y!==Me&&y!==Ie){a=h;do{if(u=!1,a=i.indexOf(")",a+1),a===-1)if(r||_){a=h;break}else b("bracket");for(d=a;i.charCodeAt(d-1)===ke;)d-=1,u=!u}while(u);g=["brackets",i.slice(h,a+1),h,a],h=a}else a=i.indexOf(")",h+1),c=i.slice(h,a+1),a===-1||Ps.test(c)?g=["(","(",h]:(g=["brackets",c,h,a],h=a);break}case lt:case vi:{o=s===lt?"'":'"',a=h;do{if(u=!1,a=i.indexOf(o,a+1),a===-1)if(r||_){a=h+1;break}else b("string");for(d=a;i.charCodeAt(d-1)===ke;)d-=1,u=!u}while(u);g=["string",i.slice(h,a+1),h,a],h=a;break}case Ms:{_e.lastIndex=h+1,_e.test(i),_e.lastIndex===0?a=i.length-1:a=_e.lastIndex-2,g=["at-word",i.slice(h,a+1),h,a],h=a;break}case ke:{for(a=h,l=!0;i.charCodeAt(a+1)===ke;)a+=1,l=!l;if(s=i.charCodeAt(a+1),l&&s!==bi&&s!==ne&&s!==xe&&s!==Pe&&s!==Ie&&s!==Me&&(a+=1,wi.test(i.charAt(a)))){for(;wi.test(i.charAt(a+1));)a+=1;i.charCodeAt(a+1)===ne&&(a+=1)}g=["word",i.slice(h,a+1),h,a],h=a;break}default:{s===bi&&i.charCodeAt(h+1)===ks?(a=i.indexOf("*/",h+2)+1,a===0&&(r||_?a=i.length:b("comment")),g=["comment",i.slice(h,a+1),h,a],h=a):(Re.lastIndex=h+1,Re.test(i),Re.lastIndex===0?a=i.length-1:a=Re.lastIndex-2,g=["word",i.slice(h,a+1),h,a],T.push(g),h=a);break}}return h++,g}function B(O){x.push(O)}return{back:B,endOfFile:M,nextToken:I,position:p}},hr=H,Be=class extends hr{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}},Ot=Be;Be.default=Be;hr.registerAtRule(Be);dr=H,q=class extends dr{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,i){let r=super.normalize(e);if(t){if(i==="prepend")this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let s of r)s.raws.before=t.raws.before}return r}removeChild(e,t){let i=this.index(e);return!t&&i===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[i].raws.before),super.removeChild(e)}toResult(e={}){return new fr(new pr,this,e).stringify()}};q.registerLazyResult=n=>{fr=n};q.registerProcessor=n=>{pr=n};fe=q;q.default=q;dr.registerRoot(q);ce={comma(n){return ce.split(n,[","],!0)},space(n){let e=[" ",`
26
26
  `," "];return ce.split(n,e)},split(n,e,t){let i=[],r="",s=!1,a=0,o=!1,c="",l=!1;for(let u of n)l?l=!1:u==="\\"?l=!0:o?u===c&&(o=!1):u==='"'||u==="'"?(o=!0,c=u):u==="("?a+=1:u===")"?a>0&&(a-=1):a===0&&e.includes(u)&&(s=!0),s?(r!==""&&i.push(r.trim()),r="",s=!1):r+=u;return(t||r!=="")&&i.push(r.trim()),i}},gr=ce;ce.default=ce;mr=H,_s=gr,Fe=class extends mr{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return _s.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,i=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(i)}},Nt=Fe;Fe.default=Fe;mr.registerRule(Fe);Rs=We,Ds=Is,Ls=Qe,Os=Ot,Ns=fe,Si=Nt,Ai={empty:!0,space:!0};$s=class{constructor(e){this.input=e,this.root=new Ns,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t=new Os;t.name=e[1].slice(1),t.name===""&&this.unnamedAtrule(t,e),this.init(t,e[2]);let i,r,s,a=!1,o=!1,c=[],l=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),i=e[0],i==="("||i==="["?l.push(i==="("?")":"]"):i==="{"&&l.length>0?l.push("}"):i===l[l.length-1]&&l.pop(),l.length===0)if(i===";"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(i==="{"){o=!0;break}else if(i==="}"){if(c.length>0){for(s=c.length-1,r=c[s];r&&r[0]==="space";)r=c[--s];r&&(t.source.end=this.getPosition(r[3]||r[2]),t.source.end.offset++)}this.end(e);break}else c.push(e);else c.push(e);if(this.tokenizer.endOfFile()){a=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(c),c.length?(t.raws.afterName=this.spacesAndCommentsFromStart(c),this.raw(t,"params",c),a&&(e=c[c.length-1],t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++,this.spaces=t.raws.between,t.raws.between="")):(t.raws.afterName="",t.params=""),o&&(t.nodes=[],this.current=t)}checkMissedSemicolon(e){let t=this.colon(e);if(t===!1)return;let i=0,r;for(let s=t-1;s>=0&&(r=e[s],!(r[0]!=="space"&&(i+=1,i===2)));s--);throw this.input.error("Missed semicolon",r[0]==="word"?r[3]+1:r[2])}colon(e){let t=0,i,r,s;for(let[a,o]of e.entries()){if(i=o,r=i[0],r==="("&&(t+=1),r===")"&&(t-=1),t===0&&r===":")if(!s)this.doubleColon(i);else{if(s[0]==="word"&&s[1]==="progid")continue;return a}s=i}return!1}comment(e){let t=new Ls;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let i=e[1].slice(2,-2);if(/^\s*$/.test(i))t.text="",t.raws.left=i,t.raws.right="";else{let r=i.match(/^(\s*)([^]*\S)(\s*)$/);t.text=r[2],t.raws.left=r[1],t.raws.right=r[3]}}createTokenizer(){this.tokenizer=Ds(this.input)}decl(e,t){let i=new Rs;this.init(i,e[0][2]);let r=e[e.length-1];for(r[0]===";"&&(this.semicolon=!0,e.pop()),i.source.end=this.getPosition(r[3]||r[2]||Us(e)),i.source.end.offset++;e[0][0]!=="word";)e.length===1&&this.unknownWord(e),i.raws.before+=e.shift()[1];for(i.source.start=this.getPosition(e[0][2]),i.prop="";e.length;){let l=e[0][0];if(l===":"||l==="space"||l==="comment")break;i.prop+=e.shift()[1]}i.raws.between="";let s;for(;e.length;)if(s=e.shift(),s[0]===":"){i.raws.between+=s[1];break}else s[0]==="word"&&/\w/.test(s[1])&&this.unknownWord([s]),i.raws.between+=s[1];(i.prop[0]==="_"||i.prop[0]==="*")&&(i.raws.before+=i.prop[0],i.prop=i.prop.slice(1));let a=[],o;for(;e.length&&(o=e[0][0],!(o!=="space"&&o!=="comment"));)a.push(e.shift());this.precheckMissedSemicolon(e);for(let l=e.length-1;l>=0;l--){if(s=e[l],s[1].toLowerCase()==="!important"){i.important=!0;let u=this.stringFrom(e,l);u=this.spacesFromEnd(e)+u,u!==" !important"&&(i.raws.important=u);break}else if(s[1].toLowerCase()==="important"){let u=e.slice(0),d="";for(let f=l;f>0;f--){let y=u[f][0];if(d.trim().indexOf("!")===0&&y!=="space")break;d=u.pop()[1]+d}d.trim().indexOf("!")===0&&(i.important=!0,i.raws.important=d,e=u)}if(s[0]!=="space"&&s[0]!=="comment")break}e.some(l=>l[0]!=="space"&&l[0]!=="comment")&&(i.raws.between+=a.map(l=>l[1]).join(""),a=[]),this.raw(i,"value",a.concat(e),t),i.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Si;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let t=this.current.nodes[this.current.nodes.length-1];t&&t.type==="rule"&&!t.raws.ownSemicolon&&(t.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="",e.type!=="comment"&&(this.semicolon=!1)}other(e){let t=!1,i=null,r=!1,s=null,a=[],o=e[1].startsWith("--"),c=[],l=e;for(;l;){if(i=l[0],c.push(l),i==="("||i==="[")s||(s=l),a.push(i==="("?")":"]");else if(o&&r&&i==="{")s||(s=l),a.push("}");else if(a.length===0)if(i===";")if(r){this.decl(c,o);return}else break;else if(i==="{"){this.rule(c);return}else if(i==="}"){this.tokenizer.back(c.pop()),t=!0;break}else i===":"&&(r=!0);else i===a[a.length-1]&&(a.pop(),a.length===0&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),a.length>0&&this.unclosedBracket(s),t&&r){if(!o)for(;c.length&&(l=c[c.length-1][0],!(l!=="space"&&l!=="comment"));)this.tokenizer.back(c.pop());this.decl(c,o)}else this.unknownWord(c)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e);break}this.endFile()}precheckMissedSemicolon(){}raw(e,t,i,r){let s,a,o=i.length,c="",l=!0,u,d;for(let f=0;f<o;f+=1)s=i[f],a=s[0],a==="space"&&f===o-1&&!r?l=!1:a==="comment"?(d=i[f-1]?i[f-1][0]:"empty",u=i[f+1]?i[f+1][0]:"empty",!Ai[d]&&!Ai[u]?c.slice(-1)===","?l=!1:c+=s[1]:l=!1):c+=s[1];if(!l){let f=i.reduce((y,g)=>y+g[1],"");e.raws[t]={raw:f,value:c}}e[t]=c}rule(e){e.pop();let t=new Si;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,i="";for(;e.length&&(t=e[e.length-1][0],!(t!=="space"&&t!=="comment"));)i=e.pop()[1]+i;return i}spacesAndCommentsFromStart(e){let t,i="";for(;e.length&&(t=e[0][0],!(t!=="space"&&t!=="comment"));)i+=e.shift()[1];return i}spacesFromEnd(e){let t,i="";for(;e.length&&(t=e[e.length-1][0],t==="space");)i=e.pop()[1]+i;return i}stringFrom(e,t){let i="";for(let r=t;r<e.length;r++)i+=e[r][1];return e.splice(t,e.length-t),i}unclosedBlock(){let e=this.current.source.start;throw this.input.error("Unclosed block",e.line,e.column)}unclosedBracket(e){throw this.input.error("Unclosed bracket",{offset:e[2]},{offset:e[2]+1})}unexpectedClose(e){throw this.input.error("Unexpected }",{offset:e[2]},{offset:e[2]+1})}unknownWord(e){throw this.input.error("Unknown word",{offset:e[0][2]},{offset:e[0][2]+e[0][1].length})}unnamedAtrule(e,t){throw this.input.error("At-rule without name",{offset:t[2]},{offset:t[2]+t[1].length})}},Hs=$s,Bs=H,Fs=Hs,Gs=je;Ut=Ge;Ge.default=Ge;Bs.registerParse(Ge);({isClean:D,my:zs}=de),Vs=Xi,Ks=Ve,Ws=H,js=Dt,Ei=Lt,Qs=Ut,Ys=fe,Js={atrule:"AtRule",comment:"Comment",decl:"Declaration",document:"Document",root:"Root",rule:"Rule"},qs={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Xs={Once:!0,postcssPlugin:!0,prepare:!0},X=0;Ct={},Z=class vr{constructor(e,t,i){this.stringified=!1,this.processed=!1;let r;if(typeof t=="object"&&t!==null&&(t.type==="root"||t.type==="document"))r=Et(t);else if(t instanceof vr||t instanceof Ei)r=Et(t.root),t.map&&(typeof i.map>"u"&&(i.map={}),i.map.inline||(i.map.inline=!1),i.map.prev=t.map);else{let s=Qs;i.syntax&&(s=i.syntax.parse),i.parser&&(s=i.parser),s.parse&&(s=s.parse);try{r=s(t,i)}catch(a){this.processed=!0,this.error=a}r&&!r[zs]&&Ws.rebuild(r)}this.result=new Ei(e,r,i),this.helpers={...Ct,postcss:Ct,result:this.result},this.plugins=this.processor.plugins.map(s=>typeof s=="object"&&s.prepare?{...s,...s.prepare(this.result)}:s)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let i=this.result.lastPlugin;try{t&&t.addToError(e),this.error=e,e.name==="CssSyntaxError"&&!e.plugin?(e.plugin=i.postcssPlugin,e.setMessage()):i.postcssVersion}catch(r){console&&console.error&&console.error(r)}return e}prepareVisitors(){this.listeners={};let e=(t,i,r)=>{this.listeners[i]||(this.listeners[i]=[]),this.listeners[i].push([t,r])};for(let t of this.plugins)if(typeof t=="object")for(let i in t){if(!qs[i]&&/^[A-Z]/.test(i))throw new Error(`Unknown event ${i} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Xs[i])if(typeof t[i]=="object")for(let r in t[i])r==="*"?e(t,i,t[i][r]):e(t,i+"-"+r.toLowerCase(),t[i][r]);else typeof t[i]=="function"&&e(t,i,t[i])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e<this.plugins.length;e++){let t=this.plugins[e],i=this.runOnRoot(t);if(se(i))try{await i}catch(r){throw this.handleError(r)}}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[D];){e[D]=!0;let t=[Ci(e)];for(;t.length>0;){let i=this.visitTick(t);if(se(i))try{await i}catch(r){let s=t[t.length-1].node;throw this.handleError(r,s)}}}if(this.listeners.OnceExit)for(let[t,i]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if(e.type==="document"){let r=e.nodes.map(s=>i(s,this.helpers));await Promise.all(r)}else await i(e,this.helpers)}catch(r){throw this.handleError(r)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if(typeof e=="object"&&e.Once){if(this.result.root.type==="document"){let t=this.result.root.nodes.map(i=>e.Once(i,this.helpers));return se(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}else if(typeof e=="function")return e(this.result.root,this.result)}catch(t){throw this.handleError(t)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=Ks;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new Vs(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){let t=this.runOnRoot(e);if(se(t))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[D];)e[D]=!0,this.walkSync(e);if(this.listeners.OnceExit)if(e.type==="document")for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[i,r]of e){this.result.lastPlugin=i;let s;try{s=r(t,this.helpers)}catch(a){throw this.handleError(a,t.proxyOf)}if(t.type!=="root"&&t.type!=="document"&&!t.parent)return!0;if(se(s))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:i,visitors:r}=t;if(i.type!=="root"&&i.type!=="document"&&!i.parent){e.pop();return}if(r.length>0&&t.visitorIndex<r.length){let[a,o]=r[t.visitorIndex];t.visitorIndex+=1,t.visitorIndex===r.length&&(t.visitors=[],t.visitorIndex=0),this.result.lastPlugin=a;try{return o(i.toProxy(),this.helpers)}catch(c){throw this.handleError(c,i)}}if(t.iterator!==0){let a=t.iterator,o;for(;o=i.nodes[i.indexes[a]];)if(i.indexes[a]+=1,!o[D]){o[D]=!0,e.push(Ci(o));return}t.iterator=0,delete i.indexes[a]}let s=t.events;for(;t.eventIndex<s.length;){let a=s[t.eventIndex];if(t.eventIndex+=1,a===X){i.nodes&&i.nodes.length&&(i[D]=!0,t.iterator=i.getIterator());return}else if(this.listeners[a]){t.visitors=this.listeners[a];return}}e.pop()}walkSync(e){e[D]=!0;let t=yr(e);for(let i of t)if(i===X)e.nodes&&e.each(r=>{r[D]||this.walkSync(r)});else{let r=this.listeners[i];if(r&&this.visitSync(r,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Z.registerPostcss=n=>{Ct=n};br=Z;Z.default=Z;Ys.registerLazyResult(Z);js.registerLazyResult(Z);Zs=Xi,ea=Ve,ta=Ut,ia=Lt,Tt=class{constructor(e,t,i){t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=i,this._map=void 0;let r,s=ea;this.result=new ia(this._processor,r,this._opts),this.result.css=t;let a=this;Object.defineProperty(this.result,"root",{get(){return a.root}});let o=new Zs(s,r,this._opts,t);if(o.isMap()){let[c,l]=o.generate();c&&(this.result.css=c),l&&(this.result.map=l)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=ta;try{e=t(this._css,this._opts)}catch(i){this.error=i}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}},ra=Tt;Tt.default=Tt;na=ra,sa=br,aa=Dt,oa=fe,le=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let i of e)if(i.postcss===!0?i=i():i.postcss&&(i=i.postcss),typeof i=="object"&&Array.isArray(i.plugins))t=t.concat(i.plugins);else if(typeof i=="object"&&i.postcssPlugin)t.push(i);else if(typeof i=="function")t.push(i);else if(!(typeof i=="object"&&(i.parse||i.stringify)))throw new Error(i+" is not a PostCSS plugin");return t}process(e,t={}){return!this.plugins.length&&!t.parser&&!t.stringifier&&!t.syntax?new na(this,e,t):new sa(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}},ca=le;le.default=le;oa.registerProcessor(le);aa.registerProcessor(le);la=We,ua=ji,ha=Qe,da=Ot,fa=je,pa=fe,ga=Nt;ma=ue;ue.default=ue;ya=It,wr=We,va=br,ba=H,$t=ca,wa=Ve,Sa=ma,Sr=Dt,Aa=ur,Ar=Qe,Er=Ot,Ea=Lt,Ca=je,Ta=Ut,ka=gr,Cr=Nt,Tr=fe,xa=Ke;w.plugin=function(e,t){let i=!1;function r(...a){console&&console.warn&&!i&&(i=!0,console.warn(e+`: postcss.plugin was deprecated. Migration guide:
27
27
  https://evilmartians.com/chronicles/postcss-8-plugin-migration`),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+`: \u91CC\u9762 postcss.plugin \u88AB\u5F03\u7528. \u8FC1\u79FB\u6307\u5357:
28
- https://www.w3ctech.com/topic/2226`));let o=t(...a);return o.postcssPlugin=e,o.postcssVersion=new $t().version,o}let s;return Object.defineProperty(r,"postcss",{get(){return s||(s=r()),s}}),r.process=function(a,o,c){return w([r(c)]).process(a,o)},r};w.stringify=wa;w.parse=Ta;w.fromJSON=Sa;w.list=ka;w.comment=n=>new Ar(n);w.atRule=n=>new Er(n);w.decl=n=>new wr(n);w.rule=n=>new Cr(n);w.root=n=>new Tr(n);w.document=n=>new Sr(n);w.CssSyntaxError=ya;w.Declaration=wr;w.Container=ba;w.Processor=$t;w.Document=Sr;w.Comment=Ar;w.Warning=Aa;w.AtRule=Er;w.Result=Ea;w.Input=Ca;w.Rule=Cr;w.Root=Tr;w.Node=xa;va.registerPostcss(w);Ma=w;w.default=w;C=Bn(Ma);C.stringify;C.fromJSON;C.plugin;C.parse;C.list;C.document;C.comment;C.atRule;C.rule;C.decl;C.root;C.CssSyntaxError;C.Declaration;C.Container;C.Processor;C.Document;C.Comment;C.Warning;C.AtRule;C.Result;C.Input;C.Rule;C.Root;C.Node;Ti={script:"noscript",altglyph:"altGlyph",altglyphdef:"altGlyphDef",altglyphitem:"altGlyphItem",animatecolor:"animateColor",animatemotion:"animateMotion",animatetransform:"animateTransform",clippath:"clipPath",feblend:"feBlend",fecolormatrix:"feColorMatrix",fecomponenttransfer:"feComponentTransfer",fecomposite:"feComposite",feconvolvematrix:"feConvolveMatrix",fediffuselighting:"feDiffuseLighting",fedisplacementmap:"feDisplacementMap",fedistantlight:"feDistantLight",fedropshadow:"feDropShadow",feflood:"feFlood",fefunca:"feFuncA",fefuncb:"feFuncB",fefuncg:"feFuncG",fefuncr:"feFuncR",fegaussianblur:"feGaussianBlur",feimage:"feImage",femerge:"feMerge",femergenode:"feMergeNode",femorphology:"feMorphology",feoffset:"feOffset",fepointlight:"fePointLight",fespecularlighting:"feSpecularLighting",fespotlight:"feSpotLight",fetile:"feTile",feturbulence:"feTurbulence",foreignobject:"foreignObject",glyphref:"glyphRef",lineargradient:"linearGradient",radialgradient:"radialGradient"}});var Mr={};z(Mr,{HeatmapTrackingManager:()=>Bt});var Ua,Bt,Pr=$(()=>{"use strict";it();rt();Ua={scrollDebounceDelay:100,batchDelay:2e3,maxBatchSize:20,debug:!1},Bt=class{constructor(e,t={}){this.isDestroyed=!1;this.currentScrollState=null;this.pendingClicks=[];this.pendingScrolls=[];this.scrollDebounceTimer=null;this.batchTimer=null;this.scrollTrackingTimer=null;this.periodicScrollTimer=null;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.SPLIT_DURATION=3e3;this.snapshotCaptured=!1;this.snapshotEnabled=!1;this.tracker=e,this.options={...Ua,...t},this.attentionQuality=new W(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}async initialize(){this.isDestroyed||(this.log("Initializing heatmap tracking"),await this.checkSnapshotConfig(),this.setupClickTracking(),this.setupScrollTracking(),this.startScrollTracking(),this.setupUnloadHandler(),this.snapshotEnabled&&!this.snapshotCaptured&&this.captureSnapshot())}normalizeUrl(e){try{let t=new URL(e),i=t.hostname.toLowerCase();return i.startsWith("www.")&&(i=i.substring(4)),`${t.protocol}//${i}${t.pathname}`}catch{return e}}async checkSnapshotConfig(){try{let e=await this.tracker.getConfigAsync("enableHeatmapSnapshot");this.snapshotEnabled=e==="true",this.log("Heatmap snapshot capture enabled:",this.snapshotEnabled)}catch(e){this.log("Failed to check snapshot config, defaulting to disabled:",e),this.snapshotEnabled=!1}}async captureSnapshot(){if(!(this.snapshotCaptured||!this.snapshotEnabled))try{this.log("Capturing DOM snapshot...");let t=(await Promise.resolve().then(()=>(xr(),kr))).snapshot(document,{maskAllInputs:!0,maskTextFn:i=>i.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"*****")});this.snapshotCaptured=!0,this.log("DOM snapshot captured successfully"),await this.uploadSnapshot(t)}catch(e){this.log("Failed to capture DOM snapshot:",e)}}async uploadSnapshot(e){try{let t=this.tracker.getEffectiveUserId(),i=this.normalizeUrl(window.location.href);this.log("Uploading snapshot to backend - sessionId:",t);let r={sessionId:t,pageUrl:i,snapshot:e};this.log("Snapshot data prepared:",{sessionId:t,pageUrl:i,snapshotSize:JSON.stringify(e).length});let s=await this.getApiUrl(),a=await this.getTenantId(),o=await this.getAuthHeaders();if(!s||!a){this.log("Cannot upload snapshot: missing API URL or tenant ID");return}let c=await fetch(`${s}/v1/events/${encodeURIComponent(a)}/snapshot`,{method:"POST",headers:{"Content-Type":"application/json",...o},body:JSON.stringify({sessionId:t,pageUrl:i,snapshot:JSON.stringify(e),timestamp:Date.now()})});if(!c.ok)throw new Error(`Snapshot upload failed: ${c.status}`);let l=await c.json();this.log("Snapshot uploaded successfully:",l)}catch(t){this.log("Failed to upload snapshot:",t)}}async getApiUrl(){try{return this.tracker.config?.apiUrl||"https://api.grainql.com"}catch{return"https://api.grainql.com"}}async getTenantId(){try{return this.tracker.config?.tenantId}catch{return}}async getAuthHeaders(){try{return typeof this.tracker.getAuthHeaders=="function"?await this.tracker.getAuthHeaders():{}}catch{return{}}}setupClickTracking(){if(typeof document>"u")return;let e=t=>{this.isDestroyed||this.handleClick(t)};document.addEventListener("click",e,{passive:!0,capture:!0})}setupScrollTracking(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.handleScroll(),this.scrollDebounceTimer=null},this.options.scrollDebounceDelay)};window.addEventListener("scroll",e,{passive:!0})}startScrollTracking(){typeof window>"u"||(this.updateScrollState(),this.scrollTrackingTimer=window.setInterval(()=>{this.isDestroyed||this.updateScrollState()},500),this.startPeriodicScrollTracking())}startPeriodicScrollTracking(){typeof window>"u"||(this.periodicScrollTimer=window.setInterval(()=>{if(this.isDestroyed||!this.currentScrollState)return;if(!this.attentionQuality.shouldTrack()){this.log("Scroll tracking paused:",this.attentionQuality.getLastFilterReason());return}let e=Date.now(),t=e-this.currentScrollState.entryTime;if(t>1e3){let i=window.scrollY||window.pageYOffset,r=window.innerHeight,s=document.documentElement.scrollHeight,a=`viewport_section_${this.currentScrollState.viewportSection}`,o=this.attentionQuality.shouldTrackSection(a,i);if(o.resetAttention){this.log(`Viewport section ${this.currentScrollState.viewportSection}: Attention reset`),this.currentScrollState.entryTime=e;return}if(!o.shouldTrack){this.log(`Viewport section ${this.currentScrollState.viewportSection}: ${o.reason}`);return}let c={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:i,durationMs:t,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:s,viewportHeight:r};this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:c.pageUrl,viewport_section:c.viewportSection,scroll_depth_px:c.scrollDepthPx,duration_ms:c.durationMs,entry_timestamp:c.entryTimestamp,exit_timestamp:c.exitTimestamp,page_height:c.pageHeight,viewport_height:c.viewportHeight,is_split:!0},{flush:!0}),this.attentionQuality.updateSectionDuration(a,t),this.currentScrollState.entryTime=e}},this.SPLIT_DURATION))}setupUnloadHandler(){if(typeof window>"u")return;let e=()=>{if(this.currentScrollState){let t=Date.now(),i=t-this.currentScrollState.entryTime;if(i>100){let r={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:i,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:t,pageHeight:document.documentElement.scrollHeight,viewportHeight:window.innerHeight};this.pendingScrolls.push(r)}}this.flushPendingEventsWithBeacon()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}handleClick(e){let t=e.target;if(!t)return;let i=this.normalizeUrl(window.location.href),r=this.generateXPath(t),s=this.generateCSSSelector(t),a,o;try{let h=t.getBoundingClientRect();h.width>0&&h.height>0&&(a=Math.max(0,Math.min(1,(e.clientX-h.left)/h.width)),o=Math.max(0,Math.min(1,(e.clientY-h.top)/h.height)))}catch(h){this.log("Failed to calculate relative coordinates:",h)}let c=Math.round(e.clientX),l=Math.round(e.clientY),u=Math.round(e.pageX),d=Math.round(e.pageY),f=t.tagName?.toLowerCase()||"unknown",y=Ae(t.textContent),g={pageUrl:i,xpath:r,selector:s,relX:a,relY:o,viewportX:c,viewportY:l,pageX:u,pageY:d,elementTag:f,elementText:y||void 0,timestamp:Date.now()};t instanceof HTMLAnchorElement&&t.href?this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:g.pageUrl,xpath:g.xpath,selector:g.selector,rel_x:g.relX,rel_y:g.relY,viewport_x:g.viewportX,viewport_y:g.viewportY,page_x:g.pageX,page_y:g.pageY,element_tag:g.elementTag,element_text:g.elementText,timestamp:g.timestamp},{flush:!0}):(this.pendingClicks.push(g),this.considerBatchFlush())}handleScroll(){this.updateScrollState()}updateScrollState(){if(typeof window>"u")return;let e=Date.now(),t=window.scrollY||window.pageYOffset,i=window.innerHeight,r=document.documentElement.scrollHeight,s=Math.floor(t/i);if(this.currentScrollState&&this.currentScrollState.viewportSection!==s){let a=e-this.currentScrollState.entryTime;if(a>100){let c={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:a,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:r,viewportHeight:i};this.pendingScrolls.push(c)}let o=`viewport_section_${this.currentScrollState.viewportSection}`;this.attentionQuality.resetSection(o)}(!this.currentScrollState||this.currentScrollState.viewportSection!==s)&&(this.currentScrollState={viewportSection:s,entryTime:e,scrollDepthPx:t}),this.lastScrollPosition=t,this.lastScrollTime=e,this.considerBatchFlush()}generateCSSSelector(e){if(!e)return"";if(e.id)return`#${e.id}`;let t=Array.from(e.attributes).filter(s=>s.name.startsWith("data-"));if(t.length>0){let s=t[0];return`${e.tagName.toLowerCase()}[${s.name}="${s.value}"]`}if(e.className&&typeof e.className=="string"){let s=e.className.split(" ").filter(a=>a&&!a.match(/^(active|hover|focus)/));if(s.length>0)return`${e.tagName.toLowerCase()}.${s[0]}`}let i=[],r=e;for(;r&&r!==document.body;){let s=r.tagName.toLowerCase();if(r.parentElement){let o=Array.from(r.parentElement.children).filter(c=>c.tagName===r.tagName);if(o.length>1){let c=o.indexOf(r)+1;s+=`:nth-child(${c})`}}if(i.unshift(s),r=r.parentElement,i.length>=5)break}return i.join(" > ")}generateXPath(e){if(!e)return"";if(e.id)return`//*[@id="${e.id}"]`;let t=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let r=0,s=i;for(;s;)s=s.previousElementSibling,s&&s.nodeName===i.nodeName&&r++;let a=i.nodeName.toLowerCase(),o=r>0?`[${r+1}]`:"";t.unshift(`${a}${o}`),i=i.parentElement}return t.length?`/${t.join("/")}`:""}considerBatchFlush(){let e=this.pendingClicks.length+this.pendingScrolls.length;if(e>=this.options.maxBatchSize){this.flushPendingEvents();return}this.batchTimer===null&&e>0&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents(),this.batchTimer=null},this.options.batchDelay))}flushPendingEvents(){if(!this.isDestroyed){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,selector:e.selector,rel_x:e.relX,rel_y:e.relY,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight});this.pendingScrolls=[]}this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null)}}flushPendingEventsWithBeacon(){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,selector:e.selector,rel_x:e.relX,rel_y:e.relY,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp},{flush:!0});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight},{flush:!0});this.pendingScrolls=[]}}log(...e){this.options.debug&&this.tracker.log("[Heatmap Tracking]",...e)}destroy(){this.isDestroyed=!0,this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.scrollTrackingTimer!==null&&(clearInterval(this.scrollTrackingTimer),this.scrollTrackingTimer=null),this.periodicScrollTimer!==null&&(clearInterval(this.periodicScrollTimer),this.periodicScrollTimer=null),this.attentionQuality.destroy(),this.flushPendingEvents()}}});var Ir={};z(Ir,{InteractionTrackingManager:()=>Ft});var Ft,_r=$(()=>{"use strict";rt();Ft=class{constructor(e,t,i={}){this.isDestroyed=!1;this.attachedListeners=new Map;this.xpathCache=new Map;this.mutationObserver=null;this.mutationDebounceTimer=null;this.tracker=e,this.interactions=t,this.config={debug:i.debug??!1,enableMutationObserver:i.enableMutationObserver??!0,mutationDebounceDelay:i.mutationDebounceDelay??500,tenantId:i.tenantId,apiUrl:i.apiUrl},typeof window<"u"&&typeof document<"u"&&(this.config.tenantId&&this.config.apiUrl?this.fetchAndMergeTrackers().then(()=>{this.attachAllListeners()}):document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.attachAllListeners()):setTimeout(()=>this.attachAllListeners(),0),this.config.enableMutationObserver&&this.setupMutationObserver())}async fetchAndMergeTrackers(){if(!(!this.config.tenantId||!this.config.apiUrl))try{let e=typeof window<"u"?window.location.href:"",t=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/trackers?url=${encodeURIComponent(e)}`;this.log("Fetching trackers from:",t);let i=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok){this.log("Failed to fetch trackers:",i.status);return}let r=await i.json();if(r.trackers&&Array.isArray(r.trackers)){this.log("Fetched",r.trackers.length,"trackers");let s=r.trackers.map(a=>({eventName:a.eventName,selector:a.selector,priority:5,label:a.eventName,description:`Tracker: ${a.eventName}`}));this.interactions=[...s,...this.interactions],this.log("Merged trackers, total interactions:",this.interactions.length)}}catch(e){this.log("Error fetching trackers:",e)}}attachAllListeners(){if(!this.isDestroyed){this.log("Attaching interaction listeners");for(let e of this.interactions)this.attachInteractionListener(e)}}attachInteractionListener(e){if(this.isDestroyed)return;let t=this.findElementByXPath(e.selector);if(!t){this.log("Element not found for interaction:",e.eventName,"selector:",e.selector);return}if(this.attachedListeners.has(t)){this.log("Listeners already attached for element:",t);return}let i=[],r=s=>this.handleInteractionClick(e,s);if(t.addEventListener("click",r,{passive:!0}),i.push({event:"click",handler:r}),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){let s=a=>this.handleInteractionFocus(e,a);t.addEventListener("focus",s,{passive:!0}),i.push({event:"focus",handler:s})}this.attachedListeners.set(t,i)}handleInteractionClick(e,t){if(this.isDestroyed)return;let i=t.target,r=i instanceof HTMLAnchorElement&&i.href,s={interaction_type:"click",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_text:Ae(i.textContent),element_id:i.id||void 0,element_class:i.className||void 0,...r&&{href:i.href},timestamp:Date.now()},a=this.tracker.track(e.eventName,s,{flush:!0});a instanceof Promise&&a.catch(o=>{this.log("Failed to track click:",o)})}handleInteractionFocus(e,t){if(this.isDestroyed)return;let i=t.target;this.tracker.track(e.eventName,{interaction_type:"focus",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_id:i.id||void 0,element_class:i.className||void 0,timestamp:Date.now()})}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}setupMutationObserver(){if(typeof MutationObserver>"u"){this.log("MutationObserver not supported");return}this.mutationObserver=new MutationObserver(e=>{this.mutationDebounceTimer!==null&&clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=window.setTimeout(()=>{this.handleMutations(e),this.mutationDebounceTimer=null},this.config.mutationDebounceDelay)}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Mutation observer setup")}handleMutations(e){if(this.isDestroyed)return;this.xpathCache.clear();let t=new Set;for(let i of e)i.removedNodes.forEach(r=>{r instanceof Element&&(t.add(r),this.attachedListeners.forEach((s,a)=>{r.contains(a)&&t.add(a)}))});t.forEach(i=>{this.detachListeners(i)}),this.attachAllListeners()}detachListeners(e){let t=this.attachedListeners.get(e);t&&(t.forEach(({event:i,handler:r})=>{e.removeEventListener(i,r)}),this.attachedListeners.delete(e))}log(...e){this.config.debug&&console.log("[InteractionTracking]",...e)}updateInteractions(e){this.isDestroyed||(this.log("Updating interactions configuration"),this.attachedListeners.forEach((t,i)=>{this.detachListeners(i)}),this.xpathCache.clear(),this.interactions=e,this.attachAllListeners())}destroy(){this.isDestroyed||(this.log("Destroying interaction tracking manager"),this.isDestroyed=!0,this.mutationDebounceTimer!==null&&(clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.attachedListeners.forEach((e,t)=>{this.detachListeners(t)}),this.attachedListeners.clear(),this.xpathCache.clear())}}});var Rr={};z(Rr,{SectionTrackingManager:()=>Gt});var $a,Gt,Dr=$(()=>{"use strict";it();$a={minDwellTime:1e3,scrollVelocityThreshold:500,intersectionThreshold:.1,debounceDelay:100,batchDelay:2e3,debug:!1},Gt=class{constructor(e,t,i={}){this.isDestroyed=!1;this.sectionStates=new Map;this.intersectionObserver=null;this.xpathCache=new Map;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.scrollVelocity=0;this.scrollDebounceTimer=null;this.pendingEvents=[];this.batchTimer=null;this.sectionTimers=new Map;this.SPLIT_DURATION=3e3;this.tracker=e,this.sections=t,this.options={...$a,...i},this.attentionQuality=new W(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}initialize(){this.isDestroyed||(this.log("Initializing section tracking"),this.setupIntersectionObserver(),this.setupScrollListener(),this.initializeSections())}setupIntersectionObserver(){if(typeof IntersectionObserver>"u"){this.log("IntersectionObserver not supported");return}this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(t=>{this.handleIntersection(t)})},{threshold:[0,.1,.25,.5,.75,1],rootMargin:"0px"}),this.log("IntersectionObserver created")}setupScrollListener(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.updateScrollVelocity(),this.scrollDebounceTimer=null},this.options.debounceDelay)};window.addEventListener("scroll",e,{passive:!0}),this.log("Scroll listener attached")}initializeSections(){for(let e of this.sections){let t=this.findElementByXPath(e.selector);if(!t){this.log("Section element not found:",e.sectionName,"selector:",e.selector);continue}let i={element:t,config:e,entryTime:null,exitTime:null,isVisible:!1,lastScrollPosition:window.scrollY,lastScrollTime:Date.now(),entryScrollSpeed:0,exitScrollSpeed:0,maxVisibleArea:0};this.sectionStates.set(e.sectionName,i),this.intersectionObserver&&this.intersectionObserver.observe(t)}}handleIntersection(e){if(this.isDestroyed)return;let t=Array.from(this.sectionStates.values()).find(s=>s.element===e.target);if(!t)return;let i=e.isIntersecting&&e.intersectionRatio>=this.options.intersectionThreshold,r=e.intersectionRatio;r>t.maxVisibleArea&&(t.maxVisibleArea=r),i&&!t.isVisible?this.handleSectionEntry(t):!i&&t.isVisible&&this.handleSectionExit(t),t.isVisible=i}handleSectionEntry(e){e.entryTime=Date.now(),e.entryScrollSpeed=this.scrollVelocity,e.lastScrollPosition=window.scrollY,e.lastScrollTime=Date.now(),e.maxVisibleArea=0,this.startPeriodicTracking(e)}startPeriodicTracking(e){this.stopPeriodicTracking(e.config.sectionName);let t=window.setInterval(()=>{if(this.isDestroyed||!e.isVisible||e.entryTime===null){this.stopPeriodicTracking(e.config.sectionName);return}let i=Date.now(),r=i-e.entryTime;if(r>=this.options.minDwellTime){let s=window.scrollY,a=this.attentionQuality.shouldTrackSection(e.config.sectionName,s);if(a.resetAttention){this.log(`Section "${e.config.sectionName}": Attention reset, restarting timer`),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity;return}if(!a.shouldTrack){this.log(`Section "${e.config.sectionName}": Tracking paused - ${a.reason}`);return}let o={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:i,duration:r,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:this.scrollVelocity};this.shouldTrackSection(o)&&(this.tracker.trackSystemEvent("_grain_section_view",{section_name:o.sectionName,section_type:o.sectionType,duration_ms:o.duration,viewport_width:o.viewportWidth,viewport_height:o.viewportHeight,scroll_depth_percent:o.scrollDepth,visible_area_percent:o.visibleAreaPercentage,scroll_speed_entry:Math.round(o.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(o.scrollSpeedAtExit||0),entry_timestamp:o.entryTime,exit_timestamp:o.exitTime,is_split:!0}),this.attentionQuality.updateSectionDuration(e.config.sectionName,r),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity)}},this.SPLIT_DURATION);this.sectionTimers.set(e.config.sectionName,t)}stopPeriodicTracking(e){let t=this.sectionTimers.get(e);t!==void 0&&(clearInterval(t),this.sectionTimers.delete(e))}handleSectionExit(e){if(this.stopPeriodicTracking(e.config.sectionName),this.attentionQuality.resetSection(e.config.sectionName),e.entryTime===null)return;e.exitTime=Date.now(),e.exitScrollSpeed=this.scrollVelocity;let t=e.exitTime-e.entryTime,i={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:e.exitTime,duration:t,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:e.exitScrollSpeed};this.shouldTrackSection(i)?this.queueSectionView(i):this.log("Section view filtered out:",e.config.sectionName,"duration:",t),e.entryTime=null}updateScrollVelocity(){let e=Date.now(),t=window.scrollY,i=e-this.lastScrollTime,r=Math.abs(t-this.lastScrollPosition);i>0&&(this.scrollVelocity=r/i*1e3),this.lastScrollPosition=t,this.lastScrollTime=e}calculateScrollDepth(){if(typeof window>"u"||typeof document>"u")return 0;let e=window.innerHeight,t=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),i=window.scrollY,r=t-e;return r<=0?100:Math.round(i/r*100)}shouldTrackSection(e){return!(e.duration<this.options.minDwellTime||(e.scrollSpeedAtEntry+e.scrollSpeedAtExit)/2>this.options.scrollVelocityThreshold*2||e.visibleAreaPercentage<10)}queueSectionView(e){this.pendingEvents.push(e),this.batchTimer===null&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents()},this.options.batchDelay))}flushPendingEvents(){if(!(this.isDestroyed||this.pendingEvents.length===0)){for(let e of this.pendingEvents)this.tracker.trackSystemEvent("_grain_section_view",{section_name:e.sectionName,section_type:e.sectionType,duration_ms:e.duration,viewport_width:e.viewportWidth,viewport_height:e.viewportHeight,scroll_depth_percent:e.scrollDepth,visible_area_percent:e.visibleAreaPercentage,scroll_speed_entry:Math.round(e.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(e.scrollSpeedAtExit||0),entry_timestamp:e.entryTime,exit_timestamp:e.exitTime});this.pendingEvents=[],this.batchTimer=null}}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}log(...e){this.options.debug&&console.log("[SectionTracking]",...e)}updateSections(e){this.isDestroyed||(this.log("Updating sections configuration"),this.intersectionObserver&&this.intersectionObserver.disconnect(),this.sectionStates.clear(),this.xpathCache.clear(),this.sections=e,this.setupIntersectionObserver(),this.initializeSections())}destroy(){this.isDestroyed||(this.log("Destroying section tracking manager"),this.isDestroyed=!0,this.sectionTimers.forEach(e=>{clearInterval(e)}),this.sectionTimers.clear(),this.flushPendingEvents(),this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.attentionQuality.destroy(),this.sectionStates.clear(),this.xpathCache.clear(),this.pendingEvents=[])}}});var Lr={};z(Lr,{DebugAgent:()=>zt});var zt,Or=$(()=>{"use strict";zt=class{constructor(e,t,i,r,s={}){this.isDestroyed=!1;this.isInspectMode=!1;this.showTrackers=!1;this.selectedElement=null;this.toolbarElement=null;this.panelElement=null;this.highlightElement=null;this.existingTrackers=[];this.trackerHighlights=[];this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.toolbarStartX=0;this.toolbarStartY=0;this.mouseMoveListener=null;this.clickListener=null;this.dragMoveListener=null;this.dragEndListener=null;this.handleEscapeKey=e=>{e.key==="Escape"&&this.isInspectMode&&this.disableInspectMode()};this.tracker=e,this.sessionId=t,this.tenantId=i,this.apiUrl=r,this.config={debug:s.debug??!1},typeof window<"u"&&typeof document<"u"&&this.initialize()}async initialize(){this.log("Initializing debug agent"),await this.loadExistingTrackers(),this.showToolbar(),this.createHighlightElement(),this.showTrackers=!0,this.showTrackerHighlights(),this.showTrackersList()}async loadExistingTrackers(){try{let e=`${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/trackers`,t=await fetch(e);t.ok&&(this.existingTrackers=await t.json(),this.log("Loaded trackers:",this.existingTrackers))}catch(e){this.log("Failed to load trackers:",e),this.existingTrackers=[]}}showToolbar(){if(this.toolbarElement)return;let e=document.createElement("div");e.id="grain-debug-toolbar",e.innerHTML=`
28
+ https://www.w3ctech.com/topic/2226`));let o=t(...a);return o.postcssPlugin=e,o.postcssVersion=new $t().version,o}let s;return Object.defineProperty(r,"postcss",{get(){return s||(s=r()),s}}),r.process=function(a,o,c){return w([r(c)]).process(a,o)},r};w.stringify=wa;w.parse=Ta;w.fromJSON=Sa;w.list=ka;w.comment=n=>new Ar(n);w.atRule=n=>new Er(n);w.decl=n=>new wr(n);w.rule=n=>new Cr(n);w.root=n=>new Tr(n);w.document=n=>new Sr(n);w.CssSyntaxError=ya;w.Declaration=wr;w.Container=ba;w.Processor=$t;w.Document=Sr;w.Comment=Ar;w.Warning=Aa;w.AtRule=Er;w.Result=Ea;w.Input=Ca;w.Rule=Cr;w.Root=Tr;w.Node=xa;va.registerPostcss(w);Ma=w;w.default=w;C=Bn(Ma);C.stringify;C.fromJSON;C.plugin;C.parse;C.list;C.document;C.comment;C.atRule;C.rule;C.decl;C.root;C.CssSyntaxError;C.Declaration;C.Container;C.Processor;C.Document;C.Comment;C.Warning;C.AtRule;C.Result;C.Input;C.Rule;C.Root;C.Node;Ti={script:"noscript",altglyph:"altGlyph",altglyphdef:"altGlyphDef",altglyphitem:"altGlyphItem",animatecolor:"animateColor",animatemotion:"animateMotion",animatetransform:"animateTransform",clippath:"clipPath",feblend:"feBlend",fecolormatrix:"feColorMatrix",fecomponenttransfer:"feComponentTransfer",fecomposite:"feComposite",feconvolvematrix:"feConvolveMatrix",fediffuselighting:"feDiffuseLighting",fedisplacementmap:"feDisplacementMap",fedistantlight:"feDistantLight",fedropshadow:"feDropShadow",feflood:"feFlood",fefunca:"feFuncA",fefuncb:"feFuncB",fefuncg:"feFuncG",fefuncr:"feFuncR",fegaussianblur:"feGaussianBlur",feimage:"feImage",femerge:"feMerge",femergenode:"feMergeNode",femorphology:"feMorphology",feoffset:"feOffset",fepointlight:"fePointLight",fespecularlighting:"feSpecularLighting",fespotlight:"feSpotLight",fetile:"feTile",feturbulence:"feTurbulence",foreignobject:"foreignObject",glyphref:"glyphRef",lineargradient:"linearGradient",radialgradient:"radialGradient"}});var Mr={};z(Mr,{HeatmapTrackingManager:()=>Bt});var Ua,Bt,Pr=$(()=>{"use strict";it();rt();Ua={scrollDebounceDelay:100,batchDelay:2e3,maxBatchSize:20,debug:!1},Bt=class{constructor(e,t={}){this.isDestroyed=!1;this.currentScrollState=null;this.pendingClicks=[];this.pendingScrolls=[];this.scrollDebounceTimer=null;this.batchTimer=null;this.scrollTrackingTimer=null;this.periodicScrollTimer=null;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.SPLIT_DURATION=3e3;this.snapshotCaptured=!1;this.snapshotEnabled=!1;this.deviceType="desktop";this.tracker=e,this.options={...Ua,...t},this.deviceType=this.detectDeviceType(),this.attentionQuality=new W(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}async initialize(){this.isDestroyed||(this.log("Initializing heatmap tracking"),await this.checkSnapshotConfig(),this.setupClickTracking(),this.setupScrollTracking(),this.startScrollTracking(),this.setupUnloadHandler(),this.snapshotEnabled&&!this.snapshotCaptured&&this.captureSnapshot())}detectDeviceType(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let t=(window.innerWidth||window.screen?.width||0)<768,i=navigator.userAgent.toLowerCase(),s=["mobile","android","iphone","ipad","ipod","blackberry","windows phone","webos"].some(a=>i.includes(a));return t||s?"mobile":"desktop"}normalizeUrl(e){try{let t=new URL(e),i=t.hostname.toLowerCase();return i.startsWith("www.")&&(i=i.substring(4)),`${t.protocol}//${i}${t.pathname}`}catch{return e}}async checkSnapshotConfig(){try{let e=await this.tracker.getConfigAsync("enableHeatmapSnapshot");this.snapshotEnabled=e==="true",this.log("Heatmap snapshot capture enabled:",this.snapshotEnabled)}catch(e){this.log("Failed to check snapshot config, defaulting to disabled:",e),this.snapshotEnabled=!1}}async captureSnapshot(){if(!(this.snapshotCaptured||!this.snapshotEnabled))try{this.log("Capturing DOM snapshot...");let t=(await Promise.resolve().then(()=>(xr(),kr))).snapshot(document,{maskAllInputs:!0,maskTextFn:i=>i.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,"*****")});this.snapshotCaptured=!0,this.log("DOM snapshot captured successfully"),await this.uploadSnapshot(t)}catch(e){this.log("Failed to capture DOM snapshot:",e)}}async uploadSnapshot(e){try{let t=this.tracker.getEffectiveUserId(),i=this.normalizeUrl(window.location.href);this.log("Uploading snapshot to backend - sessionId:",t);let r={sessionId:t,pageUrl:i,snapshot:e};this.log("Snapshot data prepared:",{sessionId:t,pageUrl:i,snapshotSize:JSON.stringify(e).length});let s=await this.getApiUrl(),a=await this.getTenantId(),o=await this.getAuthHeaders();if(!s||!a){this.log("Cannot upload snapshot: missing API URL or tenant ID");return}let c=await fetch(`${s}/v1/events/${encodeURIComponent(a)}/snapshot`,{method:"POST",headers:{"Content-Type":"application/json",...o},body:JSON.stringify({sessionId:t,pageUrl:i,snapshot:JSON.stringify(e),timestamp:Date.now(),deviceType:this.deviceType})});if(!c.ok)throw new Error(`Snapshot upload failed: ${c.status}`);let l=await c.json();this.log("Snapshot uploaded successfully:",l)}catch(t){this.log("Failed to upload snapshot:",t)}}async getApiUrl(){try{return this.tracker.config?.apiUrl||"https://api.grainql.com"}catch{return"https://api.grainql.com"}}async getTenantId(){try{return this.tracker.config?.tenantId}catch{return}}async getAuthHeaders(){try{return typeof this.tracker.getAuthHeaders=="function"?await this.tracker.getAuthHeaders():{}}catch{return{}}}setupClickTracking(){if(typeof document>"u")return;let e=t=>{this.isDestroyed||this.handleClick(t)};document.addEventListener("click",e,{passive:!0,capture:!0})}setupScrollTracking(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.handleScroll(),this.scrollDebounceTimer=null},this.options.scrollDebounceDelay)};window.addEventListener("scroll",e,{passive:!0})}startScrollTracking(){typeof window>"u"||(this.updateScrollState(),this.scrollTrackingTimer=window.setInterval(()=>{this.isDestroyed||this.updateScrollState()},500),this.startPeriodicScrollTracking())}startPeriodicScrollTracking(){typeof window>"u"||(this.periodicScrollTimer=window.setInterval(()=>{if(this.isDestroyed||!this.currentScrollState)return;if(!this.attentionQuality.shouldTrack()){this.log("Scroll tracking paused:",this.attentionQuality.getLastFilterReason());return}let e=Date.now(),t=e-this.currentScrollState.entryTime;if(t>1e3){let i=window.scrollY||window.pageYOffset,r=window.innerHeight,s=document.documentElement.scrollHeight,a=`viewport_section_${this.currentScrollState.viewportSection}`,o=this.attentionQuality.shouldTrackSection(a,i);if(o.resetAttention){this.log(`Viewport section ${this.currentScrollState.viewportSection}: Attention reset`),this.currentScrollState.entryTime=e;return}if(!o.shouldTrack){this.log(`Viewport section ${this.currentScrollState.viewportSection}: ${o.reason}`);return}let c={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:i,durationMs:t,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:s,viewportHeight:r,deviceType:this.deviceType};this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:c.pageUrl,viewport_section:c.viewportSection,scroll_depth_px:c.scrollDepthPx,duration_ms:c.durationMs,entry_timestamp:c.entryTimestamp,exit_timestamp:c.exitTimestamp,page_height:c.pageHeight,viewport_height:c.viewportHeight,device_type:c.deviceType,is_split:!0},{flush:!0}),this.attentionQuality.updateSectionDuration(a,t),this.currentScrollState.entryTime=e}},this.SPLIT_DURATION))}setupUnloadHandler(){if(typeof window>"u")return;let e=()=>{if(this.currentScrollState){let t=Date.now(),i=t-this.currentScrollState.entryTime;if(i>100){let r={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:i,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:t,pageHeight:document.documentElement.scrollHeight,viewportHeight:window.innerHeight,deviceType:this.deviceType};this.pendingScrolls.push(r)}}this.flushPendingEventsWithBeacon()};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e)}handleClick(e){let t=e.target;if(!t)return;let i=this.normalizeUrl(window.location.href),r=this.generateXPath(t),s=this.generateCSSSelector(t),a,o;try{let h=t.getBoundingClientRect();h.width>0&&h.height>0&&(a=Math.max(0,Math.min(1,(e.clientX-h.left)/h.width)),o=Math.max(0,Math.min(1,(e.clientY-h.top)/h.height)))}catch(h){this.log("Failed to calculate relative coordinates:",h)}let c=Math.round(e.clientX),l=Math.round(e.clientY),u=Math.round(e.pageX),d=Math.round(e.pageY),f=t.tagName?.toLowerCase()||"unknown",y=Ae(t.textContent),g={pageUrl:i,xpath:r,selector:s,relX:a,relY:o,viewportX:c,viewportY:l,pageX:u,pageY:d,elementTag:f,elementText:y||void 0,timestamp:Date.now(),deviceType:this.deviceType};t instanceof HTMLAnchorElement&&t.href?this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:g.pageUrl,xpath:g.xpath,selector:g.selector,rel_x:g.relX,rel_y:g.relY,viewport_x:g.viewportX,viewport_y:g.viewportY,page_x:g.pageX,page_y:g.pageY,element_tag:g.elementTag,element_text:g.elementText,timestamp:g.timestamp,device_type:g.deviceType},{flush:!0}):(this.pendingClicks.push(g),this.considerBatchFlush())}handleScroll(){this.updateScrollState()}updateScrollState(){if(typeof window>"u")return;let e=Date.now(),t=window.scrollY||window.pageYOffset,i=window.innerHeight,r=document.documentElement.scrollHeight,s=Math.floor(t/i);if(this.currentScrollState&&this.currentScrollState.viewportSection!==s){let a=e-this.currentScrollState.entryTime;if(a>100){let c={pageUrl:this.normalizeUrl(window.location.href),viewportSection:this.currentScrollState.viewportSection,scrollDepthPx:this.currentScrollState.scrollDepthPx,durationMs:a,entryTimestamp:this.currentScrollState.entryTime,exitTimestamp:e,pageHeight:r,viewportHeight:i,deviceType:this.deviceType};this.pendingScrolls.push(c)}let o=`viewport_section_${this.currentScrollState.viewportSection}`;this.attentionQuality.resetSection(o)}(!this.currentScrollState||this.currentScrollState.viewportSection!==s)&&(this.currentScrollState={viewportSection:s,entryTime:e,scrollDepthPx:t}),this.lastScrollPosition=t,this.lastScrollTime=e,this.considerBatchFlush()}generateCSSSelector(e){if(!e)return"";if(e.id)return`#${e.id}`;let t=Array.from(e.attributes).filter(s=>s.name.startsWith("data-"));if(t.length>0){let s=t[0];return`${e.tagName.toLowerCase()}[${s.name}="${s.value}"]`}if(e.className&&typeof e.className=="string"){let s=e.className.split(" ").filter(a=>a&&!a.match(/^(active|hover|focus)/));if(s.length>0)return`${e.tagName.toLowerCase()}.${s[0]}`}let i=[],r=e;for(;r&&r!==document.body;){let s=r.tagName.toLowerCase();if(r.parentElement){let o=Array.from(r.parentElement.children).filter(c=>c.tagName===r.tagName);if(o.length>1){let c=o.indexOf(r)+1;s+=`:nth-child(${c})`}}if(i.unshift(s),r=r.parentElement,i.length>=5)break}return i.join(" > ")}generateXPath(e){if(!e)return"";if(e.id)return`//*[@id="${e.id}"]`;let t=[],i=e;for(;i&&i.nodeType===Node.ELEMENT_NODE;){let r=0,s=i;for(;s;)s=s.previousElementSibling,s&&s.nodeName===i.nodeName&&r++;let a=i.nodeName.toLowerCase(),o=r>0?`[${r+1}]`:"";t.unshift(`${a}${o}`),i=i.parentElement}return t.length?`/${t.join("/")}`:""}considerBatchFlush(){let e=this.pendingClicks.length+this.pendingScrolls.length;if(e>=this.options.maxBatchSize){this.flushPendingEvents();return}this.batchTimer===null&&e>0&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents(),this.batchTimer=null},this.options.batchDelay))}flushPendingEvents(){if(!this.isDestroyed){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,selector:e.selector,rel_x:e.relX,rel_y:e.relY,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp,device_type:e.deviceType});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight,device_type:e.deviceType});this.pendingScrolls=[]}this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null)}}flushPendingEventsWithBeacon(){if(this.pendingClicks.length>0){for(let e of this.pendingClicks)this.tracker.trackSystemEvent("_grain_heatmap_click",{page_url:e.pageUrl,xpath:e.xpath,selector:e.selector,rel_x:e.relX,rel_y:e.relY,viewport_x:e.viewportX,viewport_y:e.viewportY,page_x:e.pageX,page_y:e.pageY,element_tag:e.elementTag,element_text:e.elementText,timestamp:e.timestamp,device_type:e.deviceType},{flush:!0});this.pendingClicks=[]}if(this.pendingScrolls.length>0){for(let e of this.pendingScrolls)this.tracker.trackSystemEvent("_grain_heatmap_scroll",{page_url:e.pageUrl,viewport_section:e.viewportSection,scroll_depth_px:e.scrollDepthPx,duration_ms:e.durationMs,entry_timestamp:e.entryTimestamp,exit_timestamp:e.exitTimestamp,page_height:e.pageHeight,viewport_height:e.viewportHeight,device_type:e.deviceType},{flush:!0});this.pendingScrolls=[]}}log(...e){this.options.debug&&this.tracker.log("[Heatmap Tracking]",...e)}destroy(){this.isDestroyed=!0,this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.scrollTrackingTimer!==null&&(clearInterval(this.scrollTrackingTimer),this.scrollTrackingTimer=null),this.periodicScrollTimer!==null&&(clearInterval(this.periodicScrollTimer),this.periodicScrollTimer=null),this.attentionQuality.destroy(),this.flushPendingEvents()}}});var Ir={};z(Ir,{InteractionTrackingManager:()=>Ft});var Ft,_r=$(()=>{"use strict";rt();Ft=class{constructor(e,t,i={}){this.isDestroyed=!1;this.attachedListeners=new Map;this.xpathCache=new Map;this.mutationObserver=null;this.mutationDebounceTimer=null;this.tracker=e,this.interactions=t,this.config={debug:i.debug??!1,enableMutationObserver:i.enableMutationObserver??!0,mutationDebounceDelay:i.mutationDebounceDelay??500,tenantId:i.tenantId,apiUrl:i.apiUrl},typeof window<"u"&&typeof document<"u"&&(this.config.tenantId&&this.config.apiUrl?this.fetchAndMergeTrackers().then(()=>{this.attachAllListeners()}):document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.attachAllListeners()):setTimeout(()=>this.attachAllListeners(),0),this.config.enableMutationObserver&&this.setupMutationObserver())}async fetchAndMergeTrackers(){if(!(!this.config.tenantId||!this.config.apiUrl))try{let e=typeof window<"u"?window.location.href:"",t=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/trackers?url=${encodeURIComponent(e)}`;this.log("Fetching trackers from:",t);let i=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!i.ok){this.log("Failed to fetch trackers:",i.status);return}let r=await i.json();if(r.trackers&&Array.isArray(r.trackers)){this.log("Fetched",r.trackers.length,"trackers");let s=r.trackers.map(a=>({eventName:a.eventName,selector:a.selector,priority:5,label:a.eventName,description:`Tracker: ${a.eventName}`}));this.interactions=[...s,...this.interactions],this.log("Merged trackers, total interactions:",this.interactions.length)}}catch(e){this.log("Error fetching trackers:",e)}}attachAllListeners(){if(!this.isDestroyed){this.log("Attaching interaction listeners");for(let e of this.interactions)this.attachInteractionListener(e)}}attachInteractionListener(e){if(this.isDestroyed)return;let t=this.findElementByXPath(e.selector);if(!t){this.log("Element not found for interaction:",e.eventName,"selector:",e.selector);return}if(this.attachedListeners.has(t)){this.log("Listeners already attached for element:",t);return}let i=[],r=s=>this.handleInteractionClick(e,s);if(t.addEventListener("click",r,{passive:!0}),i.push({event:"click",handler:r}),t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement){let s=a=>this.handleInteractionFocus(e,a);t.addEventListener("focus",s,{passive:!0}),i.push({event:"focus",handler:s})}this.attachedListeners.set(t,i)}handleInteractionClick(e,t){if(this.isDestroyed)return;let i=t.target,r=i instanceof HTMLAnchorElement&&i.href,s={interaction_type:"click",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_text:Ae(i.textContent),element_id:i.id||void 0,element_class:i.className||void 0,...r&&{href:i.href},timestamp:Date.now()},a=this.tracker.track(e.eventName,s,{flush:!0});a instanceof Promise&&a.catch(o=>{this.log("Failed to track click:",o)})}handleInteractionFocus(e,t){if(this.isDestroyed)return;let i=t.target;this.tracker.track(e.eventName,{interaction_type:"focus",interaction_label:e.label,interaction_description:e.description,interaction_priority:e.priority,element_tag:i.tagName?.toLowerCase(),element_id:i.id||void 0,element_class:i.className||void 0,timestamp:Date.now()})}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}setupMutationObserver(){if(typeof MutationObserver>"u"){this.log("MutationObserver not supported");return}this.mutationObserver=new MutationObserver(e=>{this.mutationDebounceTimer!==null&&clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=window.setTimeout(()=>{this.handleMutations(e),this.mutationDebounceTimer=null},this.config.mutationDebounceDelay)}),this.mutationObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Mutation observer setup")}handleMutations(e){if(this.isDestroyed)return;this.xpathCache.clear();let t=new Set;for(let i of e)i.removedNodes.forEach(r=>{r instanceof Element&&(t.add(r),this.attachedListeners.forEach((s,a)=>{r.contains(a)&&t.add(a)}))});t.forEach(i=>{this.detachListeners(i)}),this.attachAllListeners()}detachListeners(e){let t=this.attachedListeners.get(e);t&&(t.forEach(({event:i,handler:r})=>{e.removeEventListener(i,r)}),this.attachedListeners.delete(e))}log(...e){this.config.debug&&console.log("[InteractionTracking]",...e)}updateInteractions(e){this.isDestroyed||(this.log("Updating interactions configuration"),this.attachedListeners.forEach((t,i)=>{this.detachListeners(i)}),this.xpathCache.clear(),this.interactions=e,this.attachAllListeners())}destroy(){this.isDestroyed||(this.log("Destroying interaction tracking manager"),this.isDestroyed=!0,this.mutationDebounceTimer!==null&&(clearTimeout(this.mutationDebounceTimer),this.mutationDebounceTimer=null),this.mutationObserver&&(this.mutationObserver.disconnect(),this.mutationObserver=null),this.attachedListeners.forEach((e,t)=>{this.detachListeners(t)}),this.attachedListeners.clear(),this.xpathCache.clear())}}});var Rr={};z(Rr,{SectionTrackingManager:()=>Gt});var $a,Gt,Dr=$(()=>{"use strict";it();$a={minDwellTime:1e3,scrollVelocityThreshold:500,intersectionThreshold:.1,debounceDelay:100,batchDelay:2e3,debug:!1},Gt=class{constructor(e,t,i={}){this.isDestroyed=!1;this.sectionStates=new Map;this.intersectionObserver=null;this.xpathCache=new Map;this.lastScrollPosition=0;this.lastScrollTime=Date.now();this.scrollVelocity=0;this.scrollDebounceTimer=null;this.pendingEvents=[];this.batchTimer=null;this.sectionTimers=new Map;this.SPLIT_DURATION=3e3;this.tracker=e,this.sections=t,this.options={...$a,...i},this.attentionQuality=new W(e.getActivityDetector(),{maxSectionDuration:9e3,minScrollDistance:100,idleThreshold:3e4,debug:this.options.debug}),typeof window<"u"&&typeof document<"u"&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>this.initialize()):setTimeout(()=>this.initialize(),0))}initialize(){this.isDestroyed||(this.log("Initializing section tracking"),this.setupIntersectionObserver(),this.setupScrollListener(),this.initializeSections())}setupIntersectionObserver(){if(typeof IntersectionObserver>"u"){this.log("IntersectionObserver not supported");return}this.intersectionObserver=new IntersectionObserver(e=>{e.forEach(t=>{this.handleIntersection(t)})},{threshold:[0,.1,.25,.5,.75,1],rootMargin:"0px"}),this.log("IntersectionObserver created")}setupScrollListener(){if(typeof window>"u")return;let e=()=>{this.scrollDebounceTimer!==null&&clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=window.setTimeout(()=>{this.updateScrollVelocity(),this.scrollDebounceTimer=null},this.options.debounceDelay)};window.addEventListener("scroll",e,{passive:!0}),this.log("Scroll listener attached")}initializeSections(){for(let e of this.sections){let t=this.findElementByXPath(e.selector);if(!t){this.log("Section element not found:",e.sectionName,"selector:",e.selector);continue}let i={element:t,config:e,entryTime:null,exitTime:null,isVisible:!1,lastScrollPosition:window.scrollY,lastScrollTime:Date.now(),entryScrollSpeed:0,exitScrollSpeed:0,maxVisibleArea:0};this.sectionStates.set(e.sectionName,i),this.intersectionObserver&&this.intersectionObserver.observe(t)}}handleIntersection(e){if(this.isDestroyed)return;let t=Array.from(this.sectionStates.values()).find(s=>s.element===e.target);if(!t)return;let i=e.isIntersecting&&e.intersectionRatio>=this.options.intersectionThreshold,r=e.intersectionRatio;r>t.maxVisibleArea&&(t.maxVisibleArea=r),i&&!t.isVisible?this.handleSectionEntry(t):!i&&t.isVisible&&this.handleSectionExit(t),t.isVisible=i}handleSectionEntry(e){e.entryTime=Date.now(),e.entryScrollSpeed=this.scrollVelocity,e.lastScrollPosition=window.scrollY,e.lastScrollTime=Date.now(),e.maxVisibleArea=0,this.startPeriodicTracking(e)}startPeriodicTracking(e){this.stopPeriodicTracking(e.config.sectionName);let t=window.setInterval(()=>{if(this.isDestroyed||!e.isVisible||e.entryTime===null){this.stopPeriodicTracking(e.config.sectionName);return}let i=Date.now(),r=i-e.entryTime;if(r>=this.options.minDwellTime){let s=window.scrollY,a=this.attentionQuality.shouldTrackSection(e.config.sectionName,s);if(a.resetAttention){this.log(`Section "${e.config.sectionName}": Attention reset, restarting timer`),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity;return}if(!a.shouldTrack){this.log(`Section "${e.config.sectionName}": Tracking paused - ${a.reason}`);return}let o={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:i,duration:r,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:this.scrollVelocity};this.shouldTrackSection(o)&&(this.tracker.trackSystemEvent("_grain_section_view",{section_name:o.sectionName,section_type:o.sectionType,duration_ms:o.duration,viewport_width:o.viewportWidth,viewport_height:o.viewportHeight,scroll_depth_percent:o.scrollDepth,visible_area_percent:o.visibleAreaPercentage,scroll_speed_entry:Math.round(o.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(o.scrollSpeedAtExit||0),entry_timestamp:o.entryTime,exit_timestamp:o.exitTime,is_split:!0}),this.attentionQuality.updateSectionDuration(e.config.sectionName,r),e.entryTime=i,e.entryScrollSpeed=this.scrollVelocity)}},this.SPLIT_DURATION);this.sectionTimers.set(e.config.sectionName,t)}stopPeriodicTracking(e){let t=this.sectionTimers.get(e);t!==void 0&&(clearInterval(t),this.sectionTimers.delete(e))}handleSectionExit(e){if(this.stopPeriodicTracking(e.config.sectionName),this.attentionQuality.resetSection(e.config.sectionName),e.entryTime===null)return;e.exitTime=Date.now(),e.exitScrollSpeed=this.scrollVelocity;let t=e.exitTime-e.entryTime,i={sectionName:e.config.sectionName,sectionType:e.config.sectionType,entryTime:e.entryTime,exitTime:e.exitTime,duration:t,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollDepth:this.calculateScrollDepth(),visibleAreaPercentage:Math.round(e.maxVisibleArea*100),scrollSpeedAtEntry:e.entryScrollSpeed,scrollSpeedAtExit:e.exitScrollSpeed};this.shouldTrackSection(i)?this.queueSectionView(i):this.log("Section view filtered out:",e.config.sectionName,"duration:",t),e.entryTime=null}updateScrollVelocity(){let e=Date.now(),t=window.scrollY,i=e-this.lastScrollTime,r=Math.abs(t-this.lastScrollPosition);i>0&&(this.scrollVelocity=r/i*1e3),this.lastScrollPosition=t,this.lastScrollTime=e}calculateScrollDepth(){if(typeof window>"u"||typeof document>"u")return 0;let e=window.innerHeight,t=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight),i=window.scrollY,r=t-e;return r<=0?100:Math.round(i/r*100)}shouldTrackSection(e){return!(e.duration<this.options.minDwellTime||(e.scrollSpeedAtEntry+e.scrollSpeedAtExit)/2>this.options.scrollVelocityThreshold*2||e.visibleAreaPercentage<10)}queueSectionView(e){this.pendingEvents.push(e),this.batchTimer===null&&(this.batchTimer=window.setTimeout(()=>{this.flushPendingEvents()},this.options.batchDelay))}flushPendingEvents(){if(!(this.isDestroyed||this.pendingEvents.length===0)){for(let e of this.pendingEvents)this.tracker.trackSystemEvent("_grain_section_view",{section_name:e.sectionName,section_type:e.sectionType,duration_ms:e.duration,viewport_width:e.viewportWidth,viewport_height:e.viewportHeight,scroll_depth_percent:e.scrollDepth,visible_area_percent:e.visibleAreaPercentage,scroll_speed_entry:Math.round(e.scrollSpeedAtEntry||0),scroll_speed_exit:Math.round(e.scrollSpeedAtExit||0),entry_timestamp:e.entryTime,exit_timestamp:e.exitTime});this.pendingEvents=[],this.batchTimer=null}}findElementByXPath(e){if(this.xpathCache.has(e)){let t=this.xpathCache.get(e);if(t&&document.contains(t))return t;this.xpathCache.delete(e)}try{let t=e;e.startsWith("xpath=")&&(t=e.substring(6));let r=document.evaluate(t,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;return r&&this.xpathCache.set(e,r),r}catch(t){return this.log("Error evaluating XPath:",e,t),null}}log(...e){this.options.debug&&console.log("[SectionTracking]",...e)}updateSections(e){this.isDestroyed||(this.log("Updating sections configuration"),this.intersectionObserver&&this.intersectionObserver.disconnect(),this.sectionStates.clear(),this.xpathCache.clear(),this.sections=e,this.setupIntersectionObserver(),this.initializeSections())}destroy(){this.isDestroyed||(this.log("Destroying section tracking manager"),this.isDestroyed=!0,this.sectionTimers.forEach(e=>{clearInterval(e)}),this.sectionTimers.clear(),this.flushPendingEvents(),this.scrollDebounceTimer!==null&&(clearTimeout(this.scrollDebounceTimer),this.scrollDebounceTimer=null),this.batchTimer!==null&&(clearTimeout(this.batchTimer),this.batchTimer=null),this.intersectionObserver&&(this.intersectionObserver.disconnect(),this.intersectionObserver=null),this.attentionQuality.destroy(),this.sectionStates.clear(),this.xpathCache.clear(),this.pendingEvents=[])}}});var Lr={};z(Lr,{DebugAgent:()=>zt});var zt,Or=$(()=>{"use strict";zt=class{constructor(e,t,i,r,s={}){this.isDestroyed=!1;this.isInspectMode=!1;this.showTrackers=!1;this.selectedElement=null;this.toolbarElement=null;this.panelElement=null;this.highlightElement=null;this.existingTrackers=[];this.trackerHighlights=[];this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.toolbarStartX=0;this.toolbarStartY=0;this.mouseMoveListener=null;this.clickListener=null;this.dragMoveListener=null;this.dragEndListener=null;this.handleEscapeKey=e=>{e.key==="Escape"&&this.isInspectMode&&this.disableInspectMode()};this.tracker=e,this.sessionId=t,this.tenantId=i,this.apiUrl=r,this.config={debug:s.debug??!1},typeof window<"u"&&typeof document<"u"&&this.initialize()}async initialize(){this.log("Initializing debug agent"),await this.loadExistingTrackers(),this.showToolbar(),this.createHighlightElement(),this.showTrackers=!0,this.showTrackerHighlights(),this.showTrackersList()}async loadExistingTrackers(){try{let e=`${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/trackers`,t=await fetch(e);t.ok&&(this.existingTrackers=await t.json(),this.log("Loaded trackers:",this.existingTrackers))}catch(e){this.log("Failed to load trackers:",e),this.existingTrackers=[]}}showToolbar(){if(this.toolbarElement)return;let e=document.createElement("div");e.id="grain-debug-toolbar",e.innerHTML=`
29
29
  <style>
30
30
  #grain-debug-toolbar {
31
31
  position: fixed;