UNPKG

@deriv-com/analytics

Version:

Comprehensive analytics package for Deriv applications. Provides unified event tracking, A/B testing, and user analytics through RudderStack, PostHog and GrowthBook integrations with built-in caching and offline support.

3 lines 6.72 kB
import {f,d,e,c,g}from'../../chunk-TE3DYZVQ.mjs';import n from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */ var r=class r{constructor(e$1,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=e=>{if(typeof document>"u"||typeof window>"u")return;let t=`ph_${e}_posthog`,o=document.cookie.split(";").map(i=>i.trim().split("=")[0]??"").filter(i=>/^ph_.+_posthog$/.test(i)&&i!==t);if(o.length===0)return;let l=window.location.hostname,d=l.split("."),a=d.length>=2?`.${d.slice(-2).join(".")}`:l;o.forEach(i=>{[a,l,""].forEach(s=>{let g=s?`; Domain=${s}`:"";document.cookie=`${i}=; path=/${g}; max-age=0; SameSite=Lax`;});let c=!document.cookie.split(";").some(s=>s.trim().startsWith(`${i}=`));this.log(`cleanupStalePosthogCookies | ${c?"removed":"failed to remove"} stale cookie: ${i}`);});};this.init=()=>{try{let{apiKey:e$1,api_host:t,config:o={}}=this.options;if(!e$1){console.warn("Posthog: No API key provided");return}if(r._hasLoaded||n.__loaded){this.log("init | PostHog already initialized, skipping re-init"),this.has_initialized=!0;return}this.cleanupStalePosthogCookies(e$1);let l=t||d();this.log("init | loading PostHog SDK",{api_host:l});let d$1={api_host:l,ui_host:c,autocapture:{dom_event_allowlist:["click"]},rate_limiting:{events_per_second:10,events_burst_limit:100},...o,person_profiles:"identified_only",capture_pageview:"history_change",capture_pageleave:!0,session_recording:{...o.session_recording,recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,maskAllInputs:!0},before_send:a=>{if(typeof window>"u"||!a)return null;if(a.timestamp){let s=a.timestamp.getTime(),g=Date.now();if(s<g-6048e5||s>g+6048e5)return this.log("init | before_send dropped event with bad timestamp",{event:a.event,timestamp:a.timestamp.toISOString()}),null}let i=window.location.hostname;if(i!=="localhost"&&i!=="127.0.0.1"&&!e.some(s=>i.endsWith(`.${s}`)||i===s))return this.log("init | before_send blocked event from disallowed host",{currentHost:i}),null;if(o.before_send){let c=Array.isArray(o.before_send)?o.before_send:[o.before_send],s=a;for(let g of c)s=s?g(s):null;return s}return a}};n.init(e$1,d$1),r._hasLoaded=!0,this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(e){console.error("Posthog: Failed to initialize",e);}};this.resetIfStaleId=(e,t,o)=>{r.isAnonymousId(e)||(this.log(`${o} | stale identified user, resetting`,{previous:e,next:t}),n.reset());};this.identifyEvent=(e,t={})=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{if(!e||!e.trim()||r.ILLEGAL_IDS.has(e.toLowerCase())){this.log("identifyEvent | skipped \u2014 invalid user_id",{user_id:e});return}let o=n.get_distinct_id();if(o===e){this.log("identifyEvent | skipped \u2014 user already identified",{user_id:e});return}this.resetIfStaleId(o,e,"identifyEvent"),this.log("identifyEvent | identifying user",{user_id:e,traits:t}),n.identify(e,{...t,client_id:e}),this.has_identified=!0;}catch(o){console.error("Posthog: Failed to identify user",o);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),n.reset(),this.has_identified=!1;}catch(e){console.error("Posthog: Failed to reset",e);}};this.backfillPersonProperties=({user_id:e,email:t,language:o,country_of_residence:l})=>{if(!(!this.has_initialized||!e)){if(!e.trim()||r.ILLEGAL_IDS.has(e.toLowerCase())){this.log("backfillPersonProperties | skipped \u2014 invalid user_id",{user_id:e});return}try{let d=n.get_distinct_id(),a=d===e;a||this.resetIfStaleId(d,e,"backfillPersonProperties");let i={};if(n.get_property("client_id")||(i.client_id=e),t&&n.get_property("is_internal")==null&&(i.is_internal=g(t)),o&&!n.get_property("language")&&(i.language=o),l&&!n.get_property("country_of_residence")&&(i.country_of_residence=l),a){if(Object.keys(i).length===0){this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:e});return}this.log("backfillPersonProperties | backfilling person properties",{user_id:e,updates:i}),n.setPersonProperties(i);}else i.client_id||(i.client_id=e),this.log("backfillPersonProperties | user not identified, identifying now",{user_id:e,updates:i}),n.identify(e,i),this.has_identified=!0;}catch(d){console.error("Posthog: Failed to backfill person properties",d);}}};this.capture=(e,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:e,properties:t}),n.capture(e,t);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.isFeatureEnabled=e=>{if(this.has_initialized)try{let t=n.isFeatureEnabled(e);return this.log("isFeatureEnabled",{key:e,result:t}),t}catch(t){console.error("Posthog: Failed to check feature flag",t);return}};this.getFeatureFlag=e=>{if(this.has_initialized)try{let t=n.getFeatureFlag(e);return this.log("getFeatureFlag",{key:e,result:t}),t}catch(t){console.error("Posthog: Failed to get feature flag",t);return}};this.getFeatureFlagPayload=e=>{if(this.has_initialized)try{let t=n.getFeatureFlagResult(e)?.payload;return this.log("getFeatureFlagPayload",{key:e,result:t}),t}catch(t){console.error("Posthog: Failed to get feature flag payload",t);return}};this.getAllFlags=()=>{if(!this.has_initialized)return {};try{let e=n.featureFlags?.getFlagVariants()??{},t=Object.fromEntries(Object.entries(e).filter(o=>o[1]!=null));return this.log("getAllFlags",{result:t}),t}catch(e){return console.error("Posthog: Failed to get all feature flags",e),{}}};this.onFeatureFlags=e=>{if(!this.has_initialized)return ()=>{};try{this.log("onFeatureFlags | subscribing to feature flag changes");let t=n.onFeatureFlags(e);return typeof t=="function"?t:()=>{}}catch(t){return console.error("Posthog: Failed to subscribe to feature flags",t),()=>{}}};this.reloadFeatureFlags=()=>{if(this.has_initialized)try{this.log("reloadFeatureFlags | reloading feature flags"),n.reloadFeatureFlags();}catch(e){console.error("Posthog: Failed to reload feature flags",e);}};this.options=e$1,this.debug=t,this.init();}};r._hasLoaded=false,r.ILLEGAL_IDS=new Set(["restored","null","undefined","anonymous","guest","distinctid","distinct_id","id","not_authenticated","email","true","false","0","none","nan"]),r.getPosthogInstance=(e,t=false)=>(r._instance?e.apiKey&&e.apiKey!==r._instance.options.apiKey&&console.warn("Posthog: getPosthogInstance called with a different API key \u2014 returning existing instance"):r._instance=new r(e,t),r._instance),r.isAnonymousId=e=>e?/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e):true;var m=r;export{m as Posthog};//# sourceMappingURL=index.mjs.map //# sourceMappingURL=index.mjs.map