@carter-rmn/cpix-js 1.0.0-alpha.1

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/LICENCE ADDED
@@ -0,0 +1,32 @@
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.
package/README.md ADDED
@@ -0,0 +1,135 @@
1
+ # @carter-rmn/cpix
2
+
3
+ ## Overview
4
+
5
+ @carter-rmn/cpix is a JavaScript library for integrating Carter Analytics into your React applications. It provides an easy-to-use SDK for initializing and publishing events to Carter's analytics server.
6
+
7
+ ## Installation
8
+
9
+ To install the package, run the following command:
10
+
11
+ ```sh
12
+ npm install @carter-rmn/cpix
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ Below is an example of how to use the @carter-rmn/cpix package within a React application.
18
+
19
+ ## Example
20
+
21
+ ### ReactJS
22
+
23
+ ```jsx
24
+ import { useEffect } from 'react';
25
+ import reactLogo from './assets/react.svg';
26
+ import { CarterAnalytics } from '@carter-rmn/cpix';
27
+
28
+ const App = () => {
29
+ useEffect(() => {
30
+ CarterAnalytics.initialize([
31
+ {
32
+ client_id: '61e5cc16-f3aa-5e5d-9942-2e0cfefc75d3',
33
+ options: {
34
+ debug: false,
35
+ tracker_server_url: 'https://etg20oxcge.execute-api.ca-central-1.amazonaws.com/dev-lambda',
36
+ },
37
+ },
38
+ ]);
39
+ }, []);
40
+
41
+ const addToCart = () => {
42
+ CarterAnalytics.publish({
43
+ event: 'add_to_cart',
44
+ event_properties: {
45
+ product_id: '123',
46
+ product_name: 'Pixel 6',
47
+ quantity: 1,
48
+ price: 599,
49
+ },
50
+ });
51
+ };
52
+
53
+ return (
54
+ <div id="app">
55
+ <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank">
56
+ <img src={reactLogo} className="logo" alt="React logo" />
57
+ </a>
58
+ <h1>Carter Analytics | React SDK!</h1>
59
+ <div className="card">
60
+ <button type="button" onClick={addToCart}>
61
+ Publish Event
62
+ </button>
63
+ </div>
64
+ <p className="read-the-docs">Click on Publish Event Button</p>
65
+ <p className="read-the-docs">Open Dev Console</p>
66
+ </div>
67
+ );
68
+ };
69
+
70
+ export default App;
71
+ ```
72
+
73
+ ### Vanilla JavaScript
74
+
75
+ ```html
76
+ <script src="./node_modules/@carter-rmn/cpix/dist/cpix.iife.js"></script>
77
+ <script>
78
+ window.cpix.initialize([
79
+ {
80
+ client_id: 'API_KEY',
81
+ options: {
82
+ debug: true,
83
+ tracker_server_url: 'http://localhost:3001/events',
84
+ },
85
+ },
86
+ ]);
87
+ </script>
88
+ ```
89
+
90
+ ## Initialization
91
+
92
+ To initialize the Carter Analytics SDK, use the `CarterAnalytics.initialize` method. You need to pass an array of configuration objects, each containing a `client_id` and `options`.
93
+
94
+ ```js
95
+ CarterAnalytics.initialize([
96
+ {
97
+ client_id: 'your-client-id',
98
+ options: {
99
+ debug: false,
100
+ tracker_server_url: 'https://your-tracker-server-url',
101
+ },
102
+ },
103
+ ]);
104
+ ```
105
+
106
+
107
+
108
+ ## Publishing Events
109
+
110
+ To publish an event, use the `CarterAnalytics.publish` method. You need to specify the event name and the `event_properties`.
111
+
112
+ ```js
113
+ CarterAnalytics.publish({
114
+ event: 'event_name',
115
+ event_properties: {
116
+ key
117
+ // additional properties
118
+ },
119
+ });
120
+ ```
121
+
122
+ ## API
123
+
124
+ ### `CarterAnalytics.initialize(configurations)`
125
+
126
+ - `configurations`: An array of configuration objects.
127
+ - `client_id`: A string representing the client ID.
128
+ - `options`: An object containing additional options.
129
+ - `debug`: A boolean to enable or disable debug mode.
130
+ - `tracker_server_url`: A string representing the URL of the tracker server.
131
+
132
+ ### `CarterAnalytics.publish(eventData)`
133
+ - `eventData`: An object containing event data.
134
+ - `event`: A string representing the event name.
135
+ - `event_properties`: An object containing properties related to the event.
@@ -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=(o,e,t)=>e in o?v(o,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[e]=t;var a=(o,e,t)=>(E(o,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x="@carter-analytics/cpix",S="0.0.0",b="module",P=["dist"],A="dist/cpix.umd.cjs",_="dist/cpix.js",U="dist/cpix.d.ts",T={".":{import:"./dist/cpix.js",require:"./dist/cpix.umd.cjs"}},D={dev:"vite",build:"tsc && vite build",preview:"vite preview"},C={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:x,private:!0,version:S,type:b,files:P,main:A,module:_,types:U,exports:T,scripts:D,devDependencies:C,dependencies:I},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:p.version,package:p.name},l={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","utm_source_platform","utm_creative_format","utm_marketing_tactic"],n=function(){const o=()=>c.DEBUG;return{info:function(...e){console.log(...e)},debug:function(...e){o()&&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(s){n.error("Failed to publish event:",s),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(s){n.error("Failed to publish event:",s),this.scheduleRetry(t)}}})}}class m{static getBrowserInfo(){var s,u,h,f,g;const e=navigator.userAgent||"";let t,i;return/chrome/i.test(e)?(t="Chrome",i=(s=e.match(/chrome\/(\d+)/i))==null?void 0:s[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=(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(`${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 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(`${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 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 s=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)","i").exec(t);return s?s[2]?decodeURIComponent(s[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 r{static prefix(){return`__${c.TRACKER_FUNC_NAME}__`}static get(e){const t=`${r.prefix()}${e}`,i=document.cookie.split("; ").find(s=>s.startsWith(`${t}=`));return i?i.split("=")[1]:void 0}static set(e,t,i){const s=`${r.prefix()}${e}`,u=new Date;u.setTime(u.getTime()+i*60*1e3),document.cookie=`${s}=${t}; expires=${u.toUTCString()}; path=/`}static delete(e){const t=`${r.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(r.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!!r.get(e)}static setUtms(){const e=k;let t=!1;for(let i=0;i<e.length;i++){const s=e[i];if(d.isPresent(w.getParameterByName(s,window.location.href))){t=!0;break}}if(t){let i="";const s={};for(let u=0;u<e.length;u++){const h=e[u];i=w.getParameterByName(h,window.location.href),d.isPresent(i)&&(s[h]=i),s[h]=i}r.set(l.UTM,JSON.stringify(s),30)}}static getUtms(){const e=r.get(l.UTM);return d.isPresent(e)?JSON.parse(e):{}}static createSession(){r.exists(l.SESSION)||r.set(l.SESSION,d.guid(),30*24*60),r.setUtms()}}class R{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:c.QUEUE_MAX_RETRIES,initialDelay:c.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(r.exists(l.SESSION)||r.createSession(),r.exists(l.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{r.set("metaParameters",JSON.stringify(t),60*24)}),this.metaParameters=JSON.parse(r.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");this.instances=e,r.exists(l.ACCESS_TOKEN)||(this.accessToken=await m.aquireAccessToken(this.instances[0].client_id),r.set(l.ACCESS_TOKEN,this.accessToken,60*4)),this.initialized=!0,n.info("CPIX Initialized"),n.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.metaParameters.client_id=this.instances[0].client_id,r.set("metaParameters",JSON.stringify(this.metaParameters),60*24),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)}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await m.getDeviceNetworkParameters();return{session:r.get(l.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:r.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 ${r.get(l.ACCESS_TOKEN)}`}});if(!t.ok)throw 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 R;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 A=Object.defineProperty;var _=(l,d,m)=>d in l?A(l,d,{enumerable:!0,configurable:!0,writable:!0,value:m}):l[d]=m;var a=(l,d,m)=>(_(l,typeof d!="symbol"?d+"":d,m),m);const w={name:"@carter-analytics/cpix",private:!0,version:"0.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"}},o={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},c={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"],s=function(){const g=()=>o.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=>(s.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){s.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(){s.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){s.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}scheduleRetry(t){if(t.retryCount>=this.maxRetries){s.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(){s.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){s.error("Failed to publish event:",n),this.scheduleRetry(t)}}})}}class f{static getBrowserInfo(){var n,u,p,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=(u=e.match(/firefox\/(\d+)/i))==null?void 0:u[1]):/safari/i.test(e)?(t="Safari",i=(p=e.match(/version\/(\d+)/i))==null?void 0:p[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(`${o.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 s.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(`${o.API_URL}/api/authenticate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({accountId:e,metadata:{sdk:o.package,version:o.version,hostname:window.location.hostname}})})).json()).accessToken}catch(t){throw s.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 r{static prefix(){return`__${o.TRACKER_FUNC_NAME}__`}static get(e){const t=`${r.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=`${r.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=`${r.prefix()}${e}`;document.cookie=`${t}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/`}static clear(){document.cookie.split("; ").filter(e=>e.startsWith(r.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!!r.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 u=0;u<e.length;u++){const p=e[u];i=y.getParameterByName(p,window.location.href),h.isPresent(i)&&(n[p]=i),n[p]=i}r.set(c.UTM,JSON.stringify(n),30)}}static getUtms(){const e=r.get(c.UTM);return h.isPresent(e)?JSON.parse(e):{}}static createSession(){r.exists(c.SESSION)||r.set(c.SESSION,h.guid(),43200),r.setUtms()}}class P{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 b({maxRetries:o.QUEUE_MAX_RETRIES,initialDelay:o.QUEUE_INITIAL_DELAY,consumerHandler:this.publishEventToServer})}async initialize(e){if(!e||e.length===0)throw new Error("[CPIX] At least one instance configuration is required for initialization");if(r.exists(c.SESSION)||r.createSession(),r.exists(c.META_PARAMETERS)||await this.generateMetaParameters().then(t=>{r.set("metaParameters",JSON.stringify(t),1440)}),this.metaParameters=JSON.parse(r.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");this.instances=e,r.exists(c.ACCESS_TOKEN)||(this.accessToken=await f.aquireAccessToken(this.instances[0].client_id),r.set(c.ACCESS_TOKEN,this.accessToken,240)),this.initialized=!0,s.info("CPIX Initialized"),s.debug("Carter Analytics SDK initialized with options:",this.instances),o.DEBUG=this.instances[0].options.debug===!0,o.API_URL=this.instances[0].options.tracker_server_url,this.metaParameters.client_id=this.instances[0].client_id,r.set("metaParameters",JSON.stringify(this.metaParameters),1440),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};s.debug("Publishing event:",t),this.queue.publish(t)}async generateMetaParameters(){if(!window)throw new Error("[CPIX] Meta parameters can only be generated in a browser environment");const e=await f.getDeviceNetworkParameters();return{session:r.get(c.SESSION),location:{city:e.city,region:e.region,loc:e.loc,timezone:e.timezone,country:e.country},device:{category:f.getDeviceCategory(),brand:f.getDeviceManufacturer(),ip_address:e.ip_address,platform:f.getDevicePlatform()},referrer:document.referrer,utm_params:r.getUtms()}}async publishEventToServer(e){try{e.timestamp=Date.now();const t=await fetch(`${o.API_URL}/api/event`,{method:"POST",body:JSON.stringify({event_data:e}),headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.get(c.ACCESS_TOKEN)}`}});if(!t.ok)throw new Error("[CPIX] Failed to publish event");const i=await t.json();s.debug("Event published:",i)}catch(t){throw s.error("Failed to publish event:",t),new Error("[CPIX] Failed to publish event")}}}const v=new P;return typeof window<"u"&&(window.cpix=v),l.CarterAnalytics=v,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),l}({});