@altertable/altertable-js 1.0.4 → 1.0.6

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/dist/index.d.mts CHANGED
@@ -88,7 +88,7 @@ interface AltertableConfig {
88
88
  declare class Altertable {
89
89
  private _cleanupAutoCapture;
90
90
  private _config;
91
- private _eventQueue;
91
+ private _queue;
92
92
  private _isInitialized;
93
93
  private _lastUrl;
94
94
  private _logger;
@@ -148,7 +148,8 @@ declare class Altertable {
148
148
  * });
149
149
  * ```
150
150
  */
151
- identify(userId: string, traits?: UserTraits): void;
151
+ identify(userId: DistinctId, traits?: UserTraits): void;
152
+ private _identify;
152
153
  /**
153
154
  * Link a new ID to the current identity.
154
155
  *
@@ -160,6 +161,7 @@ declare class Altertable {
160
161
  * ```
161
162
  */
162
163
  alias(newUserId: DistinctId): void;
164
+ private _alias;
163
165
  /**
164
166
  * Updates user traits for the current user.
165
167
  *
@@ -173,6 +175,7 @@ declare class Altertable {
173
175
  * ```
174
176
  */
175
177
  updateTraits(traits: UserTraits): void;
178
+ private _updateTraits;
176
179
  /**
177
180
  * Resets device and session IDs.
178
181
  *
@@ -217,6 +220,7 @@ declare class Altertable {
217
220
  * - Server-side tracking where auto-capture isn't available
218
221
  */
219
222
  page(url: string): void;
223
+ private _page;
220
224
  /**
221
225
  * Tracks a custom event with optional properties.
222
226
  *
@@ -233,6 +237,7 @@ declare class Altertable {
233
237
  * ```
234
238
  */
235
239
  track(event: string, properties?: EventProperties): void;
240
+ private _track;
236
241
  /**
237
242
  * Returns the current tracking consent state.
238
243
  *
@@ -248,9 +253,13 @@ declare class Altertable {
248
253
  * ```
249
254
  */
250
255
  getTrackingConsent(): TrackingConsentType;
256
+ private _flushQueue;
257
+ private _executeQueueItem;
258
+ private _executeCommand;
251
259
  private _checkForChanges;
252
260
  private _getContext;
253
261
  private _processEvent;
262
+ private _sendEvent;
254
263
  }
255
264
 
256
265
  declare global {
package/dist/index.d.ts CHANGED
@@ -88,7 +88,7 @@ interface AltertableConfig {
88
88
  declare class Altertable {
89
89
  private _cleanupAutoCapture;
90
90
  private _config;
91
- private _eventQueue;
91
+ private _queue;
92
92
  private _isInitialized;
93
93
  private _lastUrl;
94
94
  private _logger;
@@ -148,7 +148,8 @@ declare class Altertable {
148
148
  * });
149
149
  * ```
150
150
  */
151
- identify(userId: string, traits?: UserTraits): void;
151
+ identify(userId: DistinctId, traits?: UserTraits): void;
152
+ private _identify;
152
153
  /**
153
154
  * Link a new ID to the current identity.
154
155
  *
@@ -160,6 +161,7 @@ declare class Altertable {
160
161
  * ```
161
162
  */
162
163
  alias(newUserId: DistinctId): void;
164
+ private _alias;
163
165
  /**
164
166
  * Updates user traits for the current user.
165
167
  *
@@ -173,6 +175,7 @@ declare class Altertable {
173
175
  * ```
174
176
  */
175
177
  updateTraits(traits: UserTraits): void;
178
+ private _updateTraits;
176
179
  /**
177
180
  * Resets device and session IDs.
178
181
  *
@@ -217,6 +220,7 @@ declare class Altertable {
217
220
  * - Server-side tracking where auto-capture isn't available
218
221
  */
219
222
  page(url: string): void;
223
+ private _page;
220
224
  /**
221
225
  * Tracks a custom event with optional properties.
222
226
  *
@@ -233,6 +237,7 @@ declare class Altertable {
233
237
  * ```
234
238
  */
235
239
  track(event: string, properties?: EventProperties): void;
240
+ private _track;
236
241
  /**
237
242
  * Returns the current tracking consent state.
238
243
  *
@@ -248,9 +253,13 @@ declare class Altertable {
248
253
  * ```
249
254
  */
250
255
  getTrackingConsent(): TrackingConsentType;
256
+ private _flushQueue;
257
+ private _executeQueueItem;
258
+ private _executeCommand;
251
259
  private _checkForChanges;
252
260
  private _getContext;
253
261
  private _processEvent;
262
+ private _sendEvent;
254
263
  }
255
264
 
256
265
  declare global {
@@ -1,9 +1,10 @@
1
- /*! @altertable/altertable-js 1.0.4 (UNRELEASED 5e3bf67) | MIT License | Altertable | https://github.com/altertable-ai/altertable-js */
2
- var Altertable=(()=>{var M=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var we=Object.getOwnPropertyNames;var De=Object.prototype.hasOwnProperty;var Re=(n,e)=>{for(var t in e)M(n,t,{get:e[t],enumerable:!0})},xe=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!De.call(n,r)&&r!==t&&M(n,r,{get:()=>e[r],enumerable:!(s=Ae(e,r))||s.enumerable});return n};var Pe=n=>xe(M({},"__esModule",{value:!0}),n);var ze={};Re(ze,{TrackingConsent:()=>a,altertable:()=>j});function H(n,e){return(...t)=>[n,...t].join(e)}var $e="atbl",B=H($e,"."),f=B("check"),J="session",Z="anonymous",ee="device",Ue=1e3*60,te=100,ne=30*Ue,se=1e3,re=5e3,oe="$pageview",ie="$lib",ae="$lib_version",ce="$referer",le="$release",h="$url",ge="$viewport",a={DENIED:"denied",DISMISSED:"dismissed",GRANTED:"granted",PENDING:"pending"},V=["anonymous_id","anonymous","distinct_id","distinctid","false","guest","id","not_authenticated","true","undefined","user_id","user","visitor_id","visitor"],q=new Set(["[object Object]","0","NaN","none","None","null"]);var A=class extends Error{constructor(e){super(e),this.name="AltertableError"}},m=class extends A{constructor(t,s,r,o,i){super(`HTTP ${t}: ${s}${r?` (${r})`:""}`);this.status=t;this.statusText=s;this.errorCode=r;this.details=o;this.requestContext=i;this.name="ApiError"}},w=class extends A{constructor(t,s){super(t);this.cause=s;this.name="NetworkError"}};function de(n){return n instanceof A}function ue(n){return n instanceof m}function pe(n){return n instanceof w}var x=class{_queue=[];_queueMaxSize;constructor(e){this._queueMaxSize=e}enqueue(e,t,s){this._queue.length>=this._queueMaxSize&&this._queue.shift(),this._queue.push({eventType:e,payload:t,context:s,sentAt:new Date})}flush(){let e=[...this._queue];return this._queue=[],e}clear(){this._queue=[]}getSize(){return this._queue.length}};function g(n,e){if(!n)throw new F(`[Altertable] ${typeof e=="function"?e():e}`)}var F=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};function _e(n=""){return`https://altertable.ai/dashboard${n}`}function fe(n){return{log:(...e)=>{console.log(`[${n}]`,...e)},logHeader:()=>{let e="Altertable v1.0.4 %c\u2022 Debug mode enabled";P.current[e]||(P.current[e]=!0,console.log(e,"color: #64748b;"))},logEvent:(e,{trackingConsent:t})=>{let[s,r]=z(e.event==="$pageview"?"Page":"Track"),[o,i]=Oe(e.event==="$pageview"?String(e.properties[h]):e.event),[l,d]=K(e.environment),[u,v]=Be(e.timestamp),[E,S]=Y(t);console.groupCollapsed(`[${n}] %c${s}%c ${o} %c[${l}] %c${u} %c${E}`,r,i,d,v,S);let[T,b]=p("User ID"),[k,C]=_(e.distinct_id??"Not set"),[Ie,ve]=p("Anonymous ID"),[Ee,Se]=_(e.anonymous_id??"Not set"),[Te,be]=p("Session ID"),[ke,Ce]=_(e.session_id??"Not set");console.log(`%c${T} %c${k}`,b,C),console.log(`%c${Ie} %c${Ee}`,ve,Se),console.log(`%c${Te} %c${ke}`,be,Ce),console.table(e.properties),console.groupEnd()},logIdentify:(e,{trackingConsent:t})=>{let[s,r]=z("Identify"),[o,i]=K(e.environment),[l,d]=Y(t);console.groupCollapsed(`[${n}] %c${s}%c ${e.distinct_id} %c[${o}] %c${l}`,r,"font-weight: 600;",i,d);let[u,v]=p("Distinct ID"),[E,S]=_(e.distinct_id??"Not set"),[T,b]=p("Anonymous ID"),[k,C]=_(e.anonymous_id??"Not set");console.log(`%c${u} %c${E}`,v,S),console.log(`%c${T} %c${k}`,b,C),console.table(e.traits),console.groupEnd()},logAlias:(e,{trackingConsent:t})=>{let[s,r]=z("Alias"),[o,i]=K(e.environment),[l,d]=Y(t);console.groupCollapsed(`[${n}] %c${s}%c ${e.distinct_id} %c[${o}] %c${l}`,r,"font-weight: 600;",i,d);let[u,v]=p("Distinct ID"),[E,S]=_(e.distinct_id??"Not set"),[T,b]=p("New User ID"),[k,C]=_(e.new_user_id??"Not set");console.log(`%c${u} %c${E}`,v,S),console.log(`%c${T} %c${k}`,b,C),console.groupEnd()},warn:(...e)=>{console.warn(`[${n}]`,...e)},warnDev:(e,...t)=>{return;if(!r){P.current[s]=!0;let o=`[${n}] ${s}`;console.warn(o,...t);try{throw new Error(o)}catch{}}},error:(...e)=>{console.error(`[${n}]`,...e)}}}var P={current:{}};function Ne(n){return new Date(n).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Le(n){switch(n){case"Page":return"#64748b";case"Identify":return"#a855f7";case"Track":return"#10b981";default:return"#1e293b"}}function z(n){return[n,`background: ${Le(n)}; color: #ffffff; padding: 2px 8px; border-radius: 6px; font-weight: 400;`]}function Oe(n){return[n==="$pageview"?"Page Viewed":n,"font-weight: 600;"]}function K(n){return[n,`color: ${Me(n)}; font-weight: 400;`]}function Me(n){switch(n.toLocaleLowerCase().startsWith("prod")?"production":n){case"production":return"#ef4444";default:return"#3b82f6"}}function Be(n){return[Ne(n),"color: #64748b; font-weight: 400;"]}function p(n){return[n,"color: #64748b; font-size: 11px;"]}function _(n){return[n,'background: #f8fafc; color: #1e293b; padding: 2px 8px; border: 1px solid #e2e8f0; border-radius: 6px; font-family: "SF Mono", "Monaco", monospace; font-size: 11px;']}function Y(n){switch(n){case a.GRANTED:return["",""];case a.DENIED:return["DENIED","background: #ef4444; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];case a.PENDING:case a.DISMISSED:return["PENDING","background: #f59e0b; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];default:return["UNKNOWN","background: #6b7280; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"]}}function G(n){try{let e=new URL(n);return{baseUrl:`${e.origin}${e.pathname}`,searchParams:Object.fromEntries(e.searchParams)}}catch{return null}}function he(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}var $=class{_config;constructor(e){this._config=e}_constructUrl(e){return`${this._config.baseUrl}${e}?apiKey=${encodeURIComponent(this._config.apiKey)}`}async send(e,t){return he()?this._sendWithBeacon(e,t):this._sendWithFetch(e,t)}async _sendWithBeacon(e,t){let s=this._constructUrl(e),r=new Blob([JSON.stringify(t)],{type:"application/json"});try{if(!navigator.sendBeacon(s,r))return this._sendWithFetch(e,t)}catch{return this._sendWithFetch(e,t)}}async _sendWithFetch(e,t){let s=this._constructUrl(e),r=new AbortController,o=setTimeout(()=>r.abort(),this._config.requestTimeout);try{let i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:r.signal});if(!i.ok){let l;try{l=await i.json()}catch{}throw new m(i.status,i.statusText,l?.error_code,l,{url:s,method:"POST",payload:t})}}catch(i){throw i instanceof m?i:new w(i instanceof Error?i.message:"Network request failed",i)}finally{clearTimeout(o)}}};function c(n,e=()=>{}){return typeof window>"u"?e():n({window})}function U(n){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")try{return`${n}-${crypto.randomUUID()}`}catch{}return`${n}-${Math.random().toString(36).substring(2)}`}var N=class{_defaultTrackingConsent;_logger;_sessionData;_storage;_storageKey;constructor(e){this._storage=e.storage,this._storageKey=e.storageKey,this._logger=e.logger,this._defaultTrackingConsent=e.defaultTrackingConsent??a.PENDING,this._sessionData=this._createDefaultSessionData()}init(){let e=this._storage.getItem(this._storageKey);if(!e){this._sessionData=this._createDefaultSessionData(),this._persistToStorage();return}try{let t=JSON.parse(e);this._sessionData={deviceId:t.deviceId||this._generateDeviceId(),distinctId:t.distinctId||this._generateAnonymousId(),sessionId:t.sessionId||this._generateSessionId(),anonymousId:t.anonymousId||null,lastEventAt:t.lastEventAt||null,trackingConsent:Ve(t.trackingConsent)?t.trackingConsent:this._defaultTrackingConsent}}catch{this._logger.warnDev("Failed to parse storage data. Resetting session data."),this._sessionData=this._createDefaultSessionData()}this._persistToStorage()}getSessionId(){return this._sessionData.sessionId}getDeviceId(){return this._sessionData.deviceId}getDistinctId(){return this._sessionData.distinctId}getAnonymousId(){return this._sessionData.anonymousId}isIdentified(){return!!this._sessionData.anonymousId}getLastEventAt(){return this._sessionData.lastEventAt}getTrackingConsent(){return this._sessionData.trackingConsent}identify(e){this._sessionData.anonymousId=this._sessionData.distinctId,this._sessionData.distinctId=e,this._persistToStorage()}setTrackingConsent(e){this._sessionData.trackingConsent=e,this._persistToStorage()}updateLastEventAt(e){this._sessionData.lastEventAt=e,this._persistToStorage()}renewSessionIfNeeded(){return this._shouldRenewSession()?(this._renewSession(),this._persistToStorage(),!0):!1}reset({resetDeviceId:e=!1,resetTrackingConsent:t=!1}={}){e&&(this._sessionData.deviceId=this._generateDeviceId()),t&&(this._sessionData.trackingConsent=this._defaultTrackingConsent),this._sessionData.sessionId=this._generateSessionId(),this._sessionData.anonymousId=null,this._sessionData.distinctId=this._generateAnonymousId(),this._sessionData.lastEventAt=null,this._persistToStorage()}_createDefaultSessionData(){return{anonymousId:null,deviceId:this._generateDeviceId(),distinctId:this._generateAnonymousId(),lastEventAt:null,sessionId:this._generateSessionId(),trackingConsent:this._defaultTrackingConsent}}_generateSessionId(){return U(J)}_generateDeviceId(){return U(ee)}_generateAnonymousId(){return U(Z)}_shouldRenewSession(){let{lastEventAt:e}=this._sessionData;if(!e)return!0;let t=new Date().getTime(),s=new Date(e).getTime();return t-s>ne}_renewSession(){this._sessionData.sessionId=this._generateSessionId(),this._sessionData.lastEventAt=null}_persistToStorage(){try{this._storage.setItem(this._storageKey,JSON.stringify(this._sessionData))}catch{this._logger.warnDev("Failed to persist session data to storage.")}}};function Ve(n){return typeof n=="string"&&Object.values(a).includes(n)}function Q(n,e,t){for(let s of t){let r=e.getItem(s);r!==null&&(n.setItem(s,r),e.removeItem(s))}}var y=class{store={};getItem(e){return this.store[e]??null}setItem(e,t){this.store[e]=t}removeItem(e){delete this.store[e]}migrate(e,t){Q(this,e,t)}},R=class{getItem(e){return c(({window:t})=>{let s=t.document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return s?decodeURIComponent(s[2]):null},()=>null)}setItem(e,t){c(({window:s})=>{s.document.cookie=`${e}=${encodeURIComponent(t)}; path=/;`})}removeItem(e){c(({window:t})=>{t.document.cookie=`${e}=; Max-Age=0; path=/;`})}migrate(e,t){Q(this,e,t)}},I=class{constructor(e){this.storage=e}getItem(e){return c(({window:t})=>{try{return t[this.storage].getItem(e)}catch{return null}},()=>null)}setItem(e,t){c(({window:s})=>{try{s[this.storage].setItem(e,t)}catch{}})}removeItem(e){c(({window:t})=>{try{t[this.storage].removeItem(e)}catch{}})}migrate(e,t){Q(this,e,t)}},W=class{localStore=new I("localStorage");cookieStore=new R;getItem(e){return this.localStore.getItem(e)??this.cookieStore.getItem(e)}setItem(e,t){this.localStore.setItem(e,t),this.cookieStore.setItem(e,t)}removeItem(e){this.localStore.removeItem(e),this.cookieStore.removeItem(e)}migrate(e,t){for(let s of t){let r=e.getItem(s);r!==null&&(this.localStore.setItem(s,r),this.cookieStore.setItem(s,r))}for(let s of t)e.removeItem(s)}};function D(n){return c(({window:e})=>{try{if(n==="cookie"){e.document.cookie=`${f}=1`;let t=e.document.cookie.indexOf(`${f}=`)!==-1;return e.document.cookie=`${f}=; Max-Age=0`,t}else return e[n].setItem(f,"1"),e[n].removeItem(f),!0}catch{return!1}},()=>!1)}function L(n,e){let{onFallback:t}=e;switch(n){case"localStorage":return D("localStorage")?new I("localStorage"):(t("localStorage not supported, falling back to localStorage+cookie."),L("localStorage+cookie",e));case"localStorage+cookie":{let s=D("localStorage"),r=D("cookie");return s&&r?new W:r?(t("localStorage+cookie not fully supported, falling back to cookie."),new R):s?(t("cookie not supported, falling back to localStorage."),new I("localStorage")):(t("Neither localStorage nor cookie supported, falling back to memory."),new y)}case"sessionStorage":return D("sessionStorage")?new I("sessionStorage"):(t("sessionStorage not supported, falling back to memory."),new y);case"cookie":return D("cookie")?new R:(t("cookie not supported, falling back to memory."),new y);case"memory":return new y;default:throw new Error(`Unknown storage type: "${n}". Valid types are: localStorage, sessionStorage, cookie, memory, localStorage+cookie.`)}}var qe=[...V,...q].map(n=>`- "${n}"`).join(`
3
- `),me=`List of reserved identifiers:
4
- ${qe}`;function X(n){if(!n||n.trim()==="")throw new Error("User ID cannot be empty or contain only whitespace.");if(V.some(s=>n.toLowerCase()===s.toLowerCase()))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
1
+ /*! @altertable/altertable-js 1.0.6 (UNRELEASED 8b22b09) | MIT License | Altertable | https://github.com/altertable-ai/altertable-js */
2
+ var Altertable=(()=>{var V=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Re=Object.prototype.hasOwnProperty;var Pe=(n,e)=>{for(var t in e)V(n,t,{get:e[t],enumerable:!0})},xe=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ae(e))!Re.call(n,s)&&s!==t&&V(n,s,{get:()=>e[s],enumerable:!(r=we(e,s))||r.enumerable});return n};var $e=n=>xe(V({},"__esModule",{value:!0}),n);var ze={};Pe(ze,{TrackingConsent:()=>o,altertable:()=>Z});function ee(n,e){return(...t)=>[n,...t].join(e)}var Ue="atbl",q=ee(Ue,"."),f=q("check"),te="session",ne="anonymous",re="device",Ne=1e3*60,se=100,ie=30*Ne,F=1e3,oe=5e3,ae="$pageview",ce="$lib",le="$lib_version",ge="$referer",ue="$release",y="$url",de="$viewport",o={DENIED:"denied",DISMISSED:"dismissed",GRANTED:"granted",PENDING:"pending"},Q=["anonymous_id","anonymous","distinct_id","distinctid","false","guest","id","not_authenticated","true","undefined","user_id","user","visitor_id","visitor"],z=new Set(["[object Object]","0","NaN","none","None","null"]);var C=class extends Error{constructor(e){super(e),this.name="AltertableError"}},I=class extends C{constructor(t,r,s,c,i){super(`HTTP ${t}: ${r}${s?` (${s})`:""}`);this.status=t;this.statusText=r;this.errorCode=s;this.details=c;this.requestContext=i;this.name="ApiError"}},D=class extends C{constructor(t,r){super(t);this.cause=r;this.name="NetworkError"}};function pe(n){return n instanceof C}function me(n){return n instanceof I}function _e(n){return n instanceof D}function w(n,e){if(!n)throw new G(`[Altertable] ${typeof e=="function"?e():e}`)}var G=class n extends Error{constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};function he(n=""){return`https://altertable.ai/dashboard${n}`}function fe(n){return{log:(...e)=>{console.log(`[${n}]`,...e)},logHeader:()=>{let e="Altertable v1.0.6 %c\u2022 Debug mode enabled";P.current[e]||(P.current[e]=!0,console.log(e,"color: #64748b;"))},logEvent:(e,{trackingConsent:t})=>{let[r,s]=K(e.event==="$pageview"?"Page":"Track"),[c,i]=Be(e.event==="$pageview"?String(e.properties[y]):e.event),[l,g]=Y(e.environment),[u,p]=Ve(e.timestamp),[d,m]=W(t);console.groupCollapsed(`[${n}] %c${r}%c ${c} %c[${l}] %c${u} %c${d}`,s,i,g,p,m);let[S,T]=_("User ID"),[k,b]=h(e.distinct_id??"Not set"),[ve,Ee]=_("Anonymous ID"),[Se,Te]=h(e.anonymous_id??"Not set"),[ke,be]=_("Session ID"),[Ce,De]=h(e.session_id??"Not set");console.log(`%c${S} %c${k}`,T,b),console.log(`%c${ve} %c${Se}`,Ee,Te),console.log(`%c${ke} %c${Ce}`,be,De),console.table(e.properties),console.groupEnd()},logIdentify:(e,{trackingConsent:t})=>{let[r,s]=K("Identify"),[c,i]=Y(e.environment),[l,g]=W(t);console.groupCollapsed(`[${n}] %c${r}%c ${e.distinct_id} %c[${c}] %c${l}`,s,"font-weight: 600;",i,g);let[u,p]=_("Distinct ID"),[d,m]=h(e.distinct_id??"Not set"),[S,T]=_("Anonymous ID"),[k,b]=h(e.anonymous_id??"Not set");console.log(`%c${u} %c${d}`,p,m),console.log(`%c${S} %c${k}`,T,b),console.table(e.traits),console.groupEnd()},logAlias:(e,{trackingConsent:t})=>{let[r,s]=K("Alias"),[c,i]=Y(e.environment),[l,g]=W(t);console.groupCollapsed(`[${n}] %c${r}%c ${e.distinct_id} %c[${c}] %c${l}`,s,"font-weight: 600;",i,g);let[u,p]=_("Distinct ID"),[d,m]=h(e.distinct_id??"Not set"),[S,T]=_("New User ID"),[k,b]=h(e.new_user_id??"Not set");console.log(`%c${u} %c${d}`,p,m),console.log(`%c${S} %c${k}`,T,b),console.groupEnd()},warn:(...e)=>{console.warn(`[${n}]`,...e)},warnDev:(e,...t)=>{return;if(!s){P.current[r]=!0;let c=`[${n}] ${r}`;console.warn(c,...t);try{throw new Error(c)}catch{}}},error:(...e)=>{console.error(`[${n}]`,...e)}}}var P={current:{}};function Le(n){return new Date(n).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}function Oe(n){switch(n){case"Page":return"#64748b";case"Identify":return"#a855f7";case"Track":return"#10b981";default:return"#1e293b"}}function K(n){return[n,`background: ${Oe(n)}; color: #ffffff; padding: 2px 8px; border-radius: 6px; font-weight: 400;`]}function Be(n){return[n==="$pageview"?"Page Viewed":n,"font-weight: 600;"]}function Y(n){return[n,`color: ${Me(n)}; font-weight: 400;`]}function Me(n){switch(n.toLocaleLowerCase().startsWith("prod")?"production":n){case"production":return"#ef4444";default:return"#3b82f6"}}function Ve(n){return[Le(n),"color: #64748b; font-weight: 400;"]}function _(n){return[n,"color: #64748b; font-size: 11px;"]}function h(n){return[n,'background: #f8fafc; color: #1e293b; padding: 2px 8px; border: 1px solid #e2e8f0; border-radius: 6px; font-family: "SF Mono", "Monaco", monospace; font-size: 11px;']}function W(n){switch(n){case o.GRANTED:return["",""];case o.DENIED:return["DENIED","background: #ef4444; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];case o.PENDING:case o.DISMISSED:return["PENDING","background: #f59e0b; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"];default:return["UNKNOWN","background: #6b7280; color: #ffffff; padding: 2px 6px; border-radius: 4px; font-size: 10px; font-weight: 600;"]}}function X(n){try{let e=new URL(n);return{baseUrl:`${e.origin}${e.pathname}`,searchParams:Object.fromEntries(e.searchParams)}}catch{return null}}var x=class{_items=[];_maxSize;_onDropOldest;constructor(e){this._maxSize=e.capacity,this._onDropOldest=e.onDropOldest}enqueue(e){if(this._items.length>=this._maxSize){let t=this._items.shift();t&&this._onDropOldest?.(t)}this._items.push(e)}flush(){let e=[...this._items];return this._items=[],e}clear(){this._items=[]}getSize(){return this._items.length}getAll(){return this._items}};function ye(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.sendBeacon=="function"}var $=class{_config;constructor(e){this._config=e}_constructUrl(e){return`${this._config.baseUrl}${e}?apiKey=${encodeURIComponent(this._config.apiKey)}`}async send(e,t){return ye()?this._sendWithBeacon(e,t):this._sendWithFetch(e,t)}async _sendWithBeacon(e,t){let r=this._constructUrl(e),s=new Blob([JSON.stringify(t)],{type:"application/json"});try{if(!navigator.sendBeacon(r,s))return this._sendWithFetch(e,t)}catch{return this._sendWithFetch(e,t)}}async _sendWithFetch(e,t){let r=this._constructUrl(e),s=new AbortController,c=setTimeout(()=>s.abort(),this._config.requestTimeout);try{let i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:!0,signal:s.signal});if(!i.ok){let l;try{l=await i.json()}catch{}throw new I(i.status,i.statusText,l?.error_code,l,{url:r,method:"POST",payload:t})}}catch(i){throw i instanceof I?i:new D(i instanceof Error?i.message:"Network request failed",i)}finally{clearTimeout(c)}}};function a(n,e=()=>{}){return typeof window>"u"?e():n({window})}function U(){return a(({window:n})=>`${n.innerWidth}x${n.innerHeight}`,()=>null)}function N(){return{timestamp:new Date().toISOString(),url:a(({window:n})=>n.location.href||null,()=>null),referrer:a(({window:n})=>n.document.referrer||null,()=>null),viewport:U()}}function L(n){if(typeof globalThis.crypto<"u"&&typeof globalThis.crypto.randomUUID=="function")try{return`${n}-${crypto.randomUUID()}`}catch{}return`${n}-${Math.random().toString(36).substring(2)}`}var O=class{_defaultTrackingConsent;_logger;_sessionData;_storage;_storageKey;constructor(e){this._storage=e.storage,this._storageKey=e.storageKey,this._logger=e.logger,this._defaultTrackingConsent=e.defaultTrackingConsent??o.PENDING,this._sessionData=this._createDefaultSessionData()}init(){let e=this._storage.getItem(this._storageKey);if(!e){this._sessionData=this._createDefaultSessionData(),this._persistToStorage();return}try{let t=JSON.parse(e);this._sessionData={deviceId:t.deviceId||this._generateDeviceId(),distinctId:t.distinctId||this._generateAnonymousId(),sessionId:t.sessionId||this._generateSessionId(),anonymousId:t.anonymousId||null,lastEventAt:t.lastEventAt||null,trackingConsent:qe(t.trackingConsent)?t.trackingConsent:this._defaultTrackingConsent}}catch{this._logger.warnDev("Failed to parse storage data. Resetting session data."),this._sessionData=this._createDefaultSessionData()}this._persistToStorage()}getSessionId(){return this._sessionData.sessionId}getDeviceId(){return this._sessionData.deviceId}getDistinctId(){return this._sessionData.distinctId}getAnonymousId(){return this._sessionData.anonymousId}isIdentified(){return!!this._sessionData.anonymousId}getLastEventAt(){return this._sessionData.lastEventAt}getTrackingConsent(){return this._sessionData.trackingConsent}identify(e){this._sessionData.anonymousId=this._sessionData.distinctId,this._sessionData.distinctId=e,this._persistToStorage()}setTrackingConsent(e){this._sessionData.trackingConsent=e,this._persistToStorage()}updateLastEventAt(e){this._sessionData.lastEventAt=e,this._persistToStorage()}renewSessionIfNeeded(){return this._shouldRenewSession()?(this._renewSession(),this._persistToStorage(),!0):!1}reset({resetDeviceId:e=!1,resetTrackingConsent:t=!1}={}){e&&(this._sessionData.deviceId=this._generateDeviceId()),t&&(this._sessionData.trackingConsent=this._defaultTrackingConsent),this._sessionData.sessionId=this._generateSessionId(),this._sessionData.anonymousId=null,this._sessionData.distinctId=this._generateAnonymousId(),this._sessionData.lastEventAt=null,this._persistToStorage()}_createDefaultSessionData(){return{anonymousId:null,deviceId:this._generateDeviceId(),distinctId:this._generateAnonymousId(),lastEventAt:null,sessionId:this._generateSessionId(),trackingConsent:this._defaultTrackingConsent}}_generateSessionId(){return L(te)}_generateDeviceId(){return L(re)}_generateAnonymousId(){return L(ne)}_shouldRenewSession(){let{lastEventAt:e}=this._sessionData;if(!e)return!0;let t=new Date().getTime(),r=new Date(e).getTime();return t-r>ie}_renewSession(){this._sessionData.sessionId=this._generateSessionId(),this._sessionData.lastEventAt=null}_persistToStorage(){try{this._storage.setItem(this._storageKey,JSON.stringify(this._sessionData))}catch{this._logger.warnDev("Failed to persist session data to storage.")}}};function qe(n){return typeof n=="string"&&Object.values(o).includes(n)}function H(n,e,t){for(let r of t){let s=e.getItem(r);s!==null&&(n.setItem(r,s),e.removeItem(r))}}var v=class{store={};getItem(e){return this.store[e]??null}setItem(e,t){this.store[e]=t}removeItem(e){delete this.store[e]}migrate(e,t){H(this,e,t)}},R=class{getItem(e){return a(({window:t})=>{let r=t.document.cookie.match(new RegExp("(^| )"+e+"=([^;]+)"));return r?decodeURIComponent(r[2]):null},()=>null)}setItem(e,t){a(({window:r})=>{r.document.cookie=`${e}=${encodeURIComponent(t)}; path=/;`})}removeItem(e){a(({window:t})=>{t.document.cookie=`${e}=; Max-Age=0; path=/;`})}migrate(e,t){H(this,e,t)}},E=class{constructor(e){this.storage=e}getItem(e){return a(({window:t})=>{try{return t[this.storage].getItem(e)}catch{return null}},()=>null)}setItem(e,t){a(({window:r})=>{try{r[this.storage].setItem(e,t)}catch{}})}removeItem(e){a(({window:t})=>{try{t[this.storage].removeItem(e)}catch{}})}migrate(e,t){H(this,e,t)}},j=class{localStore=new E("localStorage");cookieStore=new R;getItem(e){return this.localStore.getItem(e)??this.cookieStore.getItem(e)}setItem(e,t){this.localStore.setItem(e,t),this.cookieStore.setItem(e,t)}removeItem(e){this.localStore.removeItem(e),this.cookieStore.removeItem(e)}migrate(e,t){for(let r of t){let s=e.getItem(r);s!==null&&(this.localStore.setItem(r,s),this.cookieStore.setItem(r,s))}for(let r of t)e.removeItem(r)}};function A(n){return a(({window:e})=>{try{if(n==="cookie"){e.document.cookie=`${f}=1`;let t=e.document.cookie.indexOf(`${f}=`)!==-1;return e.document.cookie=`${f}=; Max-Age=0`,t}else return e[n].setItem(f,"1"),e[n].removeItem(f),!0}catch{return!1}},()=>!1)}function B(n,e){let{onFallback:t}=e;switch(n){case"localStorage":return A("localStorage")?new E("localStorage"):(t("localStorage not supported, falling back to localStorage+cookie."),B("localStorage+cookie",e));case"localStorage+cookie":{let r=A("localStorage"),s=A("cookie");return r&&s?new j:s?(t("localStorage+cookie not fully supported, falling back to cookie."),new R):r?(t("cookie not supported, falling back to localStorage."),new E("localStorage")):(t("Neither localStorage nor cookie supported, falling back to memory."),new v)}case"sessionStorage":return A("sessionStorage")?new E("sessionStorage"):(t("sessionStorage not supported, falling back to memory."),new v);case"cookie":return A("cookie")?new R:(t("cookie not supported, falling back to memory."),new v);case"memory":return new v;default:throw new Error(`Unknown storage type: "${n}". Valid types are: localStorage, sessionStorage, cookie, memory, localStorage+cookie.`)}}var Fe=[...Q,...z].map(n=>`- "${n}"`).join(`
3
+ `),Ie=`List of reserved identifiers:
4
+ ${Fe}`;function J(n){if(!n||n.trim()==="")throw new Error("User ID cannot be empty or contain only whitespace.");if(Q.some(r=>n.toLowerCase()===r.toLowerCase()))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
5
5
 
6
- `+me);if(q.has(n))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
6
+ `+Ie);if(z.has(n))throw new Error(`User ID "${n}" is a reserved identifier and cannot be used.
7
7
 
8
- `+me)}function ye(){return c(({window:n})=>`${n.innerWidth}x${n.innerHeight}`,()=>null)}var Fe={autoCapture:!0,baseUrl:"https://api.altertable.ai",debug:!1,environment:"production",persistence:"localStorage+cookie",release:void 0,trackingConsent:a.GRANTED},O=class{_cleanupAutoCapture;_config;_eventQueue;_isInitialized=!1;_lastUrl;_logger=fe("Altertable");_referrer;_requester;_sessionManager;_storage;_storageKey;constructor(){this._lastUrl=null,this._referrer=null,this._eventQueue=new x(se)}init(e,t={}){return g(e,"Missing API key"),this._config={...Fe,...t},this._storageKey=B(e,this._config.environment),this._referrer=c(({window:s})=>s.document.referrer||null,()=>null),this._lastUrl=c(({window:s})=>s.location.href||null,()=>null),this._storage=L(this._config.persistence,{onFallback:s=>this._logger.warn(s)}),this._requester=new $({baseUrl:this._config.baseUrl,apiKey:e,requestTimeout:re}),this._sessionManager=new N({storage:this._storage,storageKey:this._storageKey,logger:this._logger,defaultTrackingConsent:this._config.trackingConsent}),this._sessionManager.init(),this._isInitialized=!0,this._config.debug&&this._logger.logHeader(),this._handleAutoCaptureChange(this._config.autoCapture),()=>{this._cleanupAutoCapture?.()}}configure(e){if(g(this._isInitialized,"The client must be initialized with init() before configuring."),e.autoCapture!==void 0&&e.autoCapture!==this._config.autoCapture&&this._handleAutoCaptureChange(e.autoCapture),e.persistence!==void 0&&e.persistence!==this._config.persistence){let s=this._storage;this._storage=L(e.persistence,{onFallback:r=>this._logger.warn(r)}),this._storage.migrate(s,[this._storageKey])}let t=this._sessionManager.getTrackingConsent();if(e.trackingConsent!==void 0&&e.trackingConsent!==t)if(this._sessionManager.setTrackingConsent(e.trackingConsent),t!==a.GRANTED&&e.trackingConsent===a.GRANTED){let s=this._eventQueue.flush();s.length>0&&s.forEach(r=>{this._processEvent(r.eventType,r.payload,r.context)})}else e.trackingConsent===a.DENIED&&this._eventQueue.clear();this._config={...this._config,...e}}_handleAutoCaptureChange(e){if(this._cleanupAutoCapture?.(),e){this._lastUrl&&this.page(this._lastUrl);let t=this._checkForChanges.bind(this),s=setInterval(t,te);c(({window:r})=>{r.addEventListener("popstate",t),r.addEventListener("hashchange",t)}),this._cleanupAutoCapture=()=>{clearInterval(s),c(({window:r})=>{r.removeEventListener("popstate",t),r.removeEventListener("hashchange",t)})}}else this._cleanupAutoCapture=void 0}identify(e,t={}){g(this._isInitialized,"The client must be initialized with init() before identifying users."),g(!this._sessionManager.isIdentified()||e===this._sessionManager.getDistinctId(),`User (${e}) is already identified as a different user (${this._sessionManager.getDistinctId()}). This usually indicates a development issue, as it would merge two separate identities. Call reset() before identifying a new user, or use alias() to link the new ID to the existing one.`);try{X(e)}catch(o){throw new Error(`[Altertable] ${o.message}`)}e!==this._sessionManager.getDistinctId()&&this._sessionManager.identify(e);let s=this._getContext(),r={environment:s.environment,device_id:s.device_id,distinct_id:s.distinct_id,traits:t,anonymous_id:s.anonymous_id};if(this._processEvent("identify",r,s),this._config.debug){let o=this._sessionManager.getTrackingConsent();this._logger.logIdentify(r,{trackingConsent:o})}}alias(e){g(this._isInitialized,"The client must be initialized with init() before aliasing users.");try{X(e)}catch(r){throw new Error(`[Altertable] ${r.message}`)}let t=this._getContext(),s={environment:t.environment,device_id:t.device_id,anonymous_id:t.anonymous_id,distinct_id:t.distinct_id,new_user_id:e};if(this._processEvent("alias",s,t),this._config.debug){let r=this._sessionManager.getTrackingConsent();this._logger.logAlias(s,{trackingConsent:r})}}updateTraits(e){let t=this._getContext();g(t.anonymous_id!==null,"User must be identified with identify() before updating traits.");let s={environment:t.environment,device_id:t.device_id,distinct_id:t.distinct_id,traits:e,anonymous_id:t.anonymous_id,session_id:t.session_id};if(this._processEvent("identify",s,t),this._config.debug){let r=this._sessionManager.getTrackingConsent();this._logger.logIdentify(s,{trackingConsent:r})}}reset({resetDeviceId:e=!1}={}){g(this._isInitialized,"The client must be initialized with init() before resetting."),this._sessionManager.reset({resetDeviceId:e})}page(e){g(this._isInitialized,"The client must be initialized with init() before tracking page views.");let t=G(e),s=t?t.baseUrl:e;this.track(oe,{[h]:s,[ge]:ye(),[ce]:this._referrer,...t?.searchParams})}track(e,t={}){g(this._isInitialized,"The client must be initialized with init() before tracking events."),this._sessionManager.renewSessionIfNeeded();let s=new Date().toISOString();this._sessionManager.updateLastEventAt(s);let r=this._getContext(),o={timestamp:s,event:e,environment:r.environment,device_id:r.device_id,distinct_id:r.distinct_id,anonymous_id:r.anonymous_id,session_id:r.session_id,properties:{[ie]:"@altertable/altertable-js",[ae]:"1.0.4",[le]:this._config.release,...t[h]===void 0&&(()=>{let i=c(({window:u})=>u.location.href||null,()=>null),l=G(i),d=l?l.baseUrl:i;return{[h]:d}})(),...t}};if(this._processEvent("track",o,r),this._config.debug){let i=this._sessionManager.getTrackingConsent();this._logger.logEvent(o,{trackingConsent:i})}}getTrackingConsent(){return this._sessionManager.getTrackingConsent()}_checkForChanges(){c(({window:e})=>{let t=e.location.href;t!==this._lastUrl&&(this.page(t),this._referrer=this._lastUrl,this._lastUrl=t)})}_getContext(){return{environment:this._config.environment,device_id:this._sessionManager.getDeviceId(),distinct_id:this._sessionManager.getDistinctId(),anonymous_id:this._sessionManager.getAnonymousId(),session_id:this._sessionManager.getSessionId()}}async _processEvent(e,t,s){switch(this._sessionManager.getTrackingConsent()){case a.GRANTED:try{await this._requester.send(`/${e}`,t)}catch(o){de(o)&&this._config.onError?.(o),ue(o)&&o.errorCode==="environment-not-found"?this._logger.warnDev(`Environment "${this._config.environment}" not found. Please create this environment in your Altertable dashboard at ${_e(`/environments/new?name=${this._config.environment}`)} before tracking events.`):pe(o)?this._logger.error("Network error while sending event",{error:o.message,cause:o.cause,eventType:e}):this._logger.error("Failed to send event",{error:o,eventType:e,payload:t})}break;case a.PENDING:case a.DISMISSED:this._eventQueue.enqueue(e,t,s);break;case a.DENIED:break}}};var j=new O;c(({window:n})=>{let e=n.Altertable;if(e&&Array.isArray(e))for(let t of e){let s=t[0],r=t.slice(1);j[s](...r)}n.Altertable=j});return Pe(ze);})();
8
+ `+Ie)}var Qe={autoCapture:!0,baseUrl:"https://api.altertable.ai",debug:!1,environment:"production",persistence:"localStorage+cookie",release:void 0,trackingConsent:o.GRANTED},M=class{_cleanupAutoCapture;_config;_queue;_isInitialized=!1;_lastUrl;_logger=fe("Altertable");_referrer;_requester;_sessionManager;_storage;_storageKey;constructor(){this._lastUrl=null,this._referrer=null,this._queue=new x({capacity:F,onDropOldest:e=>{let t=e.type==="command"?e.method:e.eventType;this._logger.warnDev(`Queue is full (${F} items). Dropping ${t} call.`)}})}init(e,t={}){w(e,"Missing API key"),this._config={...Qe,...t},this._storageKey=q(e,this._config.environment),this._referrer=a(({window:s})=>s.document.referrer||null,()=>null),this._lastUrl=a(({window:s})=>s.location.href||null,()=>null),this._storage=B(this._config.persistence,{onFallback:s=>this._logger.warn(s)}),this._requester=new $({baseUrl:this._config.baseUrl,apiKey:e,requestTimeout:oe}),this._sessionManager=new O({storage:this._storage,storageKey:this._storageKey,logger:this._logger,defaultTrackingConsent:this._config.trackingConsent}),this._sessionManager.init(),this._isInitialized=!0,this._config.debug&&this._logger.logHeader();let r=this._sessionManager.getTrackingConsent();return r===o.GRANTED?this._flushQueue():r===o.DENIED&&this._queue.clear(),this._handleAutoCaptureChange(this._config.autoCapture),()=>{this._cleanupAutoCapture?.()}}configure(e){if(w(this._isInitialized,"The client must be initialized with init() before configuring."),e.autoCapture!==void 0&&e.autoCapture!==this._config.autoCapture&&this._handleAutoCaptureChange(e.autoCapture),e.persistence!==void 0&&e.persistence!==this._config.persistence){let r=this._storage;this._storage=B(e.persistence,{onFallback:s=>this._logger.warn(s)}),this._storage.migrate(r,[this._storageKey])}let t=this._sessionManager.getTrackingConsent();e.trackingConsent!==void 0&&e.trackingConsent!==t&&(this._sessionManager.setTrackingConsent(e.trackingConsent),t!==o.GRANTED&&e.trackingConsent===o.GRANTED?this._flushQueue():e.trackingConsent===o.DENIED&&this._queue.clear()),this._config={...this._config,...e}}_handleAutoCaptureChange(e){if(this._cleanupAutoCapture?.(),e){this._lastUrl&&this.page(this._lastUrl);let t=this._checkForChanges.bind(this),r=setInterval(t,se);a(({window:s})=>{s.addEventListener("popstate",t),s.addEventListener("hashchange",t)}),this._cleanupAutoCapture=()=>{clearInterval(r),a(({window:s})=>{s.removeEventListener("popstate",t),s.removeEventListener("hashchange",t)})}}else this._cleanupAutoCapture=void 0}identify(e,t={}){try{J(e)}catch(r){throw new Error(`[Altertable] ${r.message}`)}if(!this._isInitialized){this._queue.enqueue({type:"command",method:"identify",args:[e,{...t}]});return}this._identify(e,{...t})}_identify(e,t={}){w(!this._sessionManager.isIdentified()||e===this._sessionManager.getDistinctId(),`User (${e}) is already identified as a different user (${this._sessionManager.getDistinctId()}). This usually indicates a development issue, as it would merge two separate identities. Call reset() before identifying a new user, or use alias() to link the new ID to the existing one.`),e!==this._sessionManager.getDistinctId()&&this._sessionManager.identify(e);let r=this._getContext(),s={environment:r.environment,device_id:r.device_id,distinct_id:r.distinct_id,traits:t,anonymous_id:r.anonymous_id};if(this._processEvent("identify",s),this._config.debug){let c=this._sessionManager.getTrackingConsent();this._logger.logIdentify(s,{trackingConsent:c})}}alias(e){try{J(e)}catch(t){throw new Error(`[Altertable] ${t.message}`)}if(!this._isInitialized){this._queue.enqueue({type:"command",method:"alias",args:[e]});return}this._alias(e)}_alias(e){let t=this._getContext(),r={environment:t.environment,device_id:t.device_id,anonymous_id:t.anonymous_id,distinct_id:t.distinct_id,new_user_id:e};if(this._processEvent("alias",r),this._config.debug){let s=this._sessionManager.getTrackingConsent();this._logger.logAlias(r,{trackingConsent:s})}}updateTraits(e){if(!this._isInitialized){this._queue.enqueue({type:"command",method:"updateTraits",args:[{...e}]});return}this._updateTraits({...e})}_updateTraits(e){let t=this._getContext();w(t.anonymous_id!==null,"User must be identified with identify() before updating traits.");let r={environment:t.environment,device_id:t.device_id,distinct_id:t.distinct_id,traits:e,anonymous_id:t.anonymous_id,session_id:t.session_id};if(this._processEvent("identify",r),this._config.debug){let s=this._sessionManager.getTrackingConsent();this._logger.logIdentify(r,{trackingConsent:s})}}reset({resetDeviceId:e=!1}={}){this._queue.clear(),this._isInitialized&&this._sessionManager.reset({resetDeviceId:e})}page(e){if(!this._isInitialized){this._queue.enqueue({type:"command",method:"page",runtimeContext:N(),args:[e]});return}this._page(e)}_page(e,t){let r=X(e),s=r?r.baseUrl:e,c=t?.viewport??U(),i=t?.referrer??this._referrer;this._track(ae,{[y]:s,[de]:c,[ge]:i,...r?.searchParams},t)}track(e,t={}){if(!this._isInitialized){this._queue.enqueue({type:"command",method:"track",runtimeContext:N(),args:[e,{...t}]});return}this._track(e,{...t})}_track(e,t,r=N()){this._sessionManager.renewSessionIfNeeded(),this._sessionManager.updateLastEventAt(r.timestamp);let s=this._getContext(),{[y]:c,...i}=t,l=c!==void 0,g=l?null:r.url,u=g?X(g):null,p=u?u.baseUrl:g,d={timestamp:r.timestamp,event:e,environment:s.environment,device_id:s.device_id,distinct_id:s.distinct_id,anonymous_id:s.anonymous_id,session_id:s.session_id,properties:{[ce]:"@altertable/altertable-js",[le]:"1.0.6",[ue]:this._config.release,[y]:l?c:p,...i}};if(this._processEvent("track",d),this._config.debug){let m=this._sessionManager.getTrackingConsent();this._logger.logEvent(d,{trackingConsent:m})}}getTrackingConsent(){return this._isInitialized?this._sessionManager.getTrackingConsent():o.PENDING}_flushQueue(){let e=this._queue.flush();if(e.length!==0){this._config.debug&&this._logger.log(`Processing ${e.length} queued ${e.length===1?"item":"items"}.`);for(let t of e)this._executeQueueItem(t)}}_executeQueueItem(e){if(e.type==="event"){this._sendEvent(e.eventType,e.payload);return}this._executeCommand(e)}_executeCommand(e){try{switch(e.method){case"identify":this._identify(...e.args);break;case"track":this._track(...e.args,e.runtimeContext);break;case"page":this._page(...e.args,e.runtimeContext);break;case"alias":this._alias(...e.args);break;case"updateTraits":this._updateTraits(...e.args);break}}catch(t){let r=t instanceof Error?t.message:String(t);this._logger.warnDev(`Failed to process queued ${e.method}() command:
9
+ ${r}`)}}_checkForChanges(){a(({window:e})=>{let t=e.location.href;t!==this._lastUrl&&(this._referrer=this._lastUrl,this._lastUrl=t,this.page(t))})}_getContext(){return{environment:this._config.environment,device_id:this._sessionManager.getDeviceId(),distinct_id:this._sessionManager.getDistinctId(),anonymous_id:this._sessionManager.getAnonymousId(),session_id:this._sessionManager.getSessionId()}}_processEvent(e,t){switch(this._sessionManager.getTrackingConsent()){case o.GRANTED:this._sendEvent(e,t);break;case o.PENDING:case o.DISMISSED:this._queue.enqueue({type:"event",eventType:e,payload:t});break;case o.DENIED:break}}async _sendEvent(e,t){try{await this._requester.send(`/${e}`,t)}catch(r){pe(r)&&this._config.onError?.(r),me(r)&&r.errorCode==="environment-not-found"?this._logger.warnDev(`Environment "${this._config.environment}" not found. Please create this environment in your Altertable dashboard at ${he(`/environments/new?name=${this._config.environment}`)} before tracking events.`):_e(r)?this._logger.error("Network error while sending event",{error:r.message,cause:r.cause,eventType:e}):this._logger.error("Failed to send event",{error:r,eventType:e,payload:t})}}};var Z=new M;a(({window:n})=>{let e=n.Altertable;if(e&&Array.isArray(e))for(let t of e){let r=t[0],s=t.slice(1);Z[r](...s)}n.Altertable=Z});return $e(ze);})();
9
10
  //# sourceMappingURL=index.global.js.map