@usermaven/sdk-js 1.5.10-rc.112 → 1.5.10-rc.116

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/lib.js CHANGED
@@ -1,2 +1,2 @@
1
- (function(m,f){typeof exports=="object"&&typeof module<"u"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(m=typeof globalThis<"u"?globalThis:m||self,f(m.Usermaven={}))})(this,function(m){"use strict";var f=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s))(f||{});class ne{constructor(e){this.level=e}debug(e,...t){this.level<=0&&console.debug("[Usermaven Debug]:",e,...t)}info(e,...t){this.level<=1&&console.info("[Usermaven Info]:",e,...t)}warn(e,...t){this.level<=2&&console.warn("[Usermaven Warning]:",e,...t)}error(e,...t){this.level<=3&&console.error("[Usermaven Error]:",e,...t)}}function g(s=0){return new ne(s)}const z={logLevel:f.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class re{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,n=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,l=n?"; Secure":"",c=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${l}${c}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let n=0;n<i.length;n++){let r=i[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(i=>!isNaN(Number(i)))}extractHostname(e){let t;return e.indexOf("//")>-1?t=e.split("/")[2]:t=e.split("/")[0],t=t.split(":")[0],t=t.split("?")[0],t}extractRootDomain(e){let t=this.extractHostname(e);const i=t.split("."),n=i.length;return n>2&&(i[n-1].length==2?(t=i[n-2]+"."+i[n-1],i[n-2].length==2&&(t=i[n-3]+"."+t)):t=i[n-2]+"."+i[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,i=e.match(t);return i?i[0]:""}}const oe=Object.prototype.hasOwnProperty,x=Array.prototype.forEach,R={};function ae(s,e,t){if(Array.isArray(s)){if(x&&s.forEach===x)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===R)return}}}const D=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},ce=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function v(s,e,t){if(s!=null){if(x&&Array.isArray(s)&&s.forEach===x)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===R)return}else for(const i in s)if(oe.call(s,i)&&e.call(t,s[i],i)===R)return}}const le=function(s,...e){return ae(e,function(t){for(const i in t)t[i]!==void 0&&(s[i]=t[i])}),s};function C(s,e){return s.indexOf(e)!==-1}const ue=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},he=function(s){return s===void 0},_=function(){const s=function(i,n,r,o,a){if(!i){g().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!a);else{const l="on"+n,c=i[l];i[l]=e(i,r,c)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,l;ue(r)&&(l=r(o));const c=n.call(i,o);return(l===!1||c===!1)&&(a=!1),a}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},s}(),de=function(s){return function(...e){try{return s.apply(this,e)}catch(t){g().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},V=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=de(s[e]))};function J(s){for(let e in s)(s[e]===""||s[e]===null||s[e]===void 0||typeof s[e]=="object"&&Object.keys(s[e]).length===0)&&delete s[e];return s}function h(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return g().warn("window is not available"),!1}}function b(s=5){const e=new Uint8Array(s);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,s)}function fe(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function U(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(U):Object.keys(s).reduce((e,t)=>{const i=fe(t);return e[i]=U(s[t]),e},{})}function H(s){switch(typeof s.className){case"string":return s.className;case"object":return("baseVal"in s.className?s.className.baseVal:null)||s.getAttribute("class")||"";default:return""}}function W(s){let e="";return F(s)&&!Z(s)&&s.childNodes&&s.childNodes.length&&v(s.childNodes,function(t){X(t)&&t.textContent&&(e+=D(t.textContent).split(/(\s+)/).filter(O).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),D(e)}function K(s){return!!s&&s.nodeType===1}function y(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function X(s){return!!s&&s.nodeType===3}function B(s){return!!s&&s.nodeType===11}const I=["a","button","form","input","select","textarea","label"];function ge(s,e){if(!s||y(s,"html")||!K(s))return!1;let t=s;for(;t&&!y(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&B(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=s;t&&!y(t,"body");){if(t.parentNode&&B(t.parentNode)){t=t.parentNode.host,t&&I.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if(I.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const a=window.getComputedStyle(o);a&&a.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=o}const n=window.getComputedStyle(s);if(n&&n.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=s.tagName.toLowerCase();switch(r){case"html":return!1;case"form":return e.type==="submit";case"input":return e.type==="change"||e.type==="click";case"select":case"textarea":return e.type==="change"||e.type==="click";default:return i?e.type==="click":e.type==="click"&&(I.indexOf(r)>-1||s.getAttribute("contenteditable")==="true")}}function F(s){for(let i=s;i.parentNode&&!y(i,"body");i=i.parentNode){const n=H(i).split(" ");if(C(n,"ph-sensitive")||C(n,"ph-no-capture"))return!1}if(C(H(s).split(" "),"ph-include"))return!0;const e=s.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=s.name||s.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function Z(s){const e=["button","checkbox","submit","reset"];return!!(y(s,"input")&&!e.includes(s.type)||y(s,"select")||y(s,"textarea")||s.getAttribute("contenteditable")==="true")}function O(s){return!(s===null||he(s)||typeof s=="string"&&(s=D(s),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((s||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(s)))}function pe(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function Q(){return b(10)}function Y(s){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase())}function me(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function ye(s){const e={},t=s.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const n=t[i].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function q(s){return typeof s=="string"||s instanceof String}function E(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function we(s){if(s===null)return f.ERROR;const e=s.toUpperCase(),t=f[e];return t||t===0?t:f.ERROR}const ke=()=>{let s="false";return typeof window<"u"&&window.localStorage&&(s=localStorage.getItem("um_exclusion")),!(s==null||s==="false")};class ve{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=me(this.handleScroll.bind(this),250),this.initializeEventListener()}initializeEventListener(){window.addEventListener("scroll",this.debouncedHandleScroll)}track(){const e=this.getScrollDepth();e>this.lastScrollDepth&&(this.lastScrollDepth=e,this.checkMilestones(e))}send(e="$scroll"){if(!this.lastScrollDepth)return;const t={percent:this.lastScrollDepth,window_height:this.getWindowHeight(),document_height:this.getDocumentHeight(),scroll_distance:this.getScrollDistance()};this.client.track(e,t)}handleScroll(){this.track()}getScrollDepth(){const e=this.getWindowHeight(),t=this.getDocumentHeight(),i=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(i/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){return Math.max(document.body.scrollHeight||0,this.documentElement.scrollHeight||0,document.body.offsetHeight||0,this.documentElement.offsetHeight||0,document.body.clientHeight||0,this.documentElement.clientHeight||0)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(i=>e>=i).forEach(i=>{this.send(),this.milestones=this.milestones.filter(n=>n!==i)})}destroy(){window.removeEventListener("scroll",this.debouncedHandleScroll)}}const L=class L{constructor(e,t,i=g()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new ve(e),ce(this),V(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};_(document,"submit",e,!1,!0),_(document,"change",e,!1,!0),_(document,"click",e,!1,!0),_(document,"visibilitychange",e,!1,!0),_(document,"scroll",e,!1,!0),_(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var i,n;let t=this.getEventTarget(e);if(X(t)&&(t=t.parentNode||null),e.type==="scroll")return(i=this.scrollDepth)==null||i.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(t&&ge(t,e)){const r=[t];let o=t;for(;o.parentNode&&!y(o,"body");){if(B(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const a=[];let l,c=!1;if(v(r,w=>{const S=F(w);w.tagName.toLowerCase()==="a"&&(l=w.getAttribute("href"),l=S&&O(l)&&l);const u=H(w).split(" ");C(u,"ph-no-capture")&&(c=!0),a.push(this.getPropertiesFromElement(w,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=W(t)),l&&(a[0].attr__href=l),c)return!1;const d=le(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",d),!0}}getCustomProperties(e){const t={};return v(this.customProperties,i=>{v(i.event_selectors,n=>{const r=document.querySelectorAll(n);v(r,o=>{C(e,o)&&F(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return v(document.querySelectorAll(e.css_selector),function(i){let n;["input","select"].indexOf(i.tagName.toLowerCase())>-1?n=i.value:i.textContent&&(n=i.textContent),O(n)&&t.push(n)}),t.join(", ")}getEventTarget(e){var t;return typeof e.target>"u"?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}getPropertiesFromElement(e,t,i){const n=e.tagName.toLowerCase(),r={tag_name:n};I.indexOf(n)>-1&&!i&&(r.$el_text=W(e));const o=H(e);o.length>0&&(r.classes=o.split(" ").filter(function(d){return d!==""})),v(e.attributes,function(d){Z(e)&&["name","id","class"].indexOf(d.name)===-1||!t&&O(d.value)&&!pe(d.name)&&(r["attr__"+d.name]=d.value)});let a=1,l=1,c=e;for(;c=this.previousElementSibling(c);)a++,c.tagName===e.tagName&&l++;return r.nth_child=a,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!K(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<i}};L.FORCE_CAPTURE_ATTR="data-um-force-capture",L.PREVENT_CAPTURE_ATTR="data-um-no-capture";let N=L;class be{constructor(e){this.client=e,this.lastPageUrl=window.location.href,this.trackInitialPageview(),this.initializePageviewTracking()}trackInitialPageview(){this.trackPageview()}initializePageviewTracking(){window.addEventListener("popstate",this.handlePageview.bind(this));const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handlePageview()},window.addEventListener("hashchange",this.handlePageview.bind(this)),setInterval(this.checkForUrlChange.bind(this),1e3)}handlePageview(){this.trackPageview()}checkForUrlChange(){window.location.href!==this.lastPageUrl&&this.trackPageview()}trackPageview(){const e=window.location.href;e!==this.lastPageUrl&&(this.lastPageUrl=e,this.client.track("pageview",{url:e,referrer:document.referrer,title:document.title}))}}class _e{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${b()}?p_${b()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class G{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${b()}?p_${b()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class Ee{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(l=>{n.setRequestHeader(l,a[l])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{i(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${b()}?p_${b()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class j{constructor(e,t){this.storage={},this.storageDisabled=!1,this.quotaErrorLogged=!1,this.prefix=`usermaven_${e}_`,this.logger=t||g(),this.load()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}isStorageEnabled(){return!this.storageDisabled}load(){if(!h()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error loading from localStorage:",e)}}save(){if(!h())return this.logger.warn("localStorage is not available in this environment"),!1;if(this.storageDisabled)return!1;try{return localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage)),!0}catch(e){return this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error saving to localStorage:",e),!1}}isQuotaError(e){const t=e==null?void 0:e.name;return t==="QuotaExceededError"||t==="NS_ERROR_DOM_QUOTA_REACHED"||(e==null?void 0:e.code)===22||(e==null?void 0:e.code)===1014}logQuotaOnce(e){this.quotaErrorLogged||(this.quotaErrorLogged=!0,this.logger.error("localStorage quota exceeded; persisting disabled. Continuing with in-memory storage only.",e))}}class Pe{constructor(){this.storage={}}set(e,t){this.storage[e]=t}get(e){return this.storage[e]}remove(e){delete this.storage[e]}save(){}clear(){this.storage={}}}class ee{constructor(e,t=3,i=1e3,n=10,r=1e3,o=g(),a="default",l=1e3,c=25e5){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.totalQueueBytes=0,this.persistence=new j(`offline_queue_${a}`),this.maxQueueItems=l,this.maxQueueBytes=c,h()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};t.bytes=this.estimateItemBytes(t),this.queue.push(t),this.totalQueueBytes+=t.bytes,this.enforceQueueLimits(),h()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){h()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){h()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!h()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-e.reduce((i,n)=>i+(n.bytes||0),0));const t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),h()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}h()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.totalQueueBytes+=t.bytes||this.estimateItemBytes(t),this.enforceQueueLimits(),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);h()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}enforceQueueLimits(){if(this.maxQueueItems>0&&this.queue.length>this.maxQueueItems){const e=this.queue.length-this.maxQueueItems,t=this.queue.splice(0,e);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-t.reduce((i,n)=>i+(n.bytes||0),0)),this.logger.warn(`Retry queue exceeded ${this.maxQueueItems} items; dropped ${t.length} oldest payload(s)`)}if(this.maxQueueBytes>0&&this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>0){let e=0;for(;this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>1;){const t=this.queue.shift();t&&(this.totalQueueBytes-=t.bytes||this.estimateItemBytes(t),e++)}this.totalQueueBytes=Math.max(0,this.totalQueueBytes),e>0&&this.logger.warn(`Retry queue exceeded ${this.maxQueueBytes} bytes; dropped ${e} oldest payload(s)`)}}estimateItemBytes(e){const t={...e};delete t.bytes;try{return JSON.stringify(t).length}catch{return 0}}loadQueueFromStorage(){if(h()){const e=this.persistence.get("queue");if(!e)return;try{const t=JSON.parse(e);this.queue=t.map(i=>({...i,bytes:i.bytes||this.estimateItemBytes(i)})),this.totalQueueBytes=this.queue.reduce((i,n)=>i+(n.bytes||0),0),this.enforceQueueLimits()}catch(t){this.logger.error("Failed to parse stored queue",t),this.queue=[],this.totalQueueBytes=0}}}saveQueueToStorage(){if(h()){const e=this.queue.map(({bytes:t,...i})=>i);this.persistence.set("queue",JSON.stringify(e))}}}class Se{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),V(this)}initializeEventListener(){document.addEventListener("click",this.handleClick.bind(this))}handleClick(e){const t=e.target;this.shouldCaptureElement(t)&&this.click(e.clientX,e.clientY,Date.now())}shouldCaptureElement(e){return!e.closest(".um-no-capture")}click(e,t,i){const n={x:e,y:t,timestamp:i};this.clicks.push(n),this.clicks=this.clicks.filter(r=>i-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],i=(this.clicks[this.clicks.length-1].timestamp-e.timestamp)/1e3;this.clicks.every((r,o)=>{if(o===0)return!0;const a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class Ae{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),n={hostname:i.hostname,port:443,path:`${i.pathname}${i.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const a=(void 0)(n,l=>{l.on("data",c=>{}),l.on("end",()=>{const c=l.statusCode||0;c>=200&&c<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${c}`))})});a.on("error",l=>{o(l)}),a.write(JSON.stringify(e)),a.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class P{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",J(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",n=>{const r=this._getFieldProps(n.target);this.instance.track("$form_field_change",J({form_id:e.id,form_name:e.name||"",field:r}))})})}static getInstance(e,t="all",i={}){return P.instance||(P.instance=new P(e,t,i)),P.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e),fields:[]},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach(r=>{const o=this._getFieldProps(r);t.fields.push(o)}),t}_getFieldProps(e){const t=Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):void 0,i=this.getSafeText(e);return{tag:e.tagName.toLowerCase(),type:e instanceof HTMLInputElement?e.type:void 0,data_attributes:t,id:e.id,value:i,class:e.className,name:e.name,attributes:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):{}}_convertDOMStringMapToObject(e){const t={};for(const i in e)e.hasOwnProperty(i)&&e[i]!==void 0&&(t[i]=e[i]);return t}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,i=e.length-1;const n=[" ",`
2
- `,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&n.indexOf(e[t])>-1;)t++;for(;i>=t&&n.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class T{constructor(e){this.config=this.mergeConfig(e,z),this.logger=g(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new ee(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new re(this.config.cookieDomain),this.config.autocapture&&N.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new N(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=P.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new be(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Se(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{E(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=g(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new ee(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const n=this.findClosestLink(i.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const l=(a=this.cookieManager)==null?void 0:a.get(t);l&&(o.searchParams.append("_um",l),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){const t="https://events.usermaven.com";if(!h())return new Ae(e.trackingHost||t,e);const i="XMLHttpRequest"in window,n=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new _e(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&n)return new G(e.trackingHost||t,e,this.logger);if(i)return new Ee(e.trackingHost||t,e,this.logger);if(n)return new G(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!h()?new Pe:new j(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!h())return Q();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),c=window.location.hash.substring(1).split("~"),d=c.length>1?c[1]:void 0;t=a||d||Q()}t||(t=Q());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!E(e))throw new Error("User data must be an object");if(e.email&&!Y(e.email))throw new Error("Invalid email provided");if(!e.id||!q(e.id))throw new Error("User ID must be a string");const i=e.id;if(this.persistence.set("userId",i),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}lead(e,t=!1){if(!E(e))throw new Error("Lead payload must be a non-null object and not an array");const i=e.email;if(!q(i)){this.logger.error("Lead event requires a valid email attribute");return}const n=i.trim();if(!n||!Y(n)){this.logger.error("Lead event requires a valid email attribute");return}e.email=n,this.track("lead",e,t)}trackInternal(e,t,i=!1){if(ke()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!q(e))throw new Error("Event name must be a string");if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Event payload must be a non-null object and not an array");const r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!E(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!E(e))throw new Error("Company properties must be an object");if(!e.id||!e.name||!e.created_at)throw new Error("Company properties must include id, name, and created_at");this.persistence.set("companyProps",e),t||await this.track("group",e),this.logger.info("Company identified:",e)}createEventPayload(e,t){const i=this.persistence.get("userProps")||{},n=this.persistence.get("companyProps")||(i==null?void 0:i.company)||{},r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},a=this.persistence.get(`props_${e}`)||{};let l=t||{};const c={event_id:"",user:{anonymous_id:this.anonymousId,id:r,...i},...n&&{company:n},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...o,...a};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});c.autocapture_attributes=d}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),c.event_attributes=l);return h()&&(c.referer=document.referrer,c.url=window.location.href,c.page_title=document.title,c.doc_path=window.location.pathname,c.doc_host=window.location.hostname,c.doc_search=window.location.search,c.screen_resolution=`${window.screen.width}x${window.screen.height}`,c.vp_size=`${window.innerWidth}x${window.innerHeight}`,c.user_agent=navigator.userAgent,c.user_language=navigator.language,c.doc_encoding=document.characterSet,c.utm=this.getUtmParams()),c}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(h()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ye(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){h()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!h())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const n=history.pushState;history.pushState=function(){return i(),n.apply(this,arguments)},window.addEventListener("popstate",i)}getConfig(){return this.config}getLogger(){return this.logger}async reset(e=!1){if(this.persistence.clear(),e&&this.cookieManager){const t=this.config.cookieName||`__eventn_id_${this.config.key}`;this.cookieManager.delete(t),this.anonymousId=this.getOrCreateAnonymousId()}this.logger.info("core state reset",{resetAnonId:e,namespace:this.namespace})}set(e,t){if(!E(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};r={...r,...e},this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};delete r[e],this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function te(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Ce(){return te()?window.define:void 0}const Te="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function $(s){const e=JSON.parse(JSON.stringify(s)),t=U(e),i={...z,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const n=i.key||"",r=`${Te}${n}`;return h()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),h()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new T(i)}function $e(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:we(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="false"?!1:s.getAttribute("data-form-tracking")==="true"?"all":s.getAttribute("data-form-tracking"),autoPageview:s.getAttribute("data-auto-pageview")==="true",useBeaconApi:s.getAttribute("data-use-beacon-api")==="true",forceUseFetch:s.getAttribute("data-force-use-fetch")==="true",gaHook:s.getAttribute("data-ga-hook")==="true",segmentHook:s.getAttribute("data-segment-hook")==="true",randomizeUrl:s.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:s.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:s.getAttribute("data-id-method")||void 0,privacyPolicy:s.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:s.getAttribute("data-ip-policy")||void 0,cookiePolicy:s.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(s.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(s.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(s.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(s.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=s.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:s.getAttribute("data-exclude")||void 0,namespace:s.getAttribute("data-namespace")||void 0,crossDomainLinking:s.getAttribute("data-cross-domain-linking")!=="false",domains:s.getAttribute("data-domains")||void 0,maskAllText:s.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:s.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=$(e),i=e.namespace||"usermaven";return h()&&t.pageview(),xe(i,t),t}function xe(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const p=u[u.length-1];if(p&&typeof p.resolve=="function"){const k=u.pop();try{const A=a.apply(null,u);A&&typeof A.then=="function"?A.then(k.resolve).catch(k.reject):k.resolve(A)}catch(A){k.reject(A)}}else try{a.apply(null,u)}catch(k){console.error("Usermaven: Error processing queued command:",k)}}}}function o(){n.forEach(u=>u()),n.length=0}function a(...u){const p=u[0];if(p==="onLoad"){typeof u[1]=="function"&&(t?u[1]():n.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[p]=="function")return e[p].apply(e,u.slice(1));console.error(`Method ${p} not found on UsermavenClient`)}const l=["id","group","reset"],c=["track","lead","pageview","set","unset","rawTrack","setUserId"];[...l,...c].forEach(u=>{a[u]=function(...p){if(!t){if(l.includes(u))return new Promise((se,k)=>{i.push([u,...p,{resolve:se,reject:k}])});i.push([u,...p]);return}if(typeof e[u]=="function")return e[u].apply(e,p)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[s]=a;const w=`${s}Q`,S=window[w]||[];for(window[w]=S,S.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);S.length>0;){const u=S.shift();u&&i.push(u)}}let ie=!1,M=null;if(h()){const s=Ce();s&&s("usermaven",[],function(){return{usermavenClient:$,UsermavenClient:T,LogLevel:f,getScriptTagClient:()=>M}}),typeof window<"u"&&(window.usermavenClient=$,window.UsermavenClient=T,window.usermavenScriptTagClient=()=>M),function(e,t){const i=e.currentScript;function n(){return ie||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){n()&&(console.log("[Usermaven] Auto-initializing from script tag"),M=$e(i),ie=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!te()&&(module.exports={usermavenClient:$,UsermavenClient:T,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:f,ClientProperties:void 0}),m.LogLevel=f,m.UsermavenClient=T,m.usermavenClient=$,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
1
+ (function(w,p){typeof exports=="object"&&typeof module<"u"?p(exports):typeof define=="function"&&define.amd?define(["exports"],p):(w=typeof globalThis<"u"?globalThis:w||self,p(w.Usermaven={}))})(this,function(w){"use strict";var p=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s))(p||{});class ne{constructor(e){this.level=e}debug(e,...t){this.level<=0&&console.debug("[Usermaven Debug]:",e,...t)}info(e,...t){this.level<=1&&console.info("[Usermaven Info]:",e,...t)}warn(e,...t){this.level<=2&&console.warn("[Usermaven Warning]:",e,...t)}error(e,...t){this.level<=3&&console.error("[Usermaven Error]:",e,...t)}}function m(s=0){return new ne(s)}const V={logLevel:p.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class re{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,n=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,c=n?"; Secure":"",h=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${c}${h}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let n=0;n<i.length;n++){let r=i[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(i=>!isNaN(Number(i)))}extractHostname(e){let t;return e.indexOf("//")>-1?t=e.split("/")[2]:t=e.split("/")[0],t=t.split(":")[0],t=t.split("?")[0],t}extractRootDomain(e){let t=this.extractHostname(e);const i=t.split("."),n=i.length;return n>2&&(i[n-1].length==2?(t=i[n-2]+"."+i[n-1],i[n-2].length==2&&(t=i[n-3]+"."+t)):t=i[n-2]+"."+i[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,i=e.match(t);return i?i[0]:""}}const oe=Object.prototype.hasOwnProperty,I=Array.prototype.forEach,B={};function ae(s,e,t){if(Array.isArray(s)){if(I&&s.forEach===I)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===B)return}}}const b=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},ce=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function _(s,e,t){if(s!=null){if(I&&Array.isArray(s)&&s.forEach===I)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===B)return}else for(const i in s)if(oe.call(s,i)&&e.call(t,s[i],i)===B)return}}const le=function(s,...e){return ae(e,function(t){for(const i in t)t[i]!==void 0&&(s[i]=t[i])}),s};function $(s,e){return s.indexOf(e)!==-1}const ue=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},he=function(s){return s===void 0},A=function(){const s=function(i,n,r,o,a){if(!i){m().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!a);else{const c="on"+n,h=i[c];i[c]=e(i,r,h)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,c;ue(r)&&(c=r(o));const h=n.call(i,o);return(c===!1||h===!1)&&(a=!1),a}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},s}(),de=function(s){return function(...e){try{return s.apply(this,e)}catch(t){m().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},J=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=de(s[e]))};function W(s){for(let e in s)(s[e]===""||s[e]===null||s[e]===void 0||typeof s[e]=="object"&&Object.keys(s[e]).length===0)&&delete s[e];return s}function d(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return m().warn("window is not available"),!1}}function E(s=5){const e=new Uint8Array(s);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,s)}function fe(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function F(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(F):Object.keys(s).reduce((e,t)=>{const i=fe(t);return e[i]=F(s[t]),e},{})}function O(s){switch(typeof s.className){case"string":return s.className;case"object":return("baseVal"in s.className?s.className.baseVal:null)||s.getAttribute("class")||"";default:return""}}function K(s){let e="";return q(s)&&!Z(s)&&s.childNodes&&s.childNodes.length&&_(s.childNodes,function(t){X(t)&&t.textContent&&(e+=b(t.textContent).split(/(\s+)/).filter(L).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),b(e)}function P(s){return!!s&&s.nodeType===1}function v(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function X(s){return!!s&&s.nodeType===3}function Q(s){return!!s&&s.nodeType===11}const N=["a","button","form","input","select","textarea","label"];function ge(s,e){var o,a;if(!s||v(s,"html")||!P(s))return!1;let t=s;for(;t&&!v(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&Q(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=s;t&&!v(t,"body");){if(t.parentNode&&Q(t.parentNode)){t=t.parentNode.host,t&&P(t)&&N.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const c=t.parentNode;if(!c||!P(c))break;if(N.indexOf(c.tagName.toLowerCase())>-1)i=!0;else{const h=window.getComputedStyle(c);h&&h.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=c}const n=window.getComputedStyle(s);if(n&&n.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=(a=(o=s.tagName)==null?void 0:o.toLowerCase)==null?void 0:a.call(o);if(!r)return!1;switch(r){case"html":return!1;case"form":return e.type==="submit";case"input":return e.type==="change"||e.type==="click";case"select":case"textarea":return e.type==="change"||e.type==="click";default:return i?e.type==="click":e.type==="click"&&(N.indexOf(r)>-1||s.getAttribute("contenteditable")==="true")}}function q(s){for(let i=s;i.parentNode&&!v(i,"body");i=i.parentNode){const n=O(i).split(" ");if($(n,"ph-sensitive")||$(n,"ph-no-capture"))return!1}if($(O(s).split(" "),"ph-include"))return!0;const e=s.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=s.name||s.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function Z(s){const e=["button","checkbox","submit","reset"];return!!(v(s,"input")&&!e.includes(s.type)||v(s,"select")||v(s,"textarea")||s.getAttribute("contenteditable")==="true")}function L(s){return!(s===null||he(s)||typeof s=="string"&&(s=b(s),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((s||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(s)))}function pe(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function me(s){if(!s)return!1;const e=s.$el_text;if(typeof e=="string"&&b(e).length>0)return!0;const t=s.classes;if(Array.isArray(t)&&t.some(n=>b(n).length>0))return!0;const i=["attr__id","attr__name","attr__class","attr__aria-label","attr__aria-labelledby","attr__label","attr__href"];for(const n of i){const r=s[n];if(typeof r=="string"&&b(r).length>0)return!0}for(const[n,r]of Object.entries(s))if(n.startsWith("attr__data-")&&typeof r=="string"&&b(r).length>0)return!0;return!1}function R(){return E(10)}function Y(s){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase())}function ye(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function we(s){const e={},t=s.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const n=t[i].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function M(s){return typeof s=="string"||s instanceof String}function S(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function ve(s){if(s===null)return p.ERROR;const e=s.toUpperCase(),t=p[e];return t||t===0?t:p.ERROR}const ke=()=>{let s="false";return typeof window<"u"&&window.localStorage&&(s=localStorage.getItem("um_exclusion")),!(s==null||s==="false")};class be{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ye(this.handleScroll.bind(this),250),this.initializeEventListener()}initializeEventListener(){window.addEventListener("scroll",this.debouncedHandleScroll)}track(){const e=this.getScrollDepth();e>this.lastScrollDepth&&(this.lastScrollDepth=e,this.checkMilestones(e))}send(e="$scroll"){if(!this.lastScrollDepth)return;const t={percent:this.lastScrollDepth,window_height:this.getWindowHeight(),document_height:this.getDocumentHeight(),scroll_distance:this.getScrollDistance()};this.client.track(e,t)}handleScroll(){this.track()}getScrollDepth(){const e=this.getWindowHeight(),t=this.getDocumentHeight(),i=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(i/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){return Math.max(document.body.scrollHeight||0,this.documentElement.scrollHeight||0,document.body.offsetHeight||0,this.documentElement.offsetHeight||0,document.body.clientHeight||0,this.documentElement.clientHeight||0)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(i=>e>=i).forEach(i=>{this.send(),this.milestones=this.milestones.filter(n=>n!==i)})}destroy(){window.removeEventListener("scroll",this.debouncedHandleScroll)}}const U=class U{constructor(e,t,i=m()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new be(e),ce(this),J(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};A(document,"submit",e,!1,!0),A(document,"change",e,!1,!0),A(document,"click",e,!1,!0),A(document,"visibilitychange",e,!1,!0),A(document,"scroll",e,!1,!0),A(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var i,n;let t=this.getEventTarget(e);if(X(t)&&(t=t.parentNode||null),e.type==="scroll")return(i=this.scrollDepth)==null||i.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(!(!t||!P(t))&&t&&ge(t,e)){const r=[t];let o=t;for(;o!=null&&o.parentNode&&!v(o,"body");){if(Q(o==null?void 0:o.parentNode)){const g=(o==null?void 0:o.parentNode).host;g&&P(g)&&r.push(g),o=g;continue}const l=o==null?void 0:o.parentNode;if(!l||!P(l))break;r.push(l),o=l}const a=[];let c,h=!1;if(_(r,l=>{if(!l.tagName)return;const g=q(l);l.tagName.toLowerCase()==="a"&&(c=l.getAttribute("href"),c=g&&L(c)&&c);const u=O(l).split(" ");$(u,"ph-no-capture")&&(h=!0),a.push(this.getPropertiesFromElement(l,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=K(t)),c&&(a[0].attr__href=c),h)return!1;if(!me(a[0]))return this.logger.debug("Dropping autocapture event without identifiers."),!1;const f=le(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",f),!0}}getCustomProperties(e){const t={};return _(this.customProperties,i=>{_(i.event_selectors,n=>{const r=document.querySelectorAll(n);_(r,o=>{$(e,o)&&q(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return _(document.querySelectorAll(e.css_selector),function(i){let n;["input","select"].indexOf(i.tagName.toLowerCase())>-1?n=i.value:i.textContent&&(n=i.textContent),L(n)&&t.push(n)}),t.join(", ")}getEventTarget(e){var t;return typeof e.target>"u"?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}getPropertiesFromElement(e,t,i){const n=e.tagName.toLowerCase(),r={tag_name:n};N.indexOf(n)>-1&&!i&&(r.$el_text=K(e));const o=O(e);o.length>0&&(r.classes=o.split(" ").filter(function(f){return f!==""})),_(e.attributes,function(f){Z(e)&&["name","id","class"].indexOf(f.name)===-1||!t&&L(f.value)&&!pe(f.name)&&(r["attr__"+f.name]=f.value)});let a=1,c=1,h=e;for(;h=this.previousElementSibling(h);)a++,h.tagName===e.tagName&&c++;return r.nth_child=a,r.nth_of_type=c,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!P(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<i}};U.FORCE_CAPTURE_ATTR="data-um-force-capture",U.PREVENT_CAPTURE_ATTR="data-um-no-capture";let D=U;class _e{constructor(e){this.client=e,this.lastPageUrl=window.location.href,this.trackInitialPageview(),this.initializePageviewTracking()}trackInitialPageview(){this.trackPageview()}initializePageviewTracking(){window.addEventListener("popstate",this.handlePageview.bind(this));const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handlePageview()},window.addEventListener("hashchange",this.handlePageview.bind(this)),setInterval(this.checkForUrlChange.bind(this),1e3)}handlePageview(){this.trackPageview()}checkForUrlChange(){window.location.href!==this.lastPageUrl&&this.trackPageview()}trackPageview(){const e=window.location.href;e!==this.lastPageUrl&&(this.lastPageUrl=e,this.client.track("pageview",{url:e,referrer:document.referrer,title:document.title}))}}class Ee{constructor(e,t,i=m()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=d()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${E()}?p_${E()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class j{constructor(e,t,i=m()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=d()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${E()}?p_${E()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class Pe{constructor(e,t,i=m()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(c=>{n.setRequestHeader(c,a[c])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{i(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=d()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${E()}?p_${E()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class G{constructor(e,t){this.storage={},this.storageDisabled=!1,this.quotaErrorLogged=!1,this.prefix=`usermaven_${e}_`,this.logger=t||m(),this.load()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}isStorageEnabled(){return!this.storageDisabled}load(){if(!d()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error loading from localStorage:",e)}}save(){if(!d())return this.logger.warn("localStorage is not available in this environment"),!1;if(this.storageDisabled)return!1;try{return localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage)),!0}catch(e){return this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error saving to localStorage:",e),!1}}isQuotaError(e){const t=e==null?void 0:e.name;return t==="QuotaExceededError"||t==="NS_ERROR_DOM_QUOTA_REACHED"||(e==null?void 0:e.code)===22||(e==null?void 0:e.code)===1014}logQuotaOnce(e){this.quotaErrorLogged||(this.quotaErrorLogged=!0,this.logger.error("localStorage quota exceeded; persisting disabled. Continuing with in-memory storage only.",e))}}class Ae{constructor(){this.storage={}}set(e,t){this.storage[e]=t}get(e){return this.storage[e]}remove(e){delete this.storage[e]}save(){}clear(){this.storage={}}}class ee{constructor(e,t=3,i=1e3,n=10,r=1e3,o=m(),a="default",c=1e3,h=25e5){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.totalQueueBytes=0,this.persistence=new G(`offline_queue_${a}`),this.maxQueueItems=c,this.maxQueueBytes=h,d()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};t.bytes=this.estimateItemBytes(t),this.queue.push(t),this.totalQueueBytes+=t.bytes,this.enforceQueueLimits(),d()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){d()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){d()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!d()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-e.reduce((i,n)=>i+(n.bytes||0),0));const t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),d()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}d()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.totalQueueBytes+=t.bytes||this.estimateItemBytes(t),this.enforceQueueLimits(),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);d()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}enforceQueueLimits(){if(this.maxQueueItems>0&&this.queue.length>this.maxQueueItems){const e=this.queue.length-this.maxQueueItems,t=this.queue.splice(0,e);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-t.reduce((i,n)=>i+(n.bytes||0),0)),this.logger.warn(`Retry queue exceeded ${this.maxQueueItems} items; dropped ${t.length} oldest payload(s)`)}if(this.maxQueueBytes>0&&this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>0){let e=0;for(;this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>1;){const t=this.queue.shift();t&&(this.totalQueueBytes-=t.bytes||this.estimateItemBytes(t),e++)}this.totalQueueBytes=Math.max(0,this.totalQueueBytes),e>0&&this.logger.warn(`Retry queue exceeded ${this.maxQueueBytes} bytes; dropped ${e} oldest payload(s)`)}}estimateItemBytes(e){const t={...e};delete t.bytes;try{return JSON.stringify(t).length}catch{return 0}}loadQueueFromStorage(){if(d()){const e=this.persistence.get("queue");if(!e)return;try{const t=JSON.parse(e);this.queue=t.map(i=>({...i,bytes:i.bytes||this.estimateItemBytes(i)})),this.totalQueueBytes=this.queue.reduce((i,n)=>i+(n.bytes||0),0),this.enforceQueueLimits()}catch(t){this.logger.error("Failed to parse stored queue",t),this.queue=[],this.totalQueueBytes=0}}}saveQueueToStorage(){if(d()){const e=this.queue.map(({bytes:t,...i})=>i);this.persistence.set("queue",JSON.stringify(e))}}}class Se{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),J(this)}initializeEventListener(){document.addEventListener("click",this.handleClick.bind(this))}handleClick(e){const t=e.target;this.shouldCaptureElement(t)&&this.click(e.clientX,e.clientY,Date.now())}shouldCaptureElement(e){return!e.closest(".um-no-capture")}click(e,t,i){const n={x:e,y:t,timestamp:i};this.clicks.push(n),this.clicks=this.clicks.filter(r=>i-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],i=(this.clicks[this.clicks.length-1].timestamp-e.timestamp)/1e3;this.clicks.every((r,o)=>{if(o===0)return!0;const a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class Ce{constructor(e,t,i=m()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),n={hostname:i.hostname,port:443,path:`${i.pathname}${i.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const a=(void 0)(n,c=>{c.on("data",h=>{}),c.on("end",()=>{const h=c.statusCode||0;h>=200&&h<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${h}`))})});a.on("error",c=>{o(c)}),a.write(JSON.stringify(e)),a.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class C{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",W(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",n=>{const r=this._getFieldProps(n.target);this.instance.track("$form_field_change",W({form_id:e.id,form_name:e.name||"",field:r}))})})}static getInstance(e,t="all",i={}){return C.instance||(C.instance=new C(e,t,i)),C.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e),fields:[]},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach(r=>{const o=this._getFieldProps(r);t.fields.push(o)}),t}_getFieldProps(e){const t=Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):void 0,i=this.getSafeText(e);return{tag:e.tagName.toLowerCase(),type:e instanceof HTMLInputElement?e.type:void 0,data_attributes:t,id:e.id,value:i,class:e.className,name:e.name,attributes:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):{}}_convertDOMStringMapToObject(e){const t={};for(const i in e)e.hasOwnProperty(i)&&e[i]!==void 0&&(t[i]=e[i]);return t}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,i=e.length-1;const n=[" ",`
2
+ `,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&n.indexOf(e[t])>-1;)t++;for(;i>=t&&n.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class x{constructor(e){this.config=this.mergeConfig(e,V),this.logger=m(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new ee(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),d()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new re(this.config.cookieDomain),this.config.autocapture&&D.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new D(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=C.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new _e(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Se(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{S(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=m(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new ee(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),d()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const n=this.findClosestLink(i.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const c=(a=this.cookieManager)==null?void 0:a.get(t);c&&(o.searchParams.append("_um",c),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){const t="https://events.usermaven.com";if(!d())return new Ce(e.trackingHost||t,e);const i="XMLHttpRequest"in window,n=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new Ee(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&n)return new j(e.trackingHost||t,e,this.logger);if(i)return new Pe(e.trackingHost||t,e,this.logger);if(n)return new j(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!d()?new Ae:new G(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!d())return R();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),h=window.location.hash.substring(1).split("~"),f=h.length>1?h[1]:void 0;t=a||f||R()}t||(t=R());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!S(e))throw new Error("User data must be an object");if(e.email&&!Y(e.email))throw new Error("Invalid email provided");if(!e.id||!M(e.id))throw new Error("User ID must be a string");const i=e.id;if(this.persistence.set("userId",i),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}lead(e,t=!1){if(!S(e))throw new Error("Lead payload must be a non-null object and not an array");const i=e.email;if(!M(i)){this.logger.error("Lead event requires a valid email attribute");return}const n=i.trim();if(!n||!Y(n)){this.logger.error("Lead event requires a valid email attribute");return}e.email=n,this.track("lead",e,t)}trackInternal(e,t,i=!1){if(ke()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!M(e))throw new Error("Event name must be a string");if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Event payload must be a non-null object and not an array");const r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!S(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!S(e))throw new Error("Company properties must be an object");if(!e.id||!e.name||!e.created_at)throw new Error("Company properties must include id, name, and created_at");this.persistence.set("companyProps",e),t||await this.track("group",e),this.logger.info("Company identified:",e)}createEventPayload(e,t){const{event_id:i,...n}=t||{},r=this.persistence.get("userProps")||{},o=this.persistence.get("companyProps")||(r==null?void 0:r.company)||{},a=this.persistence.get("userId"),c=this.persistence.get("global_props")||{},h=this.persistence.get(`props_${e}`)||{};let f=n;const l={event_id:i||R(),user:{anonymous_id:this.anonymousId,id:a,...r},...o&&{company:o},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...c,...h};if(e==="$autocapture"){const g=this.processAutocaptureAttributes(t||{});l.autocapture_attributes=g}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(g=>{delete f[g]}),l.event_attributes=f);return d()&&(l.referer=document.referrer,l.url=window.location.href,l.page_title=document.title,l.doc_path=window.location.pathname,l.doc_host=window.location.hostname,l.doc_search=window.location.search,l.screen_resolution=`${window.screen.width}x${window.screen.height}`,l.vp_size=`${window.innerWidth}x${window.innerHeight}`,l.user_agent=navigator.userAgent,l.user_language=navigator.language,l.doc_encoding=document.characterSet,l.utm=this.getUtmParams()),l}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(d()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=we(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){d()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!d())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const n=history.pushState;history.pushState=function(){return i(),n.apply(this,arguments)},window.addEventListener("popstate",i)}getConfig(){return this.config}getLogger(){return this.logger}async reset(e=!1){if(this.persistence.clear(),e&&this.cookieManager){const t=this.config.cookieName||`__eventn_id_${this.config.key}`;this.cookieManager.delete(t),this.anonymousId=this.getOrCreateAnonymousId()}this.logger.info("core state reset",{resetAnonId:e,namespace:this.namespace})}set(e,t){if(!S(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};r={...r,...e},this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};delete r[e],this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function te(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Te(){return te()?window.define:void 0}const $e="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function H(s){const e=JSON.parse(JSON.stringify(s)),t=F(e),i={...V,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const n=i.key||"",r=`${$e}${n}`;return d()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),d()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new x(i)}function xe(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ve(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="false"?!1:s.getAttribute("data-form-tracking")==="true"?"all":s.getAttribute("data-form-tracking"),autoPageview:s.getAttribute("data-auto-pageview")==="true",useBeaconApi:s.getAttribute("data-use-beacon-api")==="true",forceUseFetch:s.getAttribute("data-force-use-fetch")==="true",gaHook:s.getAttribute("data-ga-hook")==="true",segmentHook:s.getAttribute("data-segment-hook")==="true",randomizeUrl:s.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:s.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:s.getAttribute("data-id-method")||void 0,privacyPolicy:s.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:s.getAttribute("data-ip-policy")||void 0,cookiePolicy:s.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(s.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(s.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(s.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(s.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=s.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:s.getAttribute("data-exclude")||void 0,namespace:s.getAttribute("data-namespace")||void 0,crossDomainLinking:s.getAttribute("data-cross-domain-linking")!=="false",domains:s.getAttribute("data-domains")||void 0,maskAllText:s.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:s.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=H(e),i=e.namespace||"usermaven";return d()&&t.pageview(),He(i,t),t}function He(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const y=u[u.length-1];if(y&&typeof y.resolve=="function"){const k=u.pop();try{const T=a.apply(null,u);T&&typeof T.then=="function"?T.then(k.resolve).catch(k.reject):k.resolve(T)}catch(T){k.reject(T)}}else try{a.apply(null,u)}catch(k){console.error("Usermaven: Error processing queued command:",k)}}}}function o(){n.forEach(u=>u()),n.length=0}function a(...u){const y=u[0];if(y==="onLoad"){typeof u[1]=="function"&&(t?u[1]():n.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[y]=="function")return e[y].apply(e,u.slice(1));console.error(`Method ${y} not found on UsermavenClient`)}const c=["id","group","reset"],h=["track","lead","pageview","set","unset","rawTrack","setUserId"];[...c,...h].forEach(u=>{a[u]=function(...y){if(!t){if(c.includes(u))return new Promise((se,k)=>{i.push([u,...y,{resolve:se,reject:k}])});i.push([u,...y]);return}if(typeof e[u]=="function")return e[u].apply(e,y)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[s]=a;const l=`${s}Q`,g=window[l]||[];for(window[l]=g,g.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);g.length>0;){const u=g.shift();u&&i.push(u)}}let ie=!1,z=null;if(d()){const s=Te();s&&s("usermaven",[],function(){return{usermavenClient:H,UsermavenClient:x,LogLevel:p,getScriptTagClient:()=>z}}),typeof window<"u"&&(window.usermavenClient=H,window.UsermavenClient=x,window.usermavenScriptTagClient=()=>z),function(e,t){const i=e.currentScript;function n(){return ie||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){n()&&(console.log("[Usermaven] Auto-initializing from script tag"),z=xe(i),ie=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!te()&&(module.exports={usermavenClient:H,UsermavenClient:x,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:p,ClientProperties:void 0}),w.LogLevel=p,w.UsermavenClient=x,w.usermavenClient=H,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var y=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s))(y||{});class se{constructor(e){this.level=e}debug(e,...t){this.level<=0&&console.debug("[Usermaven Debug]:",e,...t)}info(e,...t){this.level<=1&&console.info("[Usermaven Info]:",e,...t)}warn(e,...t){this.level<=2&&console.warn("[Usermaven Warning]:",e,...t)}error(e,...t){this.level<=3&&console.error("[Usermaven Error]:",e,...t)}}function g(s=0){return new se(s)}const Z={logLevel:y.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class ne{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,n=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,l=n?"; Secure":"",c=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${l}${c}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let n=0;n<i.length;n++){let r=i[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(i=>!isNaN(Number(i)))}extractHostname(e){let t;return e.indexOf("//")>-1?t=e.split("/")[2]:t=e.split("/")[0],t=t.split(":")[0],t=t.split("?")[0],t}extractRootDomain(e){let t=this.extractHostname(e);const i=t.split("."),n=i.length;return n>2&&(i[n-1].length==2?(t=i[n-2]+"."+i[n-1],i[n-2].length==2&&(t=i[n-3]+"."+t)):t=i[n-2]+"."+i[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,i=e.match(t);return i?i[0]:""}}const re=Object.prototype,oe=re.hasOwnProperty,ae=Array.prototype,H=ae.forEach,U={};function ce(s,e,t){if(Array.isArray(s)){if(H&&s.forEach===H)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===U)return}}}const B=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},le=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function k(s,e,t){if(s!=null){if(H&&Array.isArray(s)&&s.forEach===H)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===U)return}else for(const i in s)if(oe.call(s,i)&&e.call(t,s[i],i)===U)return}}const ue=function(s,...e){return ce(e,function(t){for(const i in t)t[i]!==void 0&&(s[i]=t[i])}),s};function A(s,e){return s.indexOf(e)!==-1}const he=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},de=function(s){return s===void 0},E=function(){const s=function(i,n,r,o,a){if(!i){g().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!a);else{const l="on"+n,c=i[l];i[l]=e(i,r,c)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,l;he(r)&&(l=r(o));const c=n.call(i,o);return(l===!1||c===!1)&&(a=!1),a}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},s}(),ge=function(s){return function(...e){try{return s.apply(this,e)}catch(t){g().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},Y=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=ge(s[e]))};function z(s){for(let e in s)(s[e]===""||s[e]===null||s[e]===void 0||typeof s[e]=="object"&&Object.keys(s[e]).length===0)&&delete s[e];return s}function h(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return g().warn("window is not available"),!1}}function v(s=5){const e=new Uint8Array(s);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,s)}function fe(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function F(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(F):Object.keys(s).reduce((e,t)=>{const i=fe(t);return e[i]=F(s[t]),e},{})}function I(s){switch(typeof s.className){case"string":return s.className;case"object":return("baseVal"in s.className?s.className.baseVal:null)||s.getAttribute("class")||"";default:return""}}function V(s){let e="";return q(s)&&!ee(s)&&s.childNodes&&s.childNodes.length&&k(s.childNodes,function(t){j(t)&&t.textContent&&(e+=B(t.textContent).split(/(\s+)/).filter(x).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),B(e)}function G(s){return!!s&&s.nodeType===1}function w(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function j(s){return!!s&&s.nodeType===3}function Q(s){return!!s&&s.nodeType===11}const $=["a","button","form","input","select","textarea","label"];function pe(s,e){if(!s||w(s,"html")||!G(s))return!1;let t=s;for(;t&&!w(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&Q(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=s;t&&!w(t,"body");){if(t.parentNode&&Q(t.parentNode)){t=t.parentNode.host,t&&$.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if($.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const a=window.getComputedStyle(o);a&&a.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=o}const n=window.getComputedStyle(s);if(n&&n.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=s.tagName.toLowerCase();switch(r){case"html":return!1;case"form":return e.type==="submit";case"input":return e.type==="change"||e.type==="click";case"select":case"textarea":return e.type==="change"||e.type==="click";default:return i?e.type==="click":e.type==="click"&&($.indexOf(r)>-1||s.getAttribute("contenteditable")==="true")}}function q(s){for(let i=s;i.parentNode&&!w(i,"body");i=i.parentNode){const n=I(i).split(" ");if(A(n,"ph-sensitive")||A(n,"ph-no-capture"))return!1}if(A(I(s).split(" "),"ph-include"))return!0;const e=s.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=s.name||s.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function ee(s){const e=["button","checkbox","submit","reset"];return!!(w(s,"input")&&!e.includes(s.type)||w(s,"select")||w(s,"textarea")||s.getAttribute("contenteditable")==="true")}function x(s){return!(s===null||de(s)||typeof s=="string"&&(s=B(s),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((s||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(s)))}function me(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function L(){return v(10)}function J(s){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase())}function ye(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function we(s){const e={},t=s.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const n=t[i].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function R(s){return typeof s=="string"||s instanceof String}function P(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function ke(s){if(s===null)return y.ERROR;const e=s.toUpperCase(),t=y[e];return t||t===0?t:y.ERROR}const ve=()=>{let s="false";return typeof window<"u"&&window.localStorage&&(s=localStorage.getItem("um_exclusion")),!(s==null||s==="false")};class be{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ye(this.handleScroll.bind(this),250),this.initializeEventListener()}initializeEventListener(){window.addEventListener("scroll",this.debouncedHandleScroll)}track(){const e=this.getScrollDepth();e>this.lastScrollDepth&&(this.lastScrollDepth=e,this.checkMilestones(e))}send(e="$scroll"){if(!this.lastScrollDepth)return;const t={percent:this.lastScrollDepth,window_height:this.getWindowHeight(),document_height:this.getDocumentHeight(),scroll_distance:this.getScrollDistance()};this.client.track(e,t)}handleScroll(){this.track()}getScrollDepth(){const e=this.getWindowHeight(),t=this.getDocumentHeight(),i=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(i/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){return Math.max(document.body.scrollHeight||0,this.documentElement.scrollHeight||0,document.body.offsetHeight||0,this.documentElement.offsetHeight||0,document.body.clientHeight||0,this.documentElement.clientHeight||0)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(i=>e>=i).forEach(i=>{this.send(),this.milestones=this.milestones.filter(n=>n!==i)})}destroy(){window.removeEventListener("scroll",this.debouncedHandleScroll)}}const N=class N{constructor(e,t,i=g()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new be(e),le(this),Y(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};E(document,"submit",e,!1,!0),E(document,"change",e,!1,!0),E(document,"click",e,!1,!0),E(document,"visibilitychange",e,!1,!0),E(document,"scroll",e,!1,!0),E(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var i,n;let t=this.getEventTarget(e);if(j(t)&&(t=t.parentNode||null),e.type==="scroll")return(i=this.scrollDepth)==null||i.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(t&&pe(t,e)){const r=[t];let o=t;for(;o.parentNode&&!w(o,"body");){if(Q(o.parentNode)){r.push(o.parentNode.host),o=o.parentNode.host;continue}r.push(o.parentNode),o=o.parentNode}const a=[];let l,c=!1;if(k(r,p=>{const b=q(p);p.tagName.toLowerCase()==="a"&&(l=p.getAttribute("href"),l=b&&x(l)&&l);const u=I(p).split(" ");A(u,"ph-no-capture")&&(c=!0),a.push(this.getPropertiesFromElement(p,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=V(t)),l&&(a[0].attr__href=l),c)return!1;const d=ue(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",d),!0}}getCustomProperties(e){const t={};return k(this.customProperties,i=>{k(i.event_selectors,n=>{const r=document.querySelectorAll(n);k(r,o=>{A(e,o)&&q(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return k(document.querySelectorAll(e.css_selector),function(i){let n;["input","select"].indexOf(i.tagName.toLowerCase())>-1?n=i.value:i.textContent&&(n=i.textContent),x(n)&&t.push(n)}),t.join(", ")}getEventTarget(e){var t;return typeof e.target>"u"?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}getPropertiesFromElement(e,t,i){const n=e.tagName.toLowerCase(),r={tag_name:n};$.indexOf(n)>-1&&!i&&(r.$el_text=V(e));const o=I(e);o.length>0&&(r.classes=o.split(" ").filter(function(d){return d!==""})),k(e.attributes,function(d){ee(e)&&["name","id","class"].indexOf(d.name)===-1||!t&&x(d.value)&&!me(d.name)&&(r["attr__"+d.name]=d.value)});let a=1,l=1,c=e;for(;c=this.previousElementSibling(c);)a++,c.tagName===e.tagName&&l++;return r.nth_child=a,r.nth_of_type=l,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!G(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<i}};N.FORCE_CAPTURE_ATTR="data-um-force-capture",N.PREVENT_CAPTURE_ATTR="data-um-no-capture";let O=N;class _e{constructor(e){this.client=e,this.lastPageUrl=window.location.href,this.trackInitialPageview(),this.initializePageviewTracking()}trackInitialPageview(){this.trackPageview()}initializePageviewTracking(){window.addEventListener("popstate",this.handlePageview.bind(this));const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handlePageview()},window.addEventListener("hashchange",this.handlePageview.bind(this)),setInterval(this.checkForUrlChange.bind(this),1e3)}handlePageview(){this.trackPageview()}checkForUrlChange(){window.location.href!==this.lastPageUrl&&this.trackPageview()}trackPageview(){const e=window.location.href;e!==this.lastPageUrl&&(this.lastPageUrl=e,this.client.track("pageview",{url:e,referrer:document.referrer,title:document.title}))}}class Ee{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class W{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class Pe{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(l=>{n.setRequestHeader(l,a[l])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{i(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=h()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${v()}?p_${v()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class te{constructor(e,t){this.storage={},this.storageDisabled=!1,this.quotaErrorLogged=!1,this.prefix=`usermaven_${e}_`,this.logger=t||g(),this.load()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}isStorageEnabled(){return!this.storageDisabled}load(){if(!h()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error loading from localStorage:",e)}}save(){if(!h())return this.logger.warn("localStorage is not available in this environment"),!1;if(this.storageDisabled)return!1;try{return localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage)),!0}catch(e){return this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error saving to localStorage:",e),!1}}isQuotaError(e){const t=e==null?void 0:e.name;return t==="QuotaExceededError"||t==="NS_ERROR_DOM_QUOTA_REACHED"||(e==null?void 0:e.code)===22||(e==null?void 0:e.code)===1014}logQuotaOnce(e){this.quotaErrorLogged||(this.quotaErrorLogged=!0,this.logger.error("localStorage quota exceeded; persisting disabled. Continuing with in-memory storage only.",e))}}class Se{constructor(){this.storage={}}set(e,t){this.storage[e]=t}get(e){return this.storage[e]}remove(e){delete this.storage[e]}save(){}clear(){this.storage={}}}class K{constructor(e,t=3,i=1e3,n=10,r=1e3,o=g(),a="default",l=1e3,c=25e5){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.totalQueueBytes=0,this.persistence=new te(`offline_queue_${a}`),this.maxQueueItems=l,this.maxQueueBytes=c,h()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};t.bytes=this.estimateItemBytes(t),this.queue.push(t),this.totalQueueBytes+=t.bytes,this.enforceQueueLimits(),h()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){h()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){h()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!h()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-e.reduce((i,n)=>i+(n.bytes||0),0));const t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),h()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}h()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.totalQueueBytes+=t.bytes||this.estimateItemBytes(t),this.enforceQueueLimits(),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);h()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}enforceQueueLimits(){if(this.maxQueueItems>0&&this.queue.length>this.maxQueueItems){const e=this.queue.length-this.maxQueueItems,t=this.queue.splice(0,e);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-t.reduce((i,n)=>i+(n.bytes||0),0)),this.logger.warn(`Retry queue exceeded ${this.maxQueueItems} items; dropped ${t.length} oldest payload(s)`)}if(this.maxQueueBytes>0&&this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>0){let e=0;for(;this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>1;){const t=this.queue.shift();t&&(this.totalQueueBytes-=t.bytes||this.estimateItemBytes(t),e++)}this.totalQueueBytes=Math.max(0,this.totalQueueBytes),e>0&&this.logger.warn(`Retry queue exceeded ${this.maxQueueBytes} bytes; dropped ${e} oldest payload(s)`)}}estimateItemBytes(e){const t={...e};delete t.bytes;try{return JSON.stringify(t).length}catch{return 0}}loadQueueFromStorage(){if(h()){const e=this.persistence.get("queue");if(!e)return;try{const t=JSON.parse(e);this.queue=t.map(i=>({...i,bytes:i.bytes||this.estimateItemBytes(i)})),this.totalQueueBytes=this.queue.reduce((i,n)=>i+(n.bytes||0),0),this.enforceQueueLimits()}catch(t){this.logger.error("Failed to parse stored queue",t),this.queue=[],this.totalQueueBytes=0}}}saveQueueToStorage(){if(h()){const e=this.queue.map(({bytes:t,...i})=>i);this.persistence.set("queue",JSON.stringify(e))}}}class Ae{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),Y(this)}initializeEventListener(){document.addEventListener("click",this.handleClick.bind(this))}handleClick(e){const t=e.target;this.shouldCaptureElement(t)&&this.click(e.clientX,e.clientY,Date.now())}shouldCaptureElement(e){return!e.closest(".um-no-capture")}click(e,t,i){const n={x:e,y:t,timestamp:i};this.clicks.push(n),this.clicks=this.clicks.filter(r=>i-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],i=(this.clicks[this.clicks.length-1].timestamp-e.timestamp)/1e3;this.clicks.every((r,o)=>{if(o===0)return!0;const a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class Ce{constructor(e,t,i=g()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),n={hostname:i.hostname,port:443,path:`${i.pathname}${i.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const a=(void 0)(n,l=>{l.on("data",c=>{}),l.on("end",()=>{const c=l.statusCode||0;c>=200&&c<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${c}`))})});a.on("error",l=>{o(l)}),a.write(JSON.stringify(e)),a.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class S{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",z(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",n=>{const r=this._getFieldProps(n.target);this.instance.track("$form_field_change",z({form_id:e.id,form_name:e.name||"",field:r}))})})}static getInstance(e,t="all",i={}){return S.instance||(S.instance=new S(e,t,i)),S.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e),fields:[]},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach(r=>{const o=this._getFieldProps(r);t.fields.push(o)}),t}_getFieldProps(e){const t=Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):void 0,i=this.getSafeText(e);return{tag:e.tagName.toLowerCase(),type:e instanceof HTMLInputElement?e.type:void 0,data_attributes:t,id:e.id,value:i,class:e.className,name:e.name,attributes:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):{}}_convertDOMStringMapToObject(e){const t={};for(const i in e)e.hasOwnProperty(i)&&e[i]!==void 0&&(t[i]=e[i]);return t}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,i=e.length-1;const n=[" ",`
2
- `,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&n.indexOf(e[t])>-1;)t++;for(;i>=t&&n.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class C{constructor(e){this.config=this.mergeConfig(e,Z),this.logger=g(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new K(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new ne(this.config.cookieDomain),this.config.autocapture&&O.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new O(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=S.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new _e(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Ae(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{P(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=g(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new K(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),h()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const n=this.findClosestLink(i.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const l=(a=this.cookieManager)==null?void 0:a.get(t);l&&(o.searchParams.append("_um",l),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){const t="https://events.usermaven.com";if(!h())return new Ce(e.trackingHost||t,e);const i="XMLHttpRequest"in window,n=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new Ee(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&n)return new W(e.trackingHost||t,e,this.logger);if(i)return new Pe(e.trackingHost||t,e,this.logger);if(n)return new W(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!h()?new Se:new te(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!h())return L();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),c=window.location.hash.substring(1).split("~"),d=c.length>1?c[1]:void 0;t=a||d||L()}t||(t=L());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!P(e))throw new Error("User data must be an object");if(e.email&&!J(e.email))throw new Error("Invalid email provided");if(!e.id||!R(e.id))throw new Error("User ID must be a string");const i=e.id;if(this.persistence.set("userId",i),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}lead(e,t=!1){if(!P(e))throw new Error("Lead payload must be a non-null object and not an array");const i=e.email;if(!R(i)){this.logger.error("Lead event requires a valid email attribute");return}const n=i.trim();if(!n||!J(n)){this.logger.error("Lead event requires a valid email attribute");return}e.email=n,this.track("lead",e,t)}trackInternal(e,t,i=!1){if(ve()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!R(e))throw new Error("Event name must be a string");if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Event payload must be a non-null object and not an array");const r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!P(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!P(e))throw new Error("Company properties must be an object");if(!e.id||!e.name||!e.created_at)throw new Error("Company properties must include id, name, and created_at");this.persistence.set("companyProps",e),t||await this.track("group",e),this.logger.info("Company identified:",e)}createEventPayload(e,t){const i=this.persistence.get("userProps")||{},n=this.persistence.get("companyProps")||(i==null?void 0:i.company)||{},r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},a=this.persistence.get(`props_${e}`)||{};let l=t||{};const c={event_id:"",user:{anonymous_id:this.anonymousId,id:r,...i},...n&&{company:n},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...o,...a};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});c.autocapture_attributes=d}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),c.event_attributes=l);return h()&&(c.referer=document.referrer,c.url=window.location.href,c.page_title=document.title,c.doc_path=window.location.pathname,c.doc_host=window.location.hostname,c.doc_search=window.location.search,c.screen_resolution=`${window.screen.width}x${window.screen.height}`,c.vp_size=`${window.innerWidth}x${window.innerHeight}`,c.user_agent=navigator.userAgent,c.user_language=navigator.language,c.doc_encoding=document.characterSet,c.utm=this.getUtmParams()),c}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(h()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=we(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){h()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!h())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const n=history.pushState;history.pushState=function(){return i(),n.apply(this,arguments)},window.addEventListener("popstate",i)}getConfig(){return this.config}getLogger(){return this.logger}async reset(e=!1){if(this.persistence.clear(),e&&this.cookieManager){const t=this.config.cookieName||`__eventn_id_${this.config.key}`;this.cookieManager.delete(t),this.anonymousId=this.getOrCreateAnonymousId()}this.logger.info("core state reset",{resetAnonId:e,namespace:this.namespace})}set(e,t){if(!P(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};r={...r,...e},this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};delete r[e],this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function ie(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Te(){return ie()?window.define:void 0}const $e="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function T(s){const e=JSON.parse(JSON.stringify(s)),t=F(e),i={...Z,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const n=i.key||"",r=`${$e}${n}`;return h()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),h()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new C(i)}function xe(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ke(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="false"?!1:s.getAttribute("data-form-tracking")==="true"?"all":s.getAttribute("data-form-tracking"),autoPageview:s.getAttribute("data-auto-pageview")==="true",useBeaconApi:s.getAttribute("data-use-beacon-api")==="true",forceUseFetch:s.getAttribute("data-force-use-fetch")==="true",gaHook:s.getAttribute("data-ga-hook")==="true",segmentHook:s.getAttribute("data-segment-hook")==="true",randomizeUrl:s.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:s.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:s.getAttribute("data-id-method")||void 0,privacyPolicy:s.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:s.getAttribute("data-ip-policy")||void 0,cookiePolicy:s.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(s.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(s.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(s.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(s.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=s.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:s.getAttribute("data-exclude")||void 0,namespace:s.getAttribute("data-namespace")||void 0,crossDomainLinking:s.getAttribute("data-cross-domain-linking")!=="false",domains:s.getAttribute("data-domains")||void 0,maskAllText:s.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:s.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=T(e),i=e.namespace||"usermaven";return h()&&t.pageview(),He(i,t),t}function He(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const f=u[u.length-1];if(f&&typeof f.resolve=="function"){const m=u.pop();try{const _=a.apply(null,u);_&&typeof _.then=="function"?_.then(m.resolve).catch(m.reject):m.resolve(_)}catch(_){m.reject(_)}}else try{a.apply(null,u)}catch(m){console.error("Usermaven: Error processing queued command:",m)}}}}function o(){n.forEach(u=>u()),n.length=0}function a(...u){const f=u[0];if(f==="onLoad"){typeof u[1]=="function"&&(t?u[1]():n.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[f]=="function")return e[f].apply(e,u.slice(1));console.error(`Method ${f} not found on UsermavenClient`)}const l=["id","group","reset"],c=["track","lead","pageview","set","unset","rawTrack","setUserId"];[...l,...c].forEach(u=>{a[u]=function(...f){if(!t){if(l.includes(u))return new Promise((M,m)=>{i.push([u,...f,{resolve:M,reject:m}])});i.push([u,...f]);return}if(typeof e[u]=="function")return e[u].apply(e,f)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[s]=a;const p=`${s}Q`,b=window[p]||[];for(window[p]=b,b.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);b.length>0;){const u=b.shift();u&&i.push(u)}}let X=!1,D=null;if(h()){const s=Te();s&&s("usermaven",[],function(){return{usermavenClient:T,UsermavenClient:C,LogLevel:y,getScriptTagClient:()=>D}}),typeof window<"u"&&(window.usermavenClient=T,window.UsermavenClient=C,window.usermavenScriptTagClient=()=>D),function(e,t){const i=e.currentScript;function n(){return X||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){n()&&(console.log("[Usermaven] Auto-initializing from script tag"),D=xe(i),X=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!ie()&&(module.exports={usermavenClient:T,UsermavenClient:C,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:y,ClientProperties:void 0});exports.LogLevel=y;exports.UsermavenClient=C;exports.usermavenClient=T;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var w=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s))(w||{});class se{constructor(e){this.level=e}debug(e,...t){this.level<=0&&console.debug("[Usermaven Debug]:",e,...t)}info(e,...t){this.level<=1&&console.info("[Usermaven Info]:",e,...t)}warn(e,...t){this.level<=2&&console.warn("[Usermaven Warning]:",e,...t)}error(e,...t){this.level<=3&&console.error("[Usermaven Error]:",e,...t)}}function p(s=0){return new se(s)}const Y={logLevel:w.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!0,disableEventPersistence:!1,gaHook:!1,segmentHook:!1,randomizeUrl:!1,capture3rdPartyCookies:["_ga","_fbp","_ym_uid","ajs_user_id","ajs_anonymous_id"],idMethod:"cookie",ipPolicy:"keep",cookiePolicy:"keep",minSendTimeout:0,maxSendTimeout:2e3,maxSendAttempts:4,propertiesStringMaxLength:null,propertyBlacklist:[],crossDomainLinking:!0,maskAllText:!1,maskAllElementAttributes:!1};class ne{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain()}set(e,t,i=365,n=!0,r=!1){const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const a=`expires=${o.toUTCString()}`,c=n?"; Secure":"",h=r?"; HttpOnly":"";document.cookie=`${e}=${t};${a};path=/;domain=${this.cookieDomain}${c}${h}`}get(e){const t=e+"=",i=document.cookie.split(";");for(let n=0;n<i.length;n++){let r=i[n].trim();if(r.indexOf(t)===0)return decodeURIComponent(r.substring(t.length))}return null}delete(e,t="/"){document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=${t};domain=${this.cookieDomain}`}getCookieDomain(){return typeof window>"u"||this.domain?this.domain||"":this.extractRoot(window.location.hostname)}extractRoot(e){if(this.isIpAddress(e)||e==="localhost")return e;let t=this.extractTopLevelDomain(e);return t||(t=this.extractRootDomain(e)),"."+t}isIpAddress(e){const t=e.split(".");return t.length===4&&t.every(i=>!isNaN(Number(i)))}extractHostname(e){let t;return e.indexOf("//")>-1?t=e.split("/")[2]:t=e.split("/")[0],t=t.split(":")[0],t=t.split("?")[0],t}extractRootDomain(e){let t=this.extractHostname(e);const i=t.split("."),n=i.length;return n>2&&(i[n-1].length==2?(t=i[n-2]+"."+i[n-1],i[n-2].length==2&&(t=i[n-3]+"."+t)):t=i[n-2]+"."+i[n-1]),t}extractTopLevelDomain(e){const t=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,i=e.match(t);return i?i[0]:""}}const re=Object.prototype,oe=re.hasOwnProperty,ae=Array.prototype,N=ae.forEach,F={};function ce(s,e,t){if(Array.isArray(s)){if(N&&s.forEach===N)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===F)return}}}const b=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},le=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function k(s,e,t){if(s!=null){if(N&&Array.isArray(s)&&s.forEach===N)s.forEach(e,t);else if("length"in s&&s.length===+s.length){for(let i=0,n=s.length;i<n;i++)if(i in s&&e.call(t,s[i],i)===F)return}else for(const i in s)if(oe.call(s,i)&&e.call(t,s[i],i)===F)return}}const ue=function(s,...e){return ce(e,function(t){for(const i in t)t[i]!==void 0&&(s[i]=t[i])}),s};function $(s,e){return s.indexOf(e)!==-1}const he=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},de=function(s){return s===void 0},A=function(){const s=function(i,n,r,o,a){if(!i){p().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!a);else{const c="on"+n,h=i[c];i[c]=e(i,r,h)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let a=!0,c;he(r)&&(c=r(o));const h=n.call(i,o);return(c===!1||h===!1)&&(a=!1),a}}function t(i){return i&&(i.preventDefault=t.preventDefault,i.stopPropagation=t.stopPropagation),i}return t.preventDefault=function(){this.returnValue=!1},t.stopPropagation=function(){this.cancelBubble=!0},s}(),fe=function(s){return function(...e){try{return s.apply(this,e)}catch(t){p().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},G=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=fe(s[e]))};function V(s){for(let e in s)(s[e]===""||s[e]===null||s[e]===void 0||typeof s[e]=="object"&&Object.keys(s[e]).length===0)&&delete s[e];return s}function d(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return p().warn("window is not available"),!1}}function E(s=5){const e=new Uint8Array(s);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(36).padStart(2,"0")).join("").slice(0,s)}function ge(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function Q(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(Q):Object.keys(s).reduce((e,t)=>{const i=ge(t);return e[i]=Q(s[t]),e},{})}function L(s){switch(typeof s.className){case"string":return s.className;case"object":return("baseVal"in s.className?s.className.baseVal:null)||s.getAttribute("class")||"";default:return""}}function J(s){let e="";return M(s)&&!ee(s)&&s.childNodes&&s.childNodes.length&&k(s.childNodes,function(t){j(t)&&t.textContent&&(e+=b(t.textContent).split(/(\s+)/).filter(O).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),b(e)}function _(s){return!!s&&s.nodeType===1}function v(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function j(s){return!!s&&s.nodeType===3}function q(s){return!!s&&s.nodeType===11}const I=["a","button","form","input","select","textarea","label"];function pe(s,e){var o,a;if(!s||v(s,"html")||!_(s))return!1;let t=s;for(;t&&!v(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&q(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=s;t&&!v(t,"body");){if(t.parentNode&&q(t.parentNode)){t=t.parentNode.host,t&&_(t)&&I.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const c=t.parentNode;if(!c||!_(c))break;if(I.indexOf(c.tagName.toLowerCase())>-1)i=!0;else{const h=window.getComputedStyle(c);h&&h.getPropertyValue("cursor")==="pointer"&&(i=!0)}t=c}const n=window.getComputedStyle(s);if(n&&n.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const r=(a=(o=s.tagName)==null?void 0:o.toLowerCase)==null?void 0:a.call(o);if(!r)return!1;switch(r){case"html":return!1;case"form":return e.type==="submit";case"input":return e.type==="change"||e.type==="click";case"select":case"textarea":return e.type==="change"||e.type==="click";default:return i?e.type==="click":e.type==="click"&&(I.indexOf(r)>-1||s.getAttribute("contenteditable")==="true")}}function M(s){for(let i=s;i.parentNode&&!v(i,"body");i=i.parentNode){const n=L(i).split(" ");if($(n,"ph-sensitive")||$(n,"ph-no-capture"))return!1}if($(L(s).split(" "),"ph-include"))return!0;const e=s.type||"";if(typeof e=="string")switch(e.toLowerCase()){case"hidden":return!1;case"password":return!1}const t=s.name||s.id||"";return!(typeof t=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(t.replace(/[^a-zA-Z0-9]/g,"")))}function ee(s){const e=["button","checkbox","submit","reset"];return!!(v(s,"input")&&!e.includes(s.type)||v(s,"select")||v(s,"textarea")||s.getAttribute("contenteditable")==="true")}function O(s){return!(s===null||de(s)||typeof s=="string"&&(s=b(s),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((s||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(s)))}function me(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function ye(s){if(!s)return!1;const e=s.$el_text;if(typeof e=="string"&&b(e).length>0)return!0;const t=s.classes;if(Array.isArray(t)&&t.some(n=>b(n).length>0))return!0;const i=["attr__id","attr__name","attr__class","attr__aria-label","attr__aria-labelledby","attr__label","attr__href"];for(const n of i){const r=s[n];if(typeof r=="string"&&b(r).length>0)return!0}for(const[n,r]of Object.entries(s))if(n.startsWith("attr__data-")&&typeof r=="string"&&b(r).length>0)return!0;return!1}function H(){return E(10)}function W(s){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase())}function we(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function ve(s){const e={},t=s.replace(/^\?/,"").split("&");for(let i=0;i<t.length;i++){const n=t[i].split("=");n[0]!==""&&(e[decodeURIComponent(n[0])]=decodeURIComponent(n[1]||""))}return e}function U(s){return typeof s=="string"||s instanceof String}function S(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function ke(s){if(s===null)return w.ERROR;const e=s.toUpperCase(),t=w[e];return t||t===0?t:w.ERROR}const be=()=>{let s="false";return typeof window<"u"&&window.localStorage&&(s=localStorage.getItem("um_exclusion")),!(s==null||s==="false")};class _e{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=we(this.handleScroll.bind(this),250),this.initializeEventListener()}initializeEventListener(){window.addEventListener("scroll",this.debouncedHandleScroll)}track(){const e=this.getScrollDepth();e>this.lastScrollDepth&&(this.lastScrollDepth=e,this.checkMilestones(e))}send(e="$scroll"){if(!this.lastScrollDepth)return;const t={percent:this.lastScrollDepth,window_height:this.getWindowHeight(),document_height:this.getDocumentHeight(),scroll_distance:this.getScrollDistance()};this.client.track(e,t)}handleScroll(){this.track()}getScrollDepth(){const e=this.getWindowHeight(),t=this.getDocumentHeight(),i=this.getScrollDistance(),n=t-e;return Math.min(100,Math.floor(i/n*100))}getWindowHeight(){return window.innerHeight||this.documentElement.clientHeight||document.body.clientHeight||0}getDocumentHeight(){return Math.max(document.body.scrollHeight||0,this.documentElement.scrollHeight||0,document.body.offsetHeight||0,this.documentElement.offsetHeight||0,document.body.clientHeight||0,this.documentElement.clientHeight||0)}getScrollDistance(){return window.pageYOffset||this.documentElement.scrollTop||document.body.scrollTop||0}checkMilestones(e){this.milestones.filter(i=>e>=i).forEach(i=>{this.send(),this.milestones=this.milestones.filter(n=>n!==i)})}destroy(){window.removeEventListener("scroll",this.debouncedHandleScroll)}}const D=class D{constructor(e,t,i=p()){this.logger=i,this.scrollDepth=null,this.customProperties=[],this.domHandlersAttached=!1,this.client=e,this.options=t,this.scrollDepth=new _e(e),le(this),G(this)}isBrowserSupported(){return typeof document<"u"&&typeof document.addEventListener=="function"}init(){if(!this.isBrowserSupported()){this.logger.debug("Browser not supported for autocapture");return}if(this.domHandlersAttached){this.logger.debug("Autocapture already initialized.");return}if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers(),this.domHandlersAttached=!0}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};A(document,"submit",e,!1,!0),A(document,"change",e,!1,!0),A(document,"click",e,!1,!0),A(document,"visibilitychange",e,!1,!0),A(document,"scroll",e,!1,!0),A(window,"popstate",e,!1,!0)}isPageRefresh(){if("PerformanceNavigationTiming"in window){const e=performance.getEntriesByType("navigation");if(e.length>0)return e[0].type==="reload"}return performance.navigation&&performance.navigation.type===1}captureEvent(e){var i,n;let t=this.getEventTarget(e);if(j(t)&&(t=t.parentNode||null),e.type==="scroll")return(i=this.scrollDepth)==null||i.track(),!0;if(e.type==="visibilitychange"&&document.visibilityState==="hidden"||e.type==="popstate")return this.isPageRefresh()||(n=this.scrollDepth)==null||n.send(),!0;if(!(!t||!_(t))&&t&&pe(t,e)){const r=[t];let o=t;for(;o!=null&&o.parentNode&&!v(o,"body");){if(q(o==null?void 0:o.parentNode)){const g=(o==null?void 0:o.parentNode).host;g&&_(g)&&r.push(g),o=g;continue}const l=o==null?void 0:o.parentNode;if(!l||!_(l))break;r.push(l),o=l}const a=[];let c,h=!1;if(k(r,l=>{if(!l.tagName)return;const g=M(l);l.tagName.toLowerCase()==="a"&&(c=l.getAttribute("href"),c=g&&O(c)&&c);const u=L(l).split(" ");$(u,"ph-no-capture")&&(h=!0),a.push(this.getPropertiesFromElement(l,this.options.maskAllElementAttributes??!1,this.options.maskAllText??!1))}),this.options.maskAllText||(a[0].$el_text=J(t)),c&&(a[0].attr__href=c),h)return!1;if(!ye(a[0]))return this.logger.debug("Dropping autocapture event without identifiers."),!1;const f=ue(this.getDefaultProperties(e.type),{$elements:a},this.getCustomProperties(r));return this.client.track("$autocapture",f),!0}}getCustomProperties(e){const t={};return k(this.customProperties,i=>{k(i.event_selectors,n=>{const r=document.querySelectorAll(n);k(r,o=>{$(e,o)&&M(o)&&(t[i.name]=this.extractCustomPropertyValue(i))})})}),t}extractCustomPropertyValue(e){const t=[];return k(document.querySelectorAll(e.css_selector),function(i){let n;["input","select"].indexOf(i.tagName.toLowerCase())>-1?n=i.value:i.textContent&&(n=i.textContent),O(n)&&t.push(n)}),t.join(", ")}getEventTarget(e){var t;return typeof e.target>"u"?e.srcElement||null:(t=e.target)!=null&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}getPropertiesFromElement(e,t,i){const n=e.tagName.toLowerCase(),r={tag_name:n};I.indexOf(n)>-1&&!i&&(r.$el_text=J(e));const o=L(e);o.length>0&&(r.classes=o.split(" ").filter(function(f){return f!==""})),k(e.attributes,function(f){ee(e)&&["name","id","class"].indexOf(f.name)===-1||!t&&O(f.value)&&!me(f.name)&&(r["attr__"+f.name]=f.value)});let a=1,c=1,h=e;for(;h=this.previousElementSibling(h);)a++,h.tagName===e.tagName&&c++;return r.nth_child=a,r.nth_of_type=c,r}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;{let t=e;do t=t.previousSibling;while(t&&!_(t));return t}}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}encodeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}static enabledForProject(e,t=10,i=10){if(!e)return!1;let n=0;for(let r=0;r<e.length;r++)n+=e.charCodeAt(r);return n%t<i}};D.FORCE_CAPTURE_ATTR="data-um-force-capture",D.PREVENT_CAPTURE_ATTR="data-um-no-capture";let R=D;class Ee{constructor(e){this.client=e,this.lastPageUrl=window.location.href,this.trackInitialPageview(),this.initializePageviewTracking()}trackInitialPageview(){this.trackPageview()}initializePageviewTracking(){window.addEventListener("popstate",this.handlePageview.bind(this));const e=history.pushState;history.pushState=(...t)=>{e.apply(history,t),this.handlePageview()},window.addEventListener("hashchange",this.handlePageview.bind(this)),setInterval(this.checkForUrlChange.bind(this),1e3)}handlePageview(){this.trackPageview()}checkForUrlChange(){window.location.href!==this.lastPageUrl&&this.trackPageview()}trackPageview(){const e=window.location.href;e!==this.lastPageUrl&&(this.lastPageUrl=e,this.client.track("pageview",{url:e,referrer:document.referrer,title:document.title}))}}class Pe{constructor(e,t,i=p()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=new Blob([JSON.stringify(e)],{type:"application/json"});if(navigator.sendBeacon(i,n))this.logger.debug(`Successfully queued ${e.length} event(s) via Beacon API`);else throw new Error("Failed to queue events via Beacon API")}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=d()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${E()}?p_${E()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class K{constructor(e,t,i=p()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=this.constructUrl(t),n=JSON.stringify(e),r={"Content-Type":"application/json",...this.getCustomHeaders()},o=await fetch(i,{method:"POST",headers:r,body:n});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);this.logger.debug(`Successfully sent ${e.length} event(s)`),this.postHandle(o.status,await o.text())}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=d()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${E()}?p_${E()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class Ae{constructor(e,t,i=p()){this.trackingHost=e,this.logger=i,this.config=t}send(e){return new Promise((t,i)=>{const n=new XMLHttpRequest,r=this.config.key,o=this.constructUrl(r);n.open("POST",o,!0),n.setRequestHeader("Content-Type","application/json");const a=this.getCustomHeaders();Object.keys(a).forEach(c=>{n.setRequestHeader(c,a[c])}),n.onload=()=>{n.status>=200&&n.status<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),t()):i(new Error(`HTTP error! status: ${n.status}`))},n.onerror=()=>{i(new Error("Network error"))},n.send(JSON.stringify(e))})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"",n=d()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${E()}?p_${E()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}postHandle(e,t){this.logger.debug(`Response received. Status: ${e}, Body: ${t}`)}}class te{constructor(e,t){this.storage={},this.storageDisabled=!1,this.quotaErrorLogged=!1,this.prefix=`usermaven_${e}_`,this.logger=t||p(),this.load()}set(e,t){this.storage[e]=t,this.save()}get(e){return this.storage[e]}remove(e){delete this.storage[e],this.save()}clear(){this.storage={},this.save()}isStorageEnabled(){return!this.storageDisabled}load(){if(!d()){this.logger.warn("localStorage is not available in this environment");return}try{const e=localStorage.getItem(this.prefix+"data");e&&(this.storage=JSON.parse(e))}catch(e){this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error loading from localStorage:",e)}}save(){if(!d())return this.logger.warn("localStorage is not available in this environment"),!1;if(this.storageDisabled)return!1;try{return localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage)),!0}catch(e){return this.isQuotaError(e)?(this.storageDisabled=!0,this.logQuotaOnce(e)):this.logger.error("Error saving to localStorage:",e),!1}}isQuotaError(e){const t=e==null?void 0:e.name;return t==="QuotaExceededError"||t==="NS_ERROR_DOM_QUOTA_REACHED"||(e==null?void 0:e.code)===22||(e==null?void 0:e.code)===1014}logQuotaOnce(e){this.quotaErrorLogged||(this.quotaErrorLogged=!0,this.logger.error("localStorage quota exceeded; persisting disabled. Continuing with in-memory storage only.",e))}}class Se{constructor(){this.storage={}}set(e,t){this.storage[e]=t}get(e){return this.storage[e]}remove(e){delete this.storage[e]}save(){}clear(){this.storage={}}}class X{constructor(e,t=3,i=1e3,n=10,r=1e3,o=p(),a="default",c=1e3,h=25e5){this.transport=e,this.maxRetries=t,this.retryInterval=i,this.batchSize=n,this.batchInterval=r,this.logger=o,this.queue=[],this.processing=!1,this.batchTimeoutId=null,this.isOnline=!0,this.totalQueueBytes=0,this.persistence=new te(`offline_queue_${a}`),this.maxQueueItems=c,this.maxQueueBytes=h,d()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};t.bytes=this.estimateItemBytes(t),this.queue.push(t),this.totalQueueBytes+=t.bytes,this.enforceQueueLimits(),d()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){d()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){d()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!d()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-e.reduce((i,n)=>i+(n.bytes||0),0));const t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),d()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}d()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.totalQueueBytes+=t.bytes||this.estimateItemBytes(t),this.enforceQueueLimits(),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);d()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}enforceQueueLimits(){if(this.maxQueueItems>0&&this.queue.length>this.maxQueueItems){const e=this.queue.length-this.maxQueueItems,t=this.queue.splice(0,e);this.totalQueueBytes=Math.max(0,this.totalQueueBytes-t.reduce((i,n)=>i+(n.bytes||0),0)),this.logger.warn(`Retry queue exceeded ${this.maxQueueItems} items; dropped ${t.length} oldest payload(s)`)}if(this.maxQueueBytes>0&&this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>0){let e=0;for(;this.totalQueueBytes>this.maxQueueBytes&&this.queue.length>1;){const t=this.queue.shift();t&&(this.totalQueueBytes-=t.bytes||this.estimateItemBytes(t),e++)}this.totalQueueBytes=Math.max(0,this.totalQueueBytes),e>0&&this.logger.warn(`Retry queue exceeded ${this.maxQueueBytes} bytes; dropped ${e} oldest payload(s)`)}}estimateItemBytes(e){const t={...e};delete t.bytes;try{return JSON.stringify(t).length}catch{return 0}}loadQueueFromStorage(){if(d()){const e=this.persistence.get("queue");if(!e)return;try{const t=JSON.parse(e);this.queue=t.map(i=>({...i,bytes:i.bytes||this.estimateItemBytes(i)})),this.totalQueueBytes=this.queue.reduce((i,n)=>i+(n.bytes||0),0),this.enforceQueueLimits()}catch(t){this.logger.error("Failed to parse stored queue",t),this.queue=[],this.totalQueueBytes=0}}}saveQueueToStorage(){if(d()){const e=this.queue.map(({bytes:t,...i})=>i);this.persistence.set("queue",JSON.stringify(e))}}}class Ce{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),G(this)}initializeEventListener(){document.addEventListener("click",this.handleClick.bind(this))}handleClick(e){const t=e.target;this.shouldCaptureElement(t)&&this.click(e.clientX,e.clientY,Date.now())}shouldCaptureElement(e){return!e.closest(".um-no-capture")}click(e,t,i){const n={x:e,y:t,timestamp:i};this.clicks.push(n),this.clicks=this.clicks.filter(r=>i-r.timestamp<this.timeWindow),this.clicks.length>=this.threshold&&this.checkRageClick()}checkRageClick(){const e=this.clicks[0],i=(this.clicks[this.clicks.length-1].timestamp-e.timestamp)/1e3;this.clicks.every((r,o)=>{if(o===0)return!0;const a=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-a.x,2)+Math.pow(r.y-a.y,2))<this.distanceThreshold})&&this.sendRageClickEvent(i)}sendRageClickEvent(e){const t=this.clicks[this.clicks.length-1];document.elementFromPoint(t.x,t.y)&&this.client.track("$rage_click",{no_of_clicks:this.clicks.length,time:e.toFixed(2)}),this.clicks=[]}}class $e{constructor(e,t,i=p()){this.trackingHost=e,this.logger=i,this.config=t}async send(e){const t=this.config.key,i=new(void 0)(this.constructUrl(t)),n={hostname:i.hostname,port:443,path:`${i.pathname}${i.search}`,method:"POST",headers:{"Content-Type":"application/json",...this.getCustomHeaders()}};return new Promise((r,o)=>{const a=(void 0)(n,c=>{c.on("data",h=>{}),c.on("end",()=>{const h=c.statusCode||0;h>=200&&h<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${h}`))})});a.on("error",c=>{o(c)}),a.write(JSON.stringify(e)),a.end()})}constructUrl(e){const t=this.config.cookiePolicy!=="keep"?`&cookie_policy=${this.config.cookiePolicy}`:"",i=this.config.ipPolicy!=="keep"?`&ip_policy=${this.config.ipPolicy}`:"";return`${this.trackingHost}/api/v1/s2s/event?token=${e}${t}${i}`}getCustomHeaders(){return typeof this.config.customHeaders=="function"?this.config.customHeaders():this.config.customHeaders?this.config.customHeaders:{}}}class C{constructor(e,t="all",i={}){this.instance=e,this.trackingType=t,this.options=i,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",this.initialize.bind(this)):this.initialize()}initialize(){this.trackingType!=="none"&&this.setupFormTracking()}setupFormTracking(){var e;this.formElements=this.trackingType==="tagged"?document.querySelectorAll("form[data-um-form]"):document.querySelectorAll("form"),(e=this.formElements)==null||e.forEach(t=>{t.addEventListener("submit",this.handleFormSubmit.bind(this))})}handleFormSubmit(e){const t=e.target,i=this._getFormDetails(t);this.instance.track("$form",V(i)),this.options.trackFieldChanges&&this.trackFieldChanges(t)}trackFieldChanges(e){e.querySelectorAll("input, select, textarea").forEach(i=>{i.addEventListener("change",n=>{const r=this._getFieldProps(n.target);this.instance.track("$form_field_change",V({form_id:e.id,form_name:e.name||"",field:r}))})})}static getInstance(e,t="all",i={}){return C.instance||(C.instance=new C(e,t,i)),C.instance}_getFormDetails(e){const t={form_id:e.id,form_name:e.name||"",form_action:e.action,form_method:e.method,form_class:e.className,form_attributes:this._getElementAttributes(e),fields:[]},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach(r=>{const o=this._getFieldProps(r);t.fields.push(o)}),t}_getFieldProps(e){const t=Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):void 0,i=this.getSafeText(e);return{tag:e.tagName.toLowerCase(),type:e instanceof HTMLInputElement?e.type:void 0,data_attributes:t,id:e.id,value:i,class:e.className,name:e.name,attributes:this._getElementAttributes(e)}}_getElementAttributes(e){return Object.keys(e.dataset).length?this._convertDOMStringMapToObject(e.dataset):{}}_convertDOMStringMapToObject(e){const t={};for(const i in e)e.hasOwnProperty(i)&&e[i]!==void 0&&(t[i]=e[i]);return t}getSafeText(e){let t="";return"value"in e&&e.type!=="password"?t=e.value:e.hasChildNodes()?t=Array.from(e.childNodes).filter(n=>n.nodeType===Node.TEXT_NODE).map(n=>n.textContent).join(""):t=e.textContent||"",this._scrubPotentiallySensitiveValues(t)}_scrubPotentiallySensitiveValues(e){return this._shouldCaptureValue(e)?e:"<redacted>"}_shouldCaptureValue(e){return!(this._isNullish(e)||this._isString(e)&&(e=this._trim(e),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((e||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(e)))}_isNullish(e){return e==null}_isString(e){return typeof e=="string"||e instanceof String}_trim(e){if(typeof String.prototype.trim=="function")return e.trim();let t=0,i=e.length-1;const n=[" ",`
2
+ `,"\r"," ","\f","\v"," "," "," "," "," "," "," "," "," "," "," "," "," ","\u2028","\u2029"," "," "," "].join("");for(;t<=i&&n.indexOf(e[t])>-1;)t++;for(;i>=t&&n.indexOf(e[i])>-1;)i--;return e.slice(t,i+1)}}class T{constructor(e){this.config=this.mergeConfig(e,Y),this.logger=p(this.config.logLevel),this.namespace=e.namespace||"default",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new X(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger,this.namespace),d()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new ne(this.config.cookieDomain),this.config.autocapture&&R.enabledForProject(this.config.key)&&!this.config.disableAutocaptureListenerRegistration&&(this.autoCapture=new R(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=C.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new Ee(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new Ce(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{S(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=p(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new X(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger,this.namespace),d()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client reinitialized for namespace: ${this.namespace}`)}manageCrossDomainLinking(){if(!this.config.crossDomainLinking||!this.config.domains)return;const e=this.config.domains.split(",").map(i=>i.trim()),t=this.config.cookieName||`__eventn_id_${this.config.key}`;document.addEventListener("click",i=>{var a;const n=this.findClosestLink(i.target);if(!n)return;const r=n.getAttribute("href");if(!r||!r.startsWith("http"))return;const o=new URL(r);if(o.hostname!==window.location.hostname&&e.includes(o.hostname)){const c=(a=this.cookieManager)==null?void 0:a.get(t);c&&(o.searchParams.append("_um",c),n.setAttribute("href",o.toString()))}}),this.logger.debug("Cross-domain linking initialized")}findClosestLink(e){for(;e&&e.tagName!=="A";)e=e.parentElement;return e}initializeTransport(e){const t="https://events.usermaven.com";if(!d())return new $e(e.trackingHost||t,e);const i="XMLHttpRequest"in window,n=typeof fetch<"u",r=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&r)return new Pe(e.trackingHost||t,e,this.logger);if(e.forceUseFetch&&n)return new K(e.trackingHost||t,e,this.logger);if(i)return new Ae(e.trackingHost||t,e,this.logger);if(n)return new K(e.trackingHost||t,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!d()?new Se:new te(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!d())return H();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return"";const e=this.config.cookieName||`__eventn_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const a=new URLSearchParams(window.location.search).get("_um"),h=window.location.hash.substring(1).split("~"),f=h.length>1?h[1]:void 0;t=a||f||H()}t||(t=H());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}async id(e,t=!1){if(!S(e))throw new Error("User data must be an object");if(e.email&&!W(e.email))throw new Error("Invalid email provided");if(!e.id||!U(e.id))throw new Error("User ID must be a string");const i=e.id;if(this.persistence.set("userId",i),this.persistence.set("userProps",e),!t){const n={...e,anonymous_id:this.anonymousId};await this.track("user_identify",n)}this.logger.info("User identified:",e)}track(e,t,i=!1){this.trackInternal(e,t,i)}lead(e,t=!1){if(!S(e))throw new Error("Lead payload must be a non-null object and not an array");const i=e.email;if(!U(i)){this.logger.error("Lead event requires a valid email attribute");return}const n=i.trim();if(!n||!W(n)){this.logger.error("Lead event requires a valid email attribute");return}e.email=n,this.track("lead",e,t)}trackInternal(e,t,i=!1){if(be()){this.logger.debug("Tracking disabled due to um_exclusion setting");return}if(!U(e))throw new Error("Event name must be a string");if(t!==void 0&&(typeof t!="object"||t===null||Array.isArray(t)))throw new Error("Event payload must be a non-null object and not an array");const r=this.createEventPayload(e,t);try{if(i){this.transport.send(r),this.logger.debug(`Event sent: ${e}`,[r]);return}this.retryQueue.add(r),this.logger.debug(`Event tracked: ${e}`,[r])}catch(o){throw this.logger.error(`Failed to track event: ${e}`,o),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!S(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!S(e))throw new Error("Company properties must be an object");if(!e.id||!e.name||!e.created_at)throw new Error("Company properties must include id, name, and created_at");this.persistence.set("companyProps",e),t||await this.track("group",e),this.logger.info("Company identified:",e)}createEventPayload(e,t){const{event_id:i,...n}=t||{},r=this.persistence.get("userProps")||{},o=this.persistence.get("companyProps")||(r==null?void 0:r.company)||{},a=this.persistence.get("userId"),c=this.persistence.get("global_props")||{},h=this.persistence.get(`props_${e}`)||{};let f=n;const l={event_id:i||H(),user:{anonymous_id:this.anonymousId,id:a,...r},...o&&{company:o},ids:this.getThirdPartyIds(),utc_time:new Date().toISOString(),local_tz_offset:new Date().getTimezoneOffset(),api_key:this.config.key,src:"usermaven",event_type:e,namespace:this.namespace,...c,...h};if(e==="$autocapture"){const g=this.processAutocaptureAttributes(t||{});l.autocapture_attributes=g}else e!=="user_identify"&&e!=="group"&&(Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(g=>{delete f[g]}),l.event_attributes=f);return d()&&(l.referer=document.referrer,l.url=window.location.href,l.page_title=document.title,l.doc_path=window.location.pathname,l.doc_host=window.location.hostname,l.doc_search=window.location.search,l.screen_resolution=`${window.screen.width}x${window.screen.height}`,l.vp_size=`${window.innerWidth}x${window.innerHeight}`,l.user_agent=navigator.userAgent,l.user_language=navigator.language,l.doc_encoding=document.characterSet,l.utm=this.getUtmParams()),l}processAutocaptureAttributes(e){let t={};const i=e.$elements||[];return i.length&&(t={...i[0]}),t.el_text=t.$el_text||"",t.event_type=e.$event_type||"",["$ce_version","$event_type","$initial_referrer","$initial_referring_domain","$referrer","$referring_domain","$elements"].forEach(n=>{delete t[n]}),delete t.$el_text,delete t.nth_child,delete t.nth_of_type,t}getCookie(e){var t;return((t=this.cookieManager)==null?void 0:t.get(e))||null}getThirdPartyIds(){const e={};if(d()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ve(window.location.search);return["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(n=>{t[n]&&(e[n.replace("utm_","")]=t[n])}),e}pageview(){d()?this.track("pageview",{url:window.location.href,referrer:document.referrer,title:document.title},!0):this.logger.warn("Pageview tracking is not available in server-side environments")}setupPageLeaveTracking(){if(!d())return;let e=!1,t=!1;const i=()=>{!e&&!t&&(e=!0,this.track("$pageleave",{url:window.location.href,referrer:document.referrer,title:document.title}))};window.addEventListener("beforeunload",r=>{t=!0,setTimeout(()=>{t=!1},100)}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&!t&&i()});const n=history.pushState;history.pushState=function(){return i(),n.apply(this,arguments)},window.addEventListener("popstate",i)}getConfig(){return this.config}getLogger(){return this.logger}async reset(e=!1){if(this.persistence.clear(),e&&this.cookieManager){const t=this.config.cookieName||`__eventn_id_${this.config.key}`;this.cookieManager.delete(t),this.anonymousId=this.getOrCreateAnonymousId()}this.logger.info("core state reset",{resetAnonId:e,namespace:this.namespace})}set(e,t){if(!S(e))throw new Error("Properties must be an object");const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};r={...r,...e},this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};r={...r,...e},this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug("Properties set",{properties:e,eventType:i||"global",persist:n})}setUserId(e){this.persistence.set("userId",e);let t=this.persistence.get("userProps")||{};t.id=e,this.persistence.set("userProps",t),this.persistence.save()}unset(e,t){const i=t==null?void 0:t.eventType,n=(t==null?void 0:t.persist)??!0;if(i){let r=this.persistence.get(`props_${i}`)||{};delete r[e],this.persistence.set(`props_${i}`,r)}else{let r=this.persistence.get("global_props")||{};delete r[e],this.persistence.set("global_props",r)}n&&this.persistence.save(),this.logger.debug(`Property unset: ${e}`,`Event type: ${i||"global"}`)}}function ie(){return typeof window<"u"&&typeof window.define=="function"&&window.define.amd}function Te(){return ie()?window.define:void 0}const xe="__USERMAVEN_AUTOCAPTURE_INITIALIZED__";function x(s){const e=JSON.parse(JSON.stringify(s)),t=Q(e),i={...Y,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");const n=i.key||"",r=`${xe}${n}`;return d()&&i.autocapture&&window[r]&&(console.warn("Usermaven: Autocapture already initialized in another instance, skipping duplicate initialization."),i.disableAutocaptureListenerRegistration=!0),d()&&i.autocapture&&!i.disableAutocaptureListenerRegistration&&(window[r]=!0),new T(i)}function He(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ke(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="false"?!1:s.getAttribute("data-form-tracking")==="true"?"all":s.getAttribute("data-form-tracking"),autoPageview:s.getAttribute("data-auto-pageview")==="true",useBeaconApi:s.getAttribute("data-use-beacon-api")==="true",forceUseFetch:s.getAttribute("data-force-use-fetch")==="true",gaHook:s.getAttribute("data-ga-hook")==="true",segmentHook:s.getAttribute("data-segment-hook")==="true",randomizeUrl:s.getAttribute("data-randomize-url")==="true",capture3rdPartyCookies:s.getAttribute("data-capture-3rd-party-cookies")==="false"?!1:void 0,idMethod:s.getAttribute("data-id-method")||void 0,privacyPolicy:s.getAttribute("data-privacy-policy")==="strict"?"strict":void 0,ipPolicy:s.getAttribute("data-ip-policy")||void 0,cookiePolicy:s.getAttribute("data-cookie-policy")||void 0,minSendTimeout:parseInt(s.getAttribute("data-min-send-timeout")||"",10)||void 0,maxSendTimeout:parseInt(s.getAttribute("data-max-send-timeout")||"",10)||void 0,maxSendAttempts:parseInt(s.getAttribute("data-max-send-attempts")||"",10)||void 0,propertiesStringMaxLength:parseInt(s.getAttribute("data-properties-string-max-length")||"",10)||null,propertyBlacklist:((n=s.getAttribute("data-property-blacklist"))==null?void 0:n.split(","))||void 0,exclude:s.getAttribute("data-exclude")||void 0,namespace:s.getAttribute("data-namespace")||void 0,crossDomainLinking:s.getAttribute("data-cross-domain-linking")!=="false",domains:s.getAttribute("data-domains")||void 0,maskAllText:s.getAttribute("data-mask-all-text")==="true",maskAllElementAttributes:s.getAttribute("data-mask-all-element-attributes")==="true"};e.privacyPolicy==="strict"&&(e.cookiePolicy="strict",e.ipPolicy="strict"),e.cookiePolicy==="comply"&&e.useBeaconApi&&(e.cookiePolicy="strict");const t=x(e),i=e.namespace||"usermaven";return d()&&t.pageview(),Ie(i,t),t}function Ie(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const u=i.shift();if(u){const m=u[u.length-1];if(m&&typeof m.resolve=="function"){const y=u.pop();try{const P=a.apply(null,u);P&&typeof P.then=="function"?P.then(y.resolve).catch(y.reject):y.resolve(P)}catch(P){y.reject(P)}}else try{a.apply(null,u)}catch(y){console.error("Usermaven: Error processing queued command:",y)}}}}function o(){n.forEach(u=>u()),n.length=0}function a(...u){const m=u[0];if(m==="onLoad"){typeof u[1]=="function"&&(t?u[1]():n.push(u[1]));return}if(!t){i.push(u);return}if(typeof e[m]=="function")return e[m].apply(e,u.slice(1));console.error(`Method ${m} not found on UsermavenClient`)}const c=["id","group","reset"],h=["track","lead","pageview","set","unset","rawTrack","setUserId"];[...c,...h].forEach(u=>{a[u]=function(...m){if(!t){if(c.includes(u))return new Promise((z,y)=>{i.push([u,...m,{resolve:z,reject:y}])});i.push([u,...m]);return}if(typeof e[u]=="function")return e[u].apply(e,m)}}),a.getConfig=function(){return t?e.getConfig():(console.warn("Usermaven client not ready yet"),null)},window[s]=a;const l=`${s}Q`,g=window[l]||[];for(window[l]=g,g.push=function(...u){return a.apply(null,u),Array.prototype.push.apply(this,u)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);g.length>0;){const u=g.shift();u&&i.push(u)}}let Z=!1,B=null;if(d()){const s=Te();s&&s("usermaven",[],function(){return{usermavenClient:x,UsermavenClient:T,LogLevel:w,getScriptTagClient:()=>B}}),typeof window<"u"&&(window.usermavenClient=x,window.UsermavenClient=T,window.usermavenScriptTagClient=()=>B),function(e,t){const i=e.currentScript;function n(){return Z||!i||!i.hasAttribute("data-key")||i.getAttribute("data-no-auto-init")==="true"?!1:i.src.includes("lib.js")}function r(){n()&&(console.log("[Usermaven] Auto-initializing from script tag"),B=He(i),Z=!0)}typeof t<"u"&&i&&(e.readyState==="loading"?e.addEventListener("DOMContentLoaded",r):r())}(document,window)}typeof module<"u"&&module.exports&&!ie()&&(module.exports={usermavenClient:x,UsermavenClient:T,Config:void 0,UserProps:void 0,EventPayload:void 0,LogLevel:w,ClientProperties:void 0});exports.LogLevel=w;exports.UsermavenClient=T;exports.usermavenClient=x;