@usermaven/sdk-js 1.4.1-rc.58 → 1.4.1-rc.60
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 +2 -2
- package/dist/usermaven.cjs.js +2 -2
- package/dist/usermaven.es.js +83 -78
- package/package.json +1 -1
package/dist/lib.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(f,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(f=typeof globalThis<"u"?globalThis:f||self,g(f.Usermaven={}))})(this,function(f){"use strict";var g=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s))(g||{});class X{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 h(s=0){return new X(s)}const N={logLevel:g.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,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 K{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain(),console.log(this.cookieDomain)}set(e,t,i=365,n=!0,r=!1){console.log("Setting cookie",e,t,i,n,r);const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}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 Z=Object.prototype.hasOwnProperty,b=Array.prototype.forEach,$={};function G(s,e,t){if(Array.isArray(s)){if(b&&s.forEach===b)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)===$)return}}}const T=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},Y=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function A(s,e,t){if(s!=null){if(b&&Array.isArray(s)&&s.forEach===b)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)===$)return}else for(const i in s)if(Z.call(s,i)&&e.call(t,s[i],i)===$)return}}const j=function(s,...e){return G(e,function(t){for(const i in t)t[i]!==void 0&&(s[i]=t[i])}),s};function E(s,e){return s.indexOf(e)!==-1}const O=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},ee=function(s){return s===void 0},y=function(){const s=function(i,n,r,o,c){if(!i){h().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!c);else{const l="on"+n,a=i[l];i[l]=e(i,r,a)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;O(r)&&(l=r(o));const a=n.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}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}(),te=function(s){return function(...e){try{return s.apply(this,e)}catch(t){h().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},L=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=te(s[e]))};function U(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return h().warn("window is not available"),!1}}function m(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 ie(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function S(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(S):Object.keys(s).reduce((e,t)=>{const i=ie(t);return e[i]=S(s[t]),e},{})}function P(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 I(s){let e="";return z(s)&&!M(s)&&s.childNodes&&s.childNodes.length&&A(s.childNodes,function(t){D(t)&&t.textContent&&(e+=T(t.textContent).split(/(\s+)/).filter(H).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),T(e)}function C(s){return!!s&&s.nodeType===1}function p(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function D(s){return!!s&&s.nodeType===3}function F(s){return!!s&&s.nodeType===11}const x=["a","button","form","input","select","textarea","label"];function se(s,e){if(!s||p(s,"html")||!C(s)||s.classList&&s.classList.contains("um-no-capture"))return!1;let t=!1;const i=[s];let n=!0,r=s;for(;r.parentNode&&!p(r,"body");){if(F(r.parentNode)){i.push(r.parentNode.host),r=r.parentNode.host;continue}if(n=r.parentNode||!1,!n)break;if(x.indexOf(n.tagName.toLowerCase())>-1)t=!0;else{const l=window.getComputedStyle(n);l&&l.getPropertyValue("cursor")==="pointer"&&(t=!0)}i.push(n),r=n}const o=window.getComputedStyle(s);if(o&&o.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const c=s.tagName.toLowerCase();switch(c){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 t?e.type==="click":e.type==="click"&&(x.indexOf(c)>-1||s.getAttribute("contenteditable")==="true")}}function z(s){if(!s||!C(s))return!1;if(typeof s.hasAttribute=="function"){if(s.hasAttribute(w.FORCE_CAPTURE_ATTR))return!0;if(s.hasAttribute(w.PREVENT_CAPTURE_ATTR))return!1}let e=s;for(;e&&e.parentElement&&!p(e,"body");){const n=P(e).split(" ");if(E(n,"ph-sensitive")||E(n,"ph-no-capture"))return!1;e=e.parentElement}if(E(P(s).split(" "),"ph-include"))return!0;const t=s.type;if(typeof t=="string")switch(t.toLowerCase()){case"hidden":case"password":return!1}const i=s.name||s.id||"";return!(typeof i=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function M(s){const e=["button","checkbox","submit","reset"];return!!(p(s,"input")&&!e.includes(s.type)||p(s,"select")||p(s,"textarea")||s.getAttribute("contenteditable")==="true")}function H(s){return!(s===null||ee(s)||typeof s=="string"&&(s=T(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 ne(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function R(){return m(10)}function re(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 oe(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function ae(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 B(s){return typeof s=="string"||s instanceof String}function _(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function ce(s){if(s===null)return g.ERROR;const e=s.toUpperCase(),t=g[e];return t||t===0?t:g.ERROR}class le{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=oe(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"){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)})}}const v=class v{constructor(e,t,i=h()){this.logger=i,this.scrollDepth=null,this.client=e,this.options=t,this.scrollDepth=new le(e),Y(this),L(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};y(document,"submit",e,!1,!0),y(document,"change",e,!1,!0),y(document,"click",e,!1,!0),y(document,"visibilitychange",e,!1,!0),y(document,"scroll",e,!1,!0),y(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(D(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&&this.shouldCaptureElement(t,e)){const r=this.getElementList(t),o=this.getElementsJson(r,e),c=j(this.getDefaultProperties(e.type),{$elements:o});return this.client.track("$autocapture",c),!0}}shouldCaptureElement(e,t){return!e||typeof e.hasAttribute!="function"?!1:e.hasAttribute(v.FORCE_CAPTURE_ATTR)?!0:e.hasAttribute(v.PREVENT_CAPTURE_ATTR)?!1:se(e,t)}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}getElementList(e){const t=[e];let i=e;for(;i.parentNode&&!p(i,"body");)F(i.parentNode)?(t.push(i.parentNode.host),i=i.parentNode.host):(t.push(i.parentNode),i=i.parentNode);return t}getElementsJson(e,t){const i=[];let n=null,r=!1;return A(e,o=>{if(p(o,"a")){const l=o.getAttribute("href");l!==null&&z(o)&&H(l)&&(n=l)}const c=P(o).split(" ");E(c,"ph-no-capture")&&(r=!0),i.push(this.getPropertiesFromElement(o))}),this.options.maskAllText||(i[0].$el_text=this.sanitizeText(I(e[0]))),n!==null&&(i[0].attr__href=n),r?[]:i}getPropertiesFromElement(e){const t={tag_name:e.tagName.toLowerCase()};x.indexOf(t.tag_name)>-1&&!this.options.maskAllText&&(t.$el_text=this.sanitizeText(I(e)));const i=P(e);i.length>0&&(t.classes=i.split(" ").filter(c=>c!=="")),A(e.attributes,c=>{M(e)&&["name","id","class"].indexOf(c.name)===-1||!this.options.maskAllElementAttributes&&H(c.value)&&!ne(c.name)&&(t["attr__"+c.name]=this.sanitizeAttributeValue(c.name,c.value))});let n=1,r=1,o=e;for(;o=this.previousElementSibling(o);)n++,o.tagName===e.tagName&&r++;return t.nth_child=n,t.nth_of_type=r,t}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;do e=e.previousSibling;while(e&&!C(e));return e}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}sanitizeText(e){e=e.replace(/<[^>]*?>/g,""),e=this.encodeHtml(e);const t=this.options.propertiesStringMaxLength||255;return e.length>t&&(e=e.substring(0,t)+"..."),e}sanitizeUrl(e){if(!e)return"";try{const t=new URL(e,window.location.href);return t.protocol!=="http:"&&t.protocol!=="https:"?"":encodeURI(t.toString())}catch{return this.encodeHtml(e)}}sanitizeAttributeValue(e,t){switch(e.toLowerCase()){case"href":case"src":return this.sanitizeUrl(t);default:return this.encodeHtml(t)}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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}static isBrowserSupported(){return O(document.querySelectorAll)}};v.FORCE_CAPTURE_ATTR="data-um-force-capture",v.PREVENT_CAPTURE_ATTR="data-um-no-capture";let w=v;class ue{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 he{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class q{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 ge{constructor(e,t,i=h()){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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 V{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||h()}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()}save(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){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.logger.error("Error loading from localStorage:",e)}}}class de{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 J{constructor(e,t=3,i=1e3,n=10,r=1e3,o=h()){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.persistence=new V("offline_queue"),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class fe{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),L(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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.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 pe{constructor(e,t,i=h()){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 c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.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 k{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",U(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,0);this.instance.track("$form_field_change",U(r))})})}static getInstance(e,t="all",i={}){return k.instance||(k.instance=new k(e,t,i)),k.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)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:i,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){const t={};for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i];n.name!=="value"&&!n.name.startsWith("data-")&&(t[n.name]=n.value)}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 Q{constructor(e){this.config=this.mergeConfig(e,N),this.logger=h(this.config.logLevel),this.namespace=e.namespace||"usermaven",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new K(this.config.cookieDomain),this.config.autocapture&&w.enabledForProject(this.config.key)&&(this.autoCapture=new w(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=k.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new ue(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new fe(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{_(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=h(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger),u()&&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||`${this.namespace}_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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){if(!u())return new pe(e.trackingHost,e);const t="XMLHttpRequest"in window,i=typeof fetch<"u",n=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&n)return new he(e.trackingHost,e,this.logger);if(e.forceUseFetch&&i)return new q(e.trackingHost,e,this.logger);if(t)return new ge(e.trackingHost,e,this.logger);if(i)return new q(e.trackingHost,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new de:new V(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!u())return R();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return this.generateFingerprint();const e=this.config.cookieName||`${this.namespace}_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),d=a.length>1?a[1]:void 0;t=c||d||R()}t||(t=R());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}generateFingerprint(){const e=navigator.userAgent,t=`${screen.width}x${screen.height}`,i=screen.colorDepth,n=Intl.DateTimeFormat().resolvedOptions().timeZone,r=`${e}|${t}|${i}|${n}`;return this.hashString(r)}hashString(e){let t=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}async id(e,t=!1){if(!_(e))throw new Error("User data must be an object");if(e.email&&!re(e.email))throw new Error("Invalid email provided");if(!e.id||!B(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)}trackInternal(e,t,i=!1){if(!B(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 n=this.createEventPayload(e,t);try{if(i){this.transport.send(n),this.logger.debug(`Event sent: ${e}`,[n]);return}this.retryQueue.add(n),this.logger.debug(`Event tracked: ${e}`,[n])}catch(r){throw this.logger.error(`Failed to track event: ${e}`,r),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!_(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!_(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")||void 0,r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=d}else Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),a.event_attributes=l;return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ae(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(){u()?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(!u())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||`${this.namespace}_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))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 W(s){const e=JSON.parse(JSON.stringify(s)),t=S(e),i={...N,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");return new Q(i)}function me(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ce(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="true"?"all":!1,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"},t=W(e),i=e.namespace||"usermaven";u()&&t.pageview(),ye(i,t)}function ye(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[s].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[s]=function(...a){const d=a[0];if(d==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[d]=="function")return e[d].apply(e,a.slice(1));console.error(`Method ${d} not found on UsermavenClient`)};const c=`${s}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[s].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}u()&&function(s,e){const t=s.currentScript;function i(){t&&t.src.includes("lib.js")&&me(t)}typeof e<"u"&&(s.readyState==="loading"?s.addEventListener("DOMContentLoaded",i):i())}(document,window),f.LogLevel=g,f.UsermavenClient=Q,f.usermavenClient=W,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(p,g){typeof exports=="object"&&typeof module<"u"?g(exports):typeof define=="function"&&define.amd?define(["exports"],g):(p=typeof globalThis<"u"?globalThis:p||self,g(p.Usermaven={}))})(this,function(p){"use strict";var g=(s=>(s[s.DEBUG=0]="DEBUG",s[s.INFO=1]="INFO",s[s.WARN=2]="WARN",s[s.ERROR=3]="ERROR",s))(g||{});class X{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 h(s=0){return new X(s)}const O={logLevel:g.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,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 K{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain(),console.log(this.cookieDomain)}set(e,t,i=365,n=!0,r=!1){console.log("Setting cookie",e,t,i,n,r);const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}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 Z=Object.prototype.hasOwnProperty,b=Array.prototype.forEach,T={};function G(s,e,t){if(Array.isArray(s)){if(b&&s.forEach===b)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)===T)return}}}const A=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},Y=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function S(s,e,t){if(s!=null){if(b&&Array.isArray(s)&&s.forEach===b)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)===T)return}else for(const i in s)if(Z.call(s,i)&&e.call(t,s[i],i)===T)return}}const j=function(s,...e){return G(e,function(t){for(const i in t)t[i]!==void 0&&(s[i]=t[i])}),s};function E(s,e){return s.indexOf(e)!==-1}const L=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},ee=function(s){return s===void 0},y=function(){const s=function(i,n,r,o,c){if(!i){h().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!c);else{const l="on"+n,a=i[l];i[l]=e(i,r,a)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;L(r)&&(l=r(o));const a=n.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}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}(),te=function(s){return function(...e){try{return s.apply(this,e)}catch(t){h().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},U=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=te(s[e]))};function I(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return h().warn("window is not available"),!1}}function m(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 ie(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function C(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(C):Object.keys(s).reduce((e,t)=>{const i=ie(t);return e[i]=C(s[t]),e},{})}function P(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 D(s){let e="";return z(s)&&!M(s)&&s.childNodes&&s.childNodes.length&&S(s.childNodes,function(t){F(t)&&t.textContent&&(e+=A(t.textContent).split(/(\s+)/).filter(R).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),A(e)}function x(s){return!!s&&s.nodeType===1}function f(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function F(s){return!!s&&s.nodeType===3}function H(s){return!!s&&s.nodeType===11}const $=["a","button","form","input","select","textarea","label"];function se(s,e){if(!s||f(s,"html")||!x(s))return!1;let t=s;for(;t&&!f(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&H(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=s;t&&!f(t,"body");){if(t.parentNode&&H(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 c=window.getComputedStyle(o);c&&c.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 z(s){if(!s||!x(s))return!1;if(typeof s.hasAttribute=="function"){if(s.hasAttribute(w.FORCE_CAPTURE_ATTR))return!0;if(s.hasAttribute(w.PREVENT_CAPTURE_ATTR))return!1}let e=s;for(;e&&e.parentElement&&!f(e,"body");){const n=P(e).split(" ");if(E(n,"ph-sensitive")||E(n,"ph-no-capture"))return!1;e=e.parentElement}if(E(P(s).split(" "),"ph-include"))return!0;const t=s.type;if(typeof t=="string")switch(t.toLowerCase()){case"hidden":case"password":return!1}const i=s.name||s.id||"";return!(typeof i=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function M(s){const e=["button","checkbox","submit","reset"];return!!(f(s,"input")&&!e.includes(s.type)||f(s,"select")||f(s,"textarea")||s.getAttribute("contenteditable")==="true")}function R(s){return!(s===null||ee(s)||typeof s=="string"&&(s=A(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 ne(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function N(){return m(10)}function re(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 oe(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function ae(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 B(s){return typeof s=="string"||s instanceof String}function _(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function ce(s){if(s===null)return g.ERROR;const e=s.toUpperCase(),t=g[e];return t||t===0?t:g.ERROR}class le{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=oe(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"){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)})}}const v=class v{constructor(e,t,i=h()){this.logger=i,this.scrollDepth=null,this.client=e,this.options=t,this.scrollDepth=new le(e),Y(this),U(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};y(document,"submit",e,!1,!0),y(document,"change",e,!1,!0),y(document,"click",e,!1,!0),y(document,"visibilitychange",e,!1,!0),y(document,"scroll",e,!1,!0),y(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(F(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&&this.shouldCaptureElement(t,e)){const r=this.getElementList(t),o=this.getElementsJson(r,e),c=j(this.getDefaultProperties(e.type),{$elements:o});return this.client.track("$autocapture",c),!0}}shouldCaptureElement(e,t){return!e||typeof e.hasAttribute!="function"?!1:e.hasAttribute(v.FORCE_CAPTURE_ATTR)?!0:e.hasAttribute(v.PREVENT_CAPTURE_ATTR)?!1:se(e,t)}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}getElementList(e){const t=[e];let i=e;for(;i.parentNode&&!f(i,"body");)H(i.parentNode)?(t.push(i.parentNode.host),i=i.parentNode.host):(t.push(i.parentNode),i=i.parentNode);return t}getElementsJson(e,t){const i=[];let n=null,r=!1;return S(e,o=>{if(f(o,"a")){const l=o.getAttribute("href");l!==null&&z(o)&&R(l)&&(n=l)}const c=P(o).split(" ");E(c,"ph-no-capture")&&(r=!0),i.push(this.getPropertiesFromElement(o))}),this.options.maskAllText||(i[0].$el_text=this.sanitizeText(D(e[0]))),n!==null&&(i[0].attr__href=n),r?[]:i}getPropertiesFromElement(e){const t={tag_name:e.tagName.toLowerCase()};$.indexOf(t.tag_name)>-1&&!this.options.maskAllText&&(t.$el_text=this.sanitizeText(D(e)));const i=P(e);i.length>0&&(t.classes=i.split(" ").filter(c=>c!=="")),S(e.attributes,c=>{M(e)&&["name","id","class"].indexOf(c.name)===-1||!this.options.maskAllElementAttributes&&R(c.value)&&!ne(c.name)&&(t["attr__"+c.name]=this.sanitizeAttributeValue(c.name,c.value))});let n=1,r=1,o=e;for(;o=this.previousElementSibling(o);)n++,o.tagName===e.tagName&&r++;return t.nth_child=n,t.nth_of_type=r,t}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;do e=e.previousSibling;while(e&&!x(e));return e}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}sanitizeText(e){e=e.replace(/<[^>]*?>/g,""),e=this.encodeHtml(e);const t=this.options.propertiesStringMaxLength||255;return e.length>t&&(e=e.substring(0,t)+"..."),e}sanitizeUrl(e){if(!e)return"";try{const t=new URL(e,window.location.href);return t.protocol!=="http:"&&t.protocol!=="https:"?"":encodeURI(t.toString())}catch{return this.encodeHtml(e)}}sanitizeAttributeValue(e,t){switch(e.toLowerCase()){case"href":case"src":return this.sanitizeUrl(t);default:return this.encodeHtml(t)}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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}static isBrowserSupported(){return L(document.querySelectorAll)}};v.FORCE_CAPTURE_ATTR="data-um-force-capture",v.PREVENT_CAPTURE_ATTR="data-um-no-capture";let w=v;class ue{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 he{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class q{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 ge{constructor(e,t,i=h()){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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${m()}?p_${m()}=${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 V{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||h()}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()}save(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){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.logger.error("Error loading from localStorage:",e)}}}class de{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 J{constructor(e,t=3,i=1e3,n=10,r=1e3,o=h()){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.persistence=new V("offline_queue"),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class fe{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),U(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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.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 pe{constructor(e,t,i=h()){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 c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.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 k{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",I(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,0);this.instance.track("$form_field_change",I(r))})})}static getInstance(e,t="all",i={}){return k.instance||(k.instance=new k(e,t,i)),k.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)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:i,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){const t={};for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i];n.name!=="value"&&!n.name.startsWith("data-")&&(t[n.name]=n.value)}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 Q{constructor(e){this.config=this.mergeConfig(e,O),this.logger=h(this.config.logLevel),this.namespace=e.namespace||"usermaven",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new K(this.config.cookieDomain),this.config.autocapture&&w.enabledForProject(this.config.key)&&(this.autoCapture=new w(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=k.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new ue(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new fe(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{_(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=h(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new J(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger),u()&&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||`${this.namespace}_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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){if(!u())return new pe(e.trackingHost,e);const t="XMLHttpRequest"in window,i=typeof fetch<"u",n=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&n)return new he(e.trackingHost,e,this.logger);if(e.forceUseFetch&&i)return new q(e.trackingHost,e,this.logger);if(t)return new ge(e.trackingHost,e,this.logger);if(i)return new q(e.trackingHost,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new de:new V(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!u())return N();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return this.generateFingerprint();const e=this.config.cookieName||`${this.namespace}_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),d=a.length>1?a[1]:void 0;t=c||d||N()}t||(t=N());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}generateFingerprint(){const e=navigator.userAgent,t=`${screen.width}x${screen.height}`,i=screen.colorDepth,n=Intl.DateTimeFormat().resolvedOptions().timeZone,r=`${e}|${t}|${i}|${n}`;return this.hashString(r)}hashString(e){let t=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}async id(e,t=!1){if(!_(e))throw new Error("User data must be an object");if(e.email&&!re(e.email))throw new Error("Invalid email provided");if(!e.id||!B(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)}trackInternal(e,t,i=!1){if(!B(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 n=this.createEventPayload(e,t);try{if(i){this.transport.send(n),this.logger.debug(`Event sent: ${e}`,[n]);return}this.retryQueue.add(n),this.logger.debug(`Event tracked: ${e}`,[n])}catch(r){throw this.logger.error(`Failed to track event: ${e}`,r),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!_(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!_(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")||void 0,r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const d=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=d}else Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(d=>{delete l[d]}),a.event_attributes=l;return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ae(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(){u()?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(!u())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||`${this.namespace}_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))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 W(s){const e=JSON.parse(JSON.stringify(s)),t=C(e),i={...O,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");return new Q(i)}function me(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:ce(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="true"?"all":!1,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"},t=W(e),i=e.namespace||"usermaven";u()&&t.pageview(),ye(i,t)}function ye(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[s].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[s]=function(...a){const d=a[0];if(d==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[d]=="function")return e[d].apply(e,a.slice(1));console.error(`Method ${d} not found on UsermavenClient`)};const c=`${s}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[s].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}u()&&function(s,e){const t=s.currentScript;function i(){t&&t.src.includes("lib.js")&&me(t)}typeof e<"u"&&(s.readyState==="loading"?s.addEventListener("DOMContentLoaded",i):i())}(document,window),p.LogLevel=g,p.UsermavenClient=Q,p.usermavenClient=W,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
|
package/dist/usermaven.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
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 W{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 h(s=0){return new W(s)}const I={logLevel:w.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,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 X{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain(),console.log(this.cookieDomain)}set(e,t,i=365,n=!0,r=!1){console.log("Setting cookie",e,t,i,n,r);const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}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 K=Object.prototype,Z=K.hasOwnProperty,G=Array.prototype,b=G.forEach,$={};function Y(s,e,t){if(Array.isArray(s)){if(b&&s.forEach===b)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)===$)return}}}const T=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},j=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function S(s,e,t){if(s!=null){if(b&&Array.isArray(s)&&s.forEach===b)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)===$)return}else for(const i in s)if(Z.call(s,i)&&e.call(t,s[i],i)===$)return}}const ee=function(s,...e){return Y(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 D=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},te=function(s){return s===void 0},p=function(){const s=function(i,n,r,o,c){if(!i){h().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!c);else{const l="on"+n,a=i[l];i[l]=e(i,r,a)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;D(r)&&(l=r(o));const a=n.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}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}(),ie=function(s){return function(...e){try{return s.apply(this,e)}catch(t){h().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},F=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=ie(s[e]))};function R(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return h().warn("window is not available"),!1}}function f(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 se(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function A(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(A):Object.keys(s).reduce((e,t)=>{const i=se(t);return e[i]=A(s[t]),e},{})}function E(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 N(s){let e="";return B(s)&&!q(s)&&s.childNodes&&s.childNodes.length&&S(s.childNodes,function(t){z(t)&&t.textContent&&(e+=T(t.textContent).split(/(\s+)/).filter(x).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),T(e)}function H(s){return!!s&&s.nodeType===1}function d(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function z(s){return!!s&&s.nodeType===3}function M(s){return!!s&&s.nodeType===11}const C=["a","button","form","input","select","textarea","label"];function ne(s,e){if(!s||d(s,"html")||!H(s)||s.classList&&s.classList.contains("um-no-capture"))return!1;let t=!1;const i=[s];let n=!0,r=s;for(;r.parentNode&&!d(r,"body");){if(M(r.parentNode)){i.push(r.parentNode.host),r=r.parentNode.host;continue}if(n=r.parentNode||!1,!n)break;if(C.indexOf(n.tagName.toLowerCase())>-1)t=!0;else{const l=window.getComputedStyle(n);l&&l.getPropertyValue("cursor")==="pointer"&&(t=!0)}i.push(n),r=n}const o=window.getComputedStyle(s);if(o&&o.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;const c=s.tagName.toLowerCase();switch(c){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 t?e.type==="click":e.type==="click"&&(C.indexOf(c)>-1||s.getAttribute("contenteditable")==="true")}}function B(s){if(!s||!H(s))return!1;if(typeof s.hasAttribute=="function"){if(s.hasAttribute(k.FORCE_CAPTURE_ATTR))return!0;if(s.hasAttribute(k.PREVENT_CAPTURE_ATTR))return!1}let e=s;for(;e&&e.parentElement&&!d(e,"body");){const n=E(e).split(" ");if(_(n,"ph-sensitive")||_(n,"ph-no-capture"))return!1;e=e.parentElement}if(_(E(s).split(" "),"ph-include"))return!0;const t=s.type;if(typeof t=="string")switch(t.toLowerCase()){case"hidden":case"password":return!1}const i=s.name||s.id||"";return!(typeof i=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function q(s){const e=["button","checkbox","submit","reset"];return!!(d(s,"input")&&!e.includes(s.type)||d(s,"select")||d(s,"textarea")||s.getAttribute("contenteditable")==="true")}function x(s){return!(s===null||te(s)||typeof s=="string"&&(s=T(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 re(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function P(){return f(10)}function oe(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 ae(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function ce(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 O(s){return typeof s=="string"||s instanceof String}function v(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function le(s){if(s===null)return w.ERROR;const e=s.toUpperCase(),t=w[e];return t||t===0?t:w.ERROR}class ue{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ae(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"){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)})}}const y=class y{constructor(e,t,i=h()){this.logger=i,this.scrollDepth=null,this.client=e,this.options=t,this.scrollDepth=new ue(e),j(this),F(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};p(document,"submit",e,!1,!0),p(document,"change",e,!1,!0),p(document,"click",e,!1,!0),p(document,"visibilitychange",e,!1,!0),p(document,"scroll",e,!1,!0),p(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(z(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&&this.shouldCaptureElement(t,e)){const r=this.getElementList(t),o=this.getElementsJson(r,e),c=ee(this.getDefaultProperties(e.type),{$elements:o});return this.client.track("$autocapture",c),!0}}shouldCaptureElement(e,t){return!e||typeof e.hasAttribute!="function"?!1:e.hasAttribute(y.FORCE_CAPTURE_ATTR)?!0:e.hasAttribute(y.PREVENT_CAPTURE_ATTR)?!1:ne(e,t)}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}getElementList(e){const t=[e];let i=e;for(;i.parentNode&&!d(i,"body");)M(i.parentNode)?(t.push(i.parentNode.host),i=i.parentNode.host):(t.push(i.parentNode),i=i.parentNode);return t}getElementsJson(e,t){const i=[];let n=null,r=!1;return S(e,o=>{if(d(o,"a")){const l=o.getAttribute("href");l!==null&&B(o)&&x(l)&&(n=l)}const c=E(o).split(" ");_(c,"ph-no-capture")&&(r=!0),i.push(this.getPropertiesFromElement(o))}),this.options.maskAllText||(i[0].$el_text=this.sanitizeText(N(e[0]))),n!==null&&(i[0].attr__href=n),r?[]:i}getPropertiesFromElement(e){const t={tag_name:e.tagName.toLowerCase()};C.indexOf(t.tag_name)>-1&&!this.options.maskAllText&&(t.$el_text=this.sanitizeText(N(e)));const i=E(e);i.length>0&&(t.classes=i.split(" ").filter(c=>c!=="")),S(e.attributes,c=>{q(e)&&["name","id","class"].indexOf(c.name)===-1||!this.options.maskAllElementAttributes&&x(c.value)&&!re(c.name)&&(t["attr__"+c.name]=this.sanitizeAttributeValue(c.name,c.value))});let n=1,r=1,o=e;for(;o=this.previousElementSibling(o);)n++,o.tagName===e.tagName&&r++;return t.nth_child=n,t.nth_of_type=r,t}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;do e=e.previousSibling;while(e&&!H(e));return e}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}sanitizeText(e){e=e.replace(/<[^>]*?>/g,""),e=this.encodeHtml(e);const t=this.options.propertiesStringMaxLength||255;return e.length>t&&(e=e.substring(0,t)+"..."),e}sanitizeUrl(e){if(!e)return"";try{const t=new URL(e,window.location.href);return t.protocol!=="http:"&&t.protocol!=="https:"?"":encodeURI(t.toString())}catch{return this.encodeHtml(e)}}sanitizeAttributeValue(e,t){switch(e.toLowerCase()){case"href":case"src":return this.sanitizeUrl(t);default:return this.encodeHtml(t)}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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}static isBrowserSupported(){return D(document.querySelectorAll)}};y.FORCE_CAPTURE_ATTR="data-um-force-capture",y.PREVENT_CAPTURE_ATTR="data-um-no-capture";let k=y;class he{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 ge{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${f()}?p_${f()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class L{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${f()}?p_${f()}=${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 de{constructor(e,t,i=h()){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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${f()}?p_${f()}=${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 V{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||h()}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()}save(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){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.logger.error("Error loading from localStorage:",e)}}}class fe{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 U{constructor(e,t=3,i=1e3,n=10,r=1e3,o=h()){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.persistence=new V("offline_queue"),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class pe{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),F(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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.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 me{constructor(e,t,i=h()){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 c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.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 m{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",R(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,0);this.instance.track("$form_field_change",R(r))})})}static getInstance(e,t="all",i={}){return m.instance||(m.instance=new m(e,t,i)),m.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)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:i,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){const t={};for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i];n.name!=="value"&&!n.name.startsWith("data-")&&(t[n.name]=n.value)}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 J{constructor(e){this.config=this.mergeConfig(e,I),this.logger=h(this.config.logLevel),this.namespace=e.namespace||"usermaven",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new U(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new X(this.config.cookieDomain),this.config.autocapture&&k.enabledForProject(this.config.key)&&(this.autoCapture=new k(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=m.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new he(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new pe(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{v(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=h(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new U(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger),u()&&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||`${this.namespace}_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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){if(!u())return new me(e.trackingHost,e);const t="XMLHttpRequest"in window,i=typeof fetch<"u",n=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&n)return new ge(e.trackingHost,e,this.logger);if(e.forceUseFetch&&i)return new L(e.trackingHost,e,this.logger);if(t)return new de(e.trackingHost,e,this.logger);if(i)return new L(e.trackingHost,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new fe:new V(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!u())return P();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return this.generateFingerprint();const e=this.config.cookieName||`${this.namespace}_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),g=a.length>1?a[1]:void 0;t=c||g||P()}t||(t=P());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}generateFingerprint(){const e=navigator.userAgent,t=`${screen.width}x${screen.height}`,i=screen.colorDepth,n=Intl.DateTimeFormat().resolvedOptions().timeZone,r=`${e}|${t}|${i}|${n}`;return this.hashString(r)}hashString(e){let t=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}async id(e,t=!1){if(!v(e))throw new Error("User data must be an object");if(e.email&&!oe(e.email))throw new Error("Invalid email provided");if(!e.id||!O(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)}trackInternal(e,t,i=!1){if(!O(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 n=this.createEventPayload(e,t);try{if(i){this.transport.send(n),this.logger.debug(`Event sent: ${e}`,[n]);return}this.retryQueue.add(n),this.logger.debug(`Event tracked: ${e}`,[n])}catch(r){throw this.logger.error(`Failed to track event: ${e}`,r),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!v(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!v(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")||void 0,r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const g=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=g}else Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(g=>{delete l[g]}),a.event_attributes=l;return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ce(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(){u()?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(!u())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||`${this.namespace}_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(!v(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 Q(s){const e=JSON.parse(JSON.stringify(s)),t=A(e),i={...I,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");return new J(i)}function ye(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:le(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="true"?"all":!1,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"},t=Q(e),i=e.namespace||"usermaven";u()&&t.pageview(),we(i,t)}function we(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[s].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[s]=function(...a){const g=a[0];if(g==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[g]=="function")return e[g].apply(e,a.slice(1));console.error(`Method ${g} not found on UsermavenClient`)};const c=`${s}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[s].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}u()&&function(s,e){const t=s.currentScript;function i(){t&&t.src.includes("lib.js")&&ye(t)}typeof e<"u"&&(s.readyState==="loading"?s.addEventListener("DOMContentLoaded",i):i())}(document,window);exports.LogLevel=w;exports.UsermavenClient=J;exports.usermavenClient=Q;
|
|
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 W{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 h(s=0){return new W(s)}const D={logLevel:w.ERROR,useBeaconApi:!1,forceUseFetch:!1,trackingHost:"t.usermaven.com",autocapture:!1,rageClick:!1,formTracking:!1,autoPageview:!1,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 X{constructor(e){this.domain=e,this.cookieDomain=this.getCookieDomain(),console.log(this.cookieDomain)}set(e,t,i=365,n=!0,r=!1){console.log("Setting cookie",e,t,i,n,r);const o=new Date;o.setTime(o.getTime()+i*24*60*60*1e3);const c=`expires=${o.toUTCString()}`,l=n?"; Secure":"",a=r?"; HttpOnly":"";document.cookie=`${e}=${t};${c};path=/;domain=${this.cookieDomain}${l}${a}`}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 K=Object.prototype,Z=K.hasOwnProperty,G=Array.prototype,E=G.forEach,T={};function Y(s,e,t){if(Array.isArray(s)){if(E&&s.forEach===E)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)===T)return}}}const S=function(s){return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")},j=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=s[e].bind(s))};function A(s,e,t){if(s!=null){if(E&&Array.isArray(s)&&s.forEach===E)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)===T)return}else for(const i in s)if(Z.call(s,i)&&e.call(t,s[i],i)===T)return}}const ee=function(s,...e){return Y(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 F=function(s){try{return/^\s*\bfunction\b/.test(s)}catch{return!1}},te=function(s){return s===void 0},p=function(){const s=function(i,n,r,o,c){if(!i){h().error("No valid element provided to register_event");return}if(i.addEventListener&&!o)i.addEventListener(n,r,!!c);else{const l="on"+n,a=i[l];i[l]=e(i,r,a)}};function e(i,n,r){return function(o){if(o=o||t(window.event),!o)return;let c=!0,l;F(r)&&(l=r(o));const a=n.call(i,o);return(l===!1||a===!1)&&(c=!1),c}}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}(),ie=function(s){return function(...e){try{return s.apply(this,e)}catch(t){h().error("Implementation error. Please turn on debug and contact support@usermaven.com.",t)}}},z=function(s){for(const e in s)typeof s[e]=="function"&&(s[e]=ie(s[e]))};function N(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 u(){try{return typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0}catch{return h().warn("window is not available"),!1}}function f(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 se(s){return s.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace("-","").replace("_",""))}function C(s){return typeof s!="object"||s===null?s:Array.isArray(s)?s.map(C):Object.keys(s).reduce((e,t)=>{const i=se(t);return e[i]=C(s[t]),e},{})}function P(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 O(s){let e="";return B(s)&&!q(s)&&s.childNodes&&s.childNodes.length&&A(s.childNodes,function(t){M(t)&&t.textContent&&(e+=S(t.textContent).split(/(\s+)/).filter(H).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),S(e)}function R(s){return!!s&&s.nodeType===1}function d(s,e){return!!s&&!!s.tagName&&s.tagName.toLowerCase()===e.toLowerCase()}function M(s){return!!s&&s.nodeType===3}function x(s){return!!s&&s.nodeType===11}const b=["a","button","form","input","select","textarea","label"];function ne(s,e){if(!s||d(s,"html")||!R(s))return!1;let t=s;for(;t&&!d(t,"body");){if(t.classList&&t.classList.contains("um-no-capture"))return!1;t.parentNode&&x(t.parentNode)?t=t.parentNode.host:t=t.parentNode}let i=!1;for(t=s;t&&!d(t,"body");){if(t.parentNode&&x(t.parentNode)){t=t.parentNode.host,t&&b.indexOf(t.tagName.toLowerCase())>-1&&(i=!0);continue}const o=t.parentNode;if(!o)break;if(b.indexOf(o.tagName.toLowerCase())>-1)i=!0;else{const c=window.getComputedStyle(o);c&&c.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"&&(b.indexOf(r)>-1||s.getAttribute("contenteditable")==="true")}}function B(s){if(!s||!R(s))return!1;if(typeof s.hasAttribute=="function"){if(s.hasAttribute(k.FORCE_CAPTURE_ATTR))return!0;if(s.hasAttribute(k.PREVENT_CAPTURE_ATTR))return!1}let e=s;for(;e&&e.parentElement&&!d(e,"body");){const n=P(e).split(" ");if(_(n,"ph-sensitive")||_(n,"ph-no-capture"))return!1;e=e.parentElement}if(_(P(s).split(" "),"ph-include"))return!0;const t=s.type;if(typeof t=="string")switch(t.toLowerCase()){case"hidden":case"password":return!1}const i=s.name||s.id||"";return!(typeof i=="string"&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function q(s){const e=["button","checkbox","submit","reset"];return!!(d(s,"input")&&!e.includes(s.type)||d(s,"select")||d(s,"textarea")||s.getAttribute("contenteditable")==="true")}function H(s){return!(s===null||te(s)||typeof s=="string"&&(s=S(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 re(s){return typeof s=="string"?s.substring(0,10)==="_ngcontent"||s.substring(0,7)==="_nghost":!1}function $(){return f(10)}function oe(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 ae(s,e){let t;return function(...i){const n=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(n,e)}}function ce(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 L(s){return typeof s=="string"||s instanceof String}function v(s){return s!==null&&typeof s=="object"&&s.constructor===Object}function le(s){if(s===null)return w.ERROR;const e=s.toUpperCase(),t=w[e];return t||t===0?t:w.ERROR}class ue{constructor(e){this.maxScrollDepth=0,this.milestones=[25,50,75,90],this.lastScrollDepth=0,this.client=e,this.documentElement=document.documentElement,this.debouncedHandleScroll=ae(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"){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)})}}const y=class y{constructor(e,t,i=h()){this.logger=i,this.scrollDepth=null,this.client=e,this.options=t,this.scrollDepth=new ue(e),j(this),z(this)}init(){if(!(document&&document.body)){this.logger.debug("Document not ready yet, trying again in 500 milliseconds..."),setTimeout(()=>this.init(),500);return}this.addDomEventHandlers()}addDomEventHandlers(){const e=t=>{t=t||window.event,this.captureEvent(t)};p(document,"submit",e,!1,!0),p(document,"change",e,!1,!0),p(document,"click",e,!1,!0),p(document,"visibilitychange",e,!1,!0),p(document,"scroll",e,!1,!0),p(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(M(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&&this.shouldCaptureElement(t,e)){const r=this.getElementList(t),o=this.getElementsJson(r,e),c=ee(this.getDefaultProperties(e.type),{$elements:o});return this.client.track("$autocapture",c),!0}}shouldCaptureElement(e,t){return!e||typeof e.hasAttribute!="function"?!1:e.hasAttribute(y.FORCE_CAPTURE_ATTR)?!0:e.hasAttribute(y.PREVENT_CAPTURE_ATTR)?!1:ne(e,t)}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}getElementList(e){const t=[e];let i=e;for(;i.parentNode&&!d(i,"body");)x(i.parentNode)?(t.push(i.parentNode.host),i=i.parentNode.host):(t.push(i.parentNode),i=i.parentNode);return t}getElementsJson(e,t){const i=[];let n=null,r=!1;return A(e,o=>{if(d(o,"a")){const l=o.getAttribute("href");l!==null&&B(o)&&H(l)&&(n=l)}const c=P(o).split(" ");_(c,"ph-no-capture")&&(r=!0),i.push(this.getPropertiesFromElement(o))}),this.options.maskAllText||(i[0].$el_text=this.sanitizeText(O(e[0]))),n!==null&&(i[0].attr__href=n),r?[]:i}getPropertiesFromElement(e){const t={tag_name:e.tagName.toLowerCase()};b.indexOf(t.tag_name)>-1&&!this.options.maskAllText&&(t.$el_text=this.sanitizeText(O(e)));const i=P(e);i.length>0&&(t.classes=i.split(" ").filter(c=>c!=="")),A(e.attributes,c=>{q(e)&&["name","id","class"].indexOf(c.name)===-1||!this.options.maskAllElementAttributes&&H(c.value)&&!re(c.name)&&(t["attr__"+c.name]=this.sanitizeAttributeValue(c.name,c.value))});let n=1,r=1,o=e;for(;o=this.previousElementSibling(o);)n++,o.tagName===e.tagName&&r++;return t.nth_child=n,t.nth_of_type=r,t}previousElementSibling(e){if(e.previousElementSibling)return e.previousElementSibling;do e=e.previousSibling;while(e&&!R(e));return e}getDefaultProperties(e){return{$event_type:e,$ce_version:1}}sanitizeText(e){e=e.replace(/<[^>]*?>/g,""),e=this.encodeHtml(e);const t=this.options.propertiesStringMaxLength||255;return e.length>t&&(e=e.substring(0,t)+"..."),e}sanitizeUrl(e){if(!e)return"";try{const t=new URL(e,window.location.href);return t.protocol!=="http:"&&t.protocol!=="https:"?"":encodeURI(t.toString())}catch{return this.encodeHtml(e)}}sanitizeAttributeValue(e,t){switch(e.toLowerCase()){case"href":case"src":return this.sanitizeUrl(t);default:return this.encodeHtml(t)}}encodeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}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}static isBrowserSupported(){return F(document.querySelectorAll)}};y.FORCE_CAPTURE_ATTR="data-um-force-capture",y.PREVENT_CAPTURE_ATTR="data-um-no-capture";let k=y;class he{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 ge{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${f()}?p_${f()}=${e}${t}${i}`:`${this.trackingHost}${n}?token=${e}${t}${i}`}}class U{constructor(e,t,i=h()){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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${f()}?p_${f()}=${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 de{constructor(e,t,i=h()){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 c=this.getCustomHeaders();Object.keys(c).forEach(l=>{n.setRequestHeader(l,c[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=u()?"/api/v1/event":"/api/v1/s2s/event";return this.config.randomizeUrl?`${this.trackingHost}/api.${f()}?p_${f()}=${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 V{constructor(e,t){this.storage={},this.prefix=`usermaven_${e}_`,this.load(),this.logger=t||h()}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()}save(){if(!u()){this.logger.warn("localStorage is not available in this environment");return}try{localStorage.setItem(this.prefix+"data",JSON.stringify(this.storage))}catch(e){this.logger.error("Error saving to localStorage:",e)}}load(){if(!u()){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.logger.error("Error loading from localStorage:",e)}}}class fe{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 I{constructor(e,t=3,i=1e3,n=10,r=1e3,o=h()){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.persistence=new V("offline_queue"),u()&&(this.isOnline=navigator.onLine,this.loadQueueFromStorage(),this.initNetworkListeners(),this.scheduleBatch())}add(e){const t={payload:e,retries:0,timestamp:Date.now()};this.queue.push(t),u()?this.saveQueueToStorage():this.processBatch()}initNetworkListeners(){u()&&(window.addEventListener("online",()=>{this.isOnline=!0,this.processBatch()}),window.addEventListener("offline",()=>{this.isOnline=!1}))}scheduleBatch(){u()&&(this.batchTimeoutId!==null&&clearTimeout(this.batchTimeoutId),this.batchTimeoutId=window.setTimeout(()=>this.processBatch(),this.batchInterval))}async processBatch(){if((!u()||this.isOnline)&&!this.processing&&this.queue.length>0){this.processing=!0;const e=this.queue.splice(0,this.batchSize),t=e.map(i=>i.payload);try{await this.transport.send(t),this.logger.debug(`Successfully sent batch of ${e.length} payloads`),u()&&this.saveQueueToStorage()}catch(i){this.logger.error("Failed to send batch",i),await this.handleBatchFailure(e)}this.processing=!1}u()&&this.scheduleBatch()}async handleBatchFailure(e){for(const t of e)t.retries<this.maxRetries?(t.retries++,this.queue.unshift(t),this.logger.warn(`Retry attempt ${t.retries} for payload`)):this.logger.error("Max retries reached, discarding payload",t.payload);u()&&(this.saveQueueToStorage(),await new Promise(t=>setTimeout(t,this.retryInterval)))}loadQueueFromStorage(){if(u()){const e=this.persistence.get("queue");e&&(this.queue=JSON.parse(e))}}saveQueueToStorage(){u()&&this.persistence.set("queue",JSON.stringify(this.queue))}}class pe{constructor(e){this.clicks=[],this.threshold=3,this.timeWindow=2e3,this.distanceThreshold=30,this.client=e,this.initializeEventListener(),z(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 c=this.clicks[o-1];return Math.sqrt(Math.pow(r.x-c.x,2)+Math.pow(r.y-c.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 me{constructor(e,t,i=h()){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 c=(void 0)(n,l=>{l.on("data",a=>{}),l.on("end",()=>{const a=l.statusCode||0;a>=200&&a<300?(this.logger.debug(`Successfully sent ${e.length} event(s)`),r()):o(new Error(`HTTP error! status: ${a}`))})});c.on("error",l=>{o(l)}),c.write(JSON.stringify(e)),c.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 m{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",N(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,0);this.instance.track("$form_field_change",N(r))})})}static getInstance(e,t="all",i={}){return m.instance||(m.instance=new m(e,t,i)),m.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)},i=e.querySelectorAll("input, select, textarea");return Array.from(i).filter(r=>!r.classList.contains("um-no-capture")).forEach((r,o)=>{const c=this._getFieldProps(r,o);Object.assign(t,c)}),t}_getFieldProps(e,t){const i=Object.keys(e.dataset).length?JSON.stringify(e.dataset):void 0,n=this.getSafeText(e);return{[`field_${t+1}_tag`]:e.tagName.toLowerCase(),[`field_${t+1}_type`]:e instanceof HTMLInputElement?e.type:void 0,[`field_${t+1}_data_attributes`]:i,[`field_${t+1}_id`]:e.id,[`field_${t+1}_value`]:n,[`field_${t+1}_class`]:e.className,[`field_${t+1}_name`]:e.name,[`field_${t+1}_attributes`]:this._getElementAttributes(e)}}_getElementAttributes(e){const t={};for(let i=0;i<e.attributes.length;i++){const n=e.attributes[i];n.name!=="value"&&!n.name.startsWith("data-")&&(t[n.name]=n.value)}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 J{constructor(e){this.config=this.mergeConfig(e,D),this.logger=h(this.config.logLevel),this.namespace=e.namespace||"usermaven",this.transport=this.initializeTransport(this.config),this.persistence=this.initializePersistence(),this.retryQueue=new I(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,200,this.logger),u()&&this.initializeBrowserFeatures(),this.anonymousId=this.getOrCreateAnonymousId(),this.logger.info(`Usermaven client initialized for namespace: ${this.namespace}`)}initializeBrowserFeatures(){if(this.cookieManager=new X(this.config.cookieDomain),this.config.autocapture&&k.enabledForProject(this.config.key)&&(this.autoCapture=new k(this,this.config,this.logger),this.autoCapture.init()),this.config.formTracking){const e=this.config.formTracking===!0?"all":this.config.formTracking;this.formTracking=m.getInstance(this,e||"none",{trackFieldChanges:!1})}this.config.autoPageview&&(this.pageviewTracking=new he(this)),this.config.crossDomainLinking&&this.manageCrossDomainLinking(),this.config.rageClick&&(this.rageClick=new pe(this)),this.setupPageLeaveTracking()}mergeConfig(e,t){const i=JSON.parse(JSON.stringify(e));let n={...t,...i};return Object.keys(t).forEach(r=>{v(t[r])&&(n[r]=this.mergeConfig(e[r],t[r]))}),n}init(e){this.config={...this.config,...e},this.logger=h(this.config.logLevel),this.namespace=e.namespace||this.namespace,this.transport=this.initializeTransport(e),this.persistence=this.initializePersistence(),this.retryQueue=new I(this.transport,this.config.maxSendAttempts||3,this.config.minSendTimeout||1e3,10,250,this.logger),u()&&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||`${this.namespace}_id_${this.config.key}`;document.addEventListener("click",i=>{var c;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=(c=this.cookieManager)==null?void 0:c.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){if(!u())return new me(e.trackingHost,e);const t="XMLHttpRequest"in window,i=typeof fetch<"u",n=typeof navigator<"u"&&"sendBeacon"in navigator;if(e.useBeaconApi&&n)return new ge(e.trackingHost,e,this.logger);if(e.forceUseFetch&&i)return new U(e.trackingHost,e,this.logger);if(t)return new de(e.trackingHost,e,this.logger);if(i)return new U(e.trackingHost,e,this.logger);throw new Error("No suitable transport method available")}initializePersistence(){return this.config.disableEventPersistence||!u()?new fe:new V(`${this.namespace}_${this.config.key}`,this.logger)}getOrCreateAnonymousId(){var i,n;if(!u())return $();if(this.config.privacyPolicy==="strict"||this.config.cookiePolicy==="strict")return this.generateFingerprint();const e=this.config.cookieName||`${this.namespace}_id_${this.config.key}`;let t=(i=this.cookieManager)==null?void 0:i.get(e);if(!t){if(this.config.crossDomainLinking){const c=new URLSearchParams(window.location.search).get("_um"),a=window.location.hash.substring(1).split("~"),g=a.length>1?a[1]:void 0;t=c||g||$()}t||(t=$());const r=365*10;(n=this.cookieManager)==null||n.set(e,t,r,document.location.protocol!=="http:",!1)}return t}generateFingerprint(){const e=navigator.userAgent,t=`${screen.width}x${screen.height}`,i=screen.colorDepth,n=Intl.DateTimeFormat().resolvedOptions().timeZone,r=`${e}|${t}|${i}|${n}`;return this.hashString(r)}hashString(e){let t=0;for(let i=0;i<e.length;i++){const n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString(36)}async id(e,t=!1){if(!v(e))throw new Error("User data must be an object");if(e.email&&!oe(e.email))throw new Error("Invalid email provided");if(!e.id||!L(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)}trackInternal(e,t,i=!1){if(!L(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 n=this.createEventPayload(e,t);try{if(i){this.transport.send(n),this.logger.debug(`Event sent: ${e}`,[n]);return}this.retryQueue.add(n),this.logger.debug(`Event tracked: ${e}`,[n])}catch(r){throw this.logger.error(`Failed to track event: ${e}`,r),new Error(`Failed to track event: ${e}`)}}rawTrack(e){if(!v(e))throw new Error("Event payload must be an object");this.track("raw",e)}async group(e,t=!1){if(!v(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")||void 0,r=this.persistence.get("userId"),o=this.persistence.get("global_props")||{},c=this.persistence.get(`props_${e}`)||{};let l=t||{};const a={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,...c};if(e==="$autocapture"){const g=this.processAutocaptureAttributes(t||{});a.autocapture_attributes=g}else Array.isArray(this.config.propertyBlacklist)&&this.config.propertyBlacklist.forEach(g=>{delete l[g]}),a.event_attributes=l;return u()&&(a.referer=document.referrer,a.url=window.location.href,a.page_title=document.title,a.doc_path=window.location.pathname,a.doc_host=window.location.hostname,a.doc_search=window.location.search,a.screen_resolution=`${window.screen.width}x${window.screen.height}`,a.vp_size=`${window.innerWidth}x${window.innerHeight}`,a.user_agent=navigator.userAgent,a.user_language=navigator.language,a.doc_encoding=document.characterSet,a.utm=this.getUtmParams()),a}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(u()){const t=this.getCookie("_fbp");t&&(e.fbp=t)}return e}getUtmParams(){const e={},t=ce(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(){u()?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(!u())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||`${this.namespace}_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(!v(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 Q(s){const e=JSON.parse(JSON.stringify(s)),t=C(e),i={...D,...t};if(!i.key)throw new Error("API key is required!");if(!i.trackingHost)throw new Error("Tracking host is required!");return new J(i)}function ye(s){var n;const e={key:s.getAttribute("data-key")||void 0,trackingHost:s.getAttribute("data-tracking-host")||"https://events.usermaven.com",logLevel:le(s.getAttribute("data-log-level")),autocapture:s.getAttribute("data-autocapture")==="true",formTracking:s.getAttribute("data-form-tracking")==="true"?"all":!1,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"},t=Q(e),i=e.namespace||"usermaven";u()&&t.pageview(),we(i,t)}function we(s,e){let t=!1;const i=[],n=[];function r(){for(;i.length>0;){const a=i.shift();a&&window[s].apply(null,a)}}function o(){n.forEach(a=>a()),n.length=0}window[s]=function(...a){const g=a[0];if(g==="onLoad"){typeof a[1]=="function"&&(t?a[1]():n.push(a[1]));return}if(!t){i.push(a);return}if(typeof e[g]=="function")return e[g].apply(e,a.slice(1));console.error(`Method ${g} not found on UsermavenClient`)};const c=`${s}Q`,l=window[c]||[];for(window[c]=l,l.push=function(...a){return window[s].apply(null,a),Array.prototype.push.apply(this,a)},setTimeout(()=>{t=!0,r(),o(),console.log(`Usermaven client for namespace ${s} is ready`)},0);l.length>0;){const a=l.shift();a&&i.push(a)}}u()&&function(s,e){const t=s.currentScript;function i(){t&&t.src.includes("lib.js")&&ye(t)}typeof e<"u"&&(s.readyState==="loading"?s.addEventListener("DOMContentLoaded",i):i())}(document,window);exports.LogLevel=w;exports.UsermavenClient=J;exports.usermavenClient=Q;
|
package/dist/usermaven.es.js
CHANGED
|
@@ -19,7 +19,7 @@ class J {
|
|
|
19
19
|
function h(s = 0) {
|
|
20
20
|
return new J(s);
|
|
21
21
|
}
|
|
22
|
-
const
|
|
22
|
+
const D = {
|
|
23
23
|
logLevel: v.ERROR,
|
|
24
24
|
useBeaconApi: !1,
|
|
25
25
|
forceUseFetch: !1,
|
|
@@ -95,35 +95,35 @@ class Q {
|
|
|
95
95
|
return i ? i[0] : "";
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
|
-
const W = Object.prototype, X = W.hasOwnProperty, K = Array.prototype,
|
|
98
|
+
const W = Object.prototype, X = W.hasOwnProperty, K = Array.prototype, E = K.forEach, T = {};
|
|
99
99
|
function Z(s, e, t) {
|
|
100
100
|
if (Array.isArray(s)) {
|
|
101
|
-
if (
|
|
101
|
+
if (E && s.forEach === E)
|
|
102
102
|
s.forEach(e, t);
|
|
103
103
|
else if ("length" in s && s.length === +s.length) {
|
|
104
104
|
for (let i = 0, n = s.length; i < n; i++)
|
|
105
|
-
if (i in s && e.call(t, s[i], i) ===
|
|
105
|
+
if (i in s && e.call(t, s[i], i) === T)
|
|
106
106
|
return;
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
|
-
const
|
|
110
|
+
const A = function(s) {
|
|
111
111
|
return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
|
|
112
112
|
}, G = function(s) {
|
|
113
113
|
for (const e in s)
|
|
114
114
|
typeof s[e] == "function" && (s[e] = s[e].bind(s));
|
|
115
115
|
};
|
|
116
|
-
function
|
|
116
|
+
function S(s, e, t) {
|
|
117
117
|
if (s != null) {
|
|
118
|
-
if (
|
|
118
|
+
if (E && Array.isArray(s) && s.forEach === E)
|
|
119
119
|
s.forEach(e, t);
|
|
120
120
|
else if ("length" in s && s.length === +s.length) {
|
|
121
121
|
for (let i = 0, n = s.length; i < n; i++)
|
|
122
|
-
if (i in s && e.call(t, s[i], i) ===
|
|
122
|
+
if (i in s && e.call(t, s[i], i) === T)
|
|
123
123
|
return;
|
|
124
124
|
} else
|
|
125
125
|
for (const i in s)
|
|
126
|
-
if (X.call(s, i) && e.call(t, s[i], i) ===
|
|
126
|
+
if (X.call(s, i) && e.call(t, s[i], i) === T)
|
|
127
127
|
return;
|
|
128
128
|
}
|
|
129
129
|
}
|
|
@@ -136,7 +136,7 @@ const Y = function(s, ...e) {
|
|
|
136
136
|
function _(s, e) {
|
|
137
137
|
return s.indexOf(e) !== -1;
|
|
138
138
|
}
|
|
139
|
-
const
|
|
139
|
+
const F = function(s) {
|
|
140
140
|
try {
|
|
141
141
|
return /^\s*\bfunction\b/.test(s);
|
|
142
142
|
} catch {
|
|
@@ -162,7 +162,7 @@ const D = function(s) {
|
|
|
162
162
|
if (o = o || t(window.event), !o)
|
|
163
163
|
return;
|
|
164
164
|
let c = !0, l;
|
|
165
|
-
|
|
165
|
+
F(r) && (l = r(o));
|
|
166
166
|
const a = n.call(i, o);
|
|
167
167
|
return (l === !1 || a === !1) && (c = !1), c;
|
|
168
168
|
};
|
|
@@ -183,11 +183,11 @@ const D = function(s) {
|
|
|
183
183
|
h().error("Implementation error. Please turn on debug and contact support@usermaven.com.", t);
|
|
184
184
|
}
|
|
185
185
|
};
|
|
186
|
-
},
|
|
186
|
+
}, z = function(s) {
|
|
187
187
|
for (const e in s)
|
|
188
188
|
typeof s[e] == "function" && (s[e] = ee(s[e]));
|
|
189
189
|
};
|
|
190
|
-
function
|
|
190
|
+
function N(s) {
|
|
191
191
|
for (let e in s)
|
|
192
192
|
(s[e] === "" || s[e] === null || s[e] === void 0 || typeof s[e] == "object" && Object.keys(s[e]).length === 0) && delete s[e];
|
|
193
193
|
return s;
|
|
@@ -209,13 +209,13 @@ function te(s) {
|
|
|
209
209
|
(e) => e.toUpperCase().replace("-", "").replace("_", "")
|
|
210
210
|
);
|
|
211
211
|
}
|
|
212
|
-
function
|
|
213
|
-
return typeof s != "object" || s === null ? s : Array.isArray(s) ? s.map(
|
|
212
|
+
function C(s) {
|
|
213
|
+
return typeof s != "object" || s === null ? s : Array.isArray(s) ? s.map(C) : Object.keys(s).reduce((e, t) => {
|
|
214
214
|
const i = te(t);
|
|
215
|
-
return e[i] =
|
|
215
|
+
return e[i] = C(s[t]), e;
|
|
216
216
|
}, {});
|
|
217
217
|
}
|
|
218
|
-
function
|
|
218
|
+
function P(s) {
|
|
219
219
|
switch (typeof s.className) {
|
|
220
220
|
case "string":
|
|
221
221
|
return s.className;
|
|
@@ -225,50 +225,55 @@ function E(s) {
|
|
|
225
225
|
return "";
|
|
226
226
|
}
|
|
227
227
|
}
|
|
228
|
-
function
|
|
228
|
+
function O(s) {
|
|
229
229
|
let e = "";
|
|
230
|
-
return M(s) && !q(s) && s.childNodes && s.childNodes.length &&
|
|
231
|
-
|
|
232
|
-
}),
|
|
230
|
+
return M(s) && !q(s) && s.childNodes && s.childNodes.length && S(s.childNodes, function(t) {
|
|
231
|
+
B(t) && t.textContent && (e += A(t.textContent).split(/(\s+)/).filter(H).join("").replace(/[\r\n]/g, " ").replace(/[ ]+/g, " ").substring(0, 255));
|
|
232
|
+
}), A(e);
|
|
233
233
|
}
|
|
234
|
-
function
|
|
234
|
+
function R(s) {
|
|
235
235
|
return !!s && s.nodeType === 1;
|
|
236
236
|
}
|
|
237
237
|
function d(s, e) {
|
|
238
238
|
return !!s && !!s.tagName && s.tagName.toLowerCase() === e.toLowerCase();
|
|
239
239
|
}
|
|
240
|
-
function
|
|
240
|
+
function B(s) {
|
|
241
241
|
return !!s && s.nodeType === 3;
|
|
242
242
|
}
|
|
243
|
-
function
|
|
243
|
+
function x(s) {
|
|
244
244
|
return !!s && s.nodeType === 11;
|
|
245
245
|
}
|
|
246
|
-
const
|
|
246
|
+
const b = ["a", "button", "form", "input", "select", "textarea", "label"];
|
|
247
247
|
function ie(s, e) {
|
|
248
|
-
if (!s || d(s, "html") || !
|
|
248
|
+
if (!s || d(s, "html") || !R(s))
|
|
249
249
|
return !1;
|
|
250
|
-
let t =
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
250
|
+
let t = s;
|
|
251
|
+
for (; t && !d(t, "body"); ) {
|
|
252
|
+
if (t.classList && t.classList.contains("um-no-capture"))
|
|
253
|
+
return !1;
|
|
254
|
+
t.parentNode && x(t.parentNode) ? t = t.parentNode.host : t = t.parentNode;
|
|
255
|
+
}
|
|
256
|
+
let i = !1;
|
|
257
|
+
for (t = s; t && !d(t, "body"); ) {
|
|
258
|
+
if (t.parentNode && x(t.parentNode)) {
|
|
259
|
+
t = t.parentNode.host, t && b.indexOf(t.tagName.toLowerCase()) > -1 && (i = !0);
|
|
256
260
|
continue;
|
|
257
261
|
}
|
|
258
|
-
|
|
259
|
-
if (
|
|
260
|
-
|
|
262
|
+
const o = t.parentNode;
|
|
263
|
+
if (!o) break;
|
|
264
|
+
if (b.indexOf(o.tagName.toLowerCase()) > -1)
|
|
265
|
+
i = !0;
|
|
261
266
|
else {
|
|
262
|
-
const
|
|
263
|
-
|
|
267
|
+
const c = window.getComputedStyle(o);
|
|
268
|
+
c && c.getPropertyValue("cursor") === "pointer" && (i = !0);
|
|
264
269
|
}
|
|
265
|
-
|
|
270
|
+
t = o;
|
|
266
271
|
}
|
|
267
|
-
const
|
|
268
|
-
if (
|
|
272
|
+
const n = window.getComputedStyle(s);
|
|
273
|
+
if (n && n.getPropertyValue("cursor") === "pointer" && e.type === "click")
|
|
269
274
|
return !0;
|
|
270
|
-
const
|
|
271
|
-
switch (
|
|
275
|
+
const r = s.tagName.toLowerCase();
|
|
276
|
+
switch (r) {
|
|
272
277
|
case "html":
|
|
273
278
|
return !1;
|
|
274
279
|
case "form":
|
|
@@ -279,11 +284,11 @@ function ie(s, e) {
|
|
|
279
284
|
case "textarea":
|
|
280
285
|
return e.type === "change" || e.type === "click";
|
|
281
286
|
default:
|
|
282
|
-
return
|
|
287
|
+
return i ? e.type === "click" : e.type === "click" && (b.indexOf(r) > -1 || s.getAttribute("contenteditable") === "true");
|
|
283
288
|
}
|
|
284
289
|
}
|
|
285
290
|
function M(s) {
|
|
286
|
-
if (!s || !
|
|
291
|
+
if (!s || !R(s))
|
|
287
292
|
return !1;
|
|
288
293
|
if (typeof s.hasAttribute == "function") {
|
|
289
294
|
if (s.hasAttribute(w.FORCE_CAPTURE_ATTR))
|
|
@@ -293,12 +298,12 @@ function M(s) {
|
|
|
293
298
|
}
|
|
294
299
|
let e = s;
|
|
295
300
|
for (; e && e.parentElement && !d(e, "body"); ) {
|
|
296
|
-
const n =
|
|
301
|
+
const n = P(e).split(" ");
|
|
297
302
|
if (_(n, "ph-sensitive") || _(n, "ph-no-capture"))
|
|
298
303
|
return !1;
|
|
299
304
|
e = e.parentElement;
|
|
300
305
|
}
|
|
301
|
-
if (_(
|
|
306
|
+
if (_(P(s).split(" "), "ph-include"))
|
|
302
307
|
return !0;
|
|
303
308
|
const t = s.type;
|
|
304
309
|
if (typeof t == "string")
|
|
@@ -314,13 +319,13 @@ function q(s) {
|
|
|
314
319
|
const e = ["button", "checkbox", "submit", "reset"];
|
|
315
320
|
return !!(d(s, "input") && !e.includes(s.type) || d(s, "select") || d(s, "textarea") || s.getAttribute("contenteditable") === "true");
|
|
316
321
|
}
|
|
317
|
-
function
|
|
318
|
-
return !(s === null || j(s) || typeof s == "string" && (s =
|
|
322
|
+
function H(s) {
|
|
323
|
+
return !(s === null || j(s) || typeof s == "string" && (s = A(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)));
|
|
319
324
|
}
|
|
320
325
|
function se(s) {
|
|
321
326
|
return typeof s == "string" ? s.substring(0, 10) === "_ngcontent" || s.substring(0, 7) === "_nghost" : !1;
|
|
322
327
|
}
|
|
323
|
-
function
|
|
328
|
+
function $() {
|
|
324
329
|
return f(10);
|
|
325
330
|
}
|
|
326
331
|
function ne(s) {
|
|
@@ -343,7 +348,7 @@ function oe(s) {
|
|
|
343
348
|
}
|
|
344
349
|
return e;
|
|
345
350
|
}
|
|
346
|
-
function
|
|
351
|
+
function L(s) {
|
|
347
352
|
return typeof s == "string" || s instanceof String;
|
|
348
353
|
}
|
|
349
354
|
function k(s) {
|
|
@@ -406,7 +411,7 @@ class ce {
|
|
|
406
411
|
}
|
|
407
412
|
const y = class y {
|
|
408
413
|
constructor(e, t, i = h()) {
|
|
409
|
-
this.logger = i, this.scrollDepth = null, this.client = e, this.options = t, this.scrollDepth = new ce(e), G(this),
|
|
414
|
+
this.logger = i, this.scrollDepth = null, this.client = e, this.options = t, this.scrollDepth = new ce(e), G(this), z(this);
|
|
410
415
|
}
|
|
411
416
|
init() {
|
|
412
417
|
if (!(document && document.body)) {
|
|
@@ -432,7 +437,7 @@ const y = class y {
|
|
|
432
437
|
captureEvent(e) {
|
|
433
438
|
var i, n;
|
|
434
439
|
let t = this.getEventTarget(e);
|
|
435
|
-
if (
|
|
440
|
+
if (B(t) && (t = t.parentNode || null), e.type === "scroll")
|
|
436
441
|
return (i = this.scrollDepth) == null || i.track(), !0;
|
|
437
442
|
if (e.type === "visibilitychange" && document.visibilityState === "hidden" || e.type === "popstate")
|
|
438
443
|
return this.isPageRefresh() || (n = this.scrollDepth) == null || n.send(), !0;
|
|
@@ -457,29 +462,29 @@ const y = class y {
|
|
|
457
462
|
const t = [e];
|
|
458
463
|
let i = e;
|
|
459
464
|
for (; i.parentNode && !d(i, "body"); )
|
|
460
|
-
|
|
465
|
+
x(i.parentNode) ? (t.push(i.parentNode.host), i = i.parentNode.host) : (t.push(i.parentNode), i = i.parentNode);
|
|
461
466
|
return t;
|
|
462
467
|
}
|
|
463
468
|
getElementsJson(e, t) {
|
|
464
469
|
const i = [];
|
|
465
470
|
let n = null, r = !1;
|
|
466
|
-
return
|
|
471
|
+
return S(e, (o) => {
|
|
467
472
|
if (d(o, "a")) {
|
|
468
473
|
const l = o.getAttribute("href");
|
|
469
|
-
l !== null && M(o) &&
|
|
474
|
+
l !== null && M(o) && H(l) && (n = l);
|
|
470
475
|
}
|
|
471
|
-
const c =
|
|
476
|
+
const c = P(o).split(" ");
|
|
472
477
|
_(c, "ph-no-capture") && (r = !0), i.push(this.getPropertiesFromElement(o));
|
|
473
|
-
}), this.options.maskAllText || (i[0].$el_text = this.sanitizeText(
|
|
478
|
+
}), this.options.maskAllText || (i[0].$el_text = this.sanitizeText(O(e[0]))), n !== null && (i[0].attr__href = n), r ? [] : i;
|
|
474
479
|
}
|
|
475
480
|
getPropertiesFromElement(e) {
|
|
476
481
|
const t = {
|
|
477
482
|
tag_name: e.tagName.toLowerCase()
|
|
478
483
|
};
|
|
479
|
-
|
|
480
|
-
const i =
|
|
481
|
-
i.length > 0 && (t.classes = i.split(" ").filter((c) => c !== "")),
|
|
482
|
-
q(e) && ["name", "id", "class"].indexOf(c.name) === -1 || !this.options.maskAllElementAttributes &&
|
|
484
|
+
b.indexOf(t.tag_name) > -1 && !this.options.maskAllText && (t.$el_text = this.sanitizeText(O(e)));
|
|
485
|
+
const i = P(e);
|
|
486
|
+
i.length > 0 && (t.classes = i.split(" ").filter((c) => c !== "")), S(e.attributes, (c) => {
|
|
487
|
+
q(e) && ["name", "id", "class"].indexOf(c.name) === -1 || !this.options.maskAllElementAttributes && H(c.value) && !se(c.name) && (t["attr__" + c.name] = this.sanitizeAttributeValue(c.name, c.value));
|
|
483
488
|
});
|
|
484
489
|
let n = 1, r = 1, o = e;
|
|
485
490
|
for (; o = this.previousElementSibling(o); )
|
|
@@ -491,7 +496,7 @@ const y = class y {
|
|
|
491
496
|
return e.previousElementSibling;
|
|
492
497
|
do
|
|
493
498
|
e = e.previousSibling;
|
|
494
|
-
while (e && !
|
|
499
|
+
while (e && !R(e));
|
|
495
500
|
return e;
|
|
496
501
|
}
|
|
497
502
|
getDefaultProperties(e) {
|
|
@@ -536,7 +541,7 @@ const y = class y {
|
|
|
536
541
|
return n % t < i;
|
|
537
542
|
}
|
|
538
543
|
static isBrowserSupported() {
|
|
539
|
-
return
|
|
544
|
+
return F(document.querySelectorAll);
|
|
540
545
|
}
|
|
541
546
|
};
|
|
542
547
|
y.FORCE_CAPTURE_ATTR = "data-um-force-capture", y.PREVENT_CAPTURE_ATTR = "data-um-no-capture";
|
|
@@ -588,7 +593,7 @@ class ue {
|
|
|
588
593
|
// Note: Beacon API doesn't support custom headers, so we can't use them here.
|
|
589
594
|
// If custom headers are crucial, you might want to fall back to XHR or Fetch in those cases.
|
|
590
595
|
}
|
|
591
|
-
class
|
|
596
|
+
class U {
|
|
592
597
|
constructor(e, t, i = h()) {
|
|
593
598
|
this.trackingHost = e, this.logger = i, this.config = t;
|
|
594
599
|
}
|
|
@@ -704,7 +709,7 @@ class ge {
|
|
|
704
709
|
this.storage = {};
|
|
705
710
|
}
|
|
706
711
|
}
|
|
707
|
-
class
|
|
712
|
+
class I {
|
|
708
713
|
// Default to true for server-side
|
|
709
714
|
constructor(e, t = 3, i = 1e3, n = 10, r = 1e3, o = h()) {
|
|
710
715
|
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.persistence = new V("offline_queue"), u() && (this.isOnline = navigator.onLine, this.loadQueueFromStorage(), this.initNetworkListeners(), this.scheduleBatch());
|
|
@@ -753,7 +758,7 @@ class U {
|
|
|
753
758
|
}
|
|
754
759
|
class de {
|
|
755
760
|
constructor(e) {
|
|
756
|
-
this.clicks = [], this.threshold = 3, this.timeWindow = 2e3, this.distanceThreshold = 30, this.client = e, this.initializeEventListener(),
|
|
761
|
+
this.clicks = [], this.threshold = 3, this.timeWindow = 2e3, this.distanceThreshold = 30, this.client = e, this.initializeEventListener(), z(this);
|
|
757
762
|
}
|
|
758
763
|
initializeEventListener() {
|
|
759
764
|
document.addEventListener("click", this.handleClick.bind(this));
|
|
@@ -836,13 +841,13 @@ class m {
|
|
|
836
841
|
}
|
|
837
842
|
handleFormSubmit(e) {
|
|
838
843
|
const t = e.target, i = this._getFormDetails(t);
|
|
839
|
-
this.instance.track("$form",
|
|
844
|
+
this.instance.track("$form", N(i)), this.options.trackFieldChanges && this.trackFieldChanges(t);
|
|
840
845
|
}
|
|
841
846
|
trackFieldChanges(e) {
|
|
842
847
|
e.querySelectorAll("input, select, textarea").forEach((i) => {
|
|
843
848
|
i.addEventListener("change", (n) => {
|
|
844
849
|
const r = this._getFieldProps(n.target, 0);
|
|
845
|
-
this.instance.track("$form_field_change",
|
|
850
|
+
this.instance.track("$form_field_change", N(r));
|
|
846
851
|
});
|
|
847
852
|
});
|
|
848
853
|
}
|
|
@@ -942,7 +947,7 @@ class m {
|
|
|
942
947
|
}
|
|
943
948
|
class pe {
|
|
944
949
|
constructor(e) {
|
|
945
|
-
this.config = this.mergeConfig(e,
|
|
950
|
+
this.config = this.mergeConfig(e, D), this.logger = h(this.config.logLevel), this.namespace = e.namespace || "usermaven", this.transport = this.initializeTransport(this.config), this.persistence = this.initializePersistence(), this.retryQueue = new I(
|
|
946
951
|
this.transport,
|
|
947
952
|
this.config.maxSendAttempts || 3,
|
|
948
953
|
this.config.minSendTimeout || 1e3,
|
|
@@ -974,7 +979,7 @@ class pe {
|
|
|
974
979
|
}), n;
|
|
975
980
|
}
|
|
976
981
|
init(e) {
|
|
977
|
-
this.config = { ...this.config, ...e }, this.logger = h(this.config.logLevel), this.namespace = e.namespace || this.namespace, this.transport = this.initializeTransport(e), this.persistence = this.initializePersistence(), this.retryQueue = new
|
|
982
|
+
this.config = { ...this.config, ...e }, this.logger = h(this.config.logLevel), this.namespace = e.namespace || this.namespace, this.transport = this.initializeTransport(e), this.persistence = this.initializePersistence(), this.retryQueue = new I(
|
|
978
983
|
this.transport,
|
|
979
984
|
this.config.maxSendAttempts || 3,
|
|
980
985
|
this.config.minSendTimeout || 1e3,
|
|
@@ -1013,11 +1018,11 @@ class pe {
|
|
|
1013
1018
|
if (e.useBeaconApi && n)
|
|
1014
1019
|
return new ue(e.trackingHost, e, this.logger);
|
|
1015
1020
|
if (e.forceUseFetch && i)
|
|
1016
|
-
return new
|
|
1021
|
+
return new U(e.trackingHost, e, this.logger);
|
|
1017
1022
|
if (t)
|
|
1018
1023
|
return new he(e.trackingHost, e, this.logger);
|
|
1019
1024
|
if (i)
|
|
1020
|
-
return new
|
|
1025
|
+
return new U(e.trackingHost, e, this.logger);
|
|
1021
1026
|
throw new Error("No suitable transport method available");
|
|
1022
1027
|
}
|
|
1023
1028
|
initializePersistence() {
|
|
@@ -1026,7 +1031,7 @@ class pe {
|
|
|
1026
1031
|
getOrCreateAnonymousId() {
|
|
1027
1032
|
var i, n;
|
|
1028
1033
|
if (!u())
|
|
1029
|
-
return
|
|
1034
|
+
return $();
|
|
1030
1035
|
if (this.config.privacyPolicy === "strict" || this.config.cookiePolicy === "strict")
|
|
1031
1036
|
return this.generateFingerprint();
|
|
1032
1037
|
const e = this.config.cookieName || `${this.namespace}_id_${this.config.key}`;
|
|
@@ -1034,9 +1039,9 @@ class pe {
|
|
|
1034
1039
|
if (!t) {
|
|
1035
1040
|
if (this.config.crossDomainLinking) {
|
|
1036
1041
|
const c = new URLSearchParams(window.location.search).get("_um"), a = window.location.hash.substring(1).split("~"), g = a.length > 1 ? a[1] : void 0;
|
|
1037
|
-
t = c || g ||
|
|
1042
|
+
t = c || g || $();
|
|
1038
1043
|
}
|
|
1039
|
-
t || (t =
|
|
1044
|
+
t || (t = $());
|
|
1040
1045
|
const r = 365 * 10;
|
|
1041
1046
|
(n = this.cookieManager) == null || n.set(e, t, r, document.location.protocol !== "http:", !1);
|
|
1042
1047
|
}
|
|
@@ -1059,7 +1064,7 @@ class pe {
|
|
|
1059
1064
|
throw new Error("User data must be an object");
|
|
1060
1065
|
if (e.email && !ne(e.email))
|
|
1061
1066
|
throw new Error("Invalid email provided");
|
|
1062
|
-
if (!e.id || !
|
|
1067
|
+
if (!e.id || !L(e.id))
|
|
1063
1068
|
throw new Error("User ID must be a string");
|
|
1064
1069
|
const i = e.id;
|
|
1065
1070
|
if (this.persistence.set("userId", i), this.persistence.set("userProps", e), !t) {
|
|
@@ -1075,7 +1080,7 @@ class pe {
|
|
|
1075
1080
|
this.trackInternal(e, t, i);
|
|
1076
1081
|
}
|
|
1077
1082
|
trackInternal(e, t, i = !1) {
|
|
1078
|
-
if (!
|
|
1083
|
+
if (!L(e))
|
|
1079
1084
|
throw new Error("Event name must be a string");
|
|
1080
1085
|
if (t !== void 0 && (typeof t != "object" || t === null || Array.isArray(t)))
|
|
1081
1086
|
throw new Error("Event payload must be a non-null object and not an array");
|
|
@@ -1234,7 +1239,7 @@ class pe {
|
|
|
1234
1239
|
}
|
|
1235
1240
|
}
|
|
1236
1241
|
function me(s) {
|
|
1237
|
-
const e = JSON.parse(JSON.stringify(s)), t =
|
|
1242
|
+
const e = JSON.parse(JSON.stringify(s)), t = C(e), i = { ...D, ...t };
|
|
1238
1243
|
if (!i.key)
|
|
1239
1244
|
throw new Error("API key is required!");
|
|
1240
1245
|
if (!i.trackingHost)
|