@carter-rmn/cpix-js 1.0.0-alpha.2 → 1.0.0-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ import { DeviceNetworkParameters } from '../types/common.types';
2
+
3
+ export default class Browser {
4
+ static getBrowserInfo(): string;
5
+ static getDeviceCategory(): string;
6
+ static getDevicePlatform(): string;
7
+ static getDeviceManufacturer(): string;
8
+ static getDeviceNetworkParameters(): Promise<DeviceNetworkParameters>;
9
+ static aquireAccessToken(accountId: string): Promise<string>;
10
+ }
@@ -0,0 +1,16 @@
1
+ export declare const CONFIG: {
2
+ DEBUG: boolean;
3
+ TRACKER_FUNC_NAME: string;
4
+ API_URL: string;
5
+ QUEUE_MAX_RETRIES: number;
6
+ QUEUE_INITIAL_DELAY: number;
7
+ version: string;
8
+ package: string;
9
+ };
10
+ export declare const COOKIE: {
11
+ SESSION: string;
12
+ META_PARAMETERS: string;
13
+ ACCESS_TOKEN: string;
14
+ UTM: string;
15
+ };
16
+ export declare const UTM_PARAMETERS: string[];
@@ -0,0 +1,11 @@
1
+ export default class Cookie {
2
+ static prefix(): string;
3
+ static get(name: string): string | undefined;
4
+ static set(name: string, value: string, minutes: number): void;
5
+ static delete(name: string): void;
6
+ static clear(): void;
7
+ static exists(name: string): boolean;
8
+ static setUtms(): void;
9
+ static getUtms(): any;
10
+ static createSession(): void;
11
+ }
@@ -0,0 +1,7 @@
1
+ export default class Helper {
2
+ static isPresent(variable: unknown): boolean;
3
+ static now(): number;
4
+ static guid(): string;
5
+ static optionalData(data: unknown): unknown;
6
+ static sleep(ms: number): Promise<unknown>;
7
+ }
@@ -0,0 +1,6 @@
1
+ declare const logger: {
2
+ info: (...args: unknown[]) => void;
3
+ debug: (...args: unknown[]) => void;
4
+ error: (...args: unknown[]) => void;
5
+ };
6
+ export default logger;
@@ -0,0 +1,28 @@
1
+ import { EnrichedEvent } from '../types/common.types';
2
+
3
+ export interface QueueMessage {
4
+ data: EnrichedEvent;
5
+ id: string;
6
+ retryCount: number;
7
+ retryDelay: number;
8
+ }
9
+ export interface QueueOptions {
10
+ maxRetries: number;
11
+ initialDelay: number;
12
+ consumerHandler: (message: EnrichedEvent) => Promise<void>;
13
+ }
14
+ export default class Queue extends EventTarget {
15
+ dataQueue: QueueMessage[];
16
+ retryQueue: QueueMessage[];
17
+ maxRetries: number;
18
+ initialDelay: number;
19
+ publishEvent: Event;
20
+ retryEvent: Event;
21
+ handler: (message: EnrichedEvent) => void;
22
+ constructor(options?: QueueOptions);
23
+ publish(data: EnrichedEvent): void;
24
+ consume(): void;
25
+ scheduleRetry(message: QueueMessage): void;
26
+ acknowledge(id: string): void;
27
+ retry(): void;
28
+ }
@@ -0,0 +1,4 @@
1
+ export default class Url {
2
+ static getParameterByName(name: string, url: string): string | null;
3
+ static externalHost(link: Record<string, any>): boolean;
4
+ }
package/dist/cpix.cjs ADDED
@@ -0,0 +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;
package/dist/cpix.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './main'
@@ -0,0 +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}({});
package/dist/cpix.js ADDED
@@ -0,0 +1,419 @@
1
+ var y = Object.defineProperty;
2
+ var v = (c, e, t) => e in c ? y(c, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : c[e] = t;
3
+ var a = (c, e, t) => (v(c, typeof e != "symbol" ? e + "" : e, t), t);
4
+ const E = "@carter-rmn/cpix-js", x = "1.0.0-alpha.4", S = "module", b = [
5
+ "dist"
6
+ ], A = "dist/cpix.umd.cjs", P = "dist/cpix.js", T = "dist/cpix.d.ts", _ = {
7
+ ".": {
8
+ import: "./dist/cpix.js",
9
+ require: "./dist/cpix.umd.cjs"
10
+ }
11
+ }, U = {
12
+ dev: "vite",
13
+ build: "tsc && vite build",
14
+ preview: "vite preview"
15
+ }, D = {
16
+ picocolors: "^1.0.0",
17
+ "rollup-plugin-visualizer": "^5.12.0",
18
+ typescript: "^5.2.2",
19
+ vite: "^5.2.0",
20
+ "vite-plugin-progress": "^0.0.7"
21
+ }, k = {
22
+ "vite-plugin-dts": "^3.8.1"
23
+ }, p = {
24
+ name: E,
25
+ version: x,
26
+ type: S,
27
+ files: b,
28
+ main: A,
29
+ module: P,
30
+ types: T,
31
+ exports: _,
32
+ scripts: U,
33
+ devDependencies: D,
34
+ dependencies: k
35
+ }, u = {
36
+ DEBUG: !1,
37
+ TRACKER_FUNC_NAME: "cpix",
38
+ API_URL: "https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda",
39
+ QUEUE_MAX_RETRIES: 3,
40
+ QUEUE_INITIAL_DELAY: 1e4,
41
+ version: p.version,
42
+ package: p.name
43
+ }, o = {
44
+ SESSION: "cpix_session",
45
+ META_PARAMETERS: "cpix_meta_parameters",
46
+ ACCESS_TOKEN: "cpix_access_token",
47
+ UTM: "cpix_utm"
48
+ }, C = [
49
+ "utm_source",
50
+ "utm_medium",
51
+ "utm_term",
52
+ "utm_content",
53
+ "utm_campaign",
54
+ "utm_source_platform",
55
+ "utm_creative_format",
56
+ "utm_marketing_tactic"
57
+ ], n = /* @__PURE__ */ function() {
58
+ const c = () => u.DEBUG;
59
+ return {
60
+ info: function(...e) {
61
+ console.log(...e);
62
+ },
63
+ debug: function(...e) {
64
+ c() && console.log(...e);
65
+ },
66
+ error: function(...e) {
67
+ console.error(...e);
68
+ }
69
+ };
70
+ }();
71
+ class I extends EventTarget {
72
+ constructor(t = {
73
+ maxRetries: 3,
74
+ initialDelay: 1e4,
75
+ consumerHandler: (i) => (n.debug("Consuming event:", i), Promise.resolve())
76
+ }) {
77
+ super();
78
+ a(this, "dataQueue");
79
+ a(this, "retryQueue");
80
+ a(this, "maxRetries");
81
+ a(this, "initialDelay");
82
+ a(this, "publishEvent");
83
+ a(this, "retryEvent");
84
+ a(this, "handler");
85
+ 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
+ }
87
+ publish(t) {
88
+ n.debug("publishing event");
89
+ const i = {
90
+ data: t,
91
+ id: `${Date.now() + Math.random()}`,
92
+ retryCount: 0,
93
+ retryDelay: this.initialDelay
94
+ };
95
+ this.dataQueue.push(i), this.dispatchEvent(this.publishEvent);
96
+ }
97
+ consume() {
98
+ n.debug("Started Consumer Queue"), this.addEventListener("eventPublished", async () => {
99
+ for (; this.dataQueue.length > 0; ) {
100
+ const t = this.dataQueue.shift(), { data: i = {} } = t;
101
+ try {
102
+ await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
103
+ } catch (r) {
104
+ n.error("Failed to publish event:", r), this.scheduleRetry(t);
105
+ }
106
+ }
107
+ });
108
+ }
109
+ scheduleRetry(t) {
110
+ if (t.retryCount >= this.maxRetries) {
111
+ n.error("Max retries reached for message:", t);
112
+ return;
113
+ }
114
+ setTimeout(() => {
115
+ this.retryQueue.push({
116
+ ...t,
117
+ retryCount: t.retryCount + 1,
118
+ retryDelay: t.retryDelay * 2
119
+ }), this.dispatchEvent(this.retryEvent);
120
+ }, t.retryDelay);
121
+ }
122
+ acknowledge(t) {
123
+ this.dataQueue = this.dataQueue.filter((i) => i.id !== t);
124
+ }
125
+ retry() {
126
+ n.debug("Started Retry Queue"), this.addEventListener("retryMessage", async () => {
127
+ for (; this.retryQueue.length > 0; ) {
128
+ const t = this.retryQueue.shift(), { data: i = {} } = t;
129
+ try {
130
+ await this.handler(i), this.acknowledge(t == null ? void 0 : t.id);
131
+ } catch (r) {
132
+ n.error("Failed to publish event:", r), this.scheduleRetry(t);
133
+ }
134
+ }
135
+ });
136
+ }
137
+ }
138
+ class m {
139
+ static getBrowserInfo() {
140
+ var r, l, h, f, g;
141
+ const e = navigator.userAgent || "";
142
+ let t, i;
143
+ 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}`;
144
+ }
145
+ static getDeviceCategory() {
146
+ const e = navigator.userAgent;
147
+ return /mobile/i.test(e) ? "Mobile" : /tablet/i.test(e) ? "Tablet" : "Desktop";
148
+ }
149
+ static getDevicePlatform() {
150
+ const e = navigator.userAgent;
151
+ 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";
152
+ }
153
+ static getDeviceManufacturer() {
154
+ const e = navigator.userAgent;
155
+ let t;
156
+ 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;
157
+ }
158
+ static async getDeviceNetworkParameters() {
159
+ try {
160
+ const e = await fetch(`${u.API_URL}/api/geolocation`), { data: t } = await e.json();
161
+ return {
162
+ city: t.city || "Unknown",
163
+ region: t.region || "Unknown",
164
+ country: t.country || "Unknown",
165
+ timezone: t.timezone || "Unknown",
166
+ loc: t.loc || "Unknown",
167
+ ip_address: t.ip_address || "Unknown"
168
+ };
169
+ } catch (e) {
170
+ return n.error("Error retrieving device network parameters:", e), {
171
+ city: "Unknown",
172
+ region: "Unknown",
173
+ country: "Unknown",
174
+ timezone: "Unknown",
175
+ loc: "Unknown",
176
+ ip_address: "Unknown"
177
+ };
178
+ }
179
+ }
180
+ static async aquireAccessToken(e) {
181
+ try {
182
+ return (await (await fetch(`${u.API_URL}/api/authenticate`, {
183
+ method: "POST",
184
+ headers: {
185
+ "Content-Type": "application/json"
186
+ },
187
+ body: JSON.stringify({
188
+ accountId: e,
189
+ metadata: {
190
+ sdk: u.package,
191
+ version: u.version,
192
+ hostname: window.location.hostname
193
+ }
194
+ })
195
+ })).json()).accessToken;
196
+ } catch (t) {
197
+ throw n.error("Error acquiring access token:", t), new Error("[CPIX] Authentication error");
198
+ }
199
+ }
200
+ }
201
+ class d {
202
+ static isPresent(e) {
203
+ return typeof e < "u" && e !== null && e !== "";
204
+ }
205
+ static now() {
206
+ return 1 * (/* @__PURE__ */ new Date()).getTime();
207
+ }
208
+ static guid() {
209
+ return p.version + "-xxxxxxxx-".replace(/[x]/g, function(e) {
210
+ const t = Math.random() * 36 | 0;
211
+ return (e == "x" ? t : t & 3 | 8).toString(36);
212
+ }) + (1 * (/* @__PURE__ */ new Date()).getTime()).toString(36);
213
+ }
214
+ // reduces all optional data down to a string
215
+ static optionalData(e) {
216
+ return d.isPresent(e) === !1 ? "" : typeof e == "object" ? d.optionalData(JSON.stringify(e)) : typeof e == "function" ? d.optionalData(e()) : String(e);
217
+ }
218
+ static sleep(e) {
219
+ return new Promise((t) => setTimeout(t, e));
220
+ }
221
+ }
222
+ class w {
223
+ static getParameterByName(e, t) {
224
+ t || (t = window.location.href), e = e.replace(/[[\]]/g, "\\$&");
225
+ const r = new RegExp("[?&]" + e + "(=([^&#]*)|&|#|$)", "i").exec(t);
226
+ return r ? r[2] ? decodeURIComponent(r[2].replace(/\+/g, " ")) : "" : null;
227
+ }
228
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
229
+ static externalHost(e) {
230
+ var t;
231
+ return e.hostname != location.hostname && ((t = e == null ? void 0 : e.protocol) == null ? void 0 : t.indexOf("http")) === 0;
232
+ }
233
+ }
234
+ class s {
235
+ static prefix() {
236
+ return `__${u.TRACKER_FUNC_NAME}__`;
237
+ }
238
+ static get(e) {
239
+ const t = `${s.prefix()}${e}`, i = document.cookie.split("; ").find((r) => r.startsWith(`${t}=`));
240
+ return i ? i.split("=")[1] : void 0;
241
+ }
242
+ static set(e, t, i) {
243
+ const r = `${s.prefix()}${e}`, l = /* @__PURE__ */ new Date();
244
+ l.setTime(l.getTime() + i * 60 * 1e3), document.cookie = `${r}=${t}; expires=${l.toUTCString()}; path=/`;
245
+ }
246
+ static delete(e) {
247
+ const t = `${s.prefix()}${e}`;
248
+ document.cookie = `${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
249
+ }
250
+ static clear() {
251
+ document.cookie.split("; ").filter((e) => e.startsWith(s.prefix())).forEach((e) => {
252
+ const t = e.split("=")[0];
253
+ document.cookie = `${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`;
254
+ });
255
+ }
256
+ static exists(e) {
257
+ return !!s.get(e);
258
+ }
259
+ static setUtms() {
260
+ const e = C;
261
+ let t = !1;
262
+ for (let i = 0; i < e.length; i++) {
263
+ const r = e[i];
264
+ if (d.isPresent(w.getParameterByName(r, window.location.href))) {
265
+ t = !0;
266
+ break;
267
+ }
268
+ }
269
+ if (t) {
270
+ let i = "";
271
+ const r = {};
272
+ for (let l = 0; l < e.length; l++) {
273
+ const h = e[l];
274
+ i = w.getParameterByName(h, window.location.href), d.isPresent(i) && (r[h] = i), r[h] = i;
275
+ }
276
+ s.set(o.UTM, JSON.stringify(r), 30);
277
+ }
278
+ }
279
+ static getUtms() {
280
+ const e = s.get(o.UTM);
281
+ return d.isPresent(e) ? JSON.parse(e) : {};
282
+ }
283
+ static createSession() {
284
+ s.exists(o.SESSION) || s.set(o.SESSION, d.guid(), 30 * 24 * 60), s.setUtms();
285
+ }
286
+ }
287
+ class N {
288
+ constructor() {
289
+ a(this, "instances", []);
290
+ a(this, "initialized", !1);
291
+ a(this, "accessToken", "");
292
+ a(this, "metaParameters", {});
293
+ a(this, "queue");
294
+ if (!window)
295
+ throw new Error(
296
+ "[CPIX] CarterAnalytics SDK can only be used in a browser environment"
297
+ );
298
+ this.queue = new I({
299
+ maxRetries: u.QUEUE_MAX_RETRIES,
300
+ initialDelay: u.QUEUE_INITIAL_DELAY,
301
+ consumerHandler: this.publishEventToServer.bind(this)
302
+ });
303
+ }
304
+ /**
305
+ * Initializes the CarterAnalytics SDK with the provided configuration options.
306
+ * @param options - The configuration options for initializing the SDK.
307
+ */
308
+ async initialize(e) {
309
+ if (!e || e.length === 0)
310
+ throw new Error(
311
+ "[CPIX] At least one instance configuration is required for initialization"
312
+ );
313
+ if (this.instances = e, s.exists(o.SESSION) || s.createSession(), s.exists(o.META_PARAMETERS) || await this.generateMetaParameters().then((t) => {
314
+ s.set("metaParameters", JSON.stringify(t), 60 * 24);
315
+ }), this.metaParameters = JSON.parse(s.get("metaParameters")), this.initialized)
316
+ throw new Error(
317
+ "[CPIX] CarterAnalytics SDK has already been initialized"
318
+ );
319
+ if (!this.metaParameters)
320
+ throw new Error("[CPIX] Meta parameters have not been generated");
321
+ s.exists(o.ACCESS_TOKEN) || (this.accessToken = await m.aquireAccessToken(
322
+ this.instances[0].client_id
323
+ ), s.set(o.ACCESS_TOKEN, this.accessToken, 60 * 4)), this.initialized = !0, n.debug("CPIX Initialized"), n.debug(
324
+ "Carter Analytics SDK initialized with options:",
325
+ this.instances
326
+ ), u.DEBUG = this.instances[0].options.debug === !0, u.API_URL = this.instances[0].options.tracker_server_url, this.publish({
327
+ event: "init",
328
+ ...this.metaParameters
329
+ }), this.publish({
330
+ event: "page_view",
331
+ event_properties: {
332
+ title: document.title,
333
+ page: window.location.pathname,
334
+ url: window.location.href
335
+ },
336
+ ...this.metaParameters
337
+ });
338
+ }
339
+ /**
340
+ * Publishes an event to the analytics queue.
341
+ * @param event - The event to be published.
342
+ */
343
+ publish(e) {
344
+ if (!this.initialized)
345
+ throw new Error(
346
+ "[CPIX] CarterAnalytics SDK has not been initialized. Please initialize before publishing events."
347
+ );
348
+ const t = {
349
+ ...e,
350
+ ...this.metaParameters
351
+ };
352
+ n.debug("Publishing event:", t), this.queue.publish(t), e.event === "logout" && (s.delete(o.SESSION), s.createSession(), this.generateMetaParameters().then((i) => {
353
+ this.metaParameters = i, s.set(
354
+ o.META_PARAMETERS,
355
+ JSON.stringify(this.metaParameters),
356
+ 60 * 24
357
+ );
358
+ }));
359
+ }
360
+ /**
361
+ * Generates meta parameters that is attached to every event before publishing.
362
+ */
363
+ async generateMetaParameters() {
364
+ if (!window)
365
+ throw new Error(
366
+ "[CPIX] Meta parameters can only be generated in a browser environment"
367
+ );
368
+ const e = await m.getDeviceNetworkParameters();
369
+ return {
370
+ client_id: this.instances[0].client_id,
371
+ session: s.get(o.SESSION),
372
+ location: {
373
+ city: e.city,
374
+ region: e.region,
375
+ loc: e.loc,
376
+ timezone: e.timezone,
377
+ country: e.country
378
+ },
379
+ device: {
380
+ category: m.getDeviceCategory(),
381
+ brand: m.getDeviceManufacturer(),
382
+ ip_address: e.ip_address,
383
+ platform: m.getDevicePlatform()
384
+ },
385
+ referrer: document.referrer,
386
+ utm_params: s.getUtms()
387
+ };
388
+ }
389
+ /**
390
+ * Publishes an event to the analytics server.
391
+ * @param message - The event to be published.
392
+ */
393
+ async publishEventToServer(e) {
394
+ try {
395
+ e.timestamp = Date.now();
396
+ const t = await fetch(`${u.API_URL}/api/event`, {
397
+ method: "POST",
398
+ body: JSON.stringify({ event_data: e }),
399
+ headers: {
400
+ "Content-Type": "application/json",
401
+ Authorization: `Bearer ${s.get(o.ACCESS_TOKEN)}`
402
+ }
403
+ });
404
+ if (!t.ok)
405
+ throw t.status === 401 && (this.accessToken = await m.aquireAccessToken(
406
+ this.instances[0].client_id
407
+ ), s.set(o.ACCESS_TOKEN, this.accessToken, 60 * 4)), new Error("[CPIX] Failed to publish event");
408
+ const i = await t.json();
409
+ n.debug("Event published:", i);
410
+ } catch (t) {
411
+ throw n.error("Failed to publish event:", t), new Error("[CPIX] Failed to publish event");
412
+ }
413
+ }
414
+ }
415
+ const R = new N();
416
+ typeof window < "u" && (window.cpix = R);
417
+ export {
418
+ R as CarterAnalytics
419
+ };
@@ -0,0 +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"})});
package/dist/logo.svg ADDED
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
package/dist/main.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { default as CarterAnalytics } from './modules/carter-analytics';
@@ -0,0 +1,34 @@
1
+ import { Event, Init } from '../types/common.types';
2
+
3
+ /**
4
+ * The `CarterAnalytics` class is responsible for initializing and publishing events to the analytics server.
5
+ */
6
+ declare class CarterAnalytics {
7
+ private instances;
8
+ private initialized;
9
+ private accessToken;
10
+ private metaParameters;
11
+ private queue;
12
+ constructor();
13
+ /**
14
+ * Initializes the CarterAnalytics SDK with the provided configuration options.
15
+ * @param options - The configuration options for initializing the SDK.
16
+ */
17
+ initialize(options: Init[]): Promise<void>;
18
+ /**
19
+ * Publishes an event to the analytics queue.
20
+ * @param event - The event to be published.
21
+ */
22
+ publish(event: Event): void;
23
+ /**
24
+ * Generates meta parameters that is attached to every event before publishing.
25
+ */
26
+ private generateMetaParameters;
27
+ /**
28
+ * Publishes an event to the analytics server.
29
+ * @param message - The event to be published.
30
+ */
31
+ private publishEventToServer;
32
+ }
33
+ declare const analytics: CarterAnalytics;
34
+ export default analytics;
@@ -0,0 +1,152 @@
1
+ import * as commonType from './common.types';
2
+ /**
3
+ * Represents the properties required to start a checkout.
4
+ */
5
+ export interface CheckoutStartProperties {
6
+ /**
7
+ * The token associated with the checkout.
8
+ */
9
+ token: string;
10
+ /**
11
+ * The total amount of the checkout.
12
+ */
13
+ amount: number;
14
+ /**
15
+ * The tax amount of the checkout.
16
+ */
17
+ tax: number;
18
+ /**
19
+ * The currency of the checkout.
20
+ */
21
+ currency: string;
22
+ /**
23
+ * The items in the checkout.
24
+ */
25
+ items: Array<commonType.CartProperties>;
26
+ /**
27
+ * The billing addresses associated with the checkout.
28
+ */
29
+ billing_address: Array<commonType.AddressProperties>;
30
+ /**
31
+ * The shipping addresses associated with the checkout.
32
+ */
33
+ shipping_address: Array<commonType.AddressProperties>;
34
+ /**
35
+ * The discounts applied to the checkout.
36
+ */
37
+ discount: Array<commonType.DiscountProperties>;
38
+ /**
39
+ * The delivery method of the checkout.
40
+ */
41
+ delivery_method: string;
42
+ /**
43
+ * The payment method of the checkout.
44
+ */
45
+ payment_method: string;
46
+ }
47
+ /**
48
+ * Represents the properties of a completed checkout.
49
+ */
50
+ export interface CheckoutCompletedProperties {
51
+ /**
52
+ * The token associated with the checkout.
53
+ */
54
+ token: string;
55
+ /**
56
+ * The order ID of the completed checkout.
57
+ */
58
+ order_id: string;
59
+ /**
60
+ * The total amount of the completed checkout.
61
+ */
62
+ amount: number;
63
+ /**
64
+ * The tax amount of the completed checkout.
65
+ */
66
+ tax: number;
67
+ /**
68
+ * The currency of the completed checkout.
69
+ */
70
+ currency: string;
71
+ /**
72
+ * The items in the completed checkout.
73
+ */
74
+ items: Array<commonType.CartProperties>;
75
+ /**
76
+ * The billing addresses associated with the completed checkout.
77
+ */
78
+ billing_address: Array<commonType.AddressProperties>;
79
+ /**
80
+ * The shipping addresses associated with the completed checkout.
81
+ */
82
+ shipping_address: Array<commonType.AddressProperties>;
83
+ /**
84
+ * The discounts applied to the completed checkout.
85
+ */
86
+ discount: Array<commonType.DiscountProperties>;
87
+ /**
88
+ * The delivery method of the completed checkout.
89
+ */
90
+ delivery_method: string;
91
+ /**
92
+ * The payment method of the completed checkout.
93
+ */
94
+ payment_method: string;
95
+ /**
96
+ * The transaction ID of the completed checkout.
97
+ */
98
+ transaction_id: string;
99
+ }
100
+ /**
101
+ * Represents the properties of a cancelled checkout.
102
+ */
103
+ export interface CheckoutCancelledProperties {
104
+ /**
105
+ * The token associated with the checkout.
106
+ */
107
+ token: string;
108
+ /**
109
+ * The total amount of the cancelled checkout.
110
+ */
111
+ amount: number;
112
+ /**
113
+ * The tax amount of the cancelled checkout.
114
+ */
115
+ tax: number;
116
+ /**
117
+ * The currency of the cancelled checkout.
118
+ */
119
+ currency: string;
120
+ /**
121
+ * The items in the cancelled checkout.
122
+ */
123
+ items: Array<commonType.CartProperties>;
124
+ /**
125
+ * The billing addresses associated with the cancelled checkout.
126
+ */
127
+ billing_address: Array<commonType.AddressProperties>;
128
+ /**
129
+ * The shipping addresses associated with the cancelled checkout.
130
+ */
131
+ shipping_address: Array<commonType.AddressProperties>;
132
+ /**
133
+ * The discounts applied to the cancelled checkout.
134
+ */
135
+ discount: Array<commonType.DiscountProperties>;
136
+ /**
137
+ * The delivery method of the cancelled checkout.
138
+ */
139
+ delivery_method: string;
140
+ /**
141
+ * The payment method of the cancelled checkout.
142
+ */
143
+ payment_method: string;
144
+ /**
145
+ * The transaction ID of the cancelled checkout.
146
+ */
147
+ transaction_id: string;
148
+ /**
149
+ * The reason for the cancellation of the checkout.
150
+ */
151
+ reason: string;
152
+ }
@@ -0,0 +1,330 @@
1
+ /**
2
+ * Represents the initialization options for the application.
3
+ */
4
+ export interface InitOptions {
5
+ debug?: boolean;
6
+ tracker_server_url: string;
7
+ }
8
+ /**
9
+ * Represents the initialization options for the application.
10
+ */
11
+ export interface Init {
12
+ /**
13
+ * The client ID for the application.
14
+ */
15
+ client_id: string;
16
+ /**
17
+ * Additional options for the application.
18
+ */
19
+ options: Record<string, unknown>;
20
+ }
21
+ /**
22
+ * Represents the event properties.
23
+ */
24
+ export interface EventProperties {
25
+ [key: string]: unknown;
26
+ }
27
+ /**
28
+ * Represents the user properties.
29
+ */
30
+ export interface UserProperties {
31
+ /**
32
+ * The user ID.
33
+ */
34
+ user_id: string;
35
+ [key: string]: unknown;
36
+ }
37
+ /**
38
+ * Represents the location information.
39
+ */
40
+ export interface Location {
41
+ /**
42
+ * The country.
43
+ */
44
+ country: string;
45
+ /**
46
+ * The region.
47
+ */
48
+ region: string;
49
+ /**
50
+ * The city.
51
+ */
52
+ city: string;
53
+ /**
54
+ * The location.
55
+ */
56
+ loc: string;
57
+ /**
58
+ * The timezone.
59
+ */
60
+ timezone: string;
61
+ }
62
+ /**
63
+ * Represents the device information.
64
+ */
65
+ export interface Device {
66
+ /**
67
+ * The category of the device.
68
+ */
69
+ category: string;
70
+ /**
71
+ * The brand of the device.
72
+ */
73
+ brand: string;
74
+ /**
75
+ * The IP address of the device.
76
+ */
77
+ ip_address: string;
78
+ /**
79
+ * The platform of the device.
80
+ */
81
+ platform: string;
82
+ }
83
+ /**
84
+ * Represents the meta parameters for an event.
85
+ */
86
+ export interface MetaParameters {
87
+ /**
88
+ * The client ID.
89
+ */
90
+ client_id?: string;
91
+ /**
92
+ * The session ID.
93
+ */
94
+ session?: string;
95
+ /**
96
+ * The location information.
97
+ */
98
+ location?: Location;
99
+ /**
100
+ * The device information.
101
+ */
102
+ device?: Device;
103
+ /**
104
+ * The timestamp of the event.
105
+ */
106
+ timestamp?: number;
107
+ /**
108
+ * The referrer URL.
109
+ */
110
+ referrer?: string;
111
+ /**
112
+ * The UTM parameters.
113
+ */
114
+ utm_params?: unknown;
115
+ }
116
+ /**
117
+ * Represents an event.
118
+ */
119
+ export interface Event {
120
+ /**
121
+ * The event name.
122
+ */
123
+ event: string;
124
+ /**
125
+ * The event properties.
126
+ */
127
+ event_properties?: EventProperties;
128
+ /**
129
+ * The user properties.
130
+ */
131
+ user_properties?: UserProperties;
132
+ }
133
+ export interface EnrichedEvent extends Event, MetaParameters {
134
+ }
135
+ /**
136
+ * Represents the properties of a product.
137
+ */
138
+ export interface ProductProperties {
139
+ /**
140
+ * The ID of the product.
141
+ */
142
+ id: string;
143
+ /**
144
+ * The SKU ID of the product.
145
+ */
146
+ sku_id?: string;
147
+ /**
148
+ * The price of the product.
149
+ */
150
+ price: number;
151
+ /**
152
+ * The currency of the product price.
153
+ */
154
+ currency: string;
155
+ /**
156
+ * The title of the product.
157
+ */
158
+ title: string;
159
+ /**
160
+ * The image URL of the product.
161
+ */
162
+ image_url?: string;
163
+ /**
164
+ * The product URL.
165
+ */
166
+ product_url?: string;
167
+ /**
168
+ * The affiliation of the product.
169
+ */
170
+ affiliation?: unknown;
171
+ /**
172
+ * The first-level category of the product.
173
+ */
174
+ product_category_1?: string;
175
+ /**
176
+ * The second-level category of the product.
177
+ */
178
+ product_category_2?: string;
179
+ /**
180
+ * The third-level category of the product.
181
+ */
182
+ product_category_3?: string;
183
+ /**
184
+ * The fourth-level category of the product.
185
+ */
186
+ product_category_4?: string;
187
+ /**
188
+ * The fifth-level category of the product.
189
+ */
190
+ product_category_5?: string;
191
+ [key: string]: unknown;
192
+ }
193
+ /**
194
+ * Represents the properties of a cart item.
195
+ */
196
+ export interface CartProperties {
197
+ /**
198
+ * The ID of the cart item.
199
+ */
200
+ id: string;
201
+ /**
202
+ * The SKU ID of the cart item.
203
+ */
204
+ sku_id?: string;
205
+ /**
206
+ * The price of the cart item.
207
+ */
208
+ price: number;
209
+ /**
210
+ * The currency of the cart item price.
211
+ */
212
+ currency: string;
213
+ /**
214
+ * The title of the cart item.
215
+ */
216
+ title: string;
217
+ /**
218
+ * The image URL of the cart item.
219
+ */
220
+ image_url?: string;
221
+ /**
222
+ * The product URL.
223
+ */
224
+ product_url?: string;
225
+ /**
226
+ * The affiliation of the cart item.
227
+ */
228
+ affiliation?: unknown;
229
+ /**
230
+ * The first-level category of the cart item.
231
+ */
232
+ product_category_1?: string;
233
+ /**
234
+ * The second-level category of the cart item.
235
+ */
236
+ product_category_2?: string;
237
+ /**
238
+ * The third-level category of the cart item.
239
+ */
240
+ product_category_3?: string;
241
+ /**
242
+ * The fourth-level category of the cart item.
243
+ */
244
+ product_category_4?: string;
245
+ /**
246
+ * The fifth-level category of the cart item.
247
+ */
248
+ product_category_5?: string;
249
+ /**
250
+ * The quantity of the cart item.
251
+ */
252
+ quantity: number;
253
+ /**
254
+ * The discount applied to the cart item.
255
+ */
256
+ discount: number;
257
+ /**
258
+ * The total amount of the cart item.
259
+ */
260
+ amount: number;
261
+ }
262
+ /**
263
+ * Represents the properties of an address.
264
+ */
265
+ export interface AddressProperties {
266
+ /**
267
+ * The address line 1.
268
+ */
269
+ address_line_1: string;
270
+ /**
271
+ * The address line 2.
272
+ */
273
+ address_line_2: string;
274
+ /**
275
+ * The city.
276
+ */
277
+ city: string;
278
+ /**
279
+ * The province.
280
+ */
281
+ province: string;
282
+ /**
283
+ * The province code.
284
+ */
285
+ province_code: string;
286
+ /**
287
+ * The Country.
288
+ */
289
+ country: string;
290
+ /**
291
+ * The country code.
292
+ */
293
+ country_code: string;
294
+ /**
295
+ * The first name.
296
+ */
297
+ first_name: string;
298
+ /**
299
+ * The last name.
300
+ */
301
+ last_name: string;
302
+ /**
303
+ * The phone number.
304
+ */
305
+ phone: string;
306
+ }
307
+ /**
308
+ * Represents the properties of a discount.
309
+ */
310
+ export interface DiscountProperties {
311
+ /**
312
+ * The application of the discount.
313
+ */
314
+ application: string;
315
+ /**
316
+ * The discount code.
317
+ */
318
+ code: string;
319
+ /**
320
+ * The amount of the discount.
321
+ */
322
+ amount: number;
323
+ /**
324
+ * The target of the discount.
325
+ */
326
+ target: string;
327
+ }
328
+ export interface DeviceNetworkParameters extends Location {
329
+ ip_address: string;
330
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Represents the properties for a search operation.
3
+ */
4
+ export interface SearchProperties {
5
+ /**
6
+ * The search query.
7
+ */
8
+ query: string;
9
+ }
10
+ /**
11
+ * Represents the properties for a signup operation.
12
+ */
13
+ export interface SignupProperties {
14
+ /**
15
+ * The signup method.
16
+ */
17
+ method: string;
18
+ /**
19
+ * The user ID.
20
+ */
21
+ user_id: string;
22
+ }
23
+ /**
24
+ * Represents the properties for a login operation.
25
+ */
26
+ export interface LoginProperties {
27
+ /**
28
+ * The login method.
29
+ */
30
+ method: string;
31
+ /**
32
+ * The user ID.
33
+ */
34
+ user_id: string;
35
+ }
@@ -0,0 +1,69 @@
1
+ import * as commonType from './common.types';
2
+ /**
3
+ * Represents the properties for adding items to a cart.
4
+ */
5
+ export interface AddToCartProperties {
6
+ /**
7
+ * The total amount of the cart.
8
+ */
9
+ cart_amount: number;
10
+ /**
11
+ * The currency of the cart amount.
12
+ */
13
+ currency: string;
14
+ /**
15
+ * The array of cart items.
16
+ */
17
+ cart_items: Array<commonType.CartProperties>;
18
+ }
19
+ /**
20
+ * Represents the properties for removing items from a cart.
21
+ */
22
+ export interface RemoveFromCartProperties {
23
+ /**
24
+ * The total amount of the cart.
25
+ */
26
+ cart_amount: number;
27
+ /**
28
+ * The currency of the cart amount.
29
+ */
30
+ currency: string;
31
+ /**
32
+ * The array of cart items.
33
+ */
34
+ cart_items: Array<commonType.CartProperties>;
35
+ }
36
+ /**
37
+ * Represents the properties for updating a cart.
38
+ */
39
+ export interface UpdateCartProperties {
40
+ /**
41
+ * The total amount of the cart.
42
+ */
43
+ cart_amount: number;
44
+ /**
45
+ * The currency of the cart amount.
46
+ */
47
+ currency: string;
48
+ /**
49
+ * The array of cart items.
50
+ */
51
+ cart_items: Array<commonType.CartProperties>;
52
+ }
53
+ /**
54
+ * Represents the properties for viewing a cart.
55
+ */
56
+ export interface ViewCartProperties {
57
+ /**
58
+ * The total amount of the cart.
59
+ */
60
+ cart_amount: number;
61
+ /**
62
+ * The currency of the cart amount.
63
+ */
64
+ currency: string;
65
+ /**
66
+ * The array of cart items.
67
+ */
68
+ cart_items: Array<commonType.CartProperties>;
69
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@carter-rmn/cpix-js",
3
- "version": "1.0.0-alpha.2",
3
+ "version": "1.0.0-alpha.4",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"