userpath-js 0.0.2 → 0.0.4
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/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var N={name:"userpath-js",version:"0.0.1",private:!1,main:"dist/index.js",types:"dist/types/src/index.d.ts",exports:{".":{types:"./dist/types/src/index.d.ts",default:"./dist/index.js"},"./server":{types:"./dist/types/src/server/index.d.ts",default:"./dist/server/index.js"}},files:["dist/index.js","dist/types","dist/server"],scripts:{dev:"bun build src/index.ts --outdir ./dist --watch",types:"tsc",build:"bun run build.client && bun run build.pixel && bun run build.server","build.prod":"bun run build.client.prod && bun run build.pixel.prod && bun run build.server.prod","build.client":"bun run types && bun build src/index.ts --outdir ./dist --no-cache","build.client.prod":"bun run types && bun build src/index.ts --outdir ./dist --minify","build.pixel":"bun build src/pixel.ts --outdir ./dist","build.pixel.prod":"bun build src/pixel.ts --outdir ./dist --minify","build.server":"bun run types && bun build src/server/index.ts --outdir ./dist/server","build.server.prod":"bun run types && bun build src/server/index.ts --outdir ./dist/server --minify",prepublish:"bun run build.prod"},devDependencies:{"bun-types":"latest",typescript:"^5.0.0"}};var j={appId:"",serverUrl:"https://api.userpath.co",version:1,flushIntervalMs:5000,autoTrack:{errors:!0,clicks:!0,scrolling:!0,forms:!0,videos:!0,pageVisibility:!0,pageInactivity:!0}};class M{serverUrl;appId;version;constructor(x){this.serverUrl=x.serverUrl||"",this.appId=x.appId,this.version=x.version||j.version}buildUrl(x){return`${this.serverUrl}/v${this.version}/${x}`}}var E=typeof window==="undefined",w={pushState:()=>{},replaceState:()=>{},go:()=>{},back:()=>{},forward:()=>{}};if(E)global.history=w;var D={location:{href:""},addEventListener:()=>{},removeEventListener:()=>{},scrollTo:()=>{},scrollBy:()=>{},setTimeout:()=>{},clearTimeout:()=>{},setInterval:()=>{},clearInterval:()=>{}};if(E)global.window=D;var P={hidden:!1,addEventListener:()=>{},removeEventListener:()=>{},querySelector:()=>null,closest:()=>null,getAttribute:()=>null,tagName:"",textContent:"",classList:{contains:()=>!1},scrollHeight:0,offsetHeight:0,clientHeight:0,pageYOffset:0,referrer:"",title:""};if(E)global.document=P;class Q{#R;#x;#$;#_;#j;#W;#X;#J;#Y;#A;#w;#D;#P;#L;#b;#Z;#V;#E;#G;#K;#g;#Q;#q;#z;#C;#M;#O;#F;#u=60000;#B;#N=!1;#y;#U;#I;constructor(x,$=j){this.#R=x,this.#I=$,this.#x=new Set,this.#$=0,this.#Z=null,this.#V=window.location.href,this.#E=new Map,this.#G=new WeakMap,this.#K=new WeakMap,this.#g=Date.now(),this.#Q=0,this.#q=this.#g,this.#z=document.hidden,this.#C=Date.now(),this.#M=null,this.#O=!1,this.#B=null,this.#_=this.handleClick.bind(this),this.#j=this.handleScroll.bind(this),this.#W=this.handleScroll.bind(this),this.#X=this.handleInputFocus.bind(this),this.#J=this.handleInputBlur.bind(this),this.#Y=this.handleFormChange.bind(this),this.#A=this.handleFormSubmit.bind(this),this.#w=this.handleVideoPlay.bind(this),this.#D=this.handleVideoPause.bind(this),this.#P=this.handleVideoEnd.bind(this),this.#L=this.handleVisibilityChange.bind(this),this.#b=this.handleBeforeUnload.bind(this),this.#F=this.handleUserActivity.bind(this),this.#y=this.handleError.bind(this),this.#U=this.handleRejection.bind(this);let R=this.#I.autoTrack||j.autoTrack;if(R.clicks!==!1)this.setupClickTracking();if(R.scrolling!==!1)this.setupScrollTracking();if(R.forms!==!1)this.setupFormTracking();if(R.videos!==!1)this.setupVideoTracking();if(R.pageVisibility!==!1)this.setupPageTimeTracking();if(R.pageInactivity!==!1)this.setupInactivityTracking()}destroy(){if(document.removeEventListener("click",this.#_),window.removeEventListener("scroll",this.#j),window.removeEventListener("resize",this.#W),document.removeEventListener("focus",this.#X,!0),document.removeEventListener("blur",this.#J,!0),document.removeEventListener("change",this.#Y,!0),document.removeEventListener("submit",this.#A,!0),document.removeEventListener("play",this.#w,!0),document.removeEventListener("pause",this.#D,!0),document.removeEventListener("ended",this.#P,!0),document.removeEventListener("visibilitychange",this.#L),window.removeEventListener("beforeunload",this.#b),this.#Z)window.clearTimeout(this.#Z);if(["mousemove","mousedown","keydown","touchstart","scroll"].forEach((x)=>{document.removeEventListener(x,this.#F,!0)}),this.#M)window.clearTimeout(this.#M);this.uninstallErrorHandler()}setupClickTracking(){document.addEventListener("click",this.#_)}handleClick(x){let $=x.target;if(!$)return;let R=this.extractClickLabel($);if(!R)return;this.trackCustomEvent("click",{label:R,element:$.tagName.toLowerCase(),id:$.id||void 0})}handleScroll(){let x=window.location.href;if(x!==this.#V)this.#V=x,this.#$=0,this.#x.clear();if(this.#Z)window.clearTimeout(this.#Z);this.#Z=window.setTimeout(()=>{let $=this.calculateScrollDepth();if($>this.#$)this.#$=$,this.checkAndTrackScrollDepth($)},100)}setupScrollTracking(){window.addEventListener("scroll",this.#j),window.addEventListener("resize",this.#W)}calculateScrollDepth(){let x=window.innerHeight,$=Math.max(document.documentElement.scrollHeight,document.documentElement.offsetHeight,document.documentElement.clientHeight),R=window.pageYOffset||document.documentElement.scrollTop;return Math.round((R+x)/$*100)}checkAndTrackScrollDepth(x){let $=window.location.href;if(x>50&&!this.#x.has($))this.#x.add($),this.trackCustomEvent("scroll")}extractClickLabel(x){let $=x.getAttribute("aria-label");if($)return`${$}`;if(x instanceof HTMLButtonElement||x instanceof HTMLAnchorElement){let _=x.textContent?.trim();if(_)return`${_}`}if(x instanceof HTMLInputElement){if(x.type==="submit"&&x.value)return`${x.value}`;if(x.type==="checkbox"){let _=this.findInputLabel(x),J=x.checked?"Checked":"Unchecked";return _?`${J} ${_}`:null}}let R=x.closest("label");if(R){let _=R.textContent?.trim();if(_)return`${_}`}return null}findInputLabel(x){let $=x.getAttribute("aria-label");if($)return $;if(x.id){let _=document.querySelector(`label[for="${x.id}"]`);if(_&&_.textContent)return _.textContent.trim()}let R=x.closest("label");if(R&&R.textContent)return R.textContent.trim().replace(x.value,"").trim();return null}trackPageView(){let x={name:"page_view",url:window.location.href,referrer:document.referrer,title:document.title,timestamp:new Date().toISOString()};this.#R.track(x)}trackCustomEvent(x,$={},R={immediate:!1}){let _={name:x,url:window.location.href,referrer:document.referrer,title:document.title,properties:$,timestamp:new Date().toISOString()};if(R.immediate)this.#R.publish([_]);else this.#R.track(_)}trackPurchase(x){let $={name:"purchase",url:window.location.href,referrer:document.referrer,title:document.title,productId:x.productId,price:x.price,currency:x.currency,properties:{...x.properties},timestamp:new Date().toISOString()};this.#R.track($)}setupFormTracking(){document.addEventListener("focus",this.#X,!0),document.addEventListener("blur",this.#J,!0),document.addEventListener("change",this.#Y,!0),document.addEventListener("submit",this.#A,!0)}handleInputFocus(x){let $=x.target;if(!$||!($ instanceof HTMLInputElement||$ instanceof HTMLTextAreaElement||$ instanceof HTMLSelectElement))return;if($ instanceof HTMLInputElement&&$.type==="password")return;this.#G.set($,this.getElementValue($));let R=$.closest("form");if(R&&!this.#E.has(R))this.#E.set(R,Date.now())}getElementValue(x){if(x instanceof HTMLSelectElement)return x.value;if(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement)return x.value;return""}handleInputBlur(x){let $=x.target;if(!$||!($ instanceof HTMLInputElement||$ instanceof HTMLTextAreaElement||$ instanceof HTMLSelectElement))return;if($ instanceof HTMLInputElement&&$.type==="password")return;let R=this.#G.get($)||"",_=this.getElementValue($);if(_!==R&&_.trim()!==""){let J=$ instanceof HTMLSelectElement?"select":$.type,W=this.findFormElementLabel($)||this.getInputIdentifier($);if(!W)return;this.trackCustomEvent("input_fill",{input_type:J,label:W,form_name:this.getFormName($)})}this.#G.delete($)}getFormName(x){let $=x.closest("form");if(!$)return;return $.getAttribute("name")||$.getAttribute("id")||$.getAttribute("aria-label")||void 0}getInputIdentifier(x){return x.getAttribute("name")||x.getAttribute("id")||x.getAttribute("placeholder")||null}findFormElementLabel(x){let $=x.getAttribute("aria-label");if($)return $;if(x.id){let _=document.querySelector(`label[for="${x.id}"]`);if(_&&_.textContent)return _.textContent.trim()}let R=x.closest("label");if(R&&R.textContent){let _=R.textContent.trim(),J=x instanceof HTMLSelectElement?x.selectedOptions[0]?.text:x.value;return J?_.replace(J,"").trim():_}return null}handleFormChange(x){let $=x.target;if(!$||!($ instanceof HTMLSelectElement||$ instanceof HTMLInputElement))return;if($ instanceof HTMLSelectElement)this.trackSelectChange($);else if($ instanceof HTMLInputElement){if($.type==="radio")this.trackRadioChange($);else if($.type==="checkbox")this.trackCheckboxChange($);else if($.type==="range")this.trackRangeChange($)}}trackSelectChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;let R=x.selectedOptions[0];this.trackCustomEvent("input_select",{input_type:"select",label:$,option_label:R?.text||"",form_name:this.getFormName(x)})}trackRadioChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;let R=x.name||$;this.trackCustomEvent("input_radio",{input_type:"radio",group:R,label:$,form_name:this.getFormName(x)})}trackCheckboxChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;this.trackCustomEvent("input_checkbox",{input_type:"checkbox",label:$,checked:x.checked,form_name:this.getFormName(x)})}trackRangeChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;this.trackCustomEvent("input_range",{input_type:"range",label:$,form_name:this.getFormName(x)})}handleFormSubmit(x){let $=x.target;if(!$||!($ instanceof HTMLFormElement))return;let R=this.#E.get($)||Date.now(),_=Date.now()-R,J=this.getFormName($)||"unknown";this.trackCustomEvent("form_submit",{form_name:J,time_to_complete:_}),this.#E.delete($)}setupVideoTracking(){document.addEventListener("play",this.#w,!0),document.addEventListener("pause",this.#D,!0),document.addEventListener("ended",this.#P,!0)}getVideoMetadata(x){return{duration:Math.round(x.duration),current_time:Math.round(x.currentTime),src:x.currentSrc||x.src||void 0,title:x.title||void 0,video_id:x.id||void 0}}handleVideoPlay(x){let $=x.target;if(!$||!($ instanceof HTMLVideoElement))return;this.#K.set($,Date.now()),this.trackCustomEvent("video_play",this.getVideoMetadata($))}handleVideoPause(x){let $=x.target;if(!$||!($ instanceof HTMLVideoElement))return;let R=this.#K.get($),_=this.getVideoMetadata($);if(R)_.watch_time=Math.round((Date.now()-R)/1000),this.#K.delete($);this.trackCustomEvent("video_pause",_)}handleVideoEnd(x){let $=x.target;if(!$||!($ instanceof HTMLVideoElement))return;let R=this.#K.get($),_=this.getVideoMetadata($);if(R)_.watch_time=Math.round((Date.now()-R)/1000),this.#K.delete($);this.trackCustomEvent("video_complete",_)}setupPageTimeTracking(){document.addEventListener("visibilitychange",this.#L),window.addEventListener("beforeunload",this.#b)}handleVisibilityChange(){let x=Date.now(),$=this.#z;if(this.#z=!document.hidden,$)this.#Q+=x-this.#q;this.#q=x,this.trackCustomEvent("page_visibility",{visible:this.#z,total_time:Math.round((x-this.#g)/1000),visible_time:Math.round(this.#Q/1000)})}handleBeforeUnload(){let x=Date.now();if(this.#z)this.#Q+=x-this.#q;this.trackCustomEvent("page_exit",{total_time:Math.round((x-this.#g)/1000),visible_time:Math.round(this.#Q/1000)},{immediate:!0})}setupInactivityTracking(){["mousemove","mousedown","keydown","touchstart","scroll"].forEach((x)=>{document.addEventListener(x,this.#F,!0)}),this.checkInactivity()}handleUserActivity(){if(this.#C=Date.now(),this.#O&&this.#B)this.#O=!1,this.trackCustomEvent("user_active",{inactive_duration:Math.round((Date.now()-this.#B)/1000),url:window.location.href,title:document.title}),this.#B=null;this.checkInactivity()}checkInactivity(){if(this.#M)window.clearTimeout(this.#M);this.#M=window.setTimeout(()=>{let x=Date.now();if(x-this.#C>=this.#u&&!this.#O)this.#O=!0,this.#B=x,this.trackCustomEvent("user_inactive")},this.#u)}installErrorHandler(){if(this.#N||typeof window==="undefined")return;window.addEventListener("error",this.#y),window.addEventListener("unhandledrejection",this.#U),this.#N=!0}uninstallErrorHandler(){if(!this.#N||typeof window==="undefined")return;window.removeEventListener("error",this.#y),window.removeEventListener("unhandledrejection",this.#U),this.#N=!1}isErrorHandlerInstalled(){return this.#N}handleError(x){if(x instanceof ErrorEvent)this.trackError(new Error(x.message),{filename:x.filename,lineno:x.lineno,colno:x.colno,source:"window.onerror"})}handleRejection(x){let $=x.reason instanceof Error?x.reason:new Error(String(x.reason||"Unhandled Promise rejection"));this.trackError($,{source:"unhandledrejection"})}trackError(x,$={},R={immediate:!1}){let{filename:_,lineno:J,colno:W,source:K,url:Y,referrer:Z,userAgent:X,...q}=$,B={name:"error",message:x.message,stack:x.stack,source:K||"client",lineno:J,colno:W,filename:_,properties:q,timestamp:new Date().toISOString(),url:Y||window.location.href,referrer:Z||document.referrer,title:document.title};if(R.immediate)this.#R.publish([B]);else this.#R.track(B)}}class z{namespace;constructor({namespace:x}){this.namespace=x}getItem(x){let $=localStorage.getItem(`${this.namespace}.${x}`)||"";try{return JSON.parse($)}catch(R){return null}}setItem(x,$){localStorage.setItem(`${this.namespace}.${x}`,JSON.stringify($))}removeItem(x){localStorage.removeItem(`${this.namespace}.${x}`)}}var f=new z({namespace:"userpath"});function G(x,$,R={}){let{days:_=7,path:J="/",domain:W,secure:K,sameSite:Y="strict"}=R,Z=_?new Date(Date.now()+_*86400000).toUTCString():"",X=`${encodeURIComponent(x)}=${encodeURIComponent($)}`;if(Z)X+=`; expires=${Z}`;if(J)X+=`; path=${J}`;if(W)X+=`; domain=${W}`;if(K)X+="; secure";if(Y)X+=`; samesite=${Y}`;document.cookie=X}function g(x){let $=encodeURIComponent(x)+"=",R=document.cookie.split(";");for(let _=0;_<R.length;_++){let J=R[_];while(J.charAt(0)===" ")J=J.substring(1,J.length);if(J.indexOf($)===0)return decodeURIComponent(J.substring($.length,J.length))}return null}class O{#R;#x=[];#$=null;#_;#j;#W="";#X=null;#J=null;#Y=5000;constructor(x,$){this.#R=x,this.#_=$?.userId,this.#j=$?.appId||"",this.#Y=$?.flushIntervalMs||j.flushIntervalMs||5000}init(x){this.#$=x,this.setup()}destroy(){if(this.#X)window.clearInterval(this.#X);if(this.#J)window.clearTimeout(this.#J);if(this.#x.length>0)this.flush()}setup(){if(typeof window==="undefined")return;this.#W=window.location.href,this.#$.trackPageView(),this.setupHistoryChange(),this.#X=window.setInterval(()=>this.flush(),this.#Y)}setupHistoryChange(){if(!this.#$)return;let{pushState:x,replaceState:$}=history;history.pushState=(...R)=>{x.apply(history,R),this.trackPageViewIfUrlChanged()},history.replaceState=(...R)=>{$.apply(history,R),this.trackPageViewIfUrlChanged()},window.addEventListener("popstate",()=>{this.trackPageViewIfUrlChanged()})}trackPageViewIfUrlChanged(){let x=window.location.href;if(x!==this.#W)this.#W=x,this.#$.trackPageView()}getUserId(){return this.#_}setUserId(x){this.#_=x}getAppId(){return this.#j}setAppId(x){this.#j=x}track(x){if(this.#x.push(x),this.#x.length>=20){this.flush();return}if(!this.#J)this.#J=window.setTimeout(()=>{this.flush(),this.#J=null},this.#Y)}async identify(x){this.setUserId(x.id),await fetch(this.#R.buildUrl("identify"),{method:"POST",headers:{"Content-Type":"application/json","X-UserPath-App":this.#j,"X-UserPath-Session":this.getSessionId(),...this.#_&&{"X-UserPath-User":this.#_}},body:JSON.stringify(x),keepalive:!0})}deduplicateEvents(x){let $=new Set;return x.filter((R)=>{let _=`${R.name}-${R.timestamp}`;if($.has(_))return!1;return $.add(_),!0})}flush(){if(this.#x.length===0)return;if(this.#J)window.clearTimeout(this.#J),this.#J=null;let x=[...this.#x];this.#x=[];let $=this.deduplicateEvents(x);this.publish($).catch((R)=>{this.#x=[...$,...this.#x].slice(0,100),console.error("Error sending analytics data:",R)})}async publish(x){return fetch(this.#R.buildUrl("log"),{method:"POST",headers:{"Content-Type":"application/json","X-UserPath-App":this.#j,"X-UserPath-Session":this.getSessionId(),...this.#_&&{"X-UserPath-User":this.#_}},body:JSON.stringify({userAgent:navigator.userAgent,screenWidth:window.screen.width,screenHeight:window.screen.height,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,events:x.map(($)=>{if(!$.timestamp)$.timestamp=new Date().toISOString();return{...$,name:$.name||$.type,properties:$.properties||{}}})}),credentials:"include",keepalive:!0})}getSessionId(){let x=g("userpath.session_id");if(!x)x=this.generateId(),G("userpath.session_id",x,{days:365});return x}generateId(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(x){let $=Math.random()*16|0;return(x==="x"?$:$&3|8).toString(16)})}}class L{#R;#x;#$;#_=j.version;constructor(x){if(this.#R=new M(x),this.#x=new O(this.#R,x),this.#$=new Q(this.#x,x),this.#_=x.version||this.#_,this.#x.init(this.#$),this.#x.setAppId(x.appId),x.autoTrack?.errors!==void 0?x.autoTrack.errors:!0)this.installErrorHandler();console.debug(`UserPath v${N.version} initialized`)}getAppId(){return this.#x.getAppId()}setAppId(x){this.#x.setAppId(x)}installErrorHandler(){this.#$.installErrorHandler()}uninstallErrorHandler(){this.#$.uninstallErrorHandler()}trackError(x,$={}){if(!this.#$.isErrorHandlerInstalled()&&$.source!=="manual")return;this.#$.trackError(x,$)}setUserId(x){this.#x.setUserId(x)}getUserId(){return this.#x.getUserId()}async identify(x){await this.#x.identify(x)}track(x,$){if(x==="page_view")this.#$.trackPageView();else if(x==="event")this.#$.trackCustomEvent($.name,$.properties||{});else if(x==="purchase")this.#$.trackPurchase({productId:$.properties?.product_id||"",price:$.price,currency:$.currency,properties:$.properties})}}export{L as UserPath,j as DEFAULT_CONFIG};
|
|
1
|
+
var G={name:"userpath-js",version:"0.0.3",private:!1,main:"dist/index.js",types:"dist/types/src/index.d.ts",exports:{".":{types:"./dist/types/src/index.d.ts",default:"./dist/index.js"},"./server":{types:"./dist/types/src/server/index.d.ts",default:"./dist/server/index.js"}},files:["dist/index.js","dist/types","dist/server"],scripts:{dev:"bun build src/index.ts --outdir ./dist --watch",types:"tsc",build:"bun run build.client && bun run build.pixel && bun run build.server","build.prod":"bun run build.client.prod && bun run build.pixel.prod && bun run build.server.prod","build.client":"bun run types && bun build src/index.ts --outdir ./dist --no-cache","build.client.prod":"bun run types && bun build src/index.ts --outdir ./dist --minify","build.pixel":"bun build src/pixel.ts --outdir ./dist","build.pixel.prod":"bun build src/pixel.ts --outdir ./dist --minify","build.server":"bun run types && bun build src/server/index.ts --outdir ./dist/server","build.server.prod":"bun run types && bun build src/server/index.ts --outdir ./dist/server --minify"},devDependencies:{"bun-types":"latest",typescript:"^5.0.0"}};class Q{namespace;constructor({namespace:x}){this.namespace=x}getItem(x){let $=localStorage.getItem(`${this.namespace}.${x}`)||"";try{return JSON.parse($)}catch(R){return null}}setItem(x,$){localStorage.setItem(`${this.namespace}.${x}`,JSON.stringify($))}removeItem(x){localStorage.removeItem(`${this.namespace}.${x}`)}}var F=new Q({namespace:"userpath"});function K(x,$,R={}){let{days:_=7,path:J="/",domain:W,secure:M,sameSite:Y="strict"}=R,Z=_?new Date(Date.now()+_*86400000).toUTCString():"",X=`${encodeURIComponent(x)}=${encodeURIComponent($)}`;if(Z)X+=`; expires=${Z}`;if(J)X+=`; path=${J}`;if(W)X+=`; domain=${W}`;if(M)X+="; secure";if(Y)X+=`; samesite=${Y}`;document.cookie=X}function g(x){let $=encodeURIComponent(x)+"=",R=document.cookie.split(";");for(let _=0;_<R.length;_++){let J=R[_];while(J.charAt(0)===" ")J=J.substring(1,J.length);if(J.indexOf($)===0)return decodeURIComponent(J.substring($.length,J.length))}return null}var j={appId:"",serverUrl:"https://api.userpath.co",version:1,flushIntervalMs:5000,autoTrack:{errors:!0,clicks:!0,scrolling:!0,forms:!0,videos:!0,pageVisibility:!0,pageInactivity:!0}};class z{serverUrl;appId;version;constructor(x){this.serverUrl=x.serverUrl||j.serverUrl,this.appId=x.appId,this.version=x.version||j.version,K("_up.app",this.appId)}buildUrl(x){return`${this.serverUrl}/v${this.version}/${x}`}}var E=typeof window==="undefined",w={pushState:()=>{},replaceState:()=>{},go:()=>{},back:()=>{},forward:()=>{}};if(E)global.history=w;var D={location:{href:""},addEventListener:()=>{},removeEventListener:()=>{},scrollTo:()=>{},scrollBy:()=>{},setTimeout:()=>{},clearTimeout:()=>{},setInterval:()=>{},clearInterval:()=>{}};if(E)global.window=D;var P={hidden:!1,addEventListener:()=>{},removeEventListener:()=>{},querySelector:()=>null,closest:()=>null,getAttribute:()=>null,tagName:"",textContent:"",classList:{contains:()=>!1},scrollHeight:0,offsetHeight:0,clientHeight:0,pageYOffset:0,referrer:"",title:""};if(E)global.document=P;class B{#R;#x;#$;#J;#j;#W;#X;#_;#Y;#A;#w;#D;#P;#L;#V;#Z;#y;#Q;#G;#K;#g;#z;#q;#E;#C;#M;#B;#F;#U=60000;#O;#N=!1;#b;#I;#u;constructor(x,$=j){this.#R=x,this.#u=$,this.#x=new Set,this.#$=0,this.#Z=null,this.#y=window.location.href,this.#Q=new Map,this.#G=new WeakMap,this.#K=new WeakMap,this.#g=Date.now(),this.#z=0,this.#q=this.#g,this.#E=document.hidden,this.#C=Date.now(),this.#M=null,this.#B=!1,this.#O=null,this.#J=this.handleClick.bind(this),this.#j=this.handleScroll.bind(this),this.#W=this.handleScroll.bind(this),this.#X=this.handleInputFocus.bind(this),this.#_=this.handleInputBlur.bind(this),this.#Y=this.handleFormChange.bind(this),this.#A=this.handleFormSubmit.bind(this),this.#w=this.handleVideoPlay.bind(this),this.#D=this.handleVideoPause.bind(this),this.#P=this.handleVideoEnd.bind(this),this.#L=this.handleVisibilityChange.bind(this),this.#V=this.handleBeforeUnload.bind(this),this.#F=this.handleUserActivity.bind(this),this.#b=this.handleError.bind(this),this.#I=this.handleRejection.bind(this);let R=this.#u.autoTrack||j.autoTrack;if(R.clicks!==!1)this.setupClickTracking();if(R.scrolling!==!1)this.setupScrollTracking();if(R.forms!==!1)this.setupFormTracking();if(R.videos!==!1)this.setupVideoTracking();if(R.pageVisibility!==!1)this.setupPageTimeTracking();if(R.pageInactivity!==!1)this.setupInactivityTracking()}destroy(){if(document.removeEventListener("click",this.#J),window.removeEventListener("scroll",this.#j),window.removeEventListener("resize",this.#W),document.removeEventListener("focus",this.#X,!0),document.removeEventListener("blur",this.#_,!0),document.removeEventListener("change",this.#Y,!0),document.removeEventListener("submit",this.#A,!0),document.removeEventListener("play",this.#w,!0),document.removeEventListener("pause",this.#D,!0),document.removeEventListener("ended",this.#P,!0),document.removeEventListener("visibilitychange",this.#L),window.removeEventListener("beforeunload",this.#V),this.#Z)window.clearTimeout(this.#Z);if(["mousemove","mousedown","keydown","touchstart","scroll"].forEach((x)=>{document.removeEventListener(x,this.#F,!0)}),this.#M)window.clearTimeout(this.#M);this.uninstallErrorHandler()}setupClickTracking(){document.addEventListener("click",this.#J)}handleClick(x){let $=x.target;if(!$)return;let R=this.extractClickLabel($);if(!R)return;this.trackCustomEvent("click",{label:R,element:$.tagName.toLowerCase(),id:$.id||void 0})}handleScroll(){let x=window.location.href;if(x!==this.#y)this.#y=x,this.#$=0,this.#x.clear();if(this.#Z)window.clearTimeout(this.#Z);this.#Z=window.setTimeout(()=>{let $=this.calculateScrollDepth();if($>this.#$)this.#$=$,this.checkAndTrackScrollDepth($)},100)}setupScrollTracking(){window.addEventListener("scroll",this.#j),window.addEventListener("resize",this.#W)}calculateScrollDepth(){let x=window.innerHeight,$=Math.max(document.documentElement.scrollHeight,document.documentElement.offsetHeight,document.documentElement.clientHeight),R=window.pageYOffset||document.documentElement.scrollTop;return Math.round((R+x)/$*100)}checkAndTrackScrollDepth(x){let $=window.location.href;if(x>50&&!this.#x.has($))this.#x.add($),this.trackCustomEvent("scroll")}extractClickLabel(x){let $=x.getAttribute("aria-label");if($)return`${$}`;if(x instanceof HTMLButtonElement||x instanceof HTMLAnchorElement){let _=x.textContent?.trim();if(_)return`${_}`}if(x instanceof HTMLInputElement){if(x.type==="submit"&&x.value)return`${x.value}`;if(x.type==="checkbox"){let _=this.findInputLabel(x),J=x.checked?"Checked":"Unchecked";return _?`${J} ${_}`:null}}let R=x.closest("label");if(R){let _=R.textContent?.trim();if(_)return`${_}`}return null}findInputLabel(x){let $=x.getAttribute("aria-label");if($)return $;if(x.id){let _=document.querySelector(`label[for="${x.id}"]`);if(_&&_.textContent)return _.textContent.trim()}let R=x.closest("label");if(R&&R.textContent)return R.textContent.trim().replace(x.value,"").trim();return null}trackPageView(){let x={name:"page_view",url:window.location.href,referrer:document.referrer,title:document.title,timestamp:new Date().toISOString()};this.#R.track(x)}trackCustomEvent(x,$={},R={immediate:!1}){let _={name:x,url:window.location.href,referrer:document.referrer,title:document.title,properties:$,timestamp:new Date().toISOString()};if(R.immediate)this.#R.publish([_]);else this.#R.track(_)}trackPurchase(x){let $={name:"purchase",url:window.location.href,referrer:document.referrer,title:document.title,productId:x.productId,price:x.price,currency:x.currency,properties:{...x.properties},timestamp:new Date().toISOString()};this.#R.track($)}setupFormTracking(){document.addEventListener("focus",this.#X,!0),document.addEventListener("blur",this.#_,!0),document.addEventListener("change",this.#Y,!0),document.addEventListener("submit",this.#A,!0)}handleInputFocus(x){let $=x.target;if(!$||!($ instanceof HTMLInputElement||$ instanceof HTMLTextAreaElement||$ instanceof HTMLSelectElement))return;if($ instanceof HTMLInputElement&&$.type==="password")return;this.#G.set($,this.getElementValue($));let R=$.closest("form");if(R&&!this.#Q.has(R))this.#Q.set(R,Date.now())}getElementValue(x){if(x instanceof HTMLSelectElement)return x.value;if(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement)return x.value;return""}handleInputBlur(x){let $=x.target;if(!$||!($ instanceof HTMLInputElement||$ instanceof HTMLTextAreaElement||$ instanceof HTMLSelectElement))return;if($ instanceof HTMLInputElement&&$.type==="password")return;let R=this.#G.get($)||"",_=this.getElementValue($);if(_!==R&&_.trim()!==""){let J=$ instanceof HTMLSelectElement?"select":$.type,W=this.findFormElementLabel($)||this.getInputIdentifier($);if(!W)return;this.trackCustomEvent("input_fill",{input_type:J,label:W,form_name:this.getFormName($)})}this.#G.delete($)}getFormName(x){let $=x.closest("form");if(!$)return;return $.getAttribute("name")||$.getAttribute("id")||$.getAttribute("aria-label")||void 0}getInputIdentifier(x){return x.getAttribute("name")||x.getAttribute("id")||x.getAttribute("placeholder")||null}findFormElementLabel(x){let $=x.getAttribute("aria-label");if($)return $;if(x.id){let _=document.querySelector(`label[for="${x.id}"]`);if(_&&_.textContent)return _.textContent.trim()}let R=x.closest("label");if(R&&R.textContent){let _=R.textContent.trim(),J=x instanceof HTMLSelectElement?x.selectedOptions[0]?.text:x.value;return J?_.replace(J,"").trim():_}return null}handleFormChange(x){let $=x.target;if(!$||!($ instanceof HTMLSelectElement||$ instanceof HTMLInputElement))return;if($ instanceof HTMLSelectElement)this.trackSelectChange($);else if($ instanceof HTMLInputElement){if($.type==="radio")this.trackRadioChange($);else if($.type==="checkbox")this.trackCheckboxChange($);else if($.type==="range")this.trackRangeChange($)}}trackSelectChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;let R=x.selectedOptions[0];this.trackCustomEvent("input_select",{input_type:"select",label:$,option_label:R?.text||"",form_name:this.getFormName(x)})}trackRadioChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;let R=x.name||$;this.trackCustomEvent("input_radio",{input_type:"radio",group:R,label:$,form_name:this.getFormName(x)})}trackCheckboxChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;this.trackCustomEvent("input_checkbox",{input_type:"checkbox",label:$,checked:x.checked,form_name:this.getFormName(x)})}trackRangeChange(x){let $=this.findFormElementLabel(x)||this.getInputIdentifier(x);if(!$)return;this.trackCustomEvent("input_range",{input_type:"range",label:$,form_name:this.getFormName(x)})}handleFormSubmit(x){let $=x.target;if(!$||!($ instanceof HTMLFormElement))return;let R=this.#Q.get($)||Date.now(),_=Date.now()-R,J=this.getFormName($)||"unknown";this.trackCustomEvent("form_submit",{form_name:J,time_to_complete:_}),this.#Q.delete($)}setupVideoTracking(){document.addEventListener("play",this.#w,!0),document.addEventListener("pause",this.#D,!0),document.addEventListener("ended",this.#P,!0)}getVideoMetadata(x){return{duration:Math.round(x.duration),current_time:Math.round(x.currentTime),src:x.currentSrc||x.src||void 0,title:x.title||void 0,video_id:x.id||void 0}}handleVideoPlay(x){let $=x.target;if(!$||!($ instanceof HTMLVideoElement))return;this.#K.set($,Date.now()),this.trackCustomEvent("video_play",this.getVideoMetadata($))}handleVideoPause(x){let $=x.target;if(!$||!($ instanceof HTMLVideoElement))return;let R=this.#K.get($),_=this.getVideoMetadata($);if(R)_.watch_time=Math.round((Date.now()-R)/1000),this.#K.delete($);this.trackCustomEvent("video_pause",_)}handleVideoEnd(x){let $=x.target;if(!$||!($ instanceof HTMLVideoElement))return;let R=this.#K.get($),_=this.getVideoMetadata($);if(R)_.watch_time=Math.round((Date.now()-R)/1000),this.#K.delete($);this.trackCustomEvent("video_complete",_)}setupPageTimeTracking(){document.addEventListener("visibilitychange",this.#L),window.addEventListener("beforeunload",this.#V)}handleVisibilityChange(){let x=Date.now(),$=this.#E;if(this.#E=!document.hidden,$)this.#z+=x-this.#q;this.#q=x,this.trackCustomEvent("page_visibility",{visible:this.#E,total_time:Math.round((x-this.#g)/1000),visible_time:Math.round(this.#z/1000)})}handleBeforeUnload(){let x=Date.now();if(this.#E)this.#z+=x-this.#q;this.trackCustomEvent("page_exit",{total_time:Math.round((x-this.#g)/1000),visible_time:Math.round(this.#z/1000)},{immediate:!0})}setupInactivityTracking(){["mousemove","mousedown","keydown","touchstart","scroll"].forEach((x)=>{document.addEventListener(x,this.#F,!0)}),this.checkInactivity()}handleUserActivity(){if(this.#C=Date.now(),this.#B&&this.#O)this.#B=!1,this.trackCustomEvent("user_active",{inactive_duration:Math.round((Date.now()-this.#O)/1000),url:window.location.href,title:document.title}),this.#O=null;this.checkInactivity()}checkInactivity(){if(this.#M)window.clearTimeout(this.#M);this.#M=window.setTimeout(()=>{let x=Date.now();if(x-this.#C>=this.#U&&!this.#B)this.#B=!0,this.#O=x,this.trackCustomEvent("user_inactive")},this.#U)}installErrorHandler(){if(this.#N||typeof window==="undefined")return;window.addEventListener("error",this.#b),window.addEventListener("unhandledrejection",this.#I),this.#N=!0}uninstallErrorHandler(){if(!this.#N||typeof window==="undefined")return;window.removeEventListener("error",this.#b),window.removeEventListener("unhandledrejection",this.#I),this.#N=!1}isErrorHandlerInstalled(){return this.#N}handleError(x){if(x instanceof ErrorEvent)this.trackError(new Error(x.message),{filename:x.filename,lineno:x.lineno,colno:x.colno,source:"window.onerror"})}handleRejection(x){let $=x.reason instanceof Error?x.reason:new Error(String(x.reason||"Unhandled Promise rejection"));this.trackError($,{source:"unhandledrejection"})}trackError(x,$={},R={immediate:!1}){let{filename:_,lineno:J,colno:W,source:M,url:Y,referrer:Z,userAgent:X,...q}=$,N={name:"error",message:x.message,stack:x.stack,source:M||"client",lineno:J,colno:W,filename:_,properties:q,timestamp:new Date().toISOString(),url:Y||window.location.href,referrer:Z||document.referrer,title:document.title};if(R.immediate)this.#R.publish([N]);else this.#R.track(N)}}class O{#R;#x=[];#$=null;#J;#j;#W="";#X=null;#_=null;#Y=5000;constructor(x,$){this.#R=x,this.#J=$?.userId,this.#j=$?.appId||"",this.#Y=$?.flushIntervalMs||j.flushIntervalMs||5000}init(x){this.#$=x,this.setup()}destroy(){if(this.#X)window.clearInterval(this.#X);if(this.#_)window.clearTimeout(this.#_);if(this.#x.length>0)this.flush()}setup(){if(typeof window==="undefined")return;this.#W=window.location.href,this.#$.trackPageView(),this.setupHistoryChange(),this.#X=window.setInterval(()=>this.flush(),this.#Y)}setupHistoryChange(){if(!this.#$)return;let{pushState:x,replaceState:$}=history;history.pushState=(...R)=>{x.apply(history,R),this.trackPageViewIfUrlChanged()},history.replaceState=(...R)=>{$.apply(history,R),this.trackPageViewIfUrlChanged()},window.addEventListener("popstate",()=>{this.trackPageViewIfUrlChanged()})}trackPageViewIfUrlChanged(){let x=window.location.href;if(x!==this.#W)this.#W=x,this.#$.trackPageView()}getUserId(){return this.#J}setUserId(x){this.#J=x}getAppId(){return this.#j}setAppId(x){this.#j=x}track(x){if(this.#x.push(x),this.#x.length>=20){this.flush();return}if(!this.#_)this.#_=window.setTimeout(()=>{this.flush(),this.#_=null},this.#Y)}async identify(x){this.setUserId(x.id),await fetch(this.#R.buildUrl("identify"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(x),keepalive:!0,credentials:"include"})}deduplicateEvents(x){let $=new Set;return x.filter((R)=>{let _=`${R.name}-${R.timestamp}`;if($.has(_))return!1;return $.add(_),!0})}flush(){if(this.#x.length===0)return;if(this.#_)window.clearTimeout(this.#_),this.#_=null;let x=[...this.#x];this.#x=[];let $=this.deduplicateEvents(x);this.publish($).catch((R)=>{this.#x=[...$,...this.#x].slice(0,100),console.error("Error sending analytics data:",R)})}async publish(x){return fetch(this.#R.buildUrl("log"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userAgent:navigator.userAgent,screenWidth:window.screen.width,screenHeight:window.screen.height,language:navigator.language,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,events:x.map(($)=>{if(!$.timestamp)$.timestamp=new Date().toISOString();return{...$,name:$.name||$.type,properties:$.properties||{}}})}),credentials:"include",keepalive:!0})}getSessionId(){let x=g("_up.sid");if(!x)x=this.generateId(),K("_up.sid",x,{days:365});return x}generateId(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(x){let $=Math.random()*16|0;return(x==="x"?$:$&3|8).toString(16)})}}class L{#R;#x;#$;#J=j.version;constructor(x){if(this.#R=new z(x),this.#x=new O(this.#R,x),this.#$=new B(this.#x,x),this.#J=x.version||this.#J,this.#x.init(this.#$),this.#x.setAppId(x.appId),x.autoTrack?.errors!==void 0?x.autoTrack.errors:!0)this.installErrorHandler();console.debug(`UserPath v${G.version} initialized`)}getAppId(){return this.#x.getAppId()}setAppId(x){this.#x.setAppId(x)}installErrorHandler(){this.#$.installErrorHandler()}uninstallErrorHandler(){this.#$.uninstallErrorHandler()}trackError(x,$={}){if(!this.#$.isErrorHandlerInstalled()&&$.source!=="manual")return;this.#$.trackError(x,$)}setUserId(x){this.#x.setUserId(x)}getUserId(){return this.#x.getUserId()}async identify(x){await this.#x.identify(x)}track(x,$){if(x==="page_view")this.#$.trackPageView();else if(x==="event")this.#$.trackCustomEvent($.name,$.properties||{});else if(x==="purchase")this.#$.trackPurchase({productId:$.properties?.product_id||"",price:$.price,currency:$.currency,properties:$.properties})}}export{L as UserPath,j as DEFAULT_CONFIG};
|
package/dist/server/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Q={async fetch(x){let A=x.method,D=new URL(x.url),J=D.pathname,K=D.origin,L=x.headers.get("cookie");console.log(L);let M=`${K}${J}`,F=new Headers;for(let[j,z]of x.headers.entries())if(!j.toLowerCase().startsWith("access-control-"))F.set(j,z);let N=await x.json().catch(()=>null),G={method:A,headers:F};if(!["GET","HEAD","OPTIONS"].includes(A))G.body=JSON.stringify(N);let f=await fetch(M,G);if(f.headers.get("content-type")?.includes("application/json"))return await f.json();else{let j=new Headers;for(let[I,P]of f.headers.entries())if(!I.toLowerCase().startsWith("access-control-"))j.set(I,P);let z=await f.text();return new Response(z,{status:f.status,statusText:f.statusText,headers:j})}}};export{Q as userpath};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../../../src/base/api.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../../../../src/base/api.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAkB,MAAM,mBAAmB,CAAC;AAE3D;;GAEG;AACH,qBAAa,SAAS;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IAEd,OAAO,EAAE,MAAM,CAAC;gBAEX,MAAM,EAAE,MAAM;IAQ1B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAG9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../../../src/base/session.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAkB,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC;;GAEG;AACH,qBAAa,aAAa;;gBAWb,GAAG,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM;IASpC,IAAI,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI;IAKhC,OAAO,IAAI,IAAI;IAYtB;;OAEG;IACH,OAAO,CAAC,KAAK;IAoBb;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAqB1B;;OAEG;IACH,OAAO,CAAC,yBAAyB;IAQjC;;OAEG;IACI,SAAS,IAAI,MAAM,GAAG,SAAS;IAItC;;OAEG;IACI,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAItC;;OAEG;IACI,QAAQ,IAAI,MAAM;IAIzB;;OAEG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAIpC;;OAEG;IACI,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAkBhC;;OAEG;IACU,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../../../../src/base/session.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAkB,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClC,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAExC;;GAEG;AACH,qBAAa,aAAa;;gBAWb,GAAG,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,MAAM;IASpC,IAAI,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI;IAKhC,OAAO,IAAI,IAAI;IAYtB;;OAEG;IACH,OAAO,CAAC,KAAK;IAoBb;;OAEG;IACH,OAAO,CAAC,kBAAkB;IAqB1B;;OAEG;IACH,OAAO,CAAC,yBAAyB;IAQjC;;OAEG;IACI,SAAS,IAAI,MAAM,GAAG,SAAS;IAItC;;OAEG;IACI,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAItC;;OAEG;IACI,QAAQ,IAAI,MAAM;IAIzB;;OAEG;IACI,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAIpC;;OAEG;IACI,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAkBhC;;OAEG;IACU,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAgB5D;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAYzB;;OAEG;IACH,SAAS,CAAC,KAAK,IAAI,IAAI;IAsBV,OAAO,CAAC,MAAM,EAAE,GAAG,EAAE;IA8BlC;;OAEG;IACI,YAAY,IAAI,MAAM;IAS7B;;OAEG;IACI,UAAU,IAAI,MAAM;CAU3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,QAAQ;IACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;mBACkB,OAAO;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/server/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,QAAQ;IACpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA+BG;mBACkB,OAAO;CAwD5B,CAAC"}
|