@grainql/analytics-web 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/attribution.d.ts +47 -0
  2. package/dist/attribution.d.ts.map +1 -0
  3. package/dist/attribution.js +228 -0
  4. package/dist/cjs/attribution.d.ts +47 -0
  5. package/dist/cjs/attribution.d.ts.map +1 -0
  6. package/dist/cjs/attribution.js +228 -0
  7. package/dist/cjs/attribution.js.map +1 -0
  8. package/dist/cjs/heartbeat.d.ts +1 -0
  9. package/dist/cjs/heartbeat.d.ts.map +1 -1
  10. package/dist/cjs/heartbeat.js +1 -1
  11. package/dist/cjs/heartbeat.js.map +1 -1
  12. package/dist/cjs/index.d.ts +25 -0
  13. package/dist/cjs/index.d.ts.map +1 -1
  14. package/dist/cjs/index.js.map +1 -1
  15. package/dist/cjs/page-tracking.d.ts +25 -0
  16. package/dist/cjs/page-tracking.d.ts.map +1 -1
  17. package/dist/cjs/page-tracking.js +158 -9
  18. package/dist/cjs/page-tracking.js.map +1 -1
  19. package/dist/esm/attribution.d.ts +47 -0
  20. package/dist/esm/attribution.d.ts.map +1 -0
  21. package/dist/esm/attribution.js +218 -0
  22. package/dist/esm/attribution.js.map +1 -0
  23. package/dist/esm/heartbeat.d.ts +1 -0
  24. package/dist/esm/heartbeat.d.ts.map +1 -1
  25. package/dist/esm/heartbeat.js +1 -1
  26. package/dist/esm/heartbeat.js.map +1 -1
  27. package/dist/esm/index.d.ts +25 -0
  28. package/dist/esm/index.d.ts.map +1 -1
  29. package/dist/esm/index.js.map +1 -1
  30. package/dist/esm/page-tracking.d.ts +25 -0
  31. package/dist/esm/page-tracking.d.ts.map +1 -1
  32. package/dist/esm/page-tracking.js +158 -9
  33. package/dist/esm/page-tracking.js.map +1 -1
  34. package/dist/heartbeat.d.ts +1 -0
  35. package/dist/heartbeat.d.ts.map +1 -1
  36. package/dist/heartbeat.js +1 -1
  37. package/dist/index.d.ts +25 -0
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.global.dev.js +464 -11
  40. package/dist/index.global.dev.js.map +3 -3
  41. package/dist/index.global.js +2 -2
  42. package/dist/index.global.js.map +4 -4
  43. package/dist/index.js +157 -1
  44. package/dist/index.mjs +155 -0
  45. package/dist/page-tracking.d.ts +25 -0
  46. package/dist/page-tracking.d.ts.map +1 -1
  47. package/dist/page-tracking.js +158 -9
  48. package/package.json +1 -1
@@ -1,3 +1,3 @@
1
- /* Grain Analytics Web SDK v2.2.1 | MIT License */
2
- "use strict";var Grain=(()=>{var C=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var A=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var x=(c,e)=>{for(var t in e)C(c,t,{get:e[t],enumerable:!0})},U=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of A(e))!T.call(c,n)&&n!==t&&C(c,n,{get:()=>e[n],enumerable:!(r=R(e,n))||r.enumerable});return c};var D=c=>U(C({},"__esModule",{value:!0}),c);var $={};x($,{GrainAnalytics:()=>u,createGrainAnalytics:()=>P,default:()=>O});var I=["necessary","analytics","functional"],f="1.0.0",p=class{constructor(e,t="opt-out"){this.consentState=null;this.listeners=[];this.consentMode=t,this.storageKey=`grain_consent_${e}`,this.loadConsentState()}loadConsentState(){if(!(typeof window>"u"))try{let e=localStorage.getItem(this.storageKey);if(e){let t=JSON.parse(e);this.consentState={...t,timestamp:new Date(t.timestamp)}}else(this.consentMode==="opt-out"||this.consentMode==="disabled")&&(this.consentState={granted:!0,categories:I,timestamp:new Date,version:f},this.saveConsentState())}catch(e){console.error("[Grain Consent] Failed to load consent state:",e)}}saveConsentState(){if(!(typeof window>"u"||!this.consentState))try{localStorage.setItem(this.storageKey,JSON.stringify(this.consentState))}catch(e){console.error("[Grain Consent] Failed to save consent state:",e)}}grantConsent(e){let t=e||I;this.consentState={granted:!0,categories:t,timestamp:new Date,version:f},this.saveConsentState(),this.notifyListeners()}revokeConsent(e){this.consentState?e?this.consentState={...this.consentState,categories:this.consentState.categories.filter(t=>!e.includes(t)),granted:this.consentState.categories.length>0,timestamp:new Date}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:f}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:f},this.saveConsentState(),this.notifyListeners()}getConsentState(){return this.consentState?{...this.consentState}:null}hasConsent(e){return this.consentMode==="disabled"?!0:this.consentMode==="opt-in"&&!this.consentState||!this.consentState?.granted?!1:e?this.consentState.categories.includes(e):!0}shouldWaitForConsent(){return this.consentMode==="opt-in"&&!this.consentState?.granted}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){this.consentState&&this.listeners.forEach(e=>{try{e(this.consentState)}catch(t){console.error("[Grain Consent] Listener error:",t)}})}clearConsent(){if(!(typeof window>"u"))try{localStorage.removeItem(this.storageKey),this.consentState=null}catch(e){console.error("[Grain Consent] Failed to clear consent:",e)}}};function b(c,e,t){if(typeof document>"u")return;let r=[`${encodeURIComponent(c)}=${encodeURIComponent(e)}`];t?.maxAge!==void 0&&r.push(`max-age=${t.maxAge}`),t?.domain&&r.push(`domain=${t.domain}`),t?.path?r.push(`path=${t.path}`):r.push("path=/"),t?.sameSite&&r.push(`samesite=${t.sameSite}`),t?.secure&&r.push("secure"),document.cookie=r.join("; ")}function w(c){if(typeof document>"u")return null;let e=encodeURIComponent(c)+"=",t=document.cookie.split(";");for(let r=0;r<t.length;r++){let n=t[r];for(;n.charAt(0)===" ";)n=n.substring(1);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length))}return null}function L(c,e){if(typeof document>"u")return;let t=[`${encodeURIComponent(c)}=`,"max-age=0"];e?.domain&&t.push(`domain=${e.domain}`),e?.path?t.push(`path=${e.path}`):t.push("path=/"),document.cookie=t.join("; ")}function k(){if(typeof document>"u")return!1;try{let c="_grain_cookie_test";b(c,"test",{maxAge:1});let e=w(c)==="test";return L(c),e}catch{return!1}}var m=class{constructor(){this.activityThreshold=3e4;this.listeners=[];this.isDestroyed=!1;this.activityEvents=["mousemove","mousedown","keydown","scroll","touchstart","click"];this.lastActivityTime=Date.now(),this.boundActivityHandler=this.debounce(this.handleActivity.bind(this),500),this.setupListeners()}setupListeners(){if(!(typeof window>"u"))for(let e of this.activityEvents)window.addEventListener(e,this.boundActivityHandler,{passive:!0})}handleActivity(){this.isDestroyed||(this.lastActivityTime=Date.now(),this.notifyListeners())}debounce(e,t){let r=null;return()=>{r!==null&&clearTimeout(r),r=window.setTimeout(()=>{e(),r=null},t)}}isActive(e){let t=e??this.activityThreshold;return Date.now()-this.lastActivityTime<t}getTimeSinceLastActivity(){return Date.now()-this.lastActivityTime}getLastActivityTime(){return this.lastActivityTime}setActivityThreshold(e){this.activityThreshold=e}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){for(let e of this.listeners)try{e()}catch(t){console.error("[Activity Detector] Listener error:",t)}}destroy(){if(!this.isDestroyed){if(typeof window<"u")for(let e of this.activityEvents)window.removeEventListener(e,this.boundActivityHandler);this.listeners=[],this.isDestroyed=!0}}};var v=class{constructor(e,t,r){this.heartbeatTimer=null;this.isDestroyed=!1;this.hasSentPageLoadHeartbeat=!1;this.tracker=e,this.activityDetector=t,this.config=r,this.lastHeartbeatTime=Date.now(),this.currentInterval=r.activeInterval,this.sendPageLoadHeartbeat(),this.scheduleNextHeartbeat()}sendPageLoadHeartbeat(){if(!(this.isDestroyed||this.hasSentPageLoadHeartbeat))if(typeof window<"u"&&document.readyState!=="complete"){let e=()=>{this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0,window.removeEventListener("load",e)};window.addEventListener("load",e)}else this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0}scheduleNextHeartbeat(){if(this.isDestroyed)return;this.heartbeatTimer!==null&&clearTimeout(this.heartbeatTimer);let e=this.activityDetector.isActive(6e4);this.currentInterval=e?this.config.activeInterval:this.config.inactiveInterval,this.heartbeatTimer=window.setTimeout(()=>{this.sendHeartbeat("periodic"),this.scheduleNextHeartbeat()},this.currentInterval),this.config.debug&&console.log(`[Heartbeat] Scheduled next heartbeat in ${this.currentInterval/1e3}s (${e?"active":"inactive"})`)}sendHeartbeat(e="periodic"){if(this.isDestroyed)return;let t=Date.now(),r=this.activityDetector.isActive(6e4),n=this.tracker.hasConsent("analytics"),s={type:"heartbeat",heartbeat_type:e,status:r?"active":"inactive",timestamp:t};if(n){let i=this.tracker.getCurrentPage();i&&(s.page=i),e==="periodic"&&(s.duration=t-this.lastHeartbeatTime,s.event_count=this.tracker.getEventCountSinceLastHeartbeat(),this.tracker.resetEventCountSinceLastHeartbeat())}this.tracker.trackSystemEvent("_grain_heartbeat",s),this.lastHeartbeatTime=t,this.config.debug&&console.log("[Heartbeat] Sent heartbeat:",s)}destroy(){this.isDestroyed||(this.heartbeatTimer!==null&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isDestroyed=!0,this.config.debug&&console.log("[Heartbeat] Destroyed"))}};var y=class{constructor(e,t){this.isDestroyed=!1;this.currentPath=null;this.originalPushState=null;this.originalReplaceState=null;this.handlePopState=()=>{this.isDestroyed||this.trackCurrentPage()};this.handleHashChange=()=>{this.isDestroyed||this.trackCurrentPage()};this.tracker=e,this.config=t,this.trackCurrentPage(),this.setupHistoryListeners(),this.setupHashChangeListener()}setupHistoryListeners(){typeof window>"u"||typeof history>"u"||(this.originalPushState=history.pushState,history.pushState=(e,t,r)=>{this.originalPushState?.call(history,e,t,r),this.trackCurrentPage()},this.originalReplaceState=history.replaceState,history.replaceState=(e,t,r)=>{this.originalReplaceState?.call(history,e,t,r),this.trackCurrentPage()},window.addEventListener("popstate",this.handlePopState))}setupHashChangeListener(){typeof window>"u"||window.addEventListener("hashchange",this.handleHashChange)}trackCurrentPage(){if(this.isDestroyed||typeof window>"u")return;let e=this.extractPath(window.location.href);if(e===this.currentPath)return;this.currentPath=e;let t=this.tracker.hasConsent("analytics"),r={page:e,timestamp:Date.now()};t&&(r.referrer=document.referrer||"",r.title=document.title||"",r.full_url=window.location.href),this.tracker.trackSystemEvent("page_view",r),this.config.debug&&console.log("[Page Tracking] Tracked page view:",r)}extractPath(e){try{let t=new URL(e),r=t.pathname+t.hash;return!this.config.stripQueryParams&&t.search&&(r+=t.search),r}catch(t){return this.config.debug&&console.warn("[Page Tracking] Failed to parse URL:",e,t),e}}getCurrentPage(){return this.currentPath}trackPage(e,t){if(this.isDestroyed)return;let r=this.tracker.hasConsent("analytics"),n={page:e,timestamp:Date.now(),...t};r&&typeof document<"u"&&(n.referrer||(n.referrer=document.referrer||""),n.title||(n.title=document.title||""),!n.full_url&&typeof window<"u"&&(n.full_url=window.location.href)),this.tracker.trackSystemEvent("page_view",n),this.config.debug&&console.log("[Page Tracking] Manually tracked page:",n)}destroy(){this.isDestroyed||(typeof history<"u"&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState)),typeof window<"u"&&(window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange)),this.isDestroyed=!0,this.config.debug&&console.log("[Page Tracking] Destroyed"))}};var u=class{constructor(e){this.eventQueue=[];this.waitingForConsentQueue=[];this.flushTimer=null;this.isDestroyed=!1;this.globalUserId=null;this.persistentAnonymousUserId=null;this.configCache=null;this.configRefreshTimer=null;this.configChangeListeners=[];this.configFetchPromise=null;this.cookiesEnabled=!1;this.activityDetector=null;this.heartbeatManager=null;this.pageTrackingManager=null;this.ephemeralSessionId=null;this.eventCountSinceLastHeartbeat=0;this.config={apiUrl:"https://api.grainql.com",authStrategy:"NONE",batchSize:50,flushInterval:5e3,retryAttempts:3,retryDelay:1e3,maxEventsPerRequest:160,debug:!1,defaultConfigurations:{},configCacheKey:"grain_config",configRefreshInterval:3e5,enableConfigCache:!0,consentMode:"opt-out",waitForConsent:!1,enableCookies:!1,anonymizeIP:!1,disableAutoProperties:!1,enableHeartbeat:!0,heartbeatActiveInterval:12e4,heartbeatInactiveInterval:3e5,enableAutoPageView:!0,stripQueryParams:!0,...e,tenantId:e.tenantId},this.consentManager=new p(this.config.tenantId,this.config.consentMode),this.config.enableCookies&&(this.cookiesEnabled=k(),!this.cookiesEnabled&&this.config.debug&&console.warn("[Grain Analytics] Cookies are not available, falling back to localStorage")),e.userId&&(this.globalUserId=e.userId),this.validateConfig(),this.initializePersistentAnonymousUserId(),this.setupBeforeUnload(),this.startFlushTimer(),this.initializeConfigCache(),this.ephemeralSessionId=this.generateUUID(),typeof window<"u"&&this.initializeAutomaticTracking(),this.consentManager.addListener(t=>{t.granted&&this.handleConsentGranted()})}validateConfig(){if(!this.config.tenantId)throw new Error("Grain Analytics: tenantId is required");if(this.config.authStrategy==="SERVER_SIDE"&&!this.config.secretKey)throw new Error("Grain Analytics: secretKey is required for SERVER_SIDE auth strategy");if(this.config.authStrategy==="JWT"&&!this.config.authProvider)throw new Error("Grain Analytics: authProvider is required for JWT auth strategy")}generateUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}shouldAllowPersistentStorage(){let e=this.consentManager.hasConsent("analytics"),t=this.config.consentMode==="opt-in",r=!!this.globalUserId,n=this.config.authStrategy==="JWT";return e||!t||r||n}generateAnonymousUserId(){return this.generateUUID()}initializePersistentAnonymousUserId(){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID initialization (GDPR compliance)");return}let e=`grain_anonymous_user_id_${this.config.tenantId}`,t="_grain_uid";try{if(this.cookiesEnabled){let n=w(t);if(n){this.persistentAnonymousUserId=n,this.log("Loaded persistent anonymous user ID from cookie:",this.persistentAnonymousUserId);return}}let r=localStorage.getItem(e);r?(this.persistentAnonymousUserId=r,this.log("Loaded persistent anonymous user ID from localStorage:",this.persistentAnonymousUserId),this.cookiesEnabled&&this.savePersistentAnonymousUserId(r)):(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId),this.log("Generated new persistent anonymous user ID:",this.persistentAnonymousUserId))}catch(r){this.log("Failed to initialize persistent anonymous user ID:",r),this.persistentAnonymousUserId=this.generateAnonymousUserId()}}savePersistentAnonymousUserId(e){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID save (GDPR compliance)");return}let t=`grain_anonymous_user_id_${this.config.tenantId}`,r="_grain_uid";try{if(this.cookiesEnabled){let n={maxAge:31536e3,sameSite:"lax",secure:typeof window<"u"&&window.location.protocol==="https:",...this.config.cookieOptions};b(r,e,n)}localStorage.setItem(t,e)}catch(n){this.log("Failed to save persistent anonymous user ID:",n)}}getEffectiveUserIdInternal(){return this.globalUserId?this.globalUserId:this.persistentAnonymousUserId?this.persistentAnonymousUserId:(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId),this.persistentAnonymousUserId)}log(...e){this.config.debug&&console.log("[Grain Analytics]",...e)}createErrorDigest(e){let t=[...new Set(e.map(i=>i.eventName))],r=[...new Set(e.map(i=>i.userId))],n=0,s=0;return e.forEach(i=>{let o=i.properties||{};n+=Object.keys(o).length,s+=JSON.stringify(i).length}),{eventCount:e.length,totalProperties:n,totalSize:s,eventNames:t,userIds:r}}formatError(e,t,r){let n=r?this.createErrorDigest(r):{eventCount:0,totalProperties:0,totalSize:0,eventNames:[],userIds:[]},s="UNKNOWN_ERROR",i="An unknown error occurred";if(e instanceof Error)i=e.message,i.includes("fetch failed")||i.includes("network error")?s="NETWORK_ERROR":i.includes("timeout")?s="TIMEOUT_ERROR":i.includes("HTTP 4")?s="CLIENT_ERROR":i.includes("HTTP 5")?s="SERVER_ERROR":i.includes("JSON")?s="PARSE_ERROR":i.includes("auth")||i.includes("unauthorized")?s="AUTH_ERROR":i.includes("rate limit")||i.includes("429")?s="RATE_LIMIT_ERROR":s="GENERAL_ERROR";else if(typeof e=="string")i=e,s="STRING_ERROR";else if(e&&typeof e=="object"&&"status"in e){let o=e.status;s=`HTTP_${o}`,i=`HTTP ${o} error`}return{code:s,message:i,digest:n,timestamp:new Date().toISOString(),context:t,originalError:e}}logError(e){let{code:t,message:r,digest:n,timestamp:s,context:i}=e,o={"\u{1F6A8} Grain Analytics Error":{"Error Code":t,Message:r,Context:i,Timestamp:s,"Event Digest":{Events:n.eventCount,Properties:n.totalProperties,"Size (bytes)":n.totalSize,"Event Names":n.eventNames.length>0?n.eventNames.join(", "):"None","User IDs":n.userIds.length>0?n.userIds.slice(0,3).join(", ")+(n.userIds.length>3?"...":""):"None"}}};console.error("\u{1F6A8} Grain Analytics Error:",o),this.config.debug&&console.error(`[Grain Analytics] ${t}: ${r} (${i}) - Events: ${n.eventCount}, Props: ${n.totalProperties}, Size: ${n.totalSize}B`)}async safeExecute(e,t,r){try{return await e()}catch(n){let s=this.formatError(n,t,r);return this.logError(s),null}}formatEvent(e){return{eventName:e.eventName,userId:e.userId||this.getEffectiveUserIdInternal(),properties:e.properties||{}}}async getAuthHeaders(){let e={"Content-Type":"application/json"};switch(this.config.authStrategy){case"NONE":break;case"SERVER_SIDE":e.Authorization=`Chase ${this.config.secretKey}`;break;case"JWT":if(this.config.authProvider){let t=await this.config.authProvider.getToken();e.Authorization=`Bearer ${t}`}break}return e}async delay(e){return new Promise(t=>setTimeout(t,e))}isRetriableError(e){if(e instanceof Error){let t=e.message.toLowerCase();if(t.includes("fetch failed")||t==="network error"||t.includes("timeout")||t.includes("connection"))return!0}if(typeof e=="object"&&e!==null&&"status"in e){let t=e.status;return t>=500||t===429}return!1}async sendEvents(e){if(e.length===0)return;let t;for(let r=0;r<=this.config.retryAttempts;r++)try{let n=await this.getAuthHeaders(),s=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;this.log(`Sending ${e.length} events to ${s} (attempt ${r+1})`);let i=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(e)});if(!i.ok){let o=`HTTP ${i.status}`;try{let h=await i.json();h?.message&&(o=h.message)}catch{let h=await i.text();h&&(o=h)}let a=new Error(`Failed to send events: ${o}`);throw a.status=i.status,a}this.log(`Successfully sent ${e.length} events`);return}catch(n){if(t=n,r===this.config.retryAttempts){let i=this.formatError(n,`sendEvents (attempt ${r+1}/${this.config.retryAttempts+1})`,e);this.logError(i);return}if(!this.isRetriableError(n)){let i=this.formatError(n,"sendEvents (non-retriable error)",e);this.logError(i);return}let s=this.config.retryDelay*Math.pow(2,r);this.log(`Retrying in ${s}ms after error:`,n),await this.delay(s)}}async sendEventsWithBeacon(e){if(e.length!==0)try{let t=await this.getAuthHeaders(),r=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,n=JSON.stringify({events:e});if(typeof navigator<"u"&&"sendBeacon"in navigator){let s=new Blob([n],{type:"application/json"});if(navigator.sendBeacon(r,s)){this.log(`Successfully sent ${e.length} events via beacon`);return}}await fetch(r,{method:"POST",headers:t,body:n,keepalive:!0}),this.log(`Successfully sent ${e.length} events via fetch (keepalive)`)}catch(t){let r=this.formatError(t,"sendEventsWithBeacon",e);this.logError(r)}}startFlushTimer(){typeof window>"u"||(this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=window.setInterval(()=>{this.eventQueue.length>0&&this.flush().catch(e=>{let t=this.formatError(e,"auto-flush");this.logError(t)})},this.config.flushInterval))}setupBeforeUnload(){if(typeof window>"u")return;let e=()=>{if(this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let r=this.chunkEvents(t,this.config.maxEventsPerRequest);r.length>0&&this.sendEventsWithBeacon(r[0]).catch(()=>{})}};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden"&&this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let r=this.chunkEvents(t,this.config.maxEventsPerRequest);r.length>0&&this.sendEventsWithBeacon(r[0]).catch(()=>{})}})}initializeAutomaticTracking(){if(this.config.enableHeartbeat)try{this.activityDetector=new m,this.heartbeatManager=new v(this,this.activityDetector,{activeInterval:this.config.heartbeatActiveInterval,inactiveInterval:this.config.heartbeatInactiveInterval,debug:this.config.debug}),this.log("Heartbeat tracking initialized")}catch(e){this.log("Failed to initialize heartbeat tracking:",e)}if(this.config.enableAutoPageView)try{this.pageTrackingManager=new y(this,{stripQueryParams:this.config.stripQueryParams,debug:this.config.debug}),this.log("Auto page view tracking initialized")}catch(e){this.log("Failed to initialize page view tracking:",e)}}handleConsentGranted(){this.flushWaitingForConsentQueue(),this.persistentAnonymousUserId||(this.initializePersistentAnonymousUserId(),this.log("Initialized persistent ID after consent grant")),this.ephemeralSessionId&&this.trackSystemEvent("_grain_consent_granted",{previous_session_id:this.ephemeralSessionId,new_user_id:this.getEffectiveUserId(),timestamp:Date.now()})}trackSystemEvent(e,t){if(this.isDestroyed)return;let r=this.consentManager.hasConsent("analytics"),n={eventName:e,userId:r?this.getEffectiveUserId():this.getEphemeralSessionId(),properties:{...t,_minimal:!r,_consent_status:r?"granted":"pending"}};this.eventQueue.push(n),this.eventCountSinceLastHeartbeat++,this.log(`Queued system event: ${e}`,t),this.eventQueue.length>=this.config.batchSize&&this.flush().catch(s=>{let i=this.formatError(s,"flush system event");this.logError(i)})}getEphemeralSessionId(){return this.ephemeralSessionId||(this.ephemeralSessionId=this.generateUUID()),this.ephemeralSessionId}getCurrentPage(){return this.pageTrackingManager?.getCurrentPage()||null}getEventCountSinceLastHeartbeat(){return this.eventCountSinceLastHeartbeat}resetEventCountSinceLastHeartbeat(){this.eventCountSinceLastHeartbeat=0}getEffectiveUserId(){return this.getEffectiveUserIdInternal()}getSessionId(){return this.consentManager.hasConsent("analytics")?this.getEffectiveUserId():this.getEphemeralSessionId()}async track(e,t,r){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),a=this.formatError(o,"track (client destroyed)");this.logError(a);return}let n,s={};if(typeof e=="string"?(n={eventName:e,properties:t},s=r||{}):(n=e,s=t||{}),this.config.allowedProperties&&n.properties){let o={};for(let a of this.config.allowedProperties)a in n.properties&&(o[a]=n.properties[a]);n.properties=o}let i=this.formatEvent(n);if(this.consentManager.shouldWaitForConsent()&&this.config.waitForConsent){this.waitingForConsentQueue.push(i),this.log(`Event waiting for consent: ${n.eventName}`,n.properties);return}if(!this.consentManager.hasConsent("analytics")){this.log(`Event blocked by consent: ${n.eventName}`);return}this.eventQueue.push(i),this.eventCountSinceLastHeartbeat++,this.log(`Queued event: ${n.eventName}`,n.properties),(s.flush||this.eventQueue.length>=this.config.batchSize)&&await this.flush()}catch(n){let s=this.formatError(n,"track");this.logError(s)}}flushWaitingForConsentQueue(){this.waitingForConsentQueue.length!==0&&(this.log(`Flushing ${this.waitingForConsentQueue.length} events waiting for consent`),this.eventQueue.push(...this.waitingForConsentQueue),this.waitingForConsentQueue=[],this.flush().catch(e=>{let t=this.formatError(e,"flush waiting for consent queue");this.logError(t)}))}identify(e){this.log(`Identified user: ${e}`),this.globalUserId=e,this.persistentAnonymousUserId=null}setUserId(e){this.log(`Set global user ID: ${e}`),this.globalUserId=e,e?this.persistentAnonymousUserId=null:this.persistentAnonymousUserId||(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId))}getUserId(){return this.globalUserId}getEffectiveUserIdPublic(){return this.getEffectiveUserIdInternal()}login(e){try{if(this.isDestroyed){let t=new Error("Grain Analytics: Client has been destroyed"),r=this.formatError(t,"login (client destroyed)");this.logError(r);return}e.userId&&(this.log(`Login: Setting user ID to ${e.userId}`),this.globalUserId=e.userId,this.persistentAnonymousUserId=null),e.authToken&&(this.log("Login: Setting auth token"),this.config.authStrategy==="NONE"&&(this.config.authStrategy="JWT"),this.config.authProvider={getToken:()=>e.authToken}),e.authStrategy&&(this.log(`Login: Setting auth strategy to ${e.authStrategy}`),this.config.authStrategy=e.authStrategy),this.log(`Login successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(t){let r=this.formatError(t,"login");this.logError(r)}}logout(){try{if(this.isDestroyed){let e=new Error("Grain Analytics: Client has been destroyed"),t=this.formatError(e,"logout (client destroyed)");this.logError(t);return}if(this.log("Logout: Clearing user session"),this.globalUserId=null,this.config.authStrategy="NONE",this.config.authProvider=void 0,!this.persistentAnonymousUserId&&(this.persistentAnonymousUserId=this.generateAnonymousUserId(),typeof window<"u"))try{let e=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.setItem(e,this.persistentAnonymousUserId)}catch(e){this.log("Failed to persist new anonymous user ID after logout:",e)}this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(e){let t=this.formatError(e,"logout");this.logError(t)}}async setProperty(e,t){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),a=this.formatError(o,"setProperty (client destroyed)");this.logError(a);return}let r=t?.userId||this.getEffectiveUserIdInternal(),n=Object.keys(e);if(n.length>4){let o=new Error("Grain Analytics: Maximum 4 properties allowed per request"),a=this.formatError(o,"setProperty (validation)");this.logError(a);return}if(n.length===0){let o=new Error("Grain Analytics: At least one property is required"),a=this.formatError(o,"setProperty (validation)");this.logError(a);return}let s={};for(let[o,a]of Object.entries(e))a==null?s[o]="":typeof a=="string"?s[o]=a:s[o]=JSON.stringify(a);let i={userId:r,...s};await this.sendProperties(i)}catch(r){let n=this.formatError(r,"setProperty");this.logError(n)}}async sendProperties(e){let t;for(let r=0;r<=this.config.retryAttempts;r++)try{let n=await this.getAuthHeaders(),s=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/properties`;this.log(`Setting properties for user ${e.userId} (attempt ${r+1})`);let i=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(e)});if(!i.ok){let o=`HTTP ${i.status}`;try{let h=await i.json();h?.message&&(o=h.message)}catch{let h=await i.text();h&&(o=h)}let a=new Error(`Failed to set properties: ${o}`);throw a.status=i.status,a}this.log(`Successfully set properties for user ${e.userId}`);return}catch(n){if(t=n,r===this.config.retryAttempts){let i=this.formatError(n,`sendProperties (attempt ${r+1}/${this.config.retryAttempts+1})`);this.logError(i);return}if(!this.isRetriableError(n)){let i=this.formatError(n,"sendProperties (non-retriable error)");this.logError(i);return}let s=this.config.retryDelay*Math.pow(2,r);this.log(`Retrying in ${s}ms after error:`,n),await this.delay(s)}}async trackLogin(e,t){try{return await this.track("login",e,t)}catch(r){let n=this.formatError(r,"trackLogin");this.logError(n)}}async trackSignup(e,t){try{return await this.track("signup",e,t)}catch(r){let n=this.formatError(r,"trackSignup");this.logError(n)}}async trackCheckout(e,t){try{return await this.track("checkout",e,t)}catch(r){let n=this.formatError(r,"trackCheckout");this.logError(n)}}async trackPageView(e,t){try{return await this.track("page_view",e,t)}catch(r){let n=this.formatError(r,"trackPageView");this.logError(n)}}async trackPurchase(e,t){try{return await this.track("purchase",e,t)}catch(r){let n=this.formatError(r,"trackPurchase");this.logError(n)}}async trackSearch(e,t){try{return await this.track("search",e,t)}catch(r){let n=this.formatError(r,"trackSearch");this.logError(n)}}async trackAddToCart(e,t){try{return await this.track("add_to_cart",e,t)}catch(r){let n=this.formatError(r,"trackAddToCart");this.logError(n)}}async trackRemoveFromCart(e,t){try{return await this.track("remove_from_cart",e,t)}catch(r){let n=this.formatError(r,"trackRemoveFromCart");this.logError(n)}}async flush(){try{if(this.eventQueue.length===0)return;let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);for(let r of t)await this.sendEvents(r)}catch(e){let t=this.formatError(e,"flush");this.logError(t)}}initializeConfigCache(){if(!(!this.config.enableConfigCache||typeof window>"u"))try{let e=localStorage.getItem(this.config.configCacheKey);e&&(this.configCache=JSON.parse(e),this.log("Loaded configuration from cache:",this.configCache))}catch(e){this.log("Failed to load configuration cache:",e)}}saveConfigCache(e){if(!(!this.config.enableConfigCache||typeof window>"u"))try{localStorage.setItem(this.config.configCacheKey,JSON.stringify(e)),this.log("Saved configuration to cache:",e)}catch(t){this.log("Failed to save configuration cache:",t)}}getConfig(e){if(this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e]}getAllConfigs(){let e={...this.config.defaultConfigurations};return this.configCache?.configurations&&Object.assign(e,this.configCache.configurations),e}async fetchConfig(e={}){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),a=this.formatError(o,"fetchConfig (client destroyed)");return this.logError(a),null}let t=e.userId||this.getEffectiveUserIdInternal(),r=e.immediateKeys||[],n=e.properties||{},s={userId:t,immediateKeys:r,properties:n},i;for(let o=0;o<=this.config.retryAttempts;o++)try{let a=await this.getAuthHeaders(),h=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`;this.log(`Fetching configurations for user ${t} (attempt ${o+1})`);let g=await fetch(h,{method:"POST",headers:a,body:JSON.stringify(s)});if(!g.ok){let E=`HTTP ${g.status}`;try{let d=await g.json();d?.message&&(E=d.message)}catch{let d=await g.text();d&&(E=d)}let S=new Error(`Failed to fetch configurations: ${E}`);throw S.status=g.status,S}let l=await g.json();return l.configurations&&this.updateConfigCache(l,t),this.log(`Successfully fetched configurations for user ${t}:`,l),l}catch(a){if(i=a,o===this.config.retryAttempts){let g=this.formatError(a,`fetchConfig (attempt ${o+1}/${this.config.retryAttempts+1})`);return this.logError(g),null}if(!this.isRetriableError(a)){let g=this.formatError(a,"fetchConfig (non-retriable error)");return this.logError(g),null}let h=this.config.retryDelay*Math.pow(2,o);this.log(`Retrying config fetch in ${h}ms after error:`,a),await this.delay(h)}return null}catch(t){let r=this.formatError(t,"fetchConfig");return this.logError(r),null}}async getConfigAsync(e,t={}){try{if(!t.forceRefresh&&this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(!t.forceRefresh&&this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e];let r=await this.fetchConfig(t);return r?r.configurations[e]:this.config.defaultConfigurations?.[e]}catch(r){let n=this.formatError(r,"getConfigAsync");return this.logError(n),this.config.defaultConfigurations?.[e]}}async getAllConfigsAsync(e={}){try{if(!e.forceRefresh&&this.configCache?.configurations)return{...this.config.defaultConfigurations,...this.configCache.configurations};let t=await this.fetchConfig(e);return t?{...this.config.defaultConfigurations,...t.configurations}:{...this.config.defaultConfigurations}}catch(t){let r=this.formatError(t,"getAllConfigsAsync");return this.logError(r),{...this.config.defaultConfigurations}}}updateConfigCache(e,t){let r={configurations:e.configurations,snapshotId:e.snapshotId,timestamp:e.timestamp,userId:t},n=this.configCache?.configurations||{};this.configCache=r,this.saveConfigCache(r),JSON.stringify(n)!==JSON.stringify(e.configurations)&&this.notifyConfigChangeListeners(e.configurations)}addConfigChangeListener(e){this.configChangeListeners.push(e)}removeConfigChangeListener(e){let t=this.configChangeListeners.indexOf(e);t>-1&&this.configChangeListeners.splice(t,1)}notifyConfigChangeListeners(e){this.configChangeListeners.forEach(t=>{try{t(e)}catch(r){console.error("[Grain Analytics] Config change listener error:",r)}})}startConfigRefreshTimer(){typeof window>"u"||(this.configRefreshTimer&&clearInterval(this.configRefreshTimer),this.configRefreshTimer=window.setInterval(()=>{this.isDestroyed||this.fetchConfig().catch(e=>{let t=this.formatError(e,"auto-config refresh");this.logError(t)})},this.config.configRefreshInterval))}stopConfigRefreshTimer(){this.configRefreshTimer&&(clearInterval(this.configRefreshTimer),this.configRefreshTimer=null)}async preloadConfig(e=[],t){try{let r=this.getEffectiveUserIdInternal();this.log(`Preloading config for user: ${r}`),await this.fetchConfig({immediateKeys:e,properties:t})&&this.startConfigRefreshTimer()}catch(r){let n=this.formatError(r,"preloadConfig");this.logError(n)}}chunkEvents(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}grantConsent(e){try{this.consentManager.grantConsent(e),this.log("Consent granted",e)}catch(t){let r=this.formatError(t,"grantConsent");this.logError(r)}}revokeConsent(e){try{this.consentManager.revokeConsent(e),this.log("Consent revoked",e),this.eventQueue=[],this.waitingForConsentQueue=[]}catch(t){let r=this.formatError(t,"revokeConsent");this.logError(r)}}getConsentState(){return this.consentManager.getConsentState()}hasConsent(e){return this.consentManager.hasConsent(e)}onConsentChange(e){this.consentManager.addListener(e)}offConsentChange(e){this.consentManager.removeListener(e)}destroy(){if(this.isDestroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.stopConfigRefreshTimer(),this.configChangeListeners=[],this.heartbeatManager&&(this.heartbeatManager.destroy(),this.heartbeatManager=null),this.pageTrackingManager&&(this.pageTrackingManager.destroy(),this.pageTrackingManager=null),this.activityDetector&&(this.activityDetector.destroy(),this.activityDetector=null),this.eventQueue.length>0){let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);if(t.length>0){this.sendEventsWithBeacon(t[0]).catch(()=>{});for(let r=1;r<t.length;r++)this.sendEventsWithBeacon(t[r]).catch(()=>{})}}}};function P(c){return new u(c)}var O=u;typeof window<"u"&&(window.Grain={GrainAnalytics:u,createGrainAnalytics:P});return D($);})();
1
+ /* Grain Analytics Web SDK v2.3.0 | MIT License */
2
+ "use strict";var Grain=(()=>{var P=Object.defineProperty;var M=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var $=Object.prototype.hasOwnProperty;var H=(a,e)=>{for(var t in e)P(a,t,{get:e[t],enumerable:!0})},F=(a,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of L(e))!$.call(a,n)&&n!==t&&P(a,n,{get:()=>e[n],enumerable:!(r=M(e,n))||r.enumerable});return a};var N=a=>F(P({},"__esModule",{value:!0}),a);var J={};H(J,{GrainAnalytics:()=>d,categorizeReferrer:()=>g,createGrainAnalytics:()=>O,default:()=>B,parseUTMParameters:()=>f});var R=["necessary","analytics","functional"],v="1.0.0",y=class{constructor(e,t="opt-out"){this.consentState=null;this.listeners=[];this.consentMode=t,this.storageKey=`grain_consent_${e}`,this.loadConsentState()}loadConsentState(){if(!(typeof window>"u"))try{let e=localStorage.getItem(this.storageKey);if(e){let t=JSON.parse(e);this.consentState={...t,timestamp:new Date(t.timestamp)}}else(this.consentMode==="opt-out"||this.consentMode==="disabled")&&(this.consentState={granted:!0,categories:R,timestamp:new Date,version:v},this.saveConsentState())}catch(e){console.error("[Grain Consent] Failed to load consent state:",e)}}saveConsentState(){if(!(typeof window>"u"||!this.consentState))try{localStorage.setItem(this.storageKey,JSON.stringify(this.consentState))}catch(e){console.error("[Grain Consent] Failed to save consent state:",e)}}grantConsent(e){let t=e||R;this.consentState={granted:!0,categories:t,timestamp:new Date,version:v},this.saveConsentState(),this.notifyListeners()}revokeConsent(e){this.consentState?e?this.consentState={...this.consentState,categories:this.consentState.categories.filter(t=>!e.includes(t)),granted:this.consentState.categories.length>0,timestamp:new Date}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:v}:this.consentState={granted:!1,categories:[],timestamp:new Date,version:v},this.saveConsentState(),this.notifyListeners()}getConsentState(){return this.consentState?{...this.consentState}:null}hasConsent(e){return this.consentMode==="disabled"?!0:this.consentMode==="opt-in"&&!this.consentState||!this.consentState?.granted?!1:e?this.consentState.categories.includes(e):!0}shouldWaitForConsent(){return this.consentMode==="opt-in"&&!this.consentState?.granted}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){this.consentState&&this.listeners.forEach(e=>{try{e(this.consentState)}catch(t){console.error("[Grain Consent] Listener error:",t)}})}clearConsent(){if(!(typeof window>"u"))try{localStorage.removeItem(this.storageKey),this.consentState=null}catch(e){console.error("[Grain Consent] Failed to clear consent:",e)}}};function I(a,e,t){if(typeof document>"u")return;let r=[`${encodeURIComponent(a)}=${encodeURIComponent(e)}`];t?.maxAge!==void 0&&r.push(`max-age=${t.maxAge}`),t?.domain&&r.push(`domain=${t.domain}`),t?.path?r.push(`path=${t.path}`):r.push("path=/"),t?.sameSite&&r.push(`samesite=${t.sameSite}`),t?.secure&&r.push("secure"),document.cookie=r.join("; ")}function k(a){if(typeof document>"u")return null;let e=encodeURIComponent(a)+"=",t=document.cookie.split(";");for(let r=0;r<t.length;r++){let n=t[r];for(;n.charAt(0)===" ";)n=n.substring(1);if(n.indexOf(e)===0)return decodeURIComponent(n.substring(e.length))}return null}function G(a,e){if(typeof document>"u")return;let t=[`${encodeURIComponent(a)}=`,"max-age=0"];e?.domain&&t.push(`domain=${e.domain}`),e?.path?t.push(`path=${e.path}`):t.push("path=/"),document.cookie=t.join("; ")}function _(){if(typeof document>"u")return!1;try{let a="_grain_cookie_test";I(a,"test",{maxAge:1});let e=k(a)==="test";return G(a),e}catch{return!1}}var E=class{constructor(){this.activityThreshold=3e4;this.listeners=[];this.isDestroyed=!1;this.activityEvents=["mousemove","mousedown","keydown","scroll","touchstart","click"];this.lastActivityTime=Date.now(),this.boundActivityHandler=this.debounce(this.handleActivity.bind(this),500),this.setupListeners()}setupListeners(){if(!(typeof window>"u"))for(let e of this.activityEvents)window.addEventListener(e,this.boundActivityHandler,{passive:!0})}handleActivity(){this.isDestroyed||(this.lastActivityTime=Date.now(),this.notifyListeners())}debounce(e,t){let r=null;return()=>{r!==null&&clearTimeout(r),r=window.setTimeout(()=>{e(),r=null},t)}}isActive(e){let t=e??this.activityThreshold;return Date.now()-this.lastActivityTime<t}getTimeSinceLastActivity(){return Date.now()-this.lastActivityTime}getLastActivityTime(){return this.lastActivityTime}setActivityThreshold(e){this.activityThreshold=e}addListener(e){this.listeners.push(e)}removeListener(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){for(let e of this.listeners)try{e()}catch(t){console.error("[Activity Detector] Listener error:",t)}}destroy(){if(!this.isDestroyed){if(typeof window<"u")for(let e of this.activityEvents)window.removeEventListener(e,this.boundActivityHandler);this.listeners=[],this.isDestroyed=!0}}};var C=class{constructor(e,t,r){this.heartbeatTimer=null;this.isDestroyed=!1;this.hasSentPageLoadHeartbeat=!1;this.tracker=e,this.activityDetector=t,this.config=r,this.lastHeartbeatTime=Date.now(),this.currentInterval=r.activeInterval,this.sendPageLoadHeartbeat(),this.scheduleNextHeartbeat()}sendPageLoadHeartbeat(){if(!(this.isDestroyed||this.hasSentPageLoadHeartbeat))if(typeof window<"u"&&document.readyState!=="complete"){let e=()=>{this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0,window.removeEventListener("load",e)};window.addEventListener("load",e)}else this.sendHeartbeat("page_load"),this.hasSentPageLoadHeartbeat=!0}scheduleNextHeartbeat(){if(this.isDestroyed)return;this.heartbeatTimer!==null&&clearTimeout(this.heartbeatTimer);let e=this.activityDetector.isActive(6e4);this.currentInterval=e?this.config.activeInterval:this.config.inactiveInterval,this.heartbeatTimer=window.setTimeout(()=>{this.sendHeartbeat("periodic"),this.scheduleNextHeartbeat()},this.currentInterval),this.config.debug&&console.log(`[Heartbeat] Scheduled next heartbeat in ${this.currentInterval/1e3}s (${e?"active":"inactive"})`)}sendHeartbeat(e="periodic"){if(this.isDestroyed)return;let t=Date.now(),r=this.activityDetector.isActive(6e4),n=this.tracker.hasConsent("analytics"),s={heartbeat_type:e,status:r?"active":"inactive",timestamp:t};if(n){let i=this.tracker.getCurrentPage();i&&(s.page=i),s.session_id=this.tracker.getSessionId(),e==="periodic"&&(s.duration=t-this.lastHeartbeatTime,s.event_count=this.tracker.getEventCountSinceLastHeartbeat(),this.tracker.resetEventCountSinceLastHeartbeat())}this.tracker.trackSystemEvent("_grain_heartbeat",s),this.lastHeartbeatTime=t,this.config.debug&&console.log("[Heartbeat] Sent heartbeat:",s)}destroy(){this.isDestroyed||(this.heartbeatTimer!==null&&(clearTimeout(this.heartbeatTimer),this.heartbeatTimer=null),this.isDestroyed=!0,this.config.debug&&console.log("[Heartbeat] Destroyed"))}};var Q=["gclid","msclkid","fbclid","ttclid","li_fat_id","twclid","ScCid"],z=["facebook.com","twitter.com","x.com","linkedin.com","instagram.com","pinterest.com","reddit.com","tiktok.com","youtube.com","snapchat.com","t.co","fb.me","lnkd.in"],W=["google.","bing.com","yahoo.com","duckduckgo.com","baidu.com","yandex.com","ecosia.org","ask.com"],q=["mail.google.com","outlook.live.com","mail.yahoo.com","mail.aol.com"];function A(a){try{return new URL(a).hostname.toLowerCase()}catch{return""}}function x(a){try{let e=new URL(a);return Q.some(t=>e.searchParams.has(t))}catch{return!1}}function g(a,e=""){if(!a||a.trim()==="")return"direct";let t=A(a);if(e){let r=A(e);if(t===r)return"direct"}return x(a)||x(e)?"paid":q.some(r=>t.includes(r))?"email":z.some(r=>t.includes(r))?"social":W.some(r=>t.includes(r))?"organic":"referral"}function f(a){try{let e=new URL(a),t={},r=e.searchParams.get("utm_source"),n=e.searchParams.get("utm_medium"),s=e.searchParams.get("utm_campaign"),i=e.searchParams.get("utm_term"),o=e.searchParams.get("utm_content");return r&&(t.utm_source=r),n&&(t.utm_medium=n),s&&(t.utm_campaign=s),i&&(t.utm_term=i),o&&(t.utm_content=o),t}catch{return{}}}function K(a){if(typeof window>"u"||typeof localStorage>"u")return null;try{let e=`_grain_first_touch_${a}`,t=localStorage.getItem(e);if(t)return JSON.parse(t)}catch(e){console.warn("[Grain Attribution] Failed to retrieve first-touch attribution:",e)}return null}function j(a,e){if(!(typeof window>"u"||typeof localStorage>"u"))try{let t=`_grain_first_touch_${a}`;localStorage.setItem(t,JSON.stringify(e))}catch(t){console.warn("[Grain Attribution] Failed to store first-touch attribution:",t)}}function w(a,e,t,r){let n=K(a);if(n)return n;let s=g(e,t),i=A(e),o={source:r.utm_source||i||"direct",medium:r.utm_medium||s,campaign:r.utm_campaign||"none",referrer:e||"direct",referrer_category:s,timestamp:Date.now()};return j(a,o),o}var U=null;function m(){return U}function D(a){U=a}var b=class{constructor(e,t){this.isDestroyed=!1;this.currentPath=null;this.originalPushState=null;this.originalReplaceState=null;this.previousPage=null;this.landingPage=null;this.pageViewCount=0;this.handlePopState=()=>{this.isDestroyed||this.trackCurrentPage()};this.handleHashChange=()=>{this.isDestroyed||this.trackCurrentPage()};this.tracker=e,this.config=t,this.trackCurrentPage(!0),this.setupHistoryListeners(),this.setupHashChangeListener()}setupHistoryListeners(){typeof window>"u"||typeof history>"u"||(this.originalPushState=history.pushState,history.pushState=(e,t,r)=>{this.originalPushState?.call(history,e,t,r),this.trackCurrentPage()},this.originalReplaceState=history.replaceState,history.replaceState=(e,t,r)=>{this.originalReplaceState?.call(history,e,t,r),this.trackCurrentPage()},window.addEventListener("popstate",this.handlePopState))}setupHashChangeListener(){typeof window>"u"||window.addEventListener("hashchange",this.handleHashChange)}trackCurrentPage(e=!1){if(this.isDestroyed||typeof window>"u")return;let t=this.extractPath(window.location.href);if(!e&&t===this.currentPath)return;this.currentPath&&(this.previousPage=this.currentPath),this.currentPath=t,this.pageViewCount++,e&&(this.landingPage=t);let r=this.tracker.hasConsent("analytics"),n=window.location.href,s=document.referrer||"",i=f(n);Object.keys(i).length>0&&(!m()||e)&&D(i);let o=m()||{},u=w(this.config.tenantId,s,n,o),c={page:t,timestamp:Date.now()};r&&(c.title=document.title||"",c.full_url=n,c.session_id=this.tracker.getSessionId(),s&&(c.referrer=s,c.referrer_domain=this.extractDomain(s),c.referrer_category=g(s,n)),this.landingPage&&!e&&(c.landing_page=this.landingPage),this.previousPage&&(c.previous_page=this.previousPage),o.utm_source&&(c.utm_source=o.utm_source),o.utm_medium&&(c.utm_medium=o.utm_medium),o.utm_campaign&&(c.utm_campaign=o.utm_campaign),o.utm_term&&(c.utm_term=o.utm_term),o.utm_content&&(c.utm_content=o.utm_content),c.first_touch_source=u.source,c.first_touch_medium=u.medium,c.first_touch_campaign=u.campaign,c.first_touch_referrer_category=u.referrer_category,c.device=this.getDeviceType(),c.browser=this.getBrowser(),c.os=this.getOS(),c.language=navigator.language||"",c.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone,c.screen_resolution=`${screen.width}x${screen.height}`,c.viewport=`${window.innerWidth}x${window.innerHeight}`),this.tracker.trackSystemEvent("page_view",c),this.config.debug&&console.log("[Page Tracking] Tracked page view:",c)}extractDomain(e){try{return new URL(e).hostname}catch{return""}}getBrowser(){let e=navigator.userAgent;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")&&!e.includes("Chrome/")?"Safari":e.includes("Opera/")||e.includes("OPR/")?"Opera":"Unknown"}getOS(){let e=navigator.userAgent;return e.includes("Win")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}getDeviceType(){let e=navigator.userAgent,t=window.innerWidth;return e.includes("iPad")||e.includes("Android")&&!e.includes("Mobile")?"Tablet":e.includes("Mobile")||e.includes("iPhone")||e.includes("Android")||t<768?"Mobile":t>=768&&t<1024?"Tablet":"Desktop"}extractPath(e){try{let t=new URL(e),r=t.pathname+t.hash;return!this.config.stripQueryParams&&t.search&&(r+=t.search),r}catch(t){return this.config.debug&&console.warn("[Page Tracking] Failed to parse URL:",e,t),e}}getCurrentPage(){return this.currentPath}trackPage(e,t){if(this.isDestroyed)return;let r=this.tracker.hasConsent("analytics"),n={page:e,timestamp:Date.now(),...t};r&&typeof document<"u"&&typeof window<"u"&&(n.referrer||(n.referrer=document.referrer||""),n.title||(n.title=document.title||""),n.full_url||(n.full_url=window.location.href),n.session_id||(n.session_id=this.tracker.getSessionId()),n.browser||(n.browser=this.getBrowser()),n.os||(n.os=this.getOS())),this.tracker.trackSystemEvent("page_view",n),this.config.debug&&console.log("[Page Tracking] Manually tracked page:",n)}getPageViewCount(){return this.pageViewCount}destroy(){this.isDestroyed||(typeof history<"u"&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState)),typeof window<"u"&&(window.removeEventListener("popstate",this.handlePopState),window.removeEventListener("hashchange",this.handleHashChange)),this.isDestroyed=!0,this.config.debug&&console.log("[Page Tracking] Destroyed"))}};var d=class{constructor(e){this.eventQueue=[];this.waitingForConsentQueue=[];this.flushTimer=null;this.isDestroyed=!1;this.globalUserId=null;this.persistentAnonymousUserId=null;this.configCache=null;this.configRefreshTimer=null;this.configChangeListeners=[];this.configFetchPromise=null;this.cookiesEnabled=!1;this.activityDetector=null;this.heartbeatManager=null;this.pageTrackingManager=null;this.ephemeralSessionId=null;this.eventCountSinceLastHeartbeat=0;this.sessionStartTime=Date.now();this.sessionEventCount=0;this.config={apiUrl:"https://api.grainql.com",authStrategy:"NONE",batchSize:50,flushInterval:5e3,retryAttempts:3,retryDelay:1e3,maxEventsPerRequest:160,debug:!1,defaultConfigurations:{},configCacheKey:"grain_config",configRefreshInterval:3e5,enableConfigCache:!0,consentMode:"opt-out",waitForConsent:!1,enableCookies:!1,anonymizeIP:!1,disableAutoProperties:!1,enableHeartbeat:!0,heartbeatActiveInterval:12e4,heartbeatInactiveInterval:3e5,enableAutoPageView:!0,stripQueryParams:!0,...e,tenantId:e.tenantId},this.consentManager=new y(this.config.tenantId,this.config.consentMode),this.config.enableCookies&&(this.cookiesEnabled=_(),!this.cookiesEnabled&&this.config.debug&&console.warn("[Grain Analytics] Cookies are not available, falling back to localStorage")),e.userId&&(this.globalUserId=e.userId),this.validateConfig(),this.initializePersistentAnonymousUserId(),this.setupBeforeUnload(),this.startFlushTimer(),this.initializeConfigCache(),this.ephemeralSessionId=this.generateUUID(),typeof window<"u"&&(this.initializeAutomaticTracking(),this.trackSessionStart()),this.consentManager.addListener(t=>{t.granted&&this.handleConsentGranted()})}validateConfig(){if(!this.config.tenantId)throw new Error("Grain Analytics: tenantId is required");if(this.config.authStrategy==="SERVER_SIDE"&&!this.config.secretKey)throw new Error("Grain Analytics: secretKey is required for SERVER_SIDE auth strategy");if(this.config.authStrategy==="JWT"&&!this.config.authProvider)throw new Error("Grain Analytics: authProvider is required for JWT auth strategy")}generateUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}shouldAllowPersistentStorage(){let e=this.consentManager.hasConsent("analytics"),t=this.config.consentMode==="opt-in",r=!!this.globalUserId,n=this.config.authStrategy==="JWT";return e||!t||r||n}generateAnonymousUserId(){return this.generateUUID()}initializePersistentAnonymousUserId(){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID initialization (GDPR compliance)");return}let e=`grain_anonymous_user_id_${this.config.tenantId}`,t="_grain_uid";try{if(this.cookiesEnabled){let n=k(t);if(n){this.persistentAnonymousUserId=n,this.log("Loaded persistent anonymous user ID from cookie:",this.persistentAnonymousUserId);return}}let r=localStorage.getItem(e);r?(this.persistentAnonymousUserId=r,this.log("Loaded persistent anonymous user ID from localStorage:",this.persistentAnonymousUserId),this.cookiesEnabled&&this.savePersistentAnonymousUserId(r)):(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId),this.log("Generated new persistent anonymous user ID:",this.persistentAnonymousUserId))}catch(r){this.log("Failed to initialize persistent anonymous user ID:",r),this.persistentAnonymousUserId=this.generateAnonymousUserId()}}savePersistentAnonymousUserId(e){if(typeof window>"u")return;if(!this.shouldAllowPersistentStorage()){this.log("Opt-in mode without consent: skipping persistent ID save (GDPR compliance)");return}let t=`grain_anonymous_user_id_${this.config.tenantId}`,r="_grain_uid";try{if(this.cookiesEnabled){let n={maxAge:31536e3,sameSite:"lax",secure:typeof window<"u"&&window.location.protocol==="https:",...this.config.cookieOptions};I(r,e,n)}localStorage.setItem(t,e)}catch(n){this.log("Failed to save persistent anonymous user ID:",n)}}getEffectiveUserIdInternal(){return this.globalUserId?this.globalUserId:this.persistentAnonymousUserId?this.persistentAnonymousUserId:(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId),this.persistentAnonymousUserId)}log(...e){this.config.debug&&console.log("[Grain Analytics]",...e)}createErrorDigest(e){let t=[...new Set(e.map(i=>i.eventName))],r=[...new Set(e.map(i=>i.userId))],n=0,s=0;return e.forEach(i=>{let o=i.properties||{};n+=Object.keys(o).length,s+=JSON.stringify(i).length}),{eventCount:e.length,totalProperties:n,totalSize:s,eventNames:t,userIds:r}}formatError(e,t,r){let n=r?this.createErrorDigest(r):{eventCount:0,totalProperties:0,totalSize:0,eventNames:[],userIds:[]},s="UNKNOWN_ERROR",i="An unknown error occurred";if(e instanceof Error)i=e.message,i.includes("fetch failed")||i.includes("network error")?s="NETWORK_ERROR":i.includes("timeout")?s="TIMEOUT_ERROR":i.includes("HTTP 4")?s="CLIENT_ERROR":i.includes("HTTP 5")?s="SERVER_ERROR":i.includes("JSON")?s="PARSE_ERROR":i.includes("auth")||i.includes("unauthorized")?s="AUTH_ERROR":i.includes("rate limit")||i.includes("429")?s="RATE_LIMIT_ERROR":s="GENERAL_ERROR";else if(typeof e=="string")i=e,s="STRING_ERROR";else if(e&&typeof e=="object"&&"status"in e){let o=e.status;s=`HTTP_${o}`,i=`HTTP ${o} error`}return{code:s,message:i,digest:n,timestamp:new Date().toISOString(),context:t,originalError:e}}logError(e){let{code:t,message:r,digest:n,timestamp:s,context:i}=e,o={"\u{1F6A8} Grain Analytics Error":{"Error Code":t,Message:r,Context:i,Timestamp:s,"Event Digest":{Events:n.eventCount,Properties:n.totalProperties,"Size (bytes)":n.totalSize,"Event Names":n.eventNames.length>0?n.eventNames.join(", "):"None","User IDs":n.userIds.length>0?n.userIds.slice(0,3).join(", ")+(n.userIds.length>3?"...":""):"None"}}};console.error("\u{1F6A8} Grain Analytics Error:",o),this.config.debug&&console.error(`[Grain Analytics] ${t}: ${r} (${i}) - Events: ${n.eventCount}, Props: ${n.totalProperties}, Size: ${n.totalSize}B`)}async safeExecute(e,t,r){try{return await e()}catch(n){let s=this.formatError(n,t,r);return this.logError(s),null}}formatEvent(e){return{eventName:e.eventName,userId:e.userId||this.getEffectiveUserIdInternal(),properties:e.properties||{}}}async getAuthHeaders(){let e={"Content-Type":"application/json"};switch(this.config.authStrategy){case"NONE":break;case"SERVER_SIDE":e.Authorization=`Chase ${this.config.secretKey}`;break;case"JWT":if(this.config.authProvider){let t=await this.config.authProvider.getToken();e.Authorization=`Bearer ${t}`}break}return e}async delay(e){return new Promise(t=>setTimeout(t,e))}isRetriableError(e){if(e instanceof Error){let t=e.message.toLowerCase();if(t.includes("fetch failed")||t==="network error"||t.includes("timeout")||t.includes("connection"))return!0}if(typeof e=="object"&&e!==null&&"status"in e){let t=e.status;return t>=500||t===429}return!1}async sendEvents(e){if(e.length===0)return;let t;for(let r=0;r<=this.config.retryAttempts;r++)try{let n=await this.getAuthHeaders(),s=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`;this.log(`Sending ${e.length} events to ${s} (attempt ${r+1})`);let i=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(e)});if(!i.ok){let o=`HTTP ${i.status}`;try{let c=await i.json();c?.message&&(o=c.message)}catch{let c=await i.text();c&&(o=c)}let u=new Error(`Failed to send events: ${o}`);throw u.status=i.status,u}this.log(`Successfully sent ${e.length} events`);return}catch(n){if(t=n,r===this.config.retryAttempts){let i=this.formatError(n,`sendEvents (attempt ${r+1}/${this.config.retryAttempts+1})`,e);this.logError(i);return}if(!this.isRetriableError(n)){let i=this.formatError(n,"sendEvents (non-retriable error)",e);this.logError(i);return}let s=this.config.retryDelay*Math.pow(2,r);this.log(`Retrying in ${s}ms after error:`,n),await this.delay(s)}}async sendEventsWithBeacon(e){if(e.length!==0)try{let t=await this.getAuthHeaders(),r=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/multi`,n=JSON.stringify({events:e});if(typeof navigator<"u"&&"sendBeacon"in navigator){let s=new Blob([n],{type:"application/json"});if(navigator.sendBeacon(r,s)){this.log(`Successfully sent ${e.length} events via beacon`);return}}await fetch(r,{method:"POST",headers:t,body:n,keepalive:!0}),this.log(`Successfully sent ${e.length} events via fetch (keepalive)`)}catch(t){let r=this.formatError(t,"sendEventsWithBeacon",e);this.logError(r)}}startFlushTimer(){typeof window>"u"||(this.flushTimer&&clearInterval(this.flushTimer),this.flushTimer=window.setInterval(()=>{this.eventQueue.length>0&&this.flush().catch(e=>{let t=this.formatError(e,"auto-flush");this.logError(t)})},this.config.flushInterval))}setupBeforeUnload(){if(typeof window>"u")return;let e=()=>{if(this.trackSessionEnd(),this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let r=this.chunkEvents(t,this.config.maxEventsPerRequest);r.length>0&&this.sendEventsWithBeacon(r[0]).catch(()=>{})}};window.addEventListener("beforeunload",e),window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",()=>{if(document.visibilityState==="hidden"&&this.eventQueue.length>0){let t=[...this.eventQueue];this.eventQueue=[];let r=this.chunkEvents(t,this.config.maxEventsPerRequest);r.length>0&&this.sendEventsWithBeacon(r[0]).catch(()=>{})}})}initializeAutomaticTracking(){if(this.config.enableHeartbeat)try{this.activityDetector=new E,this.heartbeatManager=new C(this,this.activityDetector,{activeInterval:this.config.heartbeatActiveInterval,inactiveInterval:this.config.heartbeatInactiveInterval,debug:this.config.debug}),this.log("Heartbeat tracking initialized")}catch(e){this.log("Failed to initialize heartbeat tracking:",e)}if(this.config.enableAutoPageView)try{this.pageTrackingManager=new b(this,{stripQueryParams:this.config.stripQueryParams,debug:this.config.debug,tenantId:this.config.tenantId}),this.log("Auto page view tracking initialized")}catch(e){this.log("Failed to initialize page view tracking:",e)}}trackSessionStart(){if(typeof window>"u")return;let e=this.consentManager.hasConsent("analytics"),t={session_id:this.getSessionId(),timestamp:this.sessionStartTime};if(e){let r=document.referrer||"",n=window.location.href,s=f(n),i=m()||s,o=w(this.config.tenantId,r,n,i);t.landing_page=window.location.pathname,r?(t.referrer=r,t.referrer_domain=new URL(r).hostname,t.referrer_category=g(r,n)):t.referrer_category="direct",i.utm_source&&(t.utm_source=i.utm_source),i.utm_medium&&(t.utm_medium=i.utm_medium),i.utm_campaign&&(t.utm_campaign=i.utm_campaign),i.utm_term&&(t.utm_term=i.utm_term),i.utm_content&&(t.utm_content=i.utm_content),t.first_touch_source=o.source,t.first_touch_medium=o.medium,t.first_touch_campaign=o.campaign,t.first_touch_referrer_category=o.referrer_category,t.device=this.getDeviceType(),t.screen_resolution=`${screen.width}x${screen.height}`,t.viewport=`${window.innerWidth}x${window.innerHeight}`,t.browser=this.getBrowser(),t.os=this.getOS(),t.language=navigator.language||"",t.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}this.trackSystemEvent("_grain_session_start",t),this.log("Session started:",t)}trackSessionEnd(){if(typeof window>"u")return;let e=this.consentManager.hasConsent("analytics"),t=Date.now()-this.sessionStartTime,r={session_id:this.getSessionId(),session_duration:Math.floor(t/1e3),duration:t,event_count:this.sessionEventCount,timestamp:Date.now()};if(e&&this.pageTrackingManager){let n=this.pageTrackingManager.getPageViewCount();r.pages_per_session=n,r.page_count=n}this.trackSystemEvent("_grain_session_end",r),this.log("Session ended:",r)}getBrowser(){if(typeof navigator>"u")return"Unknown";let e=navigator.userAgent;return e.includes("Firefox/")?"Firefox":e.includes("Edg/")?"Edge":e.includes("Chrome/")?"Chrome":e.includes("Safari/")&&!e.includes("Chrome/")?"Safari":e.includes("Opera/")||e.includes("OPR/")?"Opera":"Unknown"}getOS(){if(typeof navigator>"u")return"Unknown";let e=navigator.userAgent;return e.includes("Win")?"Windows":e.includes("Mac")?"macOS":e.includes("Linux")?"Linux":e.includes("Android")?"Android":e.includes("iOS")||e.includes("iPhone")||e.includes("iPad")?"iOS":"Unknown"}getDeviceType(){if(typeof window>"u"||typeof navigator>"u")return"Unknown";let e=navigator.userAgent,t=window.innerWidth;return e.includes("iPad")||e.includes("Android")&&!e.includes("Mobile")?"Tablet":e.includes("Mobile")||e.includes("iPhone")||e.includes("Android")||t<768?"Mobile":t>=768&&t<1024?"Tablet":"Desktop"}handleConsentGranted(){this.flushWaitingForConsentQueue(),this.persistentAnonymousUserId||(this.initializePersistentAnonymousUserId(),this.log("Initialized persistent ID after consent grant")),this.ephemeralSessionId&&this.trackSystemEvent("_grain_consent_granted",{previous_session_id:this.ephemeralSessionId,new_user_id:this.getEffectiveUserId(),timestamp:Date.now()})}trackSystemEvent(e,t){if(this.isDestroyed)return;let r=this.consentManager.hasConsent("analytics"),n={eventName:e,userId:r?this.getEffectiveUserId():this.getEphemeralSessionId(),properties:{...t,_minimal:!r,_consent_status:r?"granted":"pending"}};this.eventQueue.push(n),this.eventCountSinceLastHeartbeat++,this.log(`Queued system event: ${e}`,t),this.eventQueue.length>=this.config.batchSize&&this.flush().catch(s=>{let i=this.formatError(s,"flush system event");this.logError(i)})}getEphemeralSessionId(){return this.ephemeralSessionId||(this.ephemeralSessionId=this.generateUUID()),this.ephemeralSessionId}getCurrentPage(){return this.pageTrackingManager?.getCurrentPage()||null}getEventCountSinceLastHeartbeat(){return this.eventCountSinceLastHeartbeat}resetEventCountSinceLastHeartbeat(){this.eventCountSinceLastHeartbeat=0}getEffectiveUserId(){return this.getEffectiveUserIdInternal()}getSessionId(){return this.consentManager.hasConsent("analytics")?this.getEffectiveUserId():this.getEphemeralSessionId()}async track(e,t,r){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),u=this.formatError(o,"track (client destroyed)");this.logError(u);return}let n,s={};if(typeof e=="string"?(n={eventName:e,properties:t},s=r||{}):(n=e,s=t||{}),this.config.allowedProperties&&n.properties){let o={};for(let u of this.config.allowedProperties)u in n.properties&&(o[u]=n.properties[u]);n.properties=o}let i=this.formatEvent(n);if(this.consentManager.shouldWaitForConsent()&&this.config.waitForConsent){this.waitingForConsentQueue.push(i),this.log(`Event waiting for consent: ${n.eventName}`,n.properties);return}if(!this.consentManager.hasConsent("analytics")){this.log(`Event blocked by consent: ${n.eventName}`);return}this.eventQueue.push(i),this.eventCountSinceLastHeartbeat++,this.sessionEventCount++,this.log(`Queued event: ${n.eventName}`,n.properties),(s.flush||this.eventQueue.length>=this.config.batchSize)&&await this.flush()}catch(n){let s=this.formatError(n,"track");this.logError(s)}}flushWaitingForConsentQueue(){this.waitingForConsentQueue.length!==0&&(this.log(`Flushing ${this.waitingForConsentQueue.length} events waiting for consent`),this.eventQueue.push(...this.waitingForConsentQueue),this.waitingForConsentQueue=[],this.flush().catch(e=>{let t=this.formatError(e,"flush waiting for consent queue");this.logError(t)}))}identify(e){this.log(`Identified user: ${e}`),this.globalUserId=e,this.persistentAnonymousUserId=null}setUserId(e){this.log(`Set global user ID: ${e}`),this.globalUserId=e,e?this.persistentAnonymousUserId=null:this.persistentAnonymousUserId||(this.persistentAnonymousUserId=this.generateAnonymousUserId(),this.savePersistentAnonymousUserId(this.persistentAnonymousUserId))}getUserId(){return this.globalUserId}getEffectiveUserIdPublic(){return this.getEffectiveUserIdInternal()}login(e){try{if(this.isDestroyed){let t=new Error("Grain Analytics: Client has been destroyed"),r=this.formatError(t,"login (client destroyed)");this.logError(r);return}e.userId&&(this.log(`Login: Setting user ID to ${e.userId}`),this.globalUserId=e.userId,this.persistentAnonymousUserId=null),e.authToken&&(this.log("Login: Setting auth token"),this.config.authStrategy==="NONE"&&(this.config.authStrategy="JWT"),this.config.authProvider={getToken:()=>e.authToken}),e.authStrategy&&(this.log(`Login: Setting auth strategy to ${e.authStrategy}`),this.config.authStrategy=e.authStrategy),this.log(`Login successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(t){let r=this.formatError(t,"login");this.logError(r)}}logout(){try{if(this.isDestroyed){let e=new Error("Grain Analytics: Client has been destroyed"),t=this.formatError(e,"logout (client destroyed)");this.logError(t);return}if(this.log("Logout: Clearing user session"),this.globalUserId=null,this.config.authStrategy="NONE",this.config.authProvider=void 0,!this.persistentAnonymousUserId&&(this.persistentAnonymousUserId=this.generateAnonymousUserId(),typeof window<"u"))try{let e=`grain_anonymous_user_id_${this.config.tenantId}`;localStorage.setItem(e,this.persistentAnonymousUserId)}catch(e){this.log("Failed to persist new anonymous user ID after logout:",e)}this.log(`Logout successful. Effective user ID: ${this.getEffectiveUserIdInternal()}`)}catch(e){let t=this.formatError(e,"logout");this.logError(t)}}async setProperty(e,t){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),u=this.formatError(o,"setProperty (client destroyed)");this.logError(u);return}let r=t?.userId||this.getEffectiveUserIdInternal(),n=Object.keys(e);if(n.length>4){let o=new Error("Grain Analytics: Maximum 4 properties allowed per request"),u=this.formatError(o,"setProperty (validation)");this.logError(u);return}if(n.length===0){let o=new Error("Grain Analytics: At least one property is required"),u=this.formatError(o,"setProperty (validation)");this.logError(u);return}let s={};for(let[o,u]of Object.entries(e))u==null?s[o]="":typeof u=="string"?s[o]=u:s[o]=JSON.stringify(u);let i={userId:r,...s};await this.sendProperties(i)}catch(r){let n=this.formatError(r,"setProperty");this.logError(n)}}async sendProperties(e){let t;for(let r=0;r<=this.config.retryAttempts;r++)try{let n=await this.getAuthHeaders(),s=`${this.config.apiUrl}/v1/events/${encodeURIComponent(this.config.tenantId)}/properties`;this.log(`Setting properties for user ${e.userId} (attempt ${r+1})`);let i=await fetch(s,{method:"POST",headers:n,body:JSON.stringify(e)});if(!i.ok){let o=`HTTP ${i.status}`;try{let c=await i.json();c?.message&&(o=c.message)}catch{let c=await i.text();c&&(o=c)}let u=new Error(`Failed to set properties: ${o}`);throw u.status=i.status,u}this.log(`Successfully set properties for user ${e.userId}`);return}catch(n){if(t=n,r===this.config.retryAttempts){let i=this.formatError(n,`sendProperties (attempt ${r+1}/${this.config.retryAttempts+1})`);this.logError(i);return}if(!this.isRetriableError(n)){let i=this.formatError(n,"sendProperties (non-retriable error)");this.logError(i);return}let s=this.config.retryDelay*Math.pow(2,r);this.log(`Retrying in ${s}ms after error:`,n),await this.delay(s)}}async trackLogin(e,t){try{return await this.track("login",e,t)}catch(r){let n=this.formatError(r,"trackLogin");this.logError(n)}}async trackSignup(e,t){try{return await this.track("signup",e,t)}catch(r){let n=this.formatError(r,"trackSignup");this.logError(n)}}async trackCheckout(e,t){try{return await this.track("checkout",e,t)}catch(r){let n=this.formatError(r,"trackCheckout");this.logError(n)}}async trackPageView(e,t){try{return await this.track("page_view",e,t)}catch(r){let n=this.formatError(r,"trackPageView");this.logError(n)}}async trackPurchase(e,t){try{return await this.track("purchase",e,t)}catch(r){let n=this.formatError(r,"trackPurchase");this.logError(n)}}async trackSearch(e,t){try{return await this.track("search",e,t)}catch(r){let n=this.formatError(r,"trackSearch");this.logError(n)}}async trackAddToCart(e,t){try{return await this.track("add_to_cart",e,t)}catch(r){let n=this.formatError(r,"trackAddToCart");this.logError(n)}}async trackRemoveFromCart(e,t){try{return await this.track("remove_from_cart",e,t)}catch(r){let n=this.formatError(r,"trackRemoveFromCart");this.logError(n)}}async flush(){try{if(this.eventQueue.length===0)return;let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);for(let r of t)await this.sendEvents(r)}catch(e){let t=this.formatError(e,"flush");this.logError(t)}}initializeConfigCache(){if(!(!this.config.enableConfigCache||typeof window>"u"))try{let e=localStorage.getItem(this.config.configCacheKey);e&&(this.configCache=JSON.parse(e),this.log("Loaded configuration from cache:",this.configCache))}catch(e){this.log("Failed to load configuration cache:",e)}}saveConfigCache(e){if(!(!this.config.enableConfigCache||typeof window>"u"))try{localStorage.setItem(this.config.configCacheKey,JSON.stringify(e)),this.log("Saved configuration to cache:",e)}catch(t){this.log("Failed to save configuration cache:",t)}}getConfig(e){if(this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e]}getAllConfigs(){let e={...this.config.defaultConfigurations};return this.configCache?.configurations&&Object.assign(e,this.configCache.configurations),e}async fetchConfig(e={}){try{if(this.isDestroyed){let o=new Error("Grain Analytics: Client has been destroyed"),u=this.formatError(o,"fetchConfig (client destroyed)");return this.logError(u),null}let t=e.userId||this.getEffectiveUserIdInternal(),r=e.immediateKeys||[],n=e.properties||{},s={userId:t,immediateKeys:r,properties:n},i;for(let o=0;o<=this.config.retryAttempts;o++)try{let u=await this.getAuthHeaders(),c=`${this.config.apiUrl}/v1/client/${encodeURIComponent(this.config.tenantId)}/config/configurations`;this.log(`Fetching configurations for user ${t} (attempt ${o+1})`);let h=await fetch(c,{method:"POST",headers:u,body:JSON.stringify(s)});if(!h.ok){let S=`HTTP ${h.status}`;try{let l=await h.json();l?.message&&(S=l.message)}catch{let l=await h.text();l&&(S=l)}let T=new Error(`Failed to fetch configurations: ${S}`);throw T.status=h.status,T}let p=await h.json();return p.configurations&&this.updateConfigCache(p,t),this.log(`Successfully fetched configurations for user ${t}:`,p),p}catch(u){if(i=u,o===this.config.retryAttempts){let h=this.formatError(u,`fetchConfig (attempt ${o+1}/${this.config.retryAttempts+1})`);return this.logError(h),null}if(!this.isRetriableError(u)){let h=this.formatError(u,"fetchConfig (non-retriable error)");return this.logError(h),null}let c=this.config.retryDelay*Math.pow(2,o);this.log(`Retrying config fetch in ${c}ms after error:`,u),await this.delay(c)}return null}catch(t){let r=this.formatError(t,"fetchConfig");return this.logError(r),null}}async getConfigAsync(e,t={}){try{if(!t.forceRefresh&&this.configCache?.configurations?.[e])return this.configCache.configurations[e];if(!t.forceRefresh&&this.config.defaultConfigurations?.[e])return this.config.defaultConfigurations[e];let r=await this.fetchConfig(t);return r?r.configurations[e]:this.config.defaultConfigurations?.[e]}catch(r){let n=this.formatError(r,"getConfigAsync");return this.logError(n),this.config.defaultConfigurations?.[e]}}async getAllConfigsAsync(e={}){try{if(!e.forceRefresh&&this.configCache?.configurations)return{...this.config.defaultConfigurations,...this.configCache.configurations};let t=await this.fetchConfig(e);return t?{...this.config.defaultConfigurations,...t.configurations}:{...this.config.defaultConfigurations}}catch(t){let r=this.formatError(t,"getAllConfigsAsync");return this.logError(r),{...this.config.defaultConfigurations}}}updateConfigCache(e,t){let r={configurations:e.configurations,snapshotId:e.snapshotId,timestamp:e.timestamp,userId:t},n=this.configCache?.configurations||{};this.configCache=r,this.saveConfigCache(r),JSON.stringify(n)!==JSON.stringify(e.configurations)&&this.notifyConfigChangeListeners(e.configurations)}addConfigChangeListener(e){this.configChangeListeners.push(e)}removeConfigChangeListener(e){let t=this.configChangeListeners.indexOf(e);t>-1&&this.configChangeListeners.splice(t,1)}notifyConfigChangeListeners(e){this.configChangeListeners.forEach(t=>{try{t(e)}catch(r){console.error("[Grain Analytics] Config change listener error:",r)}})}startConfigRefreshTimer(){typeof window>"u"||(this.configRefreshTimer&&clearInterval(this.configRefreshTimer),this.configRefreshTimer=window.setInterval(()=>{this.isDestroyed||this.fetchConfig().catch(e=>{let t=this.formatError(e,"auto-config refresh");this.logError(t)})},this.config.configRefreshInterval))}stopConfigRefreshTimer(){this.configRefreshTimer&&(clearInterval(this.configRefreshTimer),this.configRefreshTimer=null)}async preloadConfig(e=[],t){try{let r=this.getEffectiveUserIdInternal();this.log(`Preloading config for user: ${r}`),await this.fetchConfig({immediateKeys:e,properties:t})&&this.startConfigRefreshTimer()}catch(r){let n=this.formatError(r,"preloadConfig");this.logError(n)}}chunkEvents(e,t){let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}grantConsent(e){try{this.consentManager.grantConsent(e),this.log("Consent granted",e)}catch(t){let r=this.formatError(t,"grantConsent");this.logError(r)}}revokeConsent(e){try{this.consentManager.revokeConsent(e),this.log("Consent revoked",e),this.eventQueue=[],this.waitingForConsentQueue=[]}catch(t){let r=this.formatError(t,"revokeConsent");this.logError(r)}}getConsentState(){return this.consentManager.getConsentState()}hasConsent(e){return this.consentManager.hasConsent(e)}onConsentChange(e){this.consentManager.addListener(e)}offConsentChange(e){this.consentManager.removeListener(e)}destroy(){if(this.isDestroyed=!0,this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.stopConfigRefreshTimer(),this.configChangeListeners=[],this.heartbeatManager&&(this.heartbeatManager.destroy(),this.heartbeatManager=null),this.pageTrackingManager&&(this.pageTrackingManager.destroy(),this.pageTrackingManager=null),this.activityDetector&&(this.activityDetector.destroy(),this.activityDetector=null),this.eventQueue.length>0){let e=[...this.eventQueue];this.eventQueue=[];let t=this.chunkEvents(e,this.config.maxEventsPerRequest);if(t.length>0){this.sendEventsWithBeacon(t[0]).catch(()=>{});for(let r=1;r<t.length;r++)this.sendEventsWithBeacon(t[r]).catch(()=>{})}}}};function O(a){return new d(a)}var B=d;typeof window<"u"&&(window.Grain={GrainAnalytics:d,createGrainAnalytics:O});return N(J);})();
3
3
  //# sourceMappingURL=index.global.js.map