@carter-rmn/cpix-js 1.0.0-alpha.4 → 1.0.0
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/README.md +1 -1
- package/dist/common/url.d.ts +1 -1
- package/dist/cpix.cjs +1 -1
- package/dist/cpix.iife.js +1 -1
- package/dist/cpix.js +98 -98
- package/dist/cpix.umd.cjs +1 -1
- package/dist/main.d.ts +1 -0
- package/dist/types/index.d.ts +4 -0
- package/package.json +6 -6
- package/LICENCE +0 -32
package/README.md
CHANGED
package/dist/common/url.d.ts
CHANGED
package/dist/cpix.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var v=Object.defineProperty;var E=(c,e,t)=>e in c?v(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var a=(c,e,t)=>(E(c,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S="@carter-rmn/cpix-js",x="1.0.0-alpha.4",b="module",A=["dist"],P="dist/cpix.umd.cjs",T="dist/cpix.js",_="dist/cpix.d.ts",U={".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},D={dev:"vite",build:"tsc && vite build",preview:"vite preview"},k={picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},C={"vite-plugin-dts":"^3.8.1"},p={name:S,version:x,type:b,files:A,main:P,module:T,types:_,exports:U,scripts:D,devDependencies:k,dependencies:C},u={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:p.version,package:p.name},o={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},I=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],n=function(){const c=()=>u.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){c()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class N extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(n.debug("Consuming event:",i),Promise.resolve())}){super();a(this,"dataQueue");a(this,"retryQueue");a(this,"maxRetries");a(this,"initialDelay");a(this,"publishEvent");a(this,"retryEvent");a(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){n.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){n.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(r){n.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){n.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){n.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(r){n.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}}class m{static getBrowserInfo(){var r,l,h,f,g;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(r=e.match(/chrome\/(\d+)/i))==null?void 0:r[1]):/firefox/i.test(e)?(t="Firefox",i=(l=e.match(/firefox\/(\d+)/i))==null?void 0:l[1]):/safari/i.test(e)?(t="Safari",i=(h=e.match(/version\/(\d+)/i))==null?void 0:h[1]):/edge/i.test(e)?(t="Edge",i=(f=e.match(/edge\/(\d+)/i))==null?void 0:f[1]):/trident/i.test(e)?(t="Internet Explorer",i=(g=e.match(/rv:(\d+)/i))==null?void 0:g[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${u.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return n.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${u.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:u.package,version:u.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw n.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class d{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return p.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return d.isPresent(e)===!1?"":typeof e=="object"?d.optionalData(JSON.stringify(e)):typeof e=="function"?d.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class w{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const r=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return r?r[2]?decodeURIComponent(r[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${u.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const r=`${s.prefix()}${e}`,l=new Date;l.setTime(l.getTime()+i*60*1e3),document.cookie=`${r}=${t}; expires=${l.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=I;let t=!1;for(let i=0;i<e.length;i++){const r=e[i];if(d.isPresent(w.getParameterByName(r,window.location.href))){t=!0;break}}if(t){let i="";const r={};for(let l=0;l<e.length;l++){const h=e[l];i=w.getParameterByName(h,window.location.href),d.isPresent(i)&&(r[h]=i),r[h]=i}s.set(o.UTM,JSON.stringify(r),30)}}static getUtms(){const e=s.get(o.UTM);return d.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,d.guid(),30*24*60),s.setUtms()}}class M{constructor(){a(this,"instances",[]);a(this,"initialized",!1);a(this,"accessToken","");a(this,"metaParameters",{});a(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new N({maxRetries:u.QUEUE_MAX_RETRIES,initialDelay:u.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,s.exists(o.SESSION)||s.createSession(),s.exists(o.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{s.set("metaParameters",JSON.stringify(t),60*24)}),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(o.ACCESS_TOKEN)||(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,n.debug("CPIX Initialized"),n.debug("Carter Analytics SDK initialized with options:",this.instances),u.DEBUG=this.instances[0].options.debug===!0,u.API_URL=this.instances[0].options.tracker_server_url,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};n.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(o.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(o.META_PARAMETERS,JSON.stringify(this.metaParameters),60*24)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await m.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(o.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:m.getDeviceCategory(),brand:m.getDeviceManufacturer(),ip_address:e.ip_address,platform:m.getDevicePlatform()},referrer:document.referrer,utm_params:s.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${u.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(o.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");const i=await t.json();n.debug("Event published:",i)}catch(t){throw n.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const y=new M;typeof window<"u"&&(window.cpix=y);exports.CarterAnalytics=y;
|
|
1
|
+
"use strict";var v=Object.defineProperty;var E=(u,e,t)=>e in u?v(u,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):u[e]=t;var o=(u,e,t)=>(E(u,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const S="@carter-rmn/cpix-js",x="1.0.0",b="module",A=["dist"],P="dist/cpix.umd.cjs",T="dist/cpix.js",U="dist/cpix.d.ts",_={".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},C={dev:"vite",build:"tsc && vite build",preview:"vite preview"},D={picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},I={"vite-plugin-dts":"^3.8.1"},p={name:S,version:x,type:b,files:A,main:P,module:T,types:U,exports:_,scripts:C,devDependencies:D,dependencies:I},l={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:p.version,package:p.name},c={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},k=["utm_source","utm_medium","utm_term","utm_content","utm_campaign"],a=function(){const u=()=>l.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){u()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class N extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(a.debug("Consuming event:",i),Promise.resolve())}){super();o(this,"dataQueue");o(this,"retryQueue");o(this,"maxRetries");o(this,"initialDelay");o(this,"publishEvent");o(this,"retryEvent");o(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){a.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){a.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(r){a.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){a.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){a.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(r){a.error("Failed to publish event:",r),this.scheduleRetry(t)}}})}}class h{static getBrowserInfo(){var r,n,m,f,g;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(r=e.match(/chrome\/(\d+)/i))==null?void 0:r[1]):/firefox/i.test(e)?(t="Firefox",i=(n=e.match(/firefox\/(\d+)/i))==null?void 0:n[1]):/safari/i.test(e)?(t="Safari",i=(m=e.match(/version\/(\d+)/i))==null?void 0:m[1]):/edge/i.test(e)?(t="Edge",i=(f=e.match(/edge\/(\d+)/i))==null?void 0:f[1]):/trident/i.test(e)?(t="Internet Explorer",i=(g=e.match(/rv:(\d+)/i))==null?void 0:g[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${l.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return a.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${l.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:l.package,version:l.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw a.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class d{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return p.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return d.isPresent(e)===!1?"":typeof e=="object"?d.optionalData(JSON.stringify(e)):typeof e=="function"?d.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class w{static getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),r=[];let n;for(;(n=i.exec(t))!==null;)n[2]&&r.push(decodeURIComponent(n[2].replace(/\+/g," ")));return r.length>0?r:null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${l.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(r=>r.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const r=`${s.prefix()}${e}`,n=new Date;n.setTime(n.getTime()+i*60*1e3),document.cookie=`${r}=${t}; expires=${n.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=k;let t=!1;for(let i=0;i<e.length;i++){const r=e[i];if(d.isPresent(w.getParametersByName(r,window.location.href))){t=!0;break}}if(t){let i;const r=[];for(let n=0;n<e.length;n++){const m=e[n];i=w.getParametersByName(m,window.location.href),r.push({[m]:i})}s.set(c.UTM,JSON.stringify(r),14*24*60)}}static getUtms(){const e=s.get(c.UTM);return d.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(c.SESSION)||s.set(c.SESSION,d.guid(),14*24*60),s.setUtms()}}class R{constructor(){o(this,"instances",[]);o(this,"initialized",!1);o(this,"accessToken","");o(this,"metaParameters",{});o(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new N({maxRetries:l.QUEUE_MAX_RETRIES,initialDelay:l.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,l.API_URL=this.instances[0].options.tracker_server_url,s.exists(c.SESSION)||s.createSession(),s.exists(c.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),60*24)}),s.setUtms(),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(c.ACCESS_TOKEN)||(this.accessToken=await h.aquireAccessToken(this.instances[0].client_id),s.set(c.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,a.debug("CPIX Initialized"),a.debug("Carter Analytics SDK initialized with options:",this.instances),l.DEBUG=this.instances[0].options.debug===!0,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),a.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(c.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(c.META_PARAMETERS,JSON.stringify(this.metaParameters),60*24)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await h.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(c.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:h.getDeviceCategory(),brand:h.getDeviceManufacturer(),ip_address:e.ip_address,platform:h.getDevicePlatform()},referrer:encodeURIComponent(document.referrer)}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${l.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(c.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await h.aquireAccessToken(this.instances[0].client_id),s.set(c.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");a.debug("Event published:",t.ok)}catch(t){throw a.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const y=new R;typeof window<"u"&&(window.cpix=y);exports.CarterAnalytics=y;
|
package/dist/cpix.iife.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var tracker=function(l){"use strict";var P=Object.defineProperty;var T=(l,d,m)=>d in l?P(l,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):l[d]=m;var o=(l,d,m)=>(T(l,typeof d!="symbol"?d+"":d,m),m);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.4",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},c={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},a={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},x=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],r=function(){const g=()=>c.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){g()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(r.debug("Consuming event:",i),Promise.resolve())}){super();o(this,"dataQueue");o(this,"retryQueue");o(this,"maxRetries");o(this,"initialDelay");o(this,"publishEvent");o(this,"retryEvent");o(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){r.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){r.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){r.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){r.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class p{static getBrowserInfo(){var n,u,f,E,S;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(n=e.match(/chrome\/(\d+)/i))==null?void 0:n[1]):/firefox/i.test(e)?(t="Firefox",i=(u=e.match(/firefox\/(\d+)/i))==null?void 0:u[1]):/safari/i.test(e)?(t="Safari",i=(f=e.match(/version\/(\d+)/i))==null?void 0:f[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(S=e.match(/rv:(\d+)/i))==null?void 0:S[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${c.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return r.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${c.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:c.package,version:c.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw r.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const n=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${c.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,u=new Date;u.setTime(u.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${u.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=x;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(h.isPresent(y.getParameterByName(n,window.location.href))){t=!0;break}}if(t){let i="";const n={};for(let u=0;u<e.length;u++){const f=e[u];i=y.getParameterByName(f,window.location.href),h.isPresent(i)&&(n[f]=i),n[f]=i}s.set(a.UTM,JSON.stringify(n),30)}}static getUtms(){const e=s.get(a.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(a.SESSION)||s.set(a.SESSION,h.guid(),43200),s.setUtms()}}class A{constructor(){o(this,"instances",[]);o(this,"initialized",!1);o(this,"accessToken","");o(this,"metaParameters",{});o(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:c.QUEUE_MAX_RETRIES,initialDelay:c.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,s.exists(a.SESSION)||s.createSession(),s.exists(a.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{s.set("metaParameters",JSON.stringify(t),1440)}),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(a.ACCESS_TOKEN)||(this.accessToken=await p.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,240)),this.initialized=!0,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),c.DEBUG=this.instances[0].options.debug===!0,c.API_URL=this.instances[0].options.tracker_server_url,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};r.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(a.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(a.META_PARAMETERS,JSON.stringify(this.metaParameters),1440)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await p.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(a.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:p.getDeviceCategory(),brand:p.getDeviceManufacturer(),ip_address:e.ip_address,platform:p.getDevicePlatform()},referrer:document.referrer,utm_params:s.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${c.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(a.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await p.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,240)),new Error("[CPIX] Failed to publish event");const i=await t.json();r.debug("Event published:",i)}catch(t){throw r.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new A;return typeof window<"u"&&(window.cpix=v),l.CarterAnalytics=v,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),l}({});
|
|
1
|
+
var tracker=function(l){"use strict";var P=Object.defineProperty;var T=(l,d,m)=>d in l?P(l,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):l[d]=m;var c=(l,d,m)=>(T(l,typeof d!="symbol"?d+"":d,m),m);const w={name:"@carter-rmn/cpix-js",version:"1.0.0",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},u={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},o={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},x=["utm_source","utm_medium","utm_term","utm_content","utm_campaign"],r=function(){const f=()=>u.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){f()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(r.debug("Consuming event:",i),Promise.resolve())}){super();c(this,"dataQueue");c(this,"retryQueue");c(this,"maxRetries");c(this,"initialDelay");c(this,"publishEvent");c(this,"retryEvent");c(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){r.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){r.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){r.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){r.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class p{static getBrowserInfo(){var n,a,g,E,S;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(n=e.match(/chrome\/(\d+)/i))==null?void 0:n[1]):/firefox/i.test(e)?(t="Firefox",i=(a=e.match(/firefox\/(\d+)/i))==null?void 0:a[1]):/safari/i.test(e)?(t="Safari",i=(g=e.match(/version\/(\d+)/i))==null?void 0:g[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(S=e.match(/rv:(\d+)/i))==null?void 0:S[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${u.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return r.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${u.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:u.package,version:u.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw r.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),n=[];let a;for(;(a=i.exec(t))!==null;)a[2]&&n.push(decodeURIComponent(a[2].replace(/\+/g," ")));return n.length>0?n:null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${u.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,a=new Date;a.setTime(a.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${a.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=x;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(h.isPresent(y.getParametersByName(n,window.location.href))){t=!0;break}}if(t){let i;const n=[];for(let a=0;a<e.length;a++){const g=e[a];i=y.getParametersByName(g,window.location.href),n.push({[g]:i})}s.set(o.UTM,JSON.stringify(n),20160)}}static getUtms(){const e=s.get(o.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,h.guid(),20160),s.setUtms()}}class A{constructor(){c(this,"instances",[]);c(this,"initialized",!1);c(this,"accessToken","");c(this,"metaParameters",{});c(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:u.QUEUE_MAX_RETRIES,initialDelay:u.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,u.API_URL=this.instances[0].options.tracker_server_url,s.exists(o.SESSION)||s.createSession(),s.exists(o.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),1440)}),s.setUtms(),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(o.ACCESS_TOKEN)||(this.accessToken=await p.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,240)),this.initialized=!0,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),u.DEBUG=this.instances[0].options.debug===!0,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),r.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(o.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(o.META_PARAMETERS,JSON.stringify(this.metaParameters),1440)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await p.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(o.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:p.getDeviceCategory(),brand:p.getDeviceManufacturer(),ip_address:e.ip_address,platform:p.getDevicePlatform()},referrer:encodeURIComponent(document.referrer)}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${u.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(o.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await p.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,240)),new Error("[CPIX] Failed to publish event");r.debug("Event published:",t.ok)}catch(t){throw r.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new A;return typeof window<"u"&&(window.cpix=v),l.CarterAnalytics=v,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),l}({});
|
package/dist/cpix.js
CHANGED
|
@@ -1,91 +1,88 @@
|
|
|
1
1
|
var y = Object.defineProperty;
|
|
2
|
-
var v = (
|
|
3
|
-
var
|
|
4
|
-
const E = "@carter-rmn/cpix-js",
|
|
2
|
+
var v = (u, e, t) => e in u ? y(u, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : u[e] = t;
|
|
3
|
+
var o = (u, e, t) => (v(u, typeof e != "symbol" ? e + "" : e, t), t);
|
|
4
|
+
const E = "@carter-rmn/cpix-js", S = "1.0.0", x = "module", b = [
|
|
5
5
|
"dist"
|
|
6
|
-
], A = "dist/cpix.umd.cjs", P = "dist/cpix.js", T = "dist/cpix.d.ts",
|
|
6
|
+
], A = "dist/cpix.umd.cjs", P = "dist/cpix.js", T = "dist/cpix.d.ts", U = {
|
|
7
7
|
".": {
|
|
8
8
|
import: "./dist/cpix.js",
|
|
9
9
|
require: "./dist/cpix.umd.cjs"
|
|
10
10
|
}
|
|
11
|
-
},
|
|
11
|
+
}, _ = {
|
|
12
12
|
dev: "vite",
|
|
13
13
|
build: "tsc && vite build",
|
|
14
14
|
preview: "vite preview"
|
|
15
|
-
},
|
|
15
|
+
}, C = {
|
|
16
16
|
picocolors: "^1.0.0",
|
|
17
17
|
"rollup-plugin-visualizer": "^5.12.0",
|
|
18
18
|
typescript: "^5.2.2",
|
|
19
19
|
vite: "^5.2.0",
|
|
20
20
|
"vite-plugin-progress": "^0.0.7"
|
|
21
|
-
},
|
|
21
|
+
}, D = {
|
|
22
22
|
"vite-plugin-dts": "^3.8.1"
|
|
23
23
|
}, p = {
|
|
24
24
|
name: E,
|
|
25
|
-
version:
|
|
26
|
-
type:
|
|
25
|
+
version: S,
|
|
26
|
+
type: x,
|
|
27
27
|
files: b,
|
|
28
28
|
main: A,
|
|
29
29
|
module: P,
|
|
30
30
|
types: T,
|
|
31
|
-
exports:
|
|
32
|
-
scripts:
|
|
33
|
-
devDependencies:
|
|
34
|
-
dependencies:
|
|
35
|
-
},
|
|
31
|
+
exports: U,
|
|
32
|
+
scripts: _,
|
|
33
|
+
devDependencies: C,
|
|
34
|
+
dependencies: D
|
|
35
|
+
}, l = {
|
|
36
36
|
DEBUG: !1,
|
|
37
37
|
TRACKER_FUNC_NAME: "cpix",
|
|
38
|
-
API_URL: "
|
|
38
|
+
API_URL: "",
|
|
39
39
|
QUEUE_MAX_RETRIES: 3,
|
|
40
40
|
QUEUE_INITIAL_DELAY: 1e4,
|
|
41
41
|
version: p.version,
|
|
42
42
|
package: p.name
|
|
43
|
-
},
|
|
43
|
+
}, c = {
|
|
44
44
|
SESSION: "cpix_session",
|
|
45
45
|
META_PARAMETERS: "cpix_meta_parameters",
|
|
46
46
|
ACCESS_TOKEN: "cpix_access_token",
|
|
47
47
|
UTM: "cpix_utm"
|
|
48
|
-
},
|
|
48
|
+
}, I = [
|
|
49
49
|
"utm_source",
|
|
50
50
|
"utm_medium",
|
|
51
51
|
"utm_term",
|
|
52
52
|
"utm_content",
|
|
53
|
-
"utm_campaign"
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
"utm_marketing_tactic"
|
|
57
|
-
], n = /* @__PURE__ */ function() {
|
|
58
|
-
const c = () => u.DEBUG;
|
|
53
|
+
"utm_campaign"
|
|
54
|
+
], a = /* @__PURE__ */ function() {
|
|
55
|
+
const u = () => l.DEBUG;
|
|
59
56
|
return {
|
|
60
57
|
info: function(...e) {
|
|
61
58
|
console.log(...e);
|
|
62
59
|
},
|
|
63
60
|
debug: function(...e) {
|
|
64
|
-
|
|
61
|
+
u() && console.log(...e);
|
|
65
62
|
},
|
|
66
63
|
error: function(...e) {
|
|
67
64
|
console.error(...e);
|
|
68
65
|
}
|
|
69
66
|
};
|
|
70
67
|
}();
|
|
71
|
-
class
|
|
68
|
+
class k extends EventTarget {
|
|
72
69
|
constructor(t = {
|
|
73
70
|
maxRetries: 3,
|
|
74
71
|
initialDelay: 1e4,
|
|
75
|
-
consumerHandler: (i) => (
|
|
72
|
+
consumerHandler: (i) => (a.debug("Consuming event:", i), Promise.resolve())
|
|
76
73
|
}) {
|
|
77
74
|
super();
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
75
|
+
o(this, "dataQueue");
|
|
76
|
+
o(this, "retryQueue");
|
|
77
|
+
o(this, "maxRetries");
|
|
78
|
+
o(this, "initialDelay");
|
|
79
|
+
o(this, "publishEvent");
|
|
80
|
+
o(this, "retryEvent");
|
|
81
|
+
o(this, "handler");
|
|
85
82
|
this.dataQueue = [], this.retryQueue = [], this.maxRetries = t.maxRetries, this.initialDelay = t.initialDelay, this.handler = t.consumerHandler, this.publishEvent = new Event("eventPublished"), this.retryEvent = new Event("retryMessage"), this.consume(), this.retry();
|
|
86
83
|
}
|
|
87
84
|
publish(t) {
|
|
88
|
-
|
|
85
|
+
a.debug("publishing event");
|
|
89
86
|
const i = {
|
|
90
87
|
data: t,
|
|
91
88
|
id: `${Date.now() + Math.random()}`,
|
|
@@ -95,20 +92,20 @@ class I extends EventTarget {
|
|
|
95
92
|
this.dataQueue.push(i), this.dispatchEvent(this.publishEvent);
|
|
96
93
|
}
|
|
97
94
|
consume() {
|
|
98
|
-
|
|
95
|
+
a.debug("Started Consumer Queue"), this.addEventListener("eventPublished", async () => {
|
|
99
96
|
for (; this.dataQueue.length > 0; ) {
|
|
100
97
|
const t = this.dataQueue.shift(), { data: i = {} } = t;
|
|
101
98
|
try {
|
|
102
99
|
await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
|
|
103
|
-
} catch (
|
|
104
|
-
|
|
100
|
+
} catch (n) {
|
|
101
|
+
a.error("Failed to publish event:", n), this.scheduleRetry(t);
|
|
105
102
|
}
|
|
106
103
|
}
|
|
107
104
|
});
|
|
108
105
|
}
|
|
109
106
|
scheduleRetry(t) {
|
|
110
107
|
if (t.retryCount >= this.maxRetries) {
|
|
111
|
-
|
|
108
|
+
a.error("Max retries reached for message:", t);
|
|
112
109
|
return;
|
|
113
110
|
}
|
|
114
111
|
setTimeout(() => {
|
|
@@ -123,24 +120,24 @@ class I extends EventTarget {
|
|
|
123
120
|
this.dataQueue = this.dataQueue.filter((i) => i.id !== t);
|
|
124
121
|
}
|
|
125
122
|
retry() {
|
|
126
|
-
|
|
123
|
+
a.debug("Started Retry Queue"), this.addEventListener("retryMessage", async () => {
|
|
127
124
|
for (; this.retryQueue.length > 0; ) {
|
|
128
125
|
const t = this.retryQueue.shift(), { data: i = {} } = t;
|
|
129
126
|
try {
|
|
130
127
|
await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
|
|
131
|
-
} catch (
|
|
132
|
-
|
|
128
|
+
} catch (n) {
|
|
129
|
+
a.error("Failed to publish event:", n), this.scheduleRetry(t);
|
|
133
130
|
}
|
|
134
131
|
}
|
|
135
132
|
});
|
|
136
133
|
}
|
|
137
134
|
}
|
|
138
|
-
class
|
|
135
|
+
class h {
|
|
139
136
|
static getBrowserInfo() {
|
|
140
|
-
var
|
|
137
|
+
var n, r, m, f, g;
|
|
141
138
|
const e = navigator.userAgent || "";
|
|
142
139
|
let t, i;
|
|
143
|
-
return /chrome/i.test(e) ? (t = "Chrome", i = (
|
|
140
|
+
return /chrome/i.test(e) ? (t = "Chrome", i = (n = e.match(/chrome\/(\d+)/i)) == null ? void 0 : n[1]) : /firefox/i.test(e) ? (t = "Firefox", i = (r = e.match(/firefox\/(\d+)/i)) == null ? void 0 : r[1]) : /safari/i.test(e) ? (t = "Safari", i = (m = e.match(/version\/(\d+)/i)) == null ? void 0 : m[1]) : /edge/i.test(e) ? (t = "Edge", i = (f = e.match(/edge\/(\d+)/i)) == null ? void 0 : f[1]) : /trident/i.test(e) ? (t = "Internet Explorer", i = (g = e.match(/rv:(\d+)/i)) == null ? void 0 : g[1]) : (t = "Unknown", i = "Unknown"), `${t} ${i}`;
|
|
144
141
|
}
|
|
145
142
|
static getDeviceCategory() {
|
|
146
143
|
const e = navigator.userAgent;
|
|
@@ -157,7 +154,7 @@ class m {
|
|
|
157
154
|
}
|
|
158
155
|
static async getDeviceNetworkParameters() {
|
|
159
156
|
try {
|
|
160
|
-
const e = await fetch(`${
|
|
157
|
+
const e = await fetch(`${l.API_URL}/api/geolocation`), { data: t } = await e.json();
|
|
161
158
|
return {
|
|
162
159
|
city: t.city || "Unknown",
|
|
163
160
|
region: t.region || "Unknown",
|
|
@@ -167,7 +164,7 @@ class m {
|
|
|
167
164
|
ip_address: t.ip_address || "Unknown"
|
|
168
165
|
};
|
|
169
166
|
} catch (e) {
|
|
170
|
-
return
|
|
167
|
+
return a.error("Error retrieving device network parameters:", e), {
|
|
171
168
|
city: "Unknown",
|
|
172
169
|
region: "Unknown",
|
|
173
170
|
country: "Unknown",
|
|
@@ -179,7 +176,7 @@ class m {
|
|
|
179
176
|
}
|
|
180
177
|
static async aquireAccessToken(e) {
|
|
181
178
|
try {
|
|
182
|
-
return (await (await fetch(`${
|
|
179
|
+
return (await (await fetch(`${l.API_URL}/api/authenticate`, {
|
|
183
180
|
method: "POST",
|
|
184
181
|
headers: {
|
|
185
182
|
"Content-Type": "application/json"
|
|
@@ -187,14 +184,14 @@ class m {
|
|
|
187
184
|
body: JSON.stringify({
|
|
188
185
|
accountId: e,
|
|
189
186
|
metadata: {
|
|
190
|
-
sdk:
|
|
191
|
-
version:
|
|
187
|
+
sdk: l.package,
|
|
188
|
+
version: l.version,
|
|
192
189
|
hostname: window.location.hostname
|
|
193
190
|
}
|
|
194
191
|
})
|
|
195
192
|
})).json()).accessToken;
|
|
196
193
|
} catch (t) {
|
|
197
|
-
throw
|
|
194
|
+
throw a.error("Error acquiring access token:", t), new Error("[CPIX] Authentication error");
|
|
198
195
|
}
|
|
199
196
|
}
|
|
200
197
|
}
|
|
@@ -220,10 +217,13 @@ class d {
|
|
|
220
217
|
}
|
|
221
218
|
}
|
|
222
219
|
class w {
|
|
223
|
-
static
|
|
220
|
+
static getParametersByName(e, t) {
|
|
224
221
|
t || (t = window.location.href), e = e.replace(/[[\]]/g, "\\$&");
|
|
225
|
-
const
|
|
226
|
-
|
|
222
|
+
const i = new RegExp("[?&]" + e + "(=([^&#]*)|&|#|$)", "gi"), n = [];
|
|
223
|
+
let r;
|
|
224
|
+
for (; (r = i.exec(t)) !== null; )
|
|
225
|
+
r[2] && n.push(decodeURIComponent(r[2].replace(/\+/g, " ")));
|
|
226
|
+
return n.length > 0 ? n : null;
|
|
227
227
|
}
|
|
228
228
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
229
229
|
static externalHost(e) {
|
|
@@ -233,15 +233,15 @@ class w {
|
|
|
233
233
|
}
|
|
234
234
|
class s {
|
|
235
235
|
static prefix() {
|
|
236
|
-
return `__${
|
|
236
|
+
return `__${l.TRACKER_FUNC_NAME}__`;
|
|
237
237
|
}
|
|
238
238
|
static get(e) {
|
|
239
|
-
const t = `${s.prefix()}${e}`, i = document.cookie.split("; ").find((
|
|
239
|
+
const t = `${s.prefix()}${e}`, i = document.cookie.split("; ").find((n) => n.startsWith(`${t}=`));
|
|
240
240
|
return i ? i.split("=")[1] : void 0;
|
|
241
241
|
}
|
|
242
242
|
static set(e, t, i) {
|
|
243
|
-
const
|
|
244
|
-
|
|
243
|
+
const n = `${s.prefix()}${e}`, r = /* @__PURE__ */ new Date();
|
|
244
|
+
r.setTime(r.getTime() + i * 60 * 1e3), document.cookie = `${n}=${t}; expires=${r.toUTCString()}; path=/`;
|
|
245
245
|
}
|
|
246
246
|
static delete(e) {
|
|
247
247
|
const t = `${s.prefix()}${e}`;
|
|
@@ -257,47 +257,49 @@ class s {
|
|
|
257
257
|
return !!s.get(e);
|
|
258
258
|
}
|
|
259
259
|
static setUtms() {
|
|
260
|
-
const e =
|
|
260
|
+
const e = I;
|
|
261
261
|
let t = !1;
|
|
262
262
|
for (let i = 0; i < e.length; i++) {
|
|
263
|
-
const
|
|
264
|
-
if (d.isPresent(w.
|
|
263
|
+
const n = e[i];
|
|
264
|
+
if (d.isPresent(w.getParametersByName(n, window.location.href))) {
|
|
265
265
|
t = !0;
|
|
266
266
|
break;
|
|
267
267
|
}
|
|
268
268
|
}
|
|
269
269
|
if (t) {
|
|
270
|
-
let i
|
|
271
|
-
const
|
|
272
|
-
for (let
|
|
273
|
-
const
|
|
274
|
-
i = w.
|
|
270
|
+
let i;
|
|
271
|
+
const n = [];
|
|
272
|
+
for (let r = 0; r < e.length; r++) {
|
|
273
|
+
const m = e[r];
|
|
274
|
+
i = w.getParametersByName(m, window.location.href), n.push({
|
|
275
|
+
[m]: i
|
|
276
|
+
});
|
|
275
277
|
}
|
|
276
|
-
s.set(
|
|
278
|
+
s.set(c.UTM, JSON.stringify(n), 14 * 24 * 60);
|
|
277
279
|
}
|
|
278
280
|
}
|
|
279
281
|
static getUtms() {
|
|
280
|
-
const e = s.get(
|
|
282
|
+
const e = s.get(c.UTM);
|
|
281
283
|
return d.isPresent(e) ? JSON.parse(e) : {};
|
|
282
284
|
}
|
|
283
285
|
static createSession() {
|
|
284
|
-
s.exists(
|
|
286
|
+
s.exists(c.SESSION) || s.set(c.SESSION, d.guid(), 14 * 24 * 60), s.setUtms();
|
|
285
287
|
}
|
|
286
288
|
}
|
|
287
289
|
class N {
|
|
288
290
|
constructor() {
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
291
|
+
o(this, "instances", []);
|
|
292
|
+
o(this, "initialized", !1);
|
|
293
|
+
o(this, "accessToken", "");
|
|
294
|
+
o(this, "metaParameters", {});
|
|
295
|
+
o(this, "queue");
|
|
294
296
|
if (!window)
|
|
295
297
|
throw new Error(
|
|
296
298
|
"[CPIX] CarterAnalytics SDK can only be used in a browser environment"
|
|
297
299
|
);
|
|
298
|
-
this.queue = new
|
|
299
|
-
maxRetries:
|
|
300
|
-
initialDelay:
|
|
300
|
+
this.queue = new k({
|
|
301
|
+
maxRetries: l.QUEUE_MAX_RETRIES,
|
|
302
|
+
initialDelay: l.QUEUE_INITIAL_DELAY,
|
|
301
303
|
consumerHandler: this.publishEventToServer.bind(this)
|
|
302
304
|
});
|
|
303
305
|
}
|
|
@@ -310,20 +312,20 @@ class N {
|
|
|
310
312
|
throw new Error(
|
|
311
313
|
"[CPIX] At least one instance configuration is required for initialization"
|
|
312
314
|
);
|
|
313
|
-
if (this.instances = e, s.exists(
|
|
314
|
-
s.set("metaParameters", JSON.stringify(t), 60 * 24);
|
|
315
|
-
}), this.metaParameters = JSON.parse(s.get("metaParameters")), this.initialized)
|
|
315
|
+
if (this.instances = e, l.API_URL = this.instances[0].options.tracker_server_url, s.exists(c.SESSION) || s.createSession(), s.exists(c.META_PARAMETERS) || await this.generateMetaParameters().then((t) => {
|
|
316
|
+
this.metaParameters = t, s.set("metaParameters", JSON.stringify(t), 60 * 24);
|
|
317
|
+
}), s.setUtms(), this.metaParameters = JSON.parse(s.get("metaParameters")), this.initialized)
|
|
316
318
|
throw new Error(
|
|
317
319
|
"[CPIX] CarterAnalytics SDK has already been initialized"
|
|
318
320
|
);
|
|
319
321
|
if (!this.metaParameters)
|
|
320
322
|
throw new Error("[CPIX] Meta parameters have not been generated");
|
|
321
|
-
s.exists(
|
|
323
|
+
s.exists(c.ACCESS_TOKEN) || (this.accessToken = await h.aquireAccessToken(
|
|
322
324
|
this.instances[0].client_id
|
|
323
|
-
), s.set(
|
|
325
|
+
), s.set(c.ACCESS_TOKEN, this.accessToken, 60 * 4)), this.initialized = !0, a.debug("CPIX Initialized"), a.debug(
|
|
324
326
|
"Carter Analytics SDK initialized with options:",
|
|
325
327
|
this.instances
|
|
326
|
-
),
|
|
328
|
+
), l.DEBUG = this.instances[0].options.debug === !0, this.publish({
|
|
327
329
|
event: "init",
|
|
328
330
|
...this.metaParameters
|
|
329
331
|
}), this.publish({
|
|
@@ -349,9 +351,9 @@ class N {
|
|
|
349
351
|
...e,
|
|
350
352
|
...this.metaParameters
|
|
351
353
|
};
|
|
352
|
-
|
|
354
|
+
t.utm_params = s.getUtms(), document.referrer && (t.referrer = encodeURIComponent(document.referrer)), a.debug("Publishing event:", t), this.queue.publish(t), e.event === "logout" && (s.delete(c.SESSION), s.createSession(), this.generateMetaParameters().then((i) => {
|
|
353
355
|
this.metaParameters = i, s.set(
|
|
354
|
-
|
|
356
|
+
c.META_PARAMETERS,
|
|
355
357
|
JSON.stringify(this.metaParameters),
|
|
356
358
|
60 * 24
|
|
357
359
|
);
|
|
@@ -365,10 +367,10 @@ class N {
|
|
|
365
367
|
throw new Error(
|
|
366
368
|
"[CPIX] Meta parameters can only be generated in a browser environment"
|
|
367
369
|
);
|
|
368
|
-
const e = await
|
|
370
|
+
const e = await h.getDeviceNetworkParameters();
|
|
369
371
|
return {
|
|
370
372
|
client_id: this.instances[0].client_id,
|
|
371
|
-
session: s.get(
|
|
373
|
+
session: s.get(c.SESSION),
|
|
372
374
|
location: {
|
|
373
375
|
city: e.city,
|
|
374
376
|
region: e.region,
|
|
@@ -377,13 +379,12 @@ class N {
|
|
|
377
379
|
country: e.country
|
|
378
380
|
},
|
|
379
381
|
device: {
|
|
380
|
-
category:
|
|
381
|
-
brand:
|
|
382
|
+
category: h.getDeviceCategory(),
|
|
383
|
+
brand: h.getDeviceManufacturer(),
|
|
382
384
|
ip_address: e.ip_address,
|
|
383
|
-
platform:
|
|
385
|
+
platform: h.getDevicePlatform()
|
|
384
386
|
},
|
|
385
|
-
referrer: document.referrer
|
|
386
|
-
utm_params: s.getUtms()
|
|
387
|
+
referrer: encodeURIComponent(document.referrer)
|
|
387
388
|
};
|
|
388
389
|
}
|
|
389
390
|
/**
|
|
@@ -393,22 +394,21 @@ class N {
|
|
|
393
394
|
async publishEventToServer(e) {
|
|
394
395
|
try {
|
|
395
396
|
e.timestamp = Date.now();
|
|
396
|
-
const t = await fetch(`${
|
|
397
|
+
const t = await fetch(`${l.API_URL}/api/event`, {
|
|
397
398
|
method: "POST",
|
|
398
399
|
body: JSON.stringify({ event_data: e }),
|
|
399
400
|
headers: {
|
|
400
401
|
"Content-Type": "application/json",
|
|
401
|
-
Authorization: `Bearer ${s.get(
|
|
402
|
+
Authorization: `Bearer ${s.get(c.ACCESS_TOKEN)}`
|
|
402
403
|
}
|
|
403
404
|
});
|
|
404
405
|
if (!t.ok)
|
|
405
|
-
throw t.status === 401 && (this.accessToken = await
|
|
406
|
+
throw t.status === 401 && (this.accessToken = await h.aquireAccessToken(
|
|
406
407
|
this.instances[0].client_id
|
|
407
|
-
), s.set(
|
|
408
|
-
|
|
409
|
-
n.debug("Event published:", i);
|
|
408
|
+
), s.set(c.ACCESS_TOKEN, this.accessToken, 60 * 4)), new Error("[CPIX] Failed to publish event");
|
|
409
|
+
a.debug("Event published:", t.ok);
|
|
410
410
|
} catch (t) {
|
|
411
|
-
throw
|
|
411
|
+
throw a.error("Failed to publish event:", t), new Error("[CPIX] Failed to publish event");
|
|
412
412
|
}
|
|
413
413
|
}
|
|
414
414
|
}
|
package/dist/cpix.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(c,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(c=typeof globalThis<"u"?globalThis:c||self,u(c.tracker={}))})(this,function(c){"use strict";var P=Object.defineProperty;var T=(c,u,p)=>u in c?P(c,u,{enumerable:!0,configurable:!0,writable:!0,value:p}):c[u]=p;var o=(c,u,p)=>(T(c,typeof u!="symbol"?u+"":u,p),p);const w={name:"@carter-rmn/cpix-js",version:"1.0.0-alpha.4",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},l={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},a={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},S=["utm_source","utm_medium","utm_term","utm_content","utm_campaign","utm_source_platform","utm_creative_format","utm_marketing_tactic"],r=function(){const g=()=>l.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){g()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(r.debug("Consuming event:",i),Promise.resolve())}){super();o(this,"dataQueue");o(this,"retryQueue");o(this,"maxRetries");o(this,"initialDelay");o(this,"publishEvent");o(this,"retryEvent");o(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){r.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){r.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){r.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){r.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class m{static getBrowserInfo(){var n,d,f,E,x;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(n=e.match(/chrome\/(\d+)/i))==null?void 0:n[1]):/firefox/i.test(e)?(t="Firefox",i=(d=e.match(/firefox\/(\d+)/i))==null?void 0:d[1]):/safari/i.test(e)?(t="Safari",i=(f=e.match(/version\/(\d+)/i))==null?void 0:f[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(x=e.match(/rv:(\d+)/i))==null?void 0:x[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${l.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return r.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${l.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:l.package,version:l.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw r.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParameterByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const n=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${l.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,d=new Date;d.setTime(d.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${d.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=S;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(h.isPresent(y.getParameterByName(n,window.location.href))){t=!0;break}}if(t){let i="";const n={};for(let d=0;d<e.length;d++){const f=e[d];i=y.getParameterByName(f,window.location.href),h.isPresent(i)&&(n[f]=i),n[f]=i}s.set(a.UTM,JSON.stringify(n),30)}}static getUtms(){const e=s.get(a.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(a.SESSION)||s.set(a.SESSION,h.guid(),30*24*60),s.setUtms()}}class A{constructor(){o(this,"instances",[]);o(this,"initialized",!1);o(this,"accessToken","");o(this,"metaParameters",{});o(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:l.QUEUE_MAX_RETRIES,initialDelay:l.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,s.exists(a.SESSION)||s.createSession(),s.exists(a.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{s.set("metaParameters",JSON.stringify(t),60*24)}),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(a.ACCESS_TOKEN)||(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),l.DEBUG=this.instances[0].options.debug===!0,l.API_URL=this.instances[0].options.tracker_server_url,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};r.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(a.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(a.META_PARAMETERS,JSON.stringify(this.metaParameters),60*24)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await m.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(a.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:m.getDeviceCategory(),brand:m.getDeviceManufacturer(),ip_address:e.ip_address,platform:m.getDevicePlatform()},referrer:document.referrer,utm_params:s.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${l.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(a.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(a.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");const i=await t.json();r.debug("Event published:",i)}catch(t){throw r.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new A;typeof window<"u"&&(window.cpix=v),c.CarterAnalytics=v,Object.defineProperty(c,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(u,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.tracker={}))})(this,function(u){"use strict";var P=Object.defineProperty;var T=(u,l,p)=>l in u?P(u,l,{enumerable:!0,configurable:!0,writable:!0,value:p}):u[l]=p;var c=(u,l,p)=>(T(u,typeof l!="symbol"?l+"":l,p),p);const w={name:"@carter-rmn/cpix-js",version:"1.0.0",type:"module",files:["dist"],main:"dist/cpix.umd.cjs",module:"dist/cpix.js",types:"dist/cpix.d.ts",exports:{".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},scripts:{dev:"vite",build:"tsc && vite build",preview:"vite preview"},devDependencies:{picocolors:"^1.0.0","rollup-plugin-visualizer":"^5.12.0",typescript:"^5.2.2",vite:"^5.2.0","vite-plugin-progress":"^0.0.7"},dependencies:{"vite-plugin-dts":"^3.8.1"}},d={DEBUG:!1,TRACKER_FUNC_NAME:"cpix",API_URL:"",QUEUE_MAX_RETRIES:3,QUEUE_INITIAL_DELAY:1e4,version:w.version,package:w.name},o={SESSION:"cpix_session",META_PARAMETERS:"cpix_meta_parameters",ACCESS_TOKEN:"cpix_access_token",UTM:"cpix_utm"},x=["utm_source","utm_medium","utm_term","utm_content","utm_campaign"],r=function(){const f=()=>d.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){f()&&console.log(...e)},error:function(...e){console.error(...e)}}}();class b extends EventTarget{constructor(t={maxRetries:3,initialDelay:1e4,consumerHandler:i=>(r.debug("Consuming event:",i),Promise.resolve())}){super();c(this,"dataQueue");c(this,"retryQueue");c(this,"maxRetries");c(this,"initialDelay");c(this,"publishEvent");c(this,"retryEvent");c(this,"handler");this.dataQueue=[],this.retryQueue=[],this.maxRetries=t.maxRetries,this.initialDelay=t.initialDelay,this.handler=t.consumerHandler,this.publishEvent=new Event("eventPublished"),this.retryEvent=new Event("retryMessage"),this.consume(),this.retry()}publish(t){r.debug("publishing event");const i={data:t,id:`${Date.now()+Math.random()}`,retryCount:0,retryDelay:this.initialDelay};this.dataQueue.push(i),this.dispatchEvent(this.publishEvent)}consume(){r.debug("Started Consumer Queue"),this.addEventListener("eventPublished",async()=>{for(;this.dataQueue.length>0;){const t=this.dataQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){r.error("Max retries reached for message:",t);return}setTimeout(()=>{this.retryQueue.push({...t,retryCount:t.retryCount+1,retryDelay:t.retryDelay*2}),this.dispatchEvent(this.retryEvent)},t.retryDelay)}acknowledge(t){this.dataQueue=this.dataQueue.filter(i=>i.id!==t)}retry(){r.debug("Started Retry Queue"),this.addEventListener("retryMessage",async()=>{for(;this.retryQueue.length>0;){const t=this.retryQueue.shift(),{data:i={}}=t;try{await this.handler(i),this.acknowledge(t==null?void 0:t.id)}catch(n){r.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class m{static getBrowserInfo(){var n,a,g,E,S;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(n=e.match(/chrome\/(\d+)/i))==null?void 0:n[1]):/firefox/i.test(e)?(t="Firefox",i=(a=e.match(/firefox\/(\d+)/i))==null?void 0:a[1]):/safari/i.test(e)?(t="Safari",i=(g=e.match(/version\/(\d+)/i))==null?void 0:g[1]):/edge/i.test(e)?(t="Edge",i=(E=e.match(/edge\/(\d+)/i))==null?void 0:E[1]):/trident/i.test(e)?(t="Internet Explorer",i=(S=e.match(/rv:(\d+)/i))==null?void 0:S[1]):(t="Unknown",i="Unknown"),`${t} ${i}`}static getDeviceCategory(){const e=navigator.userAgent;return/mobile/i.test(e)?"Mobile":/tablet/i.test(e)?"Tablet":"Desktop"}static getDevicePlatform(){const e=navigator.userAgent;return/android/i.test(e)?"Android":/iphone|ipad|ipod/i.test(e)?"iOS":/windows phone/i.test(e)?"Windows Phone":/mac|Macintosh/i.test(e)?"Mac":/windows|Microsoft/i.test(e)?"Windows":/linux/i.test(e)?"Linux":"Unknown"}static getDeviceManufacturer(){const e=navigator.userAgent;let t;return/iphone|ipad|ipod|mac|Macintosh/i.test(e)?t="Apple":/samsung/i.test(e)?t="Samsung":/google/i.test(e)?t="Google":/huawei/i.test(e)?t="Huawei":/xiaomi/i.test(e)?t="Xiaomi":/oneplus/i.test(e)?t="OnePlus":/dell/i.test(e)?t="Dell":/lenovo/i.test(e)?t="Lenovo":/acer/i.test(e)?t="Acer":/asus/i.test(e)?t="Asus":/toshiba/i.test(e)?t="Toshiba":t="Unknown",t}static async getDeviceNetworkParameters(){try{const e=await fetch(`${d.API_URL}/api/geolocation`),{data:t}=await e.json();return{city:t.city||"Unknown",region:t.region||"Unknown",country:t.country||"Unknown",timezone:t.timezone||"Unknown",loc:t.loc||"Unknown",ip_address:t.ip_address||"Unknown"}}catch(e){return r.error("Error retrieving device network parameters:",e),{city:"Unknown",region:"Unknown",country:"Unknown",timezone:"Unknown",loc:"Unknown",ip_address:"Unknown"}}}static async aquireAccessToken(e){try{return(await(await fetch(`${d.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:d.package,version:d.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw r.error("Error acquiring access token:",t),new Error("[CPIX] Authentication error")}}}class h{static isPresent(e){return typeof e<"u"&&e!==null&&e!==""}static now(){return 1*new Date().getTime()}static guid(){return w.version+"-xxxxxxxx-".replace(/[x]/g,function(e){const t=Math.random()*36|0;return(e=="x"?t:t&3|8).toString(36)})+(1*new Date().getTime()).toString(36)}static optionalData(e){return h.isPresent(e)===!1?"":typeof e=="object"?h.optionalData(JSON.stringify(e)):typeof e=="function"?h.optionalData(e()):String(e)}static sleep(e){return new Promise(t=>setTimeout(t,e))}}class y{static getParametersByName(e,t){t||(t=window.location.href),e=e.replace(/[[\]]/g,"\\$&");const i=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","gi"),n=[];let a;for(;(a=i.exec(t))!==null;)a[2]&&n.push(decodeURIComponent(a[2].replace(/\+/g," ")));return n.length>0?n:null}static externalHost(e){var t;return e.hostname!=location.hostname&&((t=e==null?void 0:e.protocol)==null?void 0:t.indexOf("http"))===0}}class s{static prefix(){return`__${d.TRACKER_FUNC_NAME}__`}static get(e){const t=`${s.prefix()}${e}`,i=document.cookie.split("; ").find(n=>n.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const n=`${s.prefix()}${e}`,a=new Date;a.setTime(a.getTime()+i*60*1e3),document.cookie=`${n}=${t}; expires=${a.toUTCString()}; path=/`}static delete(e){const t=`${s.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(s.prefix())).forEach(e=>{const t=e.split("=")[0];document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`})}static exists(e){return!!s.get(e)}static setUtms(){const e=x;let t=!1;for(let i=0;i<e.length;i++){const n=e[i];if(h.isPresent(y.getParametersByName(n,window.location.href))){t=!0;break}}if(t){let i;const n=[];for(let a=0;a<e.length;a++){const g=e[a];i=y.getParametersByName(g,window.location.href),n.push({[g]:i})}s.set(o.UTM,JSON.stringify(n),14*24*60)}}static getUtms(){const e=s.get(o.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){s.exists(o.SESSION)||s.set(o.SESSION,h.guid(),14*24*60),s.setUtms()}}class A{constructor(){c(this,"instances",[]);c(this,"initialized",!1);c(this,"accessToken","");c(this,"metaParameters",{});c(this,"queue");if(!window)throw new Error("[CPIX] CarterAnalytics SDK can only be used in a browser environment");this.queue=new b({maxRetries:d.QUEUE_MAX_RETRIES,initialDelay:d.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer.bind(this)})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(this.instances=e,d.API_URL=this.instances[0].options.tracker_server_url,s.exists(o.SESSION)||s.createSession(),s.exists(o.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{this.metaParameters=t,s.set("metaParameters",JSON.stringify(t),60*24)}),s.setUtms(),this.metaParameters=JSON.parse(s.get("metaParameters")),this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has already been initialized");if(!this.metaParameters)throw new Error("[CPIX] Meta parameters have not been generated");s.exists(o.ACCESS_TOKEN)||(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,r.debug("CPIX Initialized"),r.debug("Carter Analytics SDK initialized with options:",this.instances),d.DEBUG=this.instances[0].options.debug===!0,this.publish({event:"init",...this.metaParameters}),this.publish({event:"page_view",event_properties:{title:document.title,page:window.location.pathname,url:window.location.href},...this.metaParameters})}publish(e){if(!this.initialized)throw new Error("[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events.");const t={...e,...this.metaParameters};t.utm_params=s.getUtms(),document.referrer&&(t.referrer=encodeURIComponent(document.referrer)),r.debug("Publishing event:",t),this.queue.publish(t),e.event==="logout"&&(s.delete(o.SESSION),s.createSession(),this.generateMetaParameters().then(i=>{this.metaParameters=i,s.set(o.META_PARAMETERS,JSON.stringify(this.metaParameters),60*24)}))}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await m.getDeviceNetworkParameters();return{client_id:this.instances[0].client_id,session:s.get(o.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:m.getDeviceCategory(),brand:m.getDeviceManufacturer(),ip_address:e.ip_address,platform:m.getDevicePlatform()},referrer:encodeURIComponent(document.referrer)}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${d.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.get(o.ACCESS_TOKEN)}`}});if(!t.ok)throw t.status===401&&(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),s.set(o.ACCESS_TOKEN,this.accessToken,60*4)),new Error("[CPIX] Failed to publish event");r.debug("Event published:",t.ok)}catch(t){throw r.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new A;typeof window<"u"&&(window.cpix=v),u.CarterAnalytics=v,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})});
|
package/dist/main.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@carter-rmn/cpix-js",
|
|
3
|
-
"version": "1.0.0
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist"
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
"require": "./dist/cpix.umd.cjs"
|
|
15
15
|
}
|
|
16
16
|
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"dev": "vite",
|
|
19
|
+
"build": "tsc && vite build",
|
|
20
|
+
"preview": "vite preview"
|
|
21
|
+
},
|
|
17
22
|
"devDependencies": {
|
|
18
23
|
"picocolors": "^1.0.0",
|
|
19
24
|
"rollup-plugin-visualizer": "^5.12.0",
|
|
@@ -23,10 +28,5 @@
|
|
|
23
28
|
},
|
|
24
29
|
"dependencies": {
|
|
25
30
|
"vite-plugin-dts": "^3.8.1"
|
|
26
|
-
},
|
|
27
|
-
"scripts": {
|
|
28
|
-
"dev": "vite",
|
|
29
|
-
"build": "tsc && vite build",
|
|
30
|
-
"preview": "vite preview"
|
|
31
31
|
}
|
|
32
32
|
}
|
package/LICENCE
DELETED
|
@@ -1,32 +0,0 @@
|
|
|
1
|
-
Proprietary License
|
|
2
|
-
|
|
3
|
-
This software is licensed under the terms of this Proprietary License (the "License"). By using this software, you agree to comply with the terms of this License.
|
|
4
|
-
|
|
5
|
-
1. Grant of License
|
|
6
|
-
This software is licensed, not sold, to you by Carter Analytics for use only under the terms of this License. Carter Analytics retains ownership of the software itself and reserves all rights not expressly granted to you.
|
|
7
|
-
|
|
8
|
-
2. Permitted Use
|
|
9
|
-
You are granted a non-exclusive, non-transferable, limited license to use the software solely for your personal or internal business purposes, provided you have an active subscription to Carter Analytics's paid supporting service.
|
|
10
|
-
|
|
11
|
-
3. Restrictions
|
|
12
|
-
You may not:
|
|
13
|
-
a. Redistribute, sell, lease, sublicense, or otherwise transfer the software or any portion thereof.
|
|
14
|
-
b. Modify, adapt, translate, reverse engineer, decompile, or disassemble the software.
|
|
15
|
-
c. Remove or alter any proprietary notices or labels on the software.
|
|
16
|
-
|
|
17
|
-
4. Intellectual Property
|
|
18
|
-
All intellectual property rights in and to the software are and shall remain the exclusive property of Carter Analytics.
|
|
19
|
-
|
|
20
|
-
5. Disclaimer of Warranties
|
|
21
|
-
The software is provided "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose.
|
|
22
|
-
|
|
23
|
-
6. Limitation of Liability
|
|
24
|
-
In no event shall Carter Analytics be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or any other pecuniary loss) arising out of the use of or inability to use this software, even if Carter Analytics has been advised of the possibility of such damages.
|
|
25
|
-
|
|
26
|
-
7. Termination
|
|
27
|
-
This License is effective until terminated. Your rights under this License will terminate automatically without notice from Carter Analytics if you fail to comply with any term(s) of this License. Upon termination, you shall cease all use of the software and destroy all copies, full or partial, of the software.
|
|
28
|
-
|
|
29
|
-
8. Governing Law
|
|
30
|
-
This License shall be governed by and construed in accordance with the laws of [Your Jurisdiction].
|
|
31
|
-
|
|
32
|
-
By using this software, you acknowledge that you have read this License, understand it, and agree to be bound by its terms and conditions.
|