-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathop1.js
More file actions
1 lines (1 loc) · 8.74 KB
/
op1.js
File metadata and controls
1 lines (1 loc) · 8.74 KB
1
"use strict";(()=>{var g=Object.create;var h=Object.defineProperty;var P=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var m=Object.getPrototypeOf,k=Object.prototype.hasOwnProperty;var b=(a,e)=>()=>(e||a((e={exports:{}}).exports,e),e.exports);var I=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of v(e))!k.call(a,s)&&s!==t&&h(a,s,{get:()=>e[s],enumerable:!(r=P(e,s))||r.enumerable});return a};var w=(a,e,t)=>(t=a!=null?g(m(a)):{},I(e||!a||!a.__esModule?h(t,"default",{value:a,enumerable:!0}):t,a));var f=b((A,y)=>{"use strict";y.exports={}});var d=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,r]of Object.entries(this.headers)){let s=await r;s!==null&&(e[t]=s)}return e}addHeader(e,t){this.headers[e]=t}async post(e,t,r,s){try{let n=await fetch(e,{method:"POST",headers:await this.resolveHeaders(),body:t?JSON.stringify(t??{}):void 0,keepalive:!0,...r});if(n.status===401)return null;if(n.status!==200&&n.status!==202)throw new Error(`HTTP error! status: ${n.status}`);let i=await n.text();return i?JSON.parse(i):null}catch(n){if(s<this.maxRetries){let i=this.initialRetryDelay*2**s;return await new Promise(o=>setTimeout(o,i)),this.post(e,t,r,s+1)}return console.error("Max retries reached:",n),null}}async fetch(e,t,r={}){let s=`${this.baseUrl}${e}`;return this.post(s,t,r,0)}};var l=class{constructor(e){this.groups=[];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||process.env.SDK_VERSION,this.api=new d({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 r=!!this.sessionId;return this.sessionId=t?.sessionId,!r&&this.sessionId&&this.flush(),t}setGlobalProperties(e){this.global={...this.global,...e}}track(e,t){this.log("track event",e,t);let{groups:r,profileId:s,...n}=t??{},i=[...new Set([...this.groups,...r??[]])];return this.send({type:"track",payload:{name:e,profileId:s??this.profileId,groups:i.length>0?i:void 0,properties:{...this.global??{},...n}}})}identify(e){if(this.log("identify user",e),e.profileId&&(this.profileId=e.profileId,this.flush()),e.profileId&&Object.keys(e).length>1)return this.send({type:"identify",payload:{...e,properties:{...this.global,...e.properties}}})}upsertGroup(e){return this.log("upsert group",e),this.send({type:"group",payload:e})}setGroup(e){return this.log("set group",e),this.groups.includes(e)||(this.groups=[...this.groups,e]),this.send({type:"assign_group",payload:{groupIds:[e],profileId:this.profileId}})}setGroups(e){return this.log("set groups",e),this.groups=[...new Set([...this.groups,...e])],this.send({type:"assign_group",payload:{groupIds:e,profileId:this.profileId}})}alias(e){}increment(e){return this.send({type:"increment",payload:e})}decrement(e){return this.send({type:"decrement",payload:e})}revenue(e,t){let r=t?.deviceId;return delete t?.deviceId,this.track("revenue",{...t??{},...r?{__deviceId:r}:{},__revenue:e})}getDeviceId(){return this.deviceId??""}getSessionId(){return this.sessionId??""}fetchDeviceId(){return Promise.resolve(this.deviceId??"")}clear(){this.profileId=void 0,this.groups=[],this.deviceId=void 0,this.sessionId=void 0}buildFlushPayload(e){if(e.type==="replay")return e.payload;if(e.type==="track"){let t="groups"in e.payload?e.payload.groups??[]:[],r=[...new Set([...this.groups,...t])];return{...e.payload,profileId:e.payload.profileId??this.profileId,groups:r.length>0?r:void 0}}return e.type==="identify"||e.type==="increment"||e.type==="decrement"?{...e.payload,profileId:e.payload.profileId??this.profileId}:e.type==="assign_group"?{...e.payload,profileId:e.payload.profileId??this.profileId}:e.payload}flush(){let e=[];for(let t of this.queue){if(this.shouldQueue(t)){e.push(t);continue}let r=this.buildFlushPayload(t);this.send({...t,payload:r})}this.queue=e}log(...e){this.options.debug&&console.log("[OpenPanel.dev]",...e)}};var R=typeof document<"u"?document.currentScript:null;function S(a){return a.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace("-","").replace("_",""))}var c=class extends l{constructor(t){super({sdk:"web",sdkVersion:"1.4.0",...t});this.options=t;this.lastPath="";this.pendingRevenues=[];if(!this.isServer()){try{let r=sessionStorage.getItem("openpanel-pending-revenues");if(r){let s=JSON.parse(r);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 r=this.options.sessionReplay.sampleRate??1;Math.random()<r&&this.loadReplayModule().then(n=>{n&&n.startReplayRecorder(this.options.sessionReplay,i=>{this.send({type:"replay",payload:{...i}})})})}}}async loadReplayModule(){try{{let t=R,r=this.options.sessionReplay?.scriptUrl||t?.src?.replace(".js","-replay.js")||"https://openpanel.dev/op1-replay.js";return window.__openpanel_replay?window.__openpanel_replay:new Promise(s=>{let n=document.createElement("script");n.src=r,n.onload=()=>{s(window.__openpanel_replay??null)},n.onerror=()=>{console.warn("[OpenPanel] Failed to load replay script from",r),s(null)},document.head.appendChild(n)})}return await Promise.resolve().then(()=>w(f(),1))}catch(t){return console.warn("[OpenPanel] Failed to load replay module",t),null}}debounce(t,r){clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(t,r)}isServer(){return typeof document>"u"}trackOutgoingLinks(){this.isServer()||document.addEventListener("click",t=>{let r=t.target,s=r.closest("a");if(s&&r){let n=s.getAttribute("href");if(n?.startsWith("http"))try{let i=new URL(n),o=window.location.hostname;i.hostname!==o&&super.track("link_out",{href:n,text:s.innerText||s.getAttribute("title")||r.getAttribute("alt")||r.getAttribute("title")})}catch{}}})}trackScreenViews(){if(this.isServer())return;let t=history.pushState;history.pushState=function(...i){let o=t.apply(this,i);return window.dispatchEvent(new Event("pushstate")),window.dispatchEvent(new Event("locationchange")),o};let r=history.replaceState;history.replaceState=function(...i){let o=r.apply(this,i);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",t=>{let r=t.target,s=r.closest("button"),n=r.closest("a"),i=s?.getAttribute("data-track")?s:n?.getAttribute("data-track")?n:null;if(i){let o={};for(let p of i.attributes)p.name.startsWith("data-")&&p.name!=="data-track"&&(o[S(p.name.replace(/^data-/,""))]=p.value);let u=i.getAttribute("data-track");u&&super.track(u,o)}})}track(t,r){return super.track(t,{...r,__path:this.lastPath})}screenView(t,r){if(this.isServer())return;let s,n;typeof t=="string"?(s=t,n=r):(s=window.location.href,n=t),this.lastPath!==s&&(this.lastPath=s,super.track("screen_view",{...n??{},__path:s,__title:document.title}))}async flushRevenue(){let t=this.pendingRevenues.map(r=>super.revenue(r.amount,r.properties));await Promise.all(t),this.clearRevenue()}clearRevenue(){if(this.pendingRevenues=[],!this.isServer())try{sessionStorage.removeItem("openpanel-pending-revenues")}catch{}}pendingRevenue(t,r){if(this.pendingRevenues.push({amount:t,properties:r}),!this.isServer())try{sessionStorage.setItem("openpanel-pending-revenues",JSON.stringify(this.pendingRevenues))}catch{}}};(a=>{if(a.op){let e=a.op.q||[],t=new c(e.shift()[1]);e.forEach(s=>{s[0]in t&&t[s[0]](...s.slice(1))});let r=new Proxy((s,...n)=>{let i=t[s]?t[s].bind(t):void 0;typeof i=="function"?i(...n):console.warn(`OpenPanel: ${s} is not a function`)},{get(s,n){if(n==="q")return;let i=t[n];return typeof i=="function"?i.bind(t):i}});a.op=r,a.openpanel=t}})(window);})();