@deriv-com/analytics 1.41.0 → 1.42.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.
@@ -138,7 +138,7 @@ declare class Posthog {
138
138
  *
139
139
  * @param key - The feature flag key
140
140
  */
141
- getFeatureFlagPayload: (key: string) => Record<string, any> | undefined;
141
+ getFeatureFlagPayload: (key: string) => string | number | boolean | null | Record<string, unknown> | unknown[] | undefined;
142
142
  /**
143
143
  * Get all currently active feature flags and their values.
144
144
  *
@@ -138,7 +138,7 @@ declare class Posthog {
138
138
  *
139
139
  * @param key - The feature flag key
140
140
  */
141
- getFeatureFlagPayload: (key: string) => Record<string, any> | undefined;
141
+ getFeatureFlagPayload: (key: string) => string | number | boolean | null | Record<string, unknown> | unknown[] | undefined;
142
142
  /**
143
143
  * Get all currently active feature flags and their values.
144
144
  *
@@ -1,2 +1,2 @@
1
- export { P as Posthog } from '../../posthog-DYLYirAm.mjs';
1
+ export { P as Posthog } from '../../posthog-ctBaPjWr.mjs';
2
2
  import 'posthog-js';
@@ -1,2 +1,2 @@
1
- export { P as Posthog } from '../../posthog-DYLYirAm.js';
1
+ export { P as Posthog } from '../../posthog-ctBaPjWr.js';
2
2
  import 'posthog-js';
@@ -1,3 +1,3 @@
1
1
  'use strict';var chunkT4BXL6JM_js=require('../../chunk-T4BXL6JM.js'),r=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var r__default=/*#__PURE__*/_interopDefault(r);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var g=class g{constructor(e,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkT4BXL6JM_js.f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=e=>{if(typeof document>"u"||typeof window>"u")return;let t=`ph_${e}_posthog`,i=document.cookie.split(";").map(o=>o.trim().split("=")[0]??"").filter(o=>/^ph_.+_posthog$/.test(o)&&o!==t);if(i.length===0)return;let a=window.location.hostname,n=a.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:a;i.forEach(o=>{[s,a,""].forEach(l=>{let F=l?`; Domain=${l}`:"";document.cookie=`${o}=; path=/${F}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.trim().startsWith(`${o}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${o}`);});};this.init=()=>{try{let{apiKey:e,api_host:t,config:i={}}=this.options;if(!e){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(e);let a=t||chunkT4BXL6JM_js.d();this.log("init | loading PostHog SDK",{api_host:a});let n={api_host:a,ui_host:chunkT4BXL6JM_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...i.session_recording},before_send:s=>{if(typeof window>"u")return null;let o=window.location.hostname;if(o==="localhost"||o==="127.0.0.1")return s;let d=chunkT4BXL6JM_js.e.some(l=>o.endsWith(`.${l}`)||o===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:o}),d?s:null},...i};r__default.default.init(e,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(e){console.error("Posthog: Failed to initialize",e);}};this.identifyEvent=(e,t={})=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let i=typeof r__default.default._isIdentified=="function"?r__default.default._isIdentified():this.has_identified;e&&!i?(this.log("identifyEvent | identifying user",{user_id:e,traits:t}),r__default.default.identify(e,{...t,client_id:e}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:e});}catch(i){console.error("Posthog: Failed to identify user",i);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r__default.default.reset(),this.has_identified=!1;}catch(e){console.error("Posthog: Failed to reset",e);}};this.backfillPersonProperties=({user_id:e,email:t,language:i,country_of_residence:a})=>{if(!(!this.has_initialized||!e))try{let n=r__default.default.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=e),t&&n.is_internal===void 0&&(s.is_internal=chunkT4BXL6JM_js.g(t)),i&&!n.language&&(s.language=i),a&&!n.country_of_residence&&(s.country_of_residence=a),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:e,updates:s}),r__default.default.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:e,country_of_residence:a});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(e,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:e,properties:t}),r__default.default.capture(e,t);}catch(i){console.error("Posthog: Failed to capture event",i);}};this.isFeatureEnabled=e=>{if(this.has_initialized)try{let t=r__default.default.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=r__default.default.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=r__default.default.featureFlags?.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=r__default.default.featureFlags?.getFlagVariants()??{};return this.log("getAllFlags",{result:e}),e}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=r__default.default.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"),r__default.default.reloadFeatureFlags();}catch(e){console.error("Posthog: Failed to reload feature flags",e);}};this.options=e,this.debug=t,this.init();}};g.getPosthogInstance=(e,t=false)=>(g._instance||(g._instance=new g(e,t)),g._instance);var P=g;exports.Posthog=P;//# sourceMappingURL=index.js.map
2
+ var g=class g{constructor(e,t=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkT4BXL6JM_js.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 a=window.location.hostname,n=a.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:a;o.forEach(i=>{[s,a,""].forEach(l=>{let F=l?`; Domain=${l}`:"";document.cookie=`${i}=; path=/${F}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.trim().startsWith(`${i}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${i}`);});};this.init=()=>{try{let{apiKey:e,api_host:t,config:o={}}=this.options;if(!e){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(e);let a=t||chunkT4BXL6JM_js.d();this.log("init | loading PostHog SDK",{api_host:a});let n={api_host:a,ui_host:chunkT4BXL6JM_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,maskAllInputs:!0,...o.session_recording},before_send:s=>{if(typeof window>"u")return null;let i=window.location.hostname;if(i==="localhost"||i==="127.0.0.1")return s;let d=chunkT4BXL6JM_js.e.some(l=>i.endsWith(`.${l}`)||i===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:i}),d?s:null},...o};r__default.default.init(e,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(e){console.error("Posthog: Failed to initialize",e);}};this.identifyEvent=(e,t={})=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=this.has_identified&&r__default.default.get_distinct_id()===e;e&&!o?(this.log("identifyEvent | identifying user",{user_id:e,traits:t}),r__default.default.identify(e,{...t,client_id:e}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:e});}catch(o){console.error("Posthog: Failed to identify user",o);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r__default.default.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:a})=>{if(!(!this.has_initialized||!e))try{let n=r__default.default.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=e),t&&n.is_internal===void 0&&(s.is_internal=chunkT4BXL6JM_js.g(t)),o&&!n.language&&(s.language=o),a&&!n.country_of_residence&&(s.country_of_residence=a),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:e,updates:s}),r__default.default.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:e,country_of_residence:a});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(e,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:e,properties:t}),r__default.default.capture(e,t);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.isFeatureEnabled=e=>{if(this.has_initialized)try{let t=r__default.default.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=r__default.default.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=r__default.default.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=r__default.default.featureFlags?.getFlagVariants()??{};return this.log("getAllFlags",{result:e}),e}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=r__default.default.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"),r__default.default.reloadFeatureFlags();}catch(e){console.error("Posthog: Failed to reload feature flags",e);}};this.options=e,this.debug=t,this.init();}};g.getPosthogInstance=(e,t=false)=>(g._instance||(g._instance=new g(e,t)),g._instance);var P=g;exports.Posthog=P;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","currentApiKey","currentCookieName","staleCookies","c","name","hostname","domainParts","rootDomain","domain","domainAttr","deleted","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","posthog","error","user_id","traits","isIdentified","email","language","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","key","result","callback","unsubscribe","Posthog"],"mappings":";AAoBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,YAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,MAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,MAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,KAAQ,KAAA,CAAQ,KAAA,CAChB,KAAQ,GAAA,CAAMC,kBAAAA,CAAa,YAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,2BAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,KAAe,OAAO,MAAA,CAAW,IAAa,OAEtE,IAAMC,EAAoB,CAAA,GAAA,EAAMD,CAAa,CAAA,QAAA,CAAA,CACvCE,CAAAA,CAAe,QA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,CAAM,0CAAA,CAA4CA,CAAK,CAAA,CACxD,EACX,CACJ,CAAA,CASA,IAAA,CAAA,cAAA,CACIc,GACe,CACf,GAAI,CAAC,IAAA,CAAK,eAAA,CAAiB,OAAO,IAAM,CAAC,EAEzC,GAAI,CACA,KAAK,GAAA,CAAI,sDAAsD,EAC/D,IAAMC,CAAAA,CAAchB,mBAAQ,cAAA,CAAee,CAAQ,EACnD,OAAO,OAAOC,GAAgB,UAAA,CAAaA,CAAAA,CAAc,IAAM,CAAC,CACpE,OAASf,CAAAA,CAAO,CACZ,eAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,CAAA,CAC7D,IAAM,CAAC,CAClB,CACJ,EAMA,IAAA,CAAA,kBAAA,CAAqB,IAAY,CAC7B,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,IAAI,8CAA8C,CAAA,CACvDD,mBAAQ,kBAAA,GACZ,OAASC,CAAAA,CAAO,CACZ,QAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAK,EAClE,CACJ,EA/UI,IAAA,CAAK,OAAA,CAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,KAAK,IAAA,GACT,CA6UJ,CAAA,CAzVaF,CAAAA,CAoBK,mBAAqB,CAACC,CAAAA,CAA0BC,EAAQ,KAAA,IAC7DF,CAAAA,CAAQ,YACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM2C,CAAAA,CAAN3C","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Remove stale PostHog cookies that don't belong to the current project key.\n * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys\n * have been used in the same browser, old cookies pile up and should be cleaned.\n */\n private cleanupStalePosthogCookies = (currentApiKey: string): void => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return\n\n const currentCookieName = `ph_${currentApiKey}_posthog`\n const staleCookies = document.cookie\n .split(';')\n .map(c => c.trim().split('=')[0] ?? '')\n .filter(name => /^ph_.+_posthog$/.test(name) && name !== currentCookieName)\n\n if (staleCookies.length === 0) return\n\n const hostname = window.location.hostname\n const domainParts = hostname.split('.')\n // TLD+2 assumption: works for deriv.com → .deriv.com but would produce\n // .co.uk for app.deriv.co.uk. Acceptable for current Deriv domains.\n const rootDomain = domainParts.length >= 2 ? `.${domainParts.slice(-2).join('.')}` : hostname\n\n staleCookies.forEach(name => {\n // Try deleting with root domain, subdomain, and no domain\n ;[rootDomain, hostname, ''].forEach(domain => {\n const domainAttr = domain ? `; Domain=${domain}` : ''\n document.cookie = `${name}=; path=/${domainAttr}; max-age=0; SameSite=Lax`\n })\n const deleted = !document.cookie.split(';').some(c => c.trim().startsWith(`${name}=`))\n this.log(`cleanupStalePosthogCookies | ${deleted ? 'removed' : 'failed to remove'} stale cookie: ${name}`)\n })\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n this.cleanupStalePosthogCookies(apiKey)\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits = {}): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.language - The user's language (BCP 47 tag, e.g. \"en-GB\")\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n language,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n language?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (language && !storedProperties.language) {\n updates.language = language\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n\n /**\n * Check whether a feature flag is enabled for the current user.\n *\n * @param key - The feature flag key\n * @returns true/false, or undefined if PostHog is not ready\n */\n isFeatureEnabled = (key: string): boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.isFeatureEnabled(key)\n this.log('isFeatureEnabled', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to check feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the value of a feature flag.\n * Returns a string variant for multivariate flags, true/false for boolean flags,\n * or undefined if the flag does not exist or PostHog is not ready.\n *\n * @param key - The feature flag key\n */\n getFeatureFlag = (key: string): string | boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.getFeatureFlag(key)\n this.log('getFeatureFlag', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the JSON payload associated with a feature flag.\n * Payloads allow attaching structured metadata (e.g. config objects) to a flag.\n *\n * @param key - The feature flag key\n */\n getFeatureFlagPayload = (key: string): Record<string, any> | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.featureFlags?.getFeatureFlagResult(key)?.payload as Record<string, any> | undefined\n this.log('getFeatureFlagPayload', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag payload', error)\n return undefined\n }\n }\n\n /**\n * Get all currently active feature flags and their values.\n *\n * @returns A map of flag key → value (boolean or string variant)\n */\n getAllFlags = (): Record<string, string | boolean> => {\n if (!this.has_initialized) return {}\n\n try {\n const result = posthog.featureFlags?.getFlagVariants() ?? {}\n this.log('getAllFlags', { result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get all feature flags', error)\n return {}\n }\n }\n\n /**\n * Subscribe to feature flag changes.\n * The callback fires immediately with the current flags and again whenever they are reloaded.\n *\n * @param callback - Receives the list of active flag keys and a map of key → variant\n * @returns An unsubscribe function — call it to stop listening\n */\n onFeatureFlags = (\n callback: (flags: string[], variants: Record<string, string | boolean>) => void\n ): (() => void) => {\n if (!this.has_initialized) return () => {}\n\n try {\n this.log('onFeatureFlags | subscribing to feature flag changes')\n const unsubscribe = posthog.onFeatureFlags(callback)\n return typeof unsubscribe === 'function' ? unsubscribe : () => {}\n } catch (error) {\n console.error('Posthog: Failed to subscribe to feature flags', error)\n return () => {}\n }\n }\n\n /**\n * Force PostHog to reload feature flags from the server.\n * Useful after login, logout, or any attribute change that may affect targeting.\n */\n reloadFeatureFlags = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reloadFeatureFlags | reloading feature flags')\n posthog.reloadFeatureFlags()\n } catch (error) {\n console.error('Posthog: Failed to reload feature flags', error)\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","currentApiKey","currentCookieName","staleCookies","c","name","hostname","domainParts","rootDomain","domain","domainAttr","deleted","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","posthog","error","user_id","traits","alreadyThisUser","email","language","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","key","result","callback","unsubscribe","Posthog"],"mappings":";AAoBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,YAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,MAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,MAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,KAAQ,KAAA,CAAQ,KAAA,CAChB,KAAQ,GAAA,CAAMC,kBAAAA,CAAa,YAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,2BAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,KAAe,OAAO,M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X,OAASb,CAAAA,CAAO,CACZ,eAAQ,KAAA,CAAM,0CAAA,CAA4CA,CAAK,CAAA,CACxD,EACX,CACJ,CAAA,CASA,IAAA,CAAA,cAAA,CACIc,GACe,CACf,GAAI,CAAC,IAAA,CAAK,eAAA,CAAiB,OAAO,IAAM,CAAC,EAEzC,GAAI,CACA,KAAK,GAAA,CAAI,sDAAsD,EAC/D,IAAMC,CAAAA,CAAchB,mBAAQ,cAAA,CAAee,CAAQ,EACnD,OAAO,OAAOC,GAAgB,UAAA,CAAaA,CAAAA,CAAc,IAAM,CAAC,CACpE,OAASf,CAAAA,CAAO,CACZ,eAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,CAAA,CAC7D,IAAM,CAAC,CAClB,CACJ,EAMA,IAAA,CAAA,kBAAA,CAAqB,IAAY,CAC7B,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,IAAI,8CAA8C,CAAA,CACvDD,mBAAQ,kBAAA,GACZ,OAASC,CAAAA,CAAO,CACZ,QAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAK,EAClE,CACJ,EAxVI,IAAA,CAAK,OAAA,CAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,KAAK,IAAA,GACT,CAsVJ,CAAA,CAlWaF,CAAAA,CAoBK,mBAAqB,CAACC,CAAAA,CAA0BC,EAAQ,KAAA,IAC7DF,CAAAA,CAAQ,YACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM2C,CAAAA,CAAN3C","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Remove stale PostHog cookies that don't belong to the current project key.\n * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys\n * have been used in the same browser, old cookies pile up and should be cleaned.\n */\n private cleanupStalePosthogCookies = (currentApiKey: string): void => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return\n\n const currentCookieName = `ph_${currentApiKey}_posthog`\n const staleCookies = document.cookie\n .split(';')\n .map(c => c.trim().split('=')[0] ?? '')\n .filter(name => /^ph_.+_posthog$/.test(name) && name !== currentCookieName)\n\n if (staleCookies.length === 0) return\n\n const hostname = window.location.hostname\n const domainParts = hostname.split('.')\n // TLD+2 assumption: works for deriv.com → .deriv.com but would produce\n // .co.uk for app.deriv.co.uk. Acceptable for current Deriv domains.\n const rootDomain = domainParts.length >= 2 ? `.${domainParts.slice(-2).join('.')}` : hostname\n\n staleCookies.forEach(name => {\n // Try deleting with root domain, subdomain, and no domain\n ;[rootDomain, hostname, ''].forEach(domain => {\n const domainAttr = domain ? `; Domain=${domain}` : ''\n document.cookie = `${name}=; path=/${domainAttr}; max-age=0; SameSite=Lax`\n })\n const deleted = !document.cookie.split(';').some(c => c.trim().startsWith(`${name}=`))\n this.log(`cleanupStalePosthogCookies | ${deleted ? 'removed' : 'failed to remove'} stale cookie: ${name}`)\n })\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n this.cleanupStalePosthogCookies(apiKey)\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n maskAllInputs: true,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits = {}): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const alreadyThisUser = this.has_identified && posthog.get_distinct_id() === user_id\n\n if (user_id && !alreadyThisUser) {\n this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.language - The user's language (BCP 47 tag, e.g. \"en-GB\")\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n language,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n language?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (language && !storedProperties.language) {\n updates.language = language\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n\n /**\n * Check whether a feature flag is enabled for the current user.\n *\n * @param key - The feature flag key\n * @returns true/false, or undefined if PostHog is not ready\n */\n isFeatureEnabled = (key: string): boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.isFeatureEnabled(key)\n this.log('isFeatureEnabled', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to check feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the value of a feature flag.\n * Returns a string variant for multivariate flags, true/false for boolean flags,\n * or undefined if the flag does not exist or PostHog is not ready.\n *\n * @param key - The feature flag key\n */\n getFeatureFlag = (key: string): string | boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.getFeatureFlag(key)\n this.log('getFeatureFlag', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the JSON payload associated with a feature flag.\n * Payloads allow attaching structured metadata (e.g. config objects) to a flag.\n *\n * @param key - The feature flag key\n */\n getFeatureFlagPayload = (\n key: string\n ): string | number | boolean | null | Record<string, unknown> | unknown[] | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.getFeatureFlagResult(key)?.payload as\n | string\n | number\n | boolean\n | null\n | Record<string, unknown>\n | unknown[]\n | undefined\n this.log('getFeatureFlagPayload', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag payload', error)\n return undefined\n }\n }\n\n /**\n * Get all currently active feature flags and their values.\n *\n * @returns A map of flag key → value (boolean or string variant)\n */\n getAllFlags = (): Record<string, string | boolean> => {\n if (!this.has_initialized) return {}\n\n try {\n const result = posthog.featureFlags?.getFlagVariants() ?? {}\n this.log('getAllFlags', { result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get all feature flags', error)\n return {}\n }\n }\n\n /**\n * Subscribe to feature flag changes.\n * The callback fires immediately with the current flags and again whenever they are reloaded.\n *\n * @param callback - Receives the list of active flag keys and a map of key → variant\n * @returns An unsubscribe function — call it to stop listening\n */\n onFeatureFlags = (\n callback: (flags: string[], variants: Record<string, string | boolean>) => void\n ): (() => void) => {\n if (!this.has_initialized) return () => {}\n\n try {\n this.log('onFeatureFlags | subscribing to feature flag changes')\n const unsubscribe = posthog.onFeatureFlags(callback)\n return typeof unsubscribe === 'function' ? unsubscribe : () => {}\n } catch (error) {\n console.error('Posthog: Failed to subscribe to feature flags', error)\n return () => {}\n }\n }\n\n /**\n * Force PostHog to reload feature flags from the server.\n * Useful after login, logout, or any attribute change that may affect targeting.\n */\n reloadFeatureFlags = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reloadFeatureFlags | reloading feature flags')\n posthog.reloadFeatureFlags()\n } catch (error) {\n console.error('Posthog: Failed to reload feature flags', error)\n }\n }\n}\n"]}
@@ -1,3 +1,3 @@
1
1
  import {f,d,e,c,g as g$1}from'../../chunk-TE3DYZVQ.mjs';import r from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var g=class g{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`,i=document.cookie.split(";").map(o=>o.trim().split("=")[0]??"").filter(o=>/^ph_.+_posthog$/.test(o)&&o!==t);if(i.length===0)return;let a=window.location.hostname,n=a.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:a;i.forEach(o=>{[s,a,""].forEach(l=>{let F=l?`; Domain=${l}`:"";document.cookie=`${o}=; path=/${F}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.trim().startsWith(`${o}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${o}`);});};this.init=()=>{try{let{apiKey:e$1,api_host:t,config:i={}}=this.options;if(!e$1){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(e$1);let a=t||d();this.log("init | loading PostHog SDK",{api_host:a});let n={api_host:a,ui_host:c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...i.session_recording},before_send:s=>{if(typeof window>"u")return null;let o=window.location.hostname;if(o==="localhost"||o==="127.0.0.1")return s;let d=e.some(l=>o.endsWith(`.${l}`)||o===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:o}),d?s:null},...i};r.init(e$1,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(e){console.error("Posthog: Failed to initialize",e);}};this.identifyEvent=(e,t={})=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let i=typeof r._isIdentified=="function"?r._isIdentified():this.has_identified;e&&!i?(this.log("identifyEvent | identifying user",{user_id:e,traits:t}),r.identify(e,{...t,client_id:e}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:e});}catch(i){console.error("Posthog: Failed to identify user",i);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r.reset(),this.has_identified=!1;}catch(e){console.error("Posthog: Failed to reset",e);}};this.backfillPersonProperties=({user_id:e,email:t,language:i,country_of_residence:a})=>{if(!(!this.has_initialized||!e))try{let n=r.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=e),t&&n.is_internal===void 0&&(s.is_internal=g$1(t)),i&&!n.language&&(s.language=i),a&&!n.country_of_residence&&(s.country_of_residence=a),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:e,updates:s}),r.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:e,country_of_residence:a});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(e,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:e,properties:t}),r.capture(e,t);}catch(i){console.error("Posthog: Failed to capture event",i);}};this.isFeatureEnabled=e=>{if(this.has_initialized)try{let t=r.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=r.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=r.featureFlags?.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=r.featureFlags?.getFlagVariants()??{};return this.log("getAllFlags",{result:e}),e}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=r.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"),r.reloadFeatureFlags();}catch(e){console.error("Posthog: Failed to reload feature flags",e);}};this.options=e$1,this.debug=t,this.init();}};g.getPosthogInstance=(e,t=false)=>(g._instance||(g._instance=new g(e,t)),g._instance);var P=g;export{P as Posthog};//# sourceMappingURL=index.mjs.map
2
+ var g=class g{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 a=window.location.hostname,n=a.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:a;o.forEach(i=>{[s,a,""].forEach(l=>{let F=l?`; Domain=${l}`:"";document.cookie=`${i}=; path=/${F}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.trim().startsWith(`${i}=`));this.log(`cleanupStalePosthogCookies | ${d?"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}this.cleanupStalePosthogCookies(e$1);let a=t||d();this.log("init | loading PostHog SDK",{api_host:a});let n={api_host:a,ui_host:c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,maskAllInputs:!0,...o.session_recording},before_send:s=>{if(typeof window>"u")return null;let i=window.location.hostname;if(i==="localhost"||i==="127.0.0.1")return s;let d=e.some(l=>i.endsWith(`.${l}`)||i===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:i}),d?s:null},...o};r.init(e$1,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(e){console.error("Posthog: Failed to initialize",e);}};this.identifyEvent=(e,t={})=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=this.has_identified&&r.get_distinct_id()===e;e&&!o?(this.log("identifyEvent | identifying user",{user_id:e,traits:t}),r.identify(e,{...t,client_id:e}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:e});}catch(o){console.error("Posthog: Failed to identify user",o);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),r.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:a})=>{if(!(!this.has_initialized||!e))try{let n=r.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=e),t&&n.is_internal===void 0&&(s.is_internal=g$1(t)),o&&!n.language&&(s.language=o),a&&!n.country_of_residence&&(s.country_of_residence=a),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:e,updates:s}),r.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:e,country_of_residence:a});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(e,t)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:e,properties:t}),r.capture(e,t);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.isFeatureEnabled=e=>{if(this.has_initialized)try{let t=r.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=r.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=r.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=r.featureFlags?.getFlagVariants()??{};return this.log("getAllFlags",{result:e}),e}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=r.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"),r.reloadFeatureFlags();}catch(e){console.error("Posthog: Failed to reload feature flags",e);}};this.options=e$1,this.debug=t,this.init();}};g.getPosthogInstance=(e,t=false)=>(g._instance||(g._instance=new g(e,t)),g._instance);var P=g;export{P as Posthog};//# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","currentApiKey","currentCookieName","staleCookies","c","name","hostname","domainParts","rootDomain","domain","domainAttr","deleted","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","posthog","error","user_id","traits","isIdentified","email","language","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","key","result","callback","unsubscribe","Posthog"],"mappings":";AAoBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,YAAYC,GAAAA,CAA0BC,CAAAA,CAAQ,MAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,MAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,KAAQ,KAAA,CAAQ,KAAA,CAChB,KAAQ,GAAA,CAAMC,CAAAA,CAAa,YAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,2BAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,KAAe,OAAO,MAAA,CAAW,IAAa,OAEtE,IAAMC,EAAoB,CAAA,GAAA,EAAMD,CAAa,CAAA,QAAA,CAAA,CACvCE,CAAAA,CAAe,QAAA,CAAS,MAAA,CACzB,MAAM,GAAG,CAAA,CACT,IAAIC,CAAAA,EAAKA,CAAAA,CAAE,MAAK,CAAE,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,GAAK,EAAE,CAAA,CACrC,OAAOC,CAAAA,EAAQ,iBAAA,CAAkB,KAAKA,CAAI,CAAA,EAAKA,IAASH,CAAiB,CAAA,CAE9E,GAAIC,CAAAA,CAAa,MAAA,GAAW,EAAG,OAE/B,IAAMG,EAAW,MAAA,CAAO,QAAA,CAAS,SAC3BC,CAAAA,CAAcD,CAAAA,CAAS,MAAM,GAAG,CAAA,CAGhCE,EAAaD,CAAAA,CAAY,MAAA,EAAU,EAAI,CAAA,CAA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AqB,IAAY,CAC7B,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,IAAI,8CAA8C,CAAA,CACvDD,EAAQ,kBAAA,GACZ,OAASC,CAAAA,CAAO,CACZ,QAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAK,EAClE,CACJ,EA/UI,IAAA,CAAK,OAAA,CAAU1B,GAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,KAAK,IAAA,GACT,CA6UJ,CAAA,CAzVaF,CAAAA,CAoBK,mBAAqB,CAACC,CAAAA,CAA0BC,EAAQ,KAAA,IAC7DF,CAAAA,CAAQ,YACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM2C,CAAAA,CAAN3C","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Remove stale PostHog cookies that don't belong to the current project key.\n * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys\n * have been used in the same browser, old cookies pile up and should be cleaned.\n */\n private cleanupStalePosthogCookies = (currentApiKey: string): void => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return\n\n const currentCookieName = `ph_${currentApiKey}_posthog`\n const staleCookies = document.cookie\n .split(';')\n .map(c => c.trim().split('=')[0] ?? '')\n .filter(name => /^ph_.+_posthog$/.test(name) && name !== currentCookieName)\n\n if (staleCookies.length === 0) return\n\n const hostname = window.location.hostname\n const domainParts = hostname.split('.')\n // TLD+2 assumption: works for deriv.com → .deriv.com but would produce\n // .co.uk for app.deriv.co.uk. Acceptable for current Deriv domains.\n const rootDomain = domainParts.length >= 2 ? `.${domainParts.slice(-2).join('.')}` : hostname\n\n staleCookies.forEach(name => {\n // Try deleting with root domain, subdomain, and no domain\n ;[rootDomain, hostname, ''].forEach(domain => {\n const domainAttr = domain ? `; Domain=${domain}` : ''\n document.cookie = `${name}=; path=/${domainAttr}; max-age=0; SameSite=Lax`\n })\n const deleted = !document.cookie.split(';').some(c => c.trim().startsWith(`${name}=`))\n this.log(`cleanupStalePosthogCookies | ${deleted ? 'removed' : 'failed to remove'} stale cookie: ${name}`)\n })\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n this.cleanupStalePosthogCookies(apiKey)\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits = {}): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const isIdentified =\n typeof posthog._isIdentified === 'function' ? posthog._isIdentified() : this.has_identified\n\n if (user_id && !isIdentified) {\n this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.language - The user's language (BCP 47 tag, e.g. \"en-GB\")\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n language,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n language?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (language && !storedProperties.language) {\n updates.language = language\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n\n /**\n * Check whether a feature flag is enabled for the current user.\n *\n * @param key - The feature flag key\n * @returns true/false, or undefined if PostHog is not ready\n */\n isFeatureEnabled = (key: string): boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.isFeatureEnabled(key)\n this.log('isFeatureEnabled', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to check feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the value of a feature flag.\n * Returns a string variant for multivariate flags, true/false for boolean flags,\n * or undefined if the flag does not exist or PostHog is not ready.\n *\n * @param key - The feature flag key\n */\n getFeatureFlag = (key: string): string | boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.getFeatureFlag(key)\n this.log('getFeatureFlag', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the JSON payload associated with a feature flag.\n * Payloads allow attaching structured metadata (e.g. config objects) to a flag.\n *\n * @param key - The feature flag key\n */\n getFeatureFlagPayload = (key: string): Record<string, any> | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.featureFlags?.getFeatureFlagResult(key)?.payload as Record<string, any> | undefined\n this.log('getFeatureFlagPayload', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag payload', error)\n return undefined\n }\n }\n\n /**\n * Get all currently active feature flags and their values.\n *\n * @returns A map of flag key → value (boolean or string variant)\n */\n getAllFlags = (): Record<string, string | boolean> => {\n if (!this.has_initialized) return {}\n\n try {\n const result = posthog.featureFlags?.getFlagVariants() ?? {}\n this.log('getAllFlags', { result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get all feature flags', error)\n return {}\n }\n }\n\n /**\n * Subscribe to feature flag changes.\n * The callback fires immediately with the current flags and again whenever they are reloaded.\n *\n * @param callback - Receives the list of active flag keys and a map of key → variant\n * @returns An unsubscribe function — call it to stop listening\n */\n onFeatureFlags = (\n callback: (flags: string[], variants: Record<string, string | boolean>) => void\n ): (() => void) => {\n if (!this.has_initialized) return () => {}\n\n try {\n this.log('onFeatureFlags | subscribing to feature flag changes')\n const unsubscribe = posthog.onFeatureFlags(callback)\n return typeof unsubscribe === 'function' ? unsubscribe : () => {}\n } catch (error) {\n console.error('Posthog: Failed to subscribe to feature flags', error)\n return () => {}\n }\n }\n\n /**\n * Force PostHog to reload feature flags from the server.\n * Useful after login, logout, or any attribute change that may affect targeting.\n */\n reloadFeatureFlags = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reloadFeatureFlags | reloading feature flags')\n posthog.reloadFeatureFlags()\n } catch (error) {\n console.error('Posthog: Failed to reload feature flags', error)\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../../../src/providers/posthog.ts"],"names":["_Posthog","options","debug","createLogger","currentApiKey","currentCookieName","staleCookies","c","name","hostname","domainParts","rootDomain","domain","domainAttr","deleted","apiKey","api_host","config","resolvedApiHost","getPosthogApiHost","posthogConfig","posthogUiHost","event","currentHost","isAllowed","allowedDomains","posthog","error","user_id","traits","alreadyThisUser","email","language","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","key","result","callback","unsubscribe","Posthog"],"mappings":";AAoBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,YAAYC,GAAAA,CAA0BC,CAAAA,CAAQ,MAAO,CAPrD,IAAA,CAAA,eAAA,CAAkB,MAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,KAAQ,KAAA,CAAQ,KAAA,CAChB,KAAQ,GAAA,CAAMC,CAAAA,CAAa,YAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,2BAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,KAAe,OAAO,MAAA,CAAW,IAAa,OAEtE,IAAMC,EAAoB,CAAA,GAAA,EAAMD,CAAa,CAAA,QAAA,CAAA,CACvCE,CAAAA,CAAe,QAAA,CAAS,MAAA,CACzB,MAAM,GAAG,CAAA,CACT,IAAIC,CAAAA,EAAKA,CAAAA,CAAE,MAAK,CAAE,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,GAAK,EAAE,CAAA,CACrC,OAAOC,CAAAA,EAAQ,iBAAA,CAAkB,KAAKA,CAAI,CAAA,EAAKA,IAASH,CAAiB,CAAA,CAE9E,GAAIC,CAAAA,CAAa,MAAA,GAAW,EAAG,OAE/B,IAAMG,EAAW,MAAA,CAAO,QAAA,CAAS,SAC3BC,CAAAA,CAAcD,CAA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AAA,CAAA,kBAAA,CAAqB,IAAY,CAC7B,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,IAAI,8CAA8C,CAAA,CACvDD,EAAQ,kBAAA,GACZ,OAASC,CAAAA,CAAO,CACZ,QAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAK,EAClE,CACJ,EAxVI,IAAA,CAAK,OAAA,CAAU1B,GAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,KAAK,IAAA,GACT,CAsVJ,CAAA,CAlWaF,CAAAA,CAoBK,mBAAqB,CAACC,CAAAA,CAA0BC,EAAQ,KAAA,IAC7DF,CAAAA,CAAQ,YACTA,CAAAA,CAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,CAxBhB,IAAM2C,CAAAA,CAAN3C","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport { allowedDomains, getPosthogApiHost, posthogUiHost } from '../utils/urls'\nimport { createLogger, isInternalEmail } from '../utils/helpers'\n\n/**\n * PostHog analytics wrapper with singleton pattern.\n * Provides optional PostHog integration for event tracking and session recording.\n *\n * Features:\n * - Dynamically loads PostHog SDK on demand\n * - Domain allowlisting for security\n * - Automatic user identification with client_id enforcement\n * - client_id backfill for previously identified users via backfillPersonProperties\n * - Custom event tracking with property sanitization\n * - Built-in caching and retry mechanisms (handled by posthog-js library)\n *\n * Note: PostHog handles its own event queuing, caching, and retry logic internally.\n * No additional caching is needed at the wrapper level.\n */\nexport class Posthog {\n has_initialized = false\n has_identified = false\n private static _instance: Posthog\n private options: TPosthogOptions\n private debug = false\n private log = createLogger('[PostHog]', () => this.debug)\n\n constructor(options: TPosthogOptions, debug = false) {\n this.options = options\n this.debug = debug\n this.init()\n }\n\n /**\n * Get or create the singleton instance of Posthog\n * @param options - PostHog configuration options including API key\n * @param debug - Enable debug logging\n * @returns The Posthog singleton instance\n */\n public static getPosthogInstance = (options: TPosthogOptions, debug = false): Posthog => {\n if (!Posthog._instance) {\n Posthog._instance = new Posthog(options, debug)\n }\n return Posthog._instance\n }\n\n /**\n * Remove stale PostHog cookies that don't belong to the current project key.\n * PostHog sets cookies named `ph_{apiKey}_posthog` — if multiple project keys\n * have been used in the same browser, old cookies pile up and should be cleaned.\n */\n private cleanupStalePosthogCookies = (currentApiKey: string): void => {\n if (typeof document === 'undefined' || typeof window === 'undefined') return\n\n const currentCookieName = `ph_${currentApiKey}_posthog`\n const staleCookies = document.cookie\n .split(';')\n .map(c => c.trim().split('=')[0] ?? '')\n .filter(name => /^ph_.+_posthog$/.test(name) && name !== currentCookieName)\n\n if (staleCookies.length === 0) return\n\n const hostname = window.location.hostname\n const domainParts = hostname.split('.')\n // TLD+2 assumption: works for deriv.com → .deriv.com but would produce\n // .co.uk for app.deriv.co.uk. Acceptable for current Deriv domains.\n const rootDomain = domainParts.length >= 2 ? `.${domainParts.slice(-2).join('.')}` : hostname\n\n staleCookies.forEach(name => {\n // Try deleting with root domain, subdomain, and no domain\n ;[rootDomain, hostname, ''].forEach(domain => {\n const domainAttr = domain ? `; Domain=${domain}` : ''\n document.cookie = `${name}=; path=/${domainAttr}; max-age=0; SameSite=Lax`\n })\n const deleted = !document.cookie.split(';').some(c => c.trim().startsWith(`${name}=`))\n this.log(`cleanupStalePosthogCookies | ${deleted ? 'removed' : 'failed to remove'} stale cookie: ${name}`)\n })\n }\n\n /**\n * Initialize PostHog with configuration\n * Configures PostHog instance with provided options\n */\n init = (): void => {\n try {\n const { apiKey, api_host, config = {} } = this.options\n\n if (!apiKey) {\n console.warn('Posthog: No API key provided')\n return\n }\n\n this.cleanupStalePosthogCookies(apiKey)\n\n const resolvedApiHost = api_host || getPosthogApiHost()\n this.log('init | loading PostHog SDK', { api_host: resolvedApiHost })\n\n const posthogConfig: TPosthogConfig = {\n api_host: resolvedApiHost,\n ui_host: posthogUiHost,\n autocapture: true,\n capture_pageview: 'history_change',\n session_recording: {\n recordCrossOriginIframes: true,\n minimumDurationMilliseconds: 30000,\n maskAllInputs: true,\n ...config.session_recording,\n },\n before_send: event => {\n if (typeof window === 'undefined') return null\n\n const currentHost = window.location.hostname\n if (currentHost === 'localhost' || currentHost === '127.0.0.1') return event\n\n const isAllowed = allowedDomains.some(\n domain => currentHost.endsWith(`.${domain}`) || currentHost === domain\n )\n if (!isAllowed) this.log('init | before_send blocked event from disallowed host', { currentHost })\n return isAllowed ? event : null\n },\n ...config,\n }\n\n // Initialize PostHog\n posthog.init(apiKey, posthogConfig)\n this.has_initialized = true\n this.log('init | PostHog SDK loaded successfully')\n } catch (error) {\n console.error('Posthog: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with PostHog.\n * Skipped if the user is already identified — use backfillPersonProperties to backfill\n * client_id for users identified in previous sessions.\n *\n * @param user_id - The user ID to identify\n * @param traits - User properties (language, country_of_residence, etc.)\n */\n identifyEvent = (user_id: string, traits: TPosthogIdentifyTraits = {}): void => {\n if (!this.has_initialized) {\n console.warn('Posthog: Cannot identify - not initialized')\n return\n }\n\n try {\n const alreadyThisUser = this.has_identified && posthog.get_distinct_id() === user_id\n\n if (user_id && !alreadyThisUser) {\n this.log('identifyEvent | identifying user', { user_id, traits })\n posthog.identify(user_id, {\n ...traits,\n client_id: user_id,\n })\n this.has_identified = true\n } else {\n this.log('identifyEvent | skipped — user already identified', { user_id })\n }\n } catch (error) {\n console.error('Posthog: Failed to identify user', error)\n }\n }\n\n /**\n * Reset PostHog state\n * Clears user identification and resets the instance\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting PostHog session')\n posthog.reset()\n this.has_identified = false\n } catch (error) {\n console.error('Posthog: Failed to reset', error)\n }\n }\n\n /**\n * Ensure client_id is set in PostHog stored person properties.\n * Call this when the user ID is available and PostHog is loaded.\n * No-op if client_id is already present.\n *\n * @param params.user_id - The user ID to use as client_id\n * @param params.email - The user's email, used to determine is_internal\n * @param params.language - The user's language (BCP 47 tag, e.g. \"en-GB\")\n * @param params.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n language,\n country_of_residence,\n }: {\n user_id: string\n email?: string\n language?: string\n country_of_residence?: string\n }): void => {\n if (!this.has_initialized || !user_id) return\n\n try {\n const storedProperties: Record<string, any> = posthog.get_property('$stored_person_properties') ?? {}\n const updates: Record<string, any> = {}\n\n if (!storedProperties.client_id) {\n updates.client_id = user_id\n }\n if (email && storedProperties.is_internal === undefined) {\n updates.is_internal = isInternalEmail(email)\n }\n if (language && !storedProperties.language) {\n updates.language = language\n }\n if (country_of_residence && !storedProperties.country_of_residence) {\n updates.country_of_residence = country_of_residence\n }\n\n if (Object.keys(updates).length > 0) {\n this.log('backfillPersonProperties | backfilling person properties', { user_id, updates })\n posthog.setPersonProperties(updates)\n } else {\n this.log('backfillPersonProperties | skipped — all properties already present', {\n user_id,\n country_of_residence,\n })\n }\n } catch (error) {\n console.error('Posthog: Failed to backfill person properties', error)\n }\n }\n\n /**\n * Capture a custom event with properties\n * Properties are pre-flattened and cleaned by analytics.ts before being passed here\n *\n * @param event_name - The name of the event to track\n * @param properties - Event properties including core attributes (already flattened and cleaned)\n */\n capture = (event_name: string, properties?: Record<string, any>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('capture | sending event to PostHog', { event_name, properties })\n posthog.capture(event_name, properties)\n } catch (error) {\n console.error('Posthog: Failed to capture event', error)\n }\n }\n\n /**\n * Check whether a feature flag is enabled for the current user.\n *\n * @param key - The feature flag key\n * @returns true/false, or undefined if PostHog is not ready\n */\n isFeatureEnabled = (key: string): boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.isFeatureEnabled(key)\n this.log('isFeatureEnabled', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to check feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the value of a feature flag.\n * Returns a string variant for multivariate flags, true/false for boolean flags,\n * or undefined if the flag does not exist or PostHog is not ready.\n *\n * @param key - The feature flag key\n */\n getFeatureFlag = (key: string): string | boolean | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.getFeatureFlag(key)\n this.log('getFeatureFlag', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag', error)\n return undefined\n }\n }\n\n /**\n * Get the JSON payload associated with a feature flag.\n * Payloads allow attaching structured metadata (e.g. config objects) to a flag.\n *\n * @param key - The feature flag key\n */\n getFeatureFlagPayload = (\n key: string\n ): string | number | boolean | null | Record<string, unknown> | unknown[] | undefined => {\n if (!this.has_initialized) return undefined\n\n try {\n const result = posthog.getFeatureFlagResult(key)?.payload as\n | string\n | number\n | boolean\n | null\n | Record<string, unknown>\n | unknown[]\n | undefined\n this.log('getFeatureFlagPayload', { key, result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get feature flag payload', error)\n return undefined\n }\n }\n\n /**\n * Get all currently active feature flags and their values.\n *\n * @returns A map of flag key → value (boolean or string variant)\n */\n getAllFlags = (): Record<string, string | boolean> => {\n if (!this.has_initialized) return {}\n\n try {\n const result = posthog.featureFlags?.getFlagVariants() ?? {}\n this.log('getAllFlags', { result })\n return result\n } catch (error) {\n console.error('Posthog: Failed to get all feature flags', error)\n return {}\n }\n }\n\n /**\n * Subscribe to feature flag changes.\n * The callback fires immediately with the current flags and again whenever they are reloaded.\n *\n * @param callback - Receives the list of active flag keys and a map of key → variant\n * @returns An unsubscribe function — call it to stop listening\n */\n onFeatureFlags = (\n callback: (flags: string[], variants: Record<string, string | boolean>) => void\n ): (() => void) => {\n if (!this.has_initialized) return () => {}\n\n try {\n this.log('onFeatureFlags | subscribing to feature flag changes')\n const unsubscribe = posthog.onFeatureFlags(callback)\n return typeof unsubscribe === 'function' ? unsubscribe : () => {}\n } catch (error) {\n console.error('Posthog: Failed to subscribe to feature flags', error)\n return () => {}\n }\n }\n\n /**\n * Force PostHog to reload feature flags from the server.\n * Useful after login, logout, or any attribute change that may affect targeting.\n */\n reloadFeatureFlags = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reloadFeatureFlags | reloading feature flags')\n posthog.reloadFeatureFlags()\n } catch (error) {\n console.error('Posthog: Failed to reload feature flags', error)\n }\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deriv-com/analytics",
3
- "version": "1.41.0",
3
+ "version": "1.42.0",
4
4
  "description": "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.",
5
5
  "keywords": [
6
6
  "rudderstack",
@@ -63,9 +63,9 @@
63
63
  "@types/js-cookie": "^3.0.6",
64
64
  "@types/node": "^25.5.2",
65
65
  "husky": "^9.1.7",
66
- "jsdom": "^26.1.0",
66
+ "jsdom": "^29.0.2",
67
67
  "lint-staged": "^16.4.0",
68
- "prettier": "^3.8.1",
68
+ "prettier": "^3.8.3",
69
69
  "semantic-release": "^25.0.3",
70
70
  "tslib": "^2.8.1",
71
71
  "tsup": "^8.5.1",
@@ -75,7 +75,7 @@
75
75
  "dependencies": {
76
76
  "@rudderstack/analytics-js": "^3.31.0",
77
77
  "js-cookie": "^3.0.5",
78
- "posthog-js": "^1.367.0"
78
+ "posthog-js": "^1.372.9"
79
79
  },
80
80
  "optionalDependencies": {
81
81
  "@growthbook/growthbook": "^1.6.5"
@@ -83,7 +83,7 @@
83
83
  "overrides": {
84
84
  "npm": {
85
85
  "tinyglobby": {
86
- "picomatch": ">=4.0.4"
86
+ "picomatch": "4.0.4"
87
87
  }
88
88
  }
89
89
  },