2 lines
7.7 KiB
JavaScript
2 lines
7.7 KiB
JavaScript
"use strict";(()=>{var y=Object.create;var u=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var g=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty;var k=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var b=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of m(t))!w.call(e,s)&&s!==n&&u(e,s,{get:()=>t[s],enumerable:!(i=v(t,s))||i.enumerable});return e};var P=(e,t,n)=>(n=e!=null?y(g(e)):{},b(t||!e||!e.__esModule?u(n,"default",{value:e,enumerable:!0}):n,e));var f=k((L,h)=>{"use strict";h.exports={}});var R=class{constructor(e){this.baseUrl=e.baseUrl,this.headers={"Content-Type":"application/json",...e.defaultHeaders},this.maxRetries=e.maxRetries??3,this.initialRetryDelay=e.initialRetryDelay??500}async resolveHeaders(){let e={};for(let[t,n]of Object.entries(this.headers)){let i=await n;i!==null&&(e[t]=i)}return e}addHeader(e,t){this.headers[e]=t}async post(e,t,n,i){try{let s=await fetch(e,{method:"POST",headers:await this.resolveHeaders(),body:t?JSON.stringify(t??{}):void 0,keepalive:!0,...n});if(s.status===401)return null;if(s.status!==200&&s.status!==202)throw new Error(`HTTP error! status: ${s.status}`);let r=await s.text();return r?JSON.parse(r):null}catch(s){if(i<this.maxRetries){let r=this.initialRetryDelay*2**i;return await new Promise(a=>setTimeout(a,r)),this.post(e,t,n,i+1)}return console.error("Max retries reached:",s),null}}async fetch(e,t,n={}){let i=`${this.baseUrl}${e}`;return this.post(i,t,n,0)}},c=class{constructor(e){this.queue=[],this.options=e;let t={"openpanel-client-id":e.clientId};e.clientSecret&&(t["openpanel-client-secret"]=e.clientSecret),t["openpanel-sdk-name"]=e.sdk||"node",t["openpanel-sdk-version"]=e.sdkVersion||"1.2.0",this.api=new R({baseUrl:e.apiUrl||"https://api.openpanel.dev",defaultHeaders:t})}init(){}ready(){this.options.disabled=!1,this.options.waitForProfile=!1,this.flush()}shouldQueue(e){return!!(this.options.disabled||this.options.waitForProfile&&!this.profileId||e.type==="replay"&&!this.sessionId)}addQueue(e){e.type==="track"&&(e.payload.properties={...e.payload.properties??{},__timestamp:new Date().toISOString()}),this.queue.push(e)}async send(e){if(this.options.filter&&!this.options.filter(e))return Promise.resolve();if(this.shouldQueue(e))return this.addQueue(e),Promise.resolve();let t=await this.api.fetch("/track",e,{keepalive:e.type!=="replay"});this.deviceId=t?.deviceId;let n=!!this.sessionId;return this.sessionId=t?.sessionId,!n&&this.sessionId&&this.flush(),t}setGlobalProperties(e){this.global={...this.global,...e}}track(e,t){return this.log("track event",e,t),this.send({type:"track",payload:{name:e,profileId:t?.profileId??this.profileId,properties:{...this.global??{},...t??{}}}})}identify(e){if(this.log("identify user",e),e.profileId&&(this.profileId=e.profileId,this.flush()),Object.keys(e).length>1)return this.send({type:"identify",payload:{...e,properties:{...this.global,...e.properties}}})}alias(e){}increment(e){return this.send({type:"increment",payload:e})}decrement(e){return this.send({type:"decrement",payload:e})}revenue(e,t){let n=t?.deviceId;return delete t?.deviceId,this.track("revenue",{...t??{},...n?{__deviceId:n}:{},__revenue:e})}getDeviceId(){return this.deviceId??""}getSessionId(){return this.sessionId??""}fetchDeviceId(){return Promise.resolve(this.deviceId??"")}clear(){this.profileId=void 0,this.deviceId=void 0,this.sessionId=void 0}flush(){let e=[];for(let t of this.queue){if(this.shouldQueue(t)){e.push(t);continue}let n=t.type==="replay"?t.payload:{...t.payload,profileId:"profileId"in t.payload?t.payload.profileId??this.profileId:this.profileId};this.send({...t,payload:n})}this.queue=e}log(...e){this.options.debug&&console.log("[OpenPanel.dev]",...e)}};var S=typeof document<"u"?document.currentScript:null;function I(e){return e.replace(/([-_][a-z])/gi,t=>t.toUpperCase().replace("-","").replace("_",""))}var p=class extends c{constructor(n){super({sdk:"web",sdkVersion:"1.2.0",...n});this.options=n;this.lastPath="";this.pendingRevenues=[];if(!this.isServer()){try{let i=sessionStorage.getItem("openpanel-pending-revenues");if(i){let s=JSON.parse(i);Array.isArray(s)&&(this.pendingRevenues=s)}}catch{this.pendingRevenues=[]}if(this.setGlobalProperties({__referrer:document.referrer}),this.options.trackScreenViews&&(this.trackScreenViews(),setTimeout(()=>this.screenView(),0)),this.options.trackOutgoingLinks&&this.trackOutgoingLinks(),this.options.trackAttributes&&this.trackAttributes(),this.options.sessionReplay?.enabled){let i=this.options.sessionReplay.sampleRate??1;Math.random()<i&&this.loadReplayModule().then(r=>{r&&r.startReplayRecorder(this.options.sessionReplay,a=>{this.send({type:"replay",payload:{...a}})})})}}}async loadReplayModule(){try{{let n=S,i=this.options.sessionReplay?.scriptUrl||n?.src?.replace(".js","-replay.js")||"https://openpanel.dev/op1-replay.js";return window.__openpanel_replay?window.__openpanel_replay:new Promise(s=>{let r=document.createElement("script");r.src=i,r.onload=()=>{s(window.__openpanel_replay??null)},r.onerror=()=>{console.warn("[OpenPanel] Failed to load replay script from",i),s(null)},document.head.appendChild(r)})}return await Promise.resolve().then(()=>P(f(),1))}catch(n){return console.warn("[OpenPanel] Failed to load replay module",n),null}}debounce(n,i){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(n,i)}isServer(){return typeof document>"u"}trackOutgoingLinks(){this.isServer()||document.addEventListener("click",n=>{let i=n.target,s=i.closest("a");if(s&&i){let r=s.getAttribute("href");if(r?.startsWith("http"))try{let a=new URL(r),o=window.location.hostname;a.hostname!==o&&super.track("link_out",{href:r,text:s.innerText||s.getAttribute("title")||i.getAttribute("alt")||i.getAttribute("title")})}catch{}}})}trackScreenViews(){if(this.isServer())return;let n=history.pushState;history.pushState=function(...a){let o=n.apply(this,a);return window.dispatchEvent(new Event("pushstate")),window.dispatchEvent(new Event("locationchange")),o};let i=history.replaceState;history.replaceState=function(...a){let o=i.apply(this,a);return window.dispatchEvent(new Event("replacestate")),window.dispatchEvent(new Event("locationchange")),o},window.addEventListener("popstate",()=>{window.dispatchEvent(new Event("locationchange"))});let s=()=>this.debounce(()=>this.screenView(),50);this.options.trackHashChanges?window.addEventListener("hashchange",s):window.addEventListener("locationchange",s)}trackAttributes(){this.isServer()||document.addEventListener("click",n=>{let i=n.target,s=i.closest("button"),r=i.closest("a"),a=s?.getAttribute("data-track")?s:r?.getAttribute("data-track")?r:null;if(a){let o={};for(let l of a.attributes)l.name.startsWith("data-")&&l.name!=="data-track"&&(o[I(l.name.replace(/^data-/,""))]=l.value);let d=a.getAttribute("data-track");d&&super.track(d,o)}})}screenView(n,i){if(this.isServer())return;let s,r;typeof n=="string"?(s=n,r=i):(s=window.location.href,r=n),this.lastPath!==s&&(this.lastPath=s,super.track("screen_view",{...r??{},__path:s,__title:document.title}))}async flushRevenue(){let n=this.pendingRevenues.map(i=>super.revenue(i.amount,i.properties));await Promise.all(n),this.clearRevenue()}clearRevenue(){if(this.pendingRevenues=[],!this.isServer())try{sessionStorage.removeItem("openpanel-pending-revenues")}catch{}}pendingRevenue(n,i){if(this.pendingRevenues.push({amount:n,properties:i}),!this.isServer())try{sessionStorage.setItem("openpanel-pending-revenues",JSON.stringify(this.pendingRevenues))}catch{}}};(e=>{if(e.op){let t=e.op.q||[],n=new p(t.shift()[1]);t.forEach(s=>{s[0]in n&&n[s[0]](...s.slice(1))});let i=new Proxy((s,...r)=>{let a=n[s]?n[s].bind(n):void 0;typeof a=="function"?a(...r):console.warn(`OpenPanel: ${s} is not a function`)},{get(s,r){if(r==="q")return;let a=n[r];return typeof a=="function"?a.bind(n):a}});e.op=i,e.openpanel=n}})(window);})();
|