@deriv-com/analytics 1.39.7 → 1.40.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 (47) hide show
  1. package/README.md +148 -145
  2. package/dist/browser/analytics.bundle.global.js +5 -5
  3. package/dist/browser/analytics.bundle.global.js.map +1 -1
  4. package/dist/browser/analytics.esm.mjs +1 -1
  5. package/dist/browser/analytics.esm.mjs.map +1 -1
  6. package/dist/{chunk-GTT7DF4Y.mjs → chunk-4V72P52P.mjs} +2 -2
  7. package/dist/chunk-4V72P52P.mjs.map +1 -0
  8. package/dist/{chunk-YZ34YKBW.js → chunk-6BHMKTVG.js} +2 -2
  9. package/dist/chunk-6BHMKTVG.js.map +1 -0
  10. package/dist/index.d.mts +9 -10
  11. package/dist/index.d.ts +9 -10
  12. package/dist/index.js +2 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/index.mjs +2 -2
  15. package/dist/index.mjs.map +1 -1
  16. package/dist/metafile-cjs.json +1 -1
  17. package/dist/metafile-esm.json +1 -1
  18. package/dist/metafile-iife.json +1 -1
  19. package/dist/{posthog-DUxm7AzZ.d.ts → posthog-BqcxWQRm.d.mts} +4 -3
  20. package/dist/{posthog-DfHTd53-.d.mts → posthog-BqcxWQRm.d.ts} +4 -3
  21. package/dist/{posthog-B3LUVMYU.mjs → posthog-OLSRFYED.mjs} +3 -3
  22. package/dist/{posthog-B3LUVMYU.mjs.map → posthog-OLSRFYED.mjs.map} +1 -1
  23. package/dist/providers/posthog/index.d.mts +1 -2
  24. package/dist/providers/posthog/index.d.ts +1 -2
  25. package/dist/providers/posthog/index.js +2 -2
  26. package/dist/providers/posthog/index.js.map +1 -1
  27. package/dist/providers/posthog/index.mjs +2 -2
  28. package/dist/providers/posthog/index.mjs.map +1 -1
  29. package/dist/providers/rudderstack/index.d.mts +1 -2
  30. package/dist/providers/rudderstack/index.d.ts +1 -2
  31. package/dist/providers/rudderstack/index.js +1 -1
  32. package/dist/providers/rudderstack/index.mjs +1 -1
  33. package/package.json +1 -6
  34. package/dist/chunk-5PFWZVJN.mjs +0 -3
  35. package/dist/chunk-5PFWZVJN.mjs.map +0 -1
  36. package/dist/chunk-GTT7DF4Y.mjs.map +0 -1
  37. package/dist/chunk-NCHU4435.js +0 -3
  38. package/dist/chunk-NCHU4435.js.map +0 -1
  39. package/dist/chunk-YZ34YKBW.js.map +0 -1
  40. package/dist/types-DoMejCXv.d.mts +0 -361
  41. package/dist/types-DoMejCXv.d.ts +0 -361
  42. package/dist/utils/analytics-cache/index.d.mts +0 -139
  43. package/dist/utils/analytics-cache/index.d.ts +0 -139
  44. package/dist/utils/analytics-cache/index.js +0 -2
  45. package/dist/utils/analytics-cache/index.js.map +0 -1
  46. package/dist/utils/analytics-cache/index.mjs +0 -2
  47. package/dist/utils/analytics-cache/index.mjs.map +0 -1
@@ -1,3 +1,2 @@
1
- export { P as Posthog } from '../../posthog-DfHTd53-.mjs';
2
- import '../../types-DoMejCXv.mjs';
1
+ export { P as Posthog } from '../../posthog-BqcxWQRm.mjs';
3
2
  import 'posthog-js';
@@ -1,3 +1,2 @@
1
- export { P as Posthog } from '../../posthog-DUxm7AzZ.js';
2
- import '../../types-DoMejCXv.js';
1
+ export { P as Posthog } from '../../posthog-BqcxWQRm.js';
3
2
  import 'posthog-js';
@@ -1,3 +1,3 @@
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 l=class l{constructor(t,i=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkT4BXL6JM_js.f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=t=>{if(typeof document>"u"||typeof window>"u")return;let i=`ph_${t}_posthog`,o=document.cookie.split(";").map(e=>e.trim().split("=")[0]??"").filter(e=>/^ph_.+_posthog$/.test(e)&&e!==i);if(o.length===0)return;let s=window.location.hostname,n=s.split("."),c=n.length>=2?`.${n.slice(-2).join(".")}`:s;o.forEach(e=>{[c,s,""].forEach(a=>{let y=a?`; Domain=${a}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(a=>a.trim().startsWith(`${e}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${e}`);});};this.init=()=>{try{let{apiKey:t,api_host:i,config:o={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(t);let s=i||chunkT4BXL6JM_js.d();this.log("init | loading PostHog SDK",{api_host:s});let n={api_host:s,ui_host:chunkT4BXL6JM_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:c=>{if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost"||e==="127.0.0.1")return c;let d=chunkT4BXL6JM_js.e.some(a=>e.endsWith(`.${a}`)||e===a);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e}),d?c:null},...o};r__default.default.init(t,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,i)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=typeof r__default.default._isIdentified=="function"?r__default.default._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),r__default.default.identify(t,{...i,client_id:t}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:t});}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(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,country_of_residence:o})=>{if(!(!this.has_initialized||!t))try{let s=r__default.default.get_property("$stored_person_properties")??{},n={};s.client_id||(n.client_id=t),i&&s.is_internal===void 0&&(n.is_internal=chunkT4BXL6JM_js.g(i)),o&&!s.country_of_residence&&(n.country_of_residence=o),Object.keys(n).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:n}),r__default.default.setPersonProperties(n)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:o});}catch(s){console.error("Posthog: Failed to backfill person properties",s);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),r__default.default.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};l.getPosthogInstance=(t,i=false)=>(l._instance||(l._instance=new l(t,i)),l._instance);var P=l;exports.Posthog=P;//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunkT4BXL6JM_js=require('../../chunk-T4BXL6JM.js'),a=require('posthog-js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var a__default=/*#__PURE__*/_interopDefault(a);/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var c=class c{constructor(t,i=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=chunkT4BXL6JM_js.f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=t=>{if(typeof document>"u"||typeof window>"u")return;let i=`ph_${t}_posthog`,o=document.cookie.split(";").map(e=>e.trim().split("=")[0]??"").filter(e=>/^ph_.+_posthog$/.test(e)&&e!==i);if(o.length===0)return;let r=window.location.hostname,n=r.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:r;o.forEach(e=>{[s,r,""].forEach(l=>{let y=l?`; Domain=${l}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.trim().startsWith(`${e}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${e}`);});};this.init=()=>{try{let{apiKey:t,api_host:i,config:o={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(t);let r=i||chunkT4BXL6JM_js.d();this.log("init | loading PostHog SDK",{api_host:r});let n={api_host:r,ui_host:chunkT4BXL6JM_js.c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:s=>{if(typeof window>"u")return null;let e=window.location.hostname;if(e==="localhost"||e==="127.0.0.1")return s;let d=chunkT4BXL6JM_js.e.some(l=>e.endsWith(`.${l}`)||e===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e}),d?s:null},...o};a__default.default.init(t,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,i)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=typeof a__default.default._isIdentified=="function"?a__default.default._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),a__default.default.identify(t,{...i,client_id:t}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:t});}catch(o){console.error("Posthog: Failed to identify user",o);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),a__default.default.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,language:o,country_of_residence:r})=>{if(!(!this.has_initialized||!t))try{let n=a__default.default.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=t),i&&n.is_internal===void 0&&(s.is_internal=chunkT4BXL6JM_js.g(i)),o&&!n.language&&(s.language=o),r&&!n.country_of_residence&&(s.country_of_residence=r),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:s}),a__default.default.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:r});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),a__default.default.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};c.getPosthogInstance=(t,i=false)=>(c._instance||(c._instance=new c(t,i)),c._instance);var P=c;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","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,qBAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,mBAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,0BAAA,CAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,GAAA,EAAe,OAAO,MAAA,CAAW,GAAA,CAAa,OAEtE,IAAMC,CAAAA,CAAoB,CAAA,GAAA,EAAMD,CAAa,CAAA,QAAA,CAAA,CACvCE,CAAAA,CAAe,QAAA,CAAS,MAAA,CACzB,MAAM,GAAG,CAAA,CACT,GAAA,CAAIC,CAAAA,EAAKA,CAAAA,CAAE,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,EAAK,EAAE,CAAA,CACrC,MAAA,CAAOC,CAAA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CAAA,MAASV,CAAAA,CAAO,CACZ,QAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAxNI,IAAA,CAAK,OAAA,CAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CAsNJ,EAlOaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,CAAAA,CAAQ,SAAA,GACTA,EAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,KAxBVsC,CAAAA,CAANtC","file":"index.js","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\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.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: 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 (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> & Partial<TCoreAttributes>): 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"]}
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","Posthog"],"mappings":";AAoBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,qBAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGj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AAA,CAAI,0DAAA,CAA4D,CAAE,OAAA,CAAAP,CAAAA,CAAS,OAAA,CAAAO,CAAQ,CAAC,CAAA,CACzFT,kBAAAA,CAAQ,mBAAA,CAAoBS,CAAO,CAAA,EAEnC,IAAA,CAAK,GAAA,CAAI,2EAAuE,CAC5E,OAAA,CAAAP,CAAAA,CACA,oBAAA,CAAAK,CACJ,CAAC,EAET,CAAA,MAASN,EAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,+CAAA,CAAiDA,CAAK,EACxE,CACJ,CAAA,CASA,aAAU,CAACU,CAAAA,CAAoBC,CAAAA,GAA2C,CACtE,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,UAAA,CAAAC,CAAW,CAAC,CAAA,CACzEZ,kBAAAA,CAAQ,OAAA,CAAQW,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASX,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CA9NI,IAAA,CAAK,QAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CA4NJ,EAxOaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,CAAAA,CAAQ,SAAA,GACTA,EAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,KAxBVuC,CAAAA,CAANvC","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"]}
@@ -1,3 +1,3 @@
1
- import {f,d,e,c,g}from'../../chunk-TE3DYZVQ.mjs';import r from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var l=class l{constructor(t,i=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=t=>{if(typeof document>"u"||typeof window>"u")return;let i=`ph_${t}_posthog`,o=document.cookie.split(";").map(e=>e.trim().split("=")[0]??"").filter(e=>/^ph_.+_posthog$/.test(e)&&e!==i);if(o.length===0)return;let s=window.location.hostname,n=s.split("."),c=n.length>=2?`.${n.slice(-2).join(".")}`:s;o.forEach(e=>{[c,s,""].forEach(a=>{let y=a?`; Domain=${a}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(a=>a.trim().startsWith(`${e}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${e}`);});};this.init=()=>{try{let{apiKey:t,api_host:i,config:o={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(t);let s=i||d();this.log("init | loading PostHog SDK",{api_host:s});let n={api_host:s,ui_host:c,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:c=>{if(typeof window>"u")return null;let e$1=window.location.hostname;if(e$1==="localhost"||e$1==="127.0.0.1")return c;let d=e.some(a=>e$1.endsWith(`.${a}`)||e$1===a);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e$1}),d?c:null},...o};r.init(t,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,i)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=typeof r._isIdentified=="function"?r._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),r.identify(t,{...i,client_id:t}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:t});}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(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,country_of_residence:o})=>{if(!(!this.has_initialized||!t))try{let s=r.get_property("$stored_person_properties")??{},n={};s.client_id||(n.client_id=t),i&&s.is_internal===void 0&&(n.is_internal=g(i)),o&&!s.country_of_residence&&(n.country_of_residence=o),Object.keys(n).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:n}),r.setPersonProperties(n)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:o});}catch(s){console.error("Posthog: Failed to backfill person properties",s);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),r.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};l.getPosthogInstance=(t,i=false)=>(l._instance||(l._instance=new l(t,i)),l._instance);var P=l;export{P as Posthog};//# sourceMappingURL=index.mjs.map
1
+ import {f,d,e,c as c$1,g}from'../../chunk-TE3DYZVQ.mjs';import a from'posthog-js';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
+ var c=class c{constructor(t,i=false){this.has_initialized=false;this.has_identified=false;this.debug=false;this.log=f("[PostHog]",()=>this.debug);this.cleanupStalePosthogCookies=t=>{if(typeof document>"u"||typeof window>"u")return;let i=`ph_${t}_posthog`,o=document.cookie.split(";").map(e=>e.trim().split("=")[0]??"").filter(e=>/^ph_.+_posthog$/.test(e)&&e!==i);if(o.length===0)return;let r=window.location.hostname,n=r.split("."),s=n.length>=2?`.${n.slice(-2).join(".")}`:r;o.forEach(e=>{[s,r,""].forEach(l=>{let y=l?`; Domain=${l}`:"";document.cookie=`${e}=; path=/${y}; max-age=0; SameSite=Lax`;});let d=!document.cookie.split(";").some(l=>l.trim().startsWith(`${e}=`));this.log(`cleanupStalePosthogCookies | ${d?"removed":"failed to remove"} stale cookie: ${e}`);});};this.init=()=>{try{let{apiKey:t,api_host:i,config:o={}}=this.options;if(!t){console.warn("Posthog: No API key provided");return}this.cleanupStalePosthogCookies(t);let r=i||d();this.log("init | loading PostHog SDK",{api_host:r});let n={api_host:r,ui_host:c$1,autocapture:!0,capture_pageview:"history_change",session_recording:{recordCrossOriginIframes:!0,minimumDurationMilliseconds:3e4,...o.session_recording},before_send:s=>{if(typeof window>"u")return null;let e$1=window.location.hostname;if(e$1==="localhost"||e$1==="127.0.0.1")return s;let d=e.some(l=>e$1.endsWith(`.${l}`)||e$1===l);return d||this.log("init | before_send blocked event from disallowed host",{currentHost:e$1}),d?s:null},...o};a.init(t,n),this.has_initialized=!0,this.log("init | PostHog SDK loaded successfully");}catch(t){console.error("Posthog: Failed to initialize",t);}};this.identifyEvent=(t,i)=>{if(!this.has_initialized){console.warn("Posthog: Cannot identify - not initialized");return}try{let o=typeof a._isIdentified=="function"?a._isIdentified():this.has_identified;t&&!o?(this.log("identifyEvent | identifying user",{user_id:t,traits:i}),a.identify(t,{...i,client_id:t}),this.has_identified=!0):this.log("identifyEvent | skipped \u2014 user already identified",{user_id:t});}catch(o){console.error("Posthog: Failed to identify user",o);}};this.reset=()=>{if(this.has_initialized)try{this.log("reset | resetting PostHog session"),a.reset(),this.has_identified=!1;}catch(t){console.error("Posthog: Failed to reset",t);}};this.backfillPersonProperties=({user_id:t,email:i,language:o,country_of_residence:r})=>{if(!(!this.has_initialized||!t))try{let n=a.get_property("$stored_person_properties")??{},s={};n.client_id||(s.client_id=t),i&&n.is_internal===void 0&&(s.is_internal=g(i)),o&&!n.language&&(s.language=o),r&&!n.country_of_residence&&(s.country_of_residence=r),Object.keys(s).length>0?(this.log("backfillPersonProperties | backfilling person properties",{user_id:t,updates:s}),a.setPersonProperties(s)):this.log("backfillPersonProperties | skipped \u2014 all properties already present",{user_id:t,country_of_residence:r});}catch(n){console.error("Posthog: Failed to backfill person properties",n);}};this.capture=(t,i)=>{if(this.has_initialized)try{this.log("capture | sending event to PostHog",{event_name:t,properties:i}),a.capture(t,i);}catch(o){console.error("Posthog: Failed to capture event",o);}};this.options=t,this.debug=i,this.init();}};c.getPosthogInstance=(t,i=false)=>(c._instance||(c._instance=new c(t,i)),c._instance);var P=c;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","country_of_residence","storedProperties","updates","isInternalEmail","event_name","properties","Posthog"],"mappings":";AAqBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,qBAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,EAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,0BAAA,CAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,GAAA,EAAe,OAAO,MAAA,CAAW,GAAA,CAAa,OAEtE,IAAMC,CAAAA,CAAoB,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AU,CAACS,CAAAA,CAAoBC,CAAAA,GAAsE,CACjG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,KAAK,GAAA,CAAI,oCAAA,CAAsC,CAAE,UAAA,CAAAD,CAAAA,CAAY,UAAA,CAAAC,CAAW,CAAC,EACzEX,CAAAA,CAAQ,OAAA,CAAQU,CAAAA,CAAYC,CAAU,EAC1C,CAAA,MAASV,CAAAA,CAAO,CACZ,QAAQ,KAAA,CAAM,kCAAA,CAAoCA,CAAK,EAC3D,CACJ,CAAA,CAxNI,IAAA,CAAK,OAAA,CAAU1B,CAAAA,CACf,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,GACT,CAsNJ,EAlOaF,CAAAA,CAoBK,kBAAA,CAAqB,CAACC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,IAC7DF,CAAAA,CAAQ,SAAA,GACTA,EAAQ,SAAA,CAAY,IAAIA,CAAAA,CAAQC,CAAAA,CAASC,CAAK,CAAA,CAAA,CAE3CF,CAAAA,CAAQ,SAAA,CAAA,KAxBVsC,CAAAA,CAANtC","file":"index.mjs","sourcesContent":["import posthog from 'posthog-js'\nimport type { TPosthogConfig, TPosthogIdentifyTraits, TPosthogOptions } from './posthogTypes'\nimport type { TCoreAttributes } from '../types'\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.country_of_residence - The user's country of residence\n */\n backfillPersonProperties = ({\n user_id,\n email,\n country_of_residence,\n }: {\n user_id: string\n email?: 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 (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> & Partial<TCoreAttributes>): 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"]}
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","Posthog"],"mappings":";AAoBO,IAAMA,CAAAA,CAAN,MAAMA,CAAQ,CAQjB,WAAA,CAAYC,CAAAA,CAA0BC,CAAAA,CAAQ,KAAA,CAAO,CAPrD,qBAAkB,KAAA,CAClB,IAAA,CAAA,cAAA,CAAiB,KAAA,CAGjB,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,EAAa,WAAA,CAAa,IAAM,IAAA,CAAK,KAAK,CAAA,CA0BxD,IAAA,CAAQ,0BAAA,CAA8BC,CAAAA,EAAgC,CAClE,GAAI,OAAO,QAAA,CAAa,GAAA,EAAe,OAAO,MAAA,CAAW,GAAA,CAAa,OAEtE,IAAMC,CAAAA,CAAoB,CAAA,GAAA,EAAMD,CAAa,CAAA,QAAA,CAAA,CACvCE,CAAAA,CAAe,QAAA,CAAS,MAAA,CACzB,KAAA,CAAM,GAAG,CAAA,CACT,GAAA,CAAIC,CAAAA,EAAKA,CAAAA,CAAE,IAAA,EAAK,CAAE,KAAA,CAAM,GAAG,EAAE,CAAC,CAAA,EAAK,EAAE,CAAA,CACrC,MAAA,CAAOC,CAAAA,EAAQ,iBAAA,CAAkB,IAAA,CAAKA,CAAI,CAAA,EAAKA,CAAAA,GAASH,CAAiB,CAAA,CAE9E,GAAIC,CAAAA,CAAa,MAAA,GAAW,CAAA,CAAG,OAE/B,IAAMG,CAAAA,CAAW,MAAA,CAAO,QAAA,CAAS,QAAA,CAC3BC,CAAAA,CAAcD,CAAAA,CAAS,MAAM,GAAG,CAAA,CAGhCE,CAAAA,CAAaD,CAAAA,CAAY,MAAA,EAAU,CAAA,CAAI,CAAA,CAAA,EAAIA,CAAAA,CAAY,MAAM,EAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAC,CAAA,CAAA,CAAKD,CAAAA,CAErFH,CAAAA,CAAa,QAAQE,CAAAA,EAAQ,CAExB,CAACG,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Q,SAAA,CAAA,KAxBVuC,CAAAA,CAANvC","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"]}
@@ -1,5 +1,4 @@
1
1
  import { RudderAnalytics } from '@rudderstack/analytics-js';
2
- import { a as TAllEvents, T as TCoreAttributes } from '../../types-DoMejCXv.mjs';
3
2
 
4
3
  /**
5
4
  * RudderStack analytics wrapper with singleton pattern.
@@ -70,7 +69,7 @@ declare class RudderStack {
70
69
  * @param event - The event name
71
70
  * @param payload - The event payload with core attributes
72
71
  */
73
- track: <T extends keyof TAllEvents>(event: T, payload: TAllEvents[T] & Partial<TCoreAttributes>) => void;
72
+ track: (event: string, payload: Record<string, any>) => void;
74
73
  }
75
74
 
76
75
  export { RudderStack };
@@ -1,5 +1,4 @@
1
1
  import { RudderAnalytics } from '@rudderstack/analytics-js';
2
- import { a as TAllEvents, T as TCoreAttributes } from '../../types-DoMejCXv.js';
3
2
 
4
3
  /**
5
4
  * RudderStack analytics wrapper with singleton pattern.
@@ -70,7 +69,7 @@ declare class RudderStack {
70
69
  * @param event - The event name
71
70
  * @param payload - The event payload with core attributes
72
71
  */
73
- track: <T extends keyof TAllEvents>(event: T, payload: TAllEvents[T] & Partial<TCoreAttributes>) => void;
72
+ track: (event: string, payload: Record<string, any>) => void;
74
73
  }
75
74
 
76
75
  export { RudderStack };
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkYZ34YKBW_js=require('../../chunk-YZ34YKBW.js');require('../../chunk-T4BXL6JM.js');Object.defineProperty(exports,"RudderStack",{enumerable:true,get:function(){return chunkYZ34YKBW_js.a}});//# sourceMappingURL=index.js.map
1
+ 'use strict';var chunk6BHMKTVG_js=require('../../chunk-6BHMKTVG.js');require('../../chunk-T4BXL6JM.js');Object.defineProperty(exports,"RudderStack",{enumerable:true,get:function(){return chunk6BHMKTVG_js.a}});//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{a as RudderStack}from'../../chunk-GTT7DF4Y.mjs';import'../../chunk-TE3DYZVQ.mjs';//# sourceMappingURL=index.mjs.map
1
+ export{a as RudderStack}from'../../chunk-4V72P52P.mjs';import'../../chunk-TE3DYZVQ.mjs';//# sourceMappingURL=index.mjs.map
2
2
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deriv-com/analytics",
3
- "version": "1.39.7",
3
+ "version": "1.40.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",
@@ -38,11 +38,6 @@
38
38
  "types": "./dist/providers/posthog/index.d.ts",
39
39
  "import": "./dist/providers/posthog/index.mjs",
40
40
  "require": "./dist/providers/posthog/index.js"
41
- },
42
- "./cache": {
43
- "types": "./dist/utils/analytics-cache/index.d.ts",
44
- "import": "./dist/utils/analytics-cache/index.mjs",
45
- "require": "./dist/utils/analytics-cache/index.js"
46
41
  }
47
42
  },
48
43
  "scripts": {
@@ -1,3 +0,0 @@
1
- import {f as f$1}from'./chunk-TE3DYZVQ.mjs';/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var p=class{constructor(){this.interval=null;this.responses=[];this.isTrackingResponses=false;this.delegatedSelectors=new Set;this.debug=false;this.log=f$1("[CacheManager]",()=>this.debug);this.addEventhandler=this.addEventHandler.bind(this);}setDebug(e){this.debug=e;}hash(e,n=32){let t=i=>{let o=2166136261;for(let l=0;l<i.length;l++)o^=i.charCodeAt(l),o=o*16777619>>>0;return o.toString(16)},a=i=>btoa(i),s=t(e),r=a(s);for(;r.length<n;)r+=a(t(r));return r.substring(0,n)}getCookies(e){let t=`; ${document.cookie}`.split(`; ${e}=`);if(t.length===2){let a=decodeURIComponent(t.pop().split(";").shift());try{return JSON.parse(a)}catch{return a}}return null}trackPageUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.isPageViewSent()||this.push("cached_analytics_page_views",{name:window.location.origin+window.location.pathname});});}trackResponses(){if(typeof window>"u"||typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,a){return this._url=a,this._method=t,e.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){return this.addEventListener("load",function(){let a=null;if(typeof t=="string")try{a=JSON.parse(t);}catch{a=t;}let s={url:this._url,method:this._method,status:this.status,headers:this.getAllResponseHeaders(),data:this.responseText,payload:a};f.responses.push(s);}),n.apply(this,arguments)},this.isTrackingResponses=true;}getAnalyticsInstance(){return typeof window>"u"?null:window.AnalyticsInstance??window.DerivAnalytics?.Analytics??window.Analytics?.Analytics}isReady(){if(typeof window>"u")return false;let e=this.getAnalyticsInstance();return e?!!e.getInstances?.()?.tracking:false}parseFromLocalStorage(e){if(typeof localStorage>"u")return null;try{let n=localStorage.getItem(e);return n===null?null:JSON.parse(n)}catch{return null}}isPageViewSent(){return !!this.responses.find(e=>e.payload?.type==="page"&&e.payload?.anonymousId)}set(e){this.log("set | caching event to localStorage",e),this.push("cached_analytics_events",e);}push(e,n){if(typeof localStorage>"u")return;let t=this.parseFromLocalStorage(e),a=Array.isArray(t)?t:[];a.push(n);try{localStorage.setItem(e,JSON.stringify(a));}catch(s){console.warn("AnalyticsCacheManager: Failed to push to localStorage",s);}}processEvent(e){let n=this.getCookies("client_information");if(n){let{email:t=null}=n;t&&(e.properties.email_hash=this.hash(t));}if(e?.properties?.email){let t=e.properties.email;delete e.properties.email,e.properties.email_hash=this.hash(t);}return e}track(e,n=false){if(typeof window>"u")return;let t=this.processEvent(e),a=this.getAnalyticsInstance();this.isReady()&&!n?(this.log("track | analytics ready \u2014 calling trackEvent",{event:t.name,properties:t.properties}),a.trackEvent(t.name,t.properties)):(this.log("track | analytics not ready or cache=true \u2014 storing event",{event:t.name,cache:n}),this.set(t));}pageView(){typeof window>"u"||(this.log("pageView | starting page view polling"),this.isTrackingResponses||(this.trackResponses(),this.trackPageUnload()),this.interval=setInterval(()=>{let e=window.Analytics;typeof e<"u"&&typeof e.Analytics?.pageView=="function"&&this.isReady()&&(this.log("pageView | analytics ready \u2014 sending page view",{href:window.location.href}),e.Analytics.pageView(window.location.href,"Trader's hub")),this.isPageViewSent()&&(this.log("pageView | page view confirmed sent \u2014 clearing interval"),this.interval&&clearInterval(this.interval));},1e3));}listen(e,{name:n="",properties:t={}},a=false,s=null){let r=o=>{o.dataset?.clickEventTracking||(o.addEventListener("click",l=>{let c={name:n,properties:t,cache:a};if(typeof s=="function"){let d=s(l);c={...d,cache:d.cache??a};}this.track(c,c.cache??false);}),o.dataset.clickEventTracking="true");};(e instanceof NodeList?Array.from(e):[e]).forEach(r);}addEventHandler(e){return typeof window>"u"?this:(e.forEach(({element:n,event:t={name:"",properties:{}},cache:a=false,callback:s=null})=>{if(typeof n=="string"){let r=n;if(!this.delegatedSelectors.has(r)){let i=o=>{let l=o.target;if(!l)return;let c=l.closest(r);if(c&&!c.dataset?.clickEventTracking){let d={name:t.name,properties:t.properties,cache:a};if(typeof s=="function"){let h=s(o);d={...h,cache:h.cache??a};}c.dataset.clickEventTracking="true",this.track(d,d.cache??false);}};document.addEventListener("click",i),this.delegatedSelectors.add(r);}}else (n instanceof NodeList?Array.from(n):[n]).forEach(i=>{i&&!i.dataset?.clickEventTracking&&this.listen(i,t,a,s);});}),this)}loadEvent(e){return this.log("loadEvent | firing load events",e.map(n=>n.event.name)),e.forEach(({event:n})=>{let{name:t,properties:a}=n;this.track({name:t,properties:a});}),this}pageLoadEvent(e){if(typeof window>"u")return this;let n=window.location.pathname.slice(1);return this.log("pageLoadEvent | checking page load events",{pathname:n}),e.forEach(({pages:t=[],excludedPages:a=[],event:s,callback:r=null})=>{let i=false;if(t.length?t.includes(n)&&(i=true):a.length&&a.includes(n)||(i=true),i){let o=r?r():s;this.log("pageLoadEvent | dispatching event for page",{pathname:n,event:o.name}),this.loadEvent([{event:o}]);}else this.log("pageLoadEvent | skipped event for page",{pathname:n,event:s.name,pages:t,excludedPages:a});}),this}clearInterval(){this.interval&&(clearInterval(this.interval),this.interval=null);}cleanup(){this.clearInterval(),this.responses=[],this.isTrackingResponses=false;}},f=new p;typeof window<"u"&&(window.cacheTrackEvents=f);export{f as a};//# sourceMappingURL=chunk-5PFWZVJN.mjs.map
3
- //# sourceMappingURL=chunk-5PFWZVJN.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/analytics-cache.ts"],"names":["AnalyticsCacheManager","createLogger","debug","inputString","desiredLength","fnv1aHash","string","hash","i","base64Encode","combined","name","parts","cookieValue","originalXhrOpen","originalXhrSend","method","url","body","parsedPayload","responseData","cacheTrackEvents","instance","key","raw","event","data","existing","stored","err","clientInfo","email","originalEvent","cache","Analytics","element","properties","callback","addClickListener","el","e","callbackResult","items","selector","delegatedHandler","target","matched","evt","pathname","pages","excludedPages","dispatch","eventData"],"mappings":";AA+CA,IAAMA,CAAAA,CAAN,KAA4B,CAA5B,WAAA,EAAA,CACI,IAAA,CAAQ,QAAA,CAAkC,IAAA,CAC1C,IAAA,CAAQ,SAAA,CAA4B,EAAC,CACrC,IAAA,CAAQ,mBAAA,CAAsB,KAAA,CAC9B,IAAA,CAAQ,kBAAA,CAAkC,IAAI,GAAA,CAC9C,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,GAAAA,CAAa,gBAAA,CAA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CAAA,CAERD,CAAAA,CAAc,MAAA,EAChBA,CAAAA,CAAc,QAAA,CAASF,CAAQ,CAAA,GAChCG,CAAAA,CAAW,IAAA,CAAA,CAMfA,CAAAA,CAAU,CACV,IAAMC,CAAAA,CAAYf,CAAAA,CAAWA,CAAAA,EAAS,CAAIZ,CAAAA,CAC1C,IAAA,CAAK,GAAA,CAAI,4CAAA,CAA8C,CAAE,QAAA,CAAAuB,EAAU,KAAA,CAAOI,CAAAA,CAAU,IAAK,CAAC,CAAA,CAC1F,IAAA,CAAK,SAAA,CAAU,CAAC,CAAE,KAAA,CAAOA,CAAU,CAAC,CAAC,EACzC,CAAA,KACI,IAAA,CAAK,GAAA,CAAI,wCAAA,CAA0C,CAC/C,QAAA,CAAAJ,CAAAA,CACA,KAAA,CAAOvB,CAAAA,CAAM,IAAA,CACb,KAAA,CAAAwB,CAAAA,CACA,aAAA,CAAAC,CACJ,CAAC,EAET,CAAC,CAAA,CAEM,IACX,CAKA,aAAA,EAAsB,CACd,IAAA,CAAK,QAAA,GACL,aAAA,CAAc,IAAA,CAAK,QAAQ,CAAA,CAC3B,IAAA,CAAK,QAAA,CAAW,IAAA,EAExB,CAKA,OAAA,EAAgB,CACZ,IAAA,CAAK,eAAc,CACnB,IAAA,CAAK,SAAA,CAAY,EAAC,CAClB,IAAA,CAAK,mBAAA,CAAsB,MAC/B,CACJ,CAAA,CAGa7B,CAAAA,CAAmB,IAAIrB,EAGhC,OAAO,MAAA,CAAW,GAAA,GAChB,OAAe,gBAAA,CAAmBqB,CAAAA,CAAAA","file":"chunk-5PFWZVJN.mjs","sourcesContent":["/**\n * Analytics Cache Manager - Version 1.1.0\n * Enhanced TypeScript implementation with better type safety and SSR support\n */\nimport { createLogger } from './helpers'\n\ntype CachedEvent = {\n name: string\n properties: Record<string, any>\n}\n\ntype ResponseData = {\n url: string\n method: string\n status: number\n headers: string\n data: string\n payload: any\n}\n\ntype EventListenerConfig = {\n element: Element | NodeList | string\n event: {\n name: string\n properties: Record<string, any>\n }\n cache?: boolean\n callback?: (e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }\n}\n\ntype LoadEventConfig = {\n event: {\n name: string\n properties: Record<string, any>\n }\n}\n\ntype PageLoadEventConfig = {\n pages?: string[]\n excludedPages?: string[]\n event: {\n name: string\n properties: Record<string, any>\n }\n callback?: () => { name: string; properties: Record<string, any> }\n}\n\nclass AnalyticsCacheManager {\n private interval: NodeJS.Timeout | null = null\n private responses: ResponseData[] = []\n private isTrackingResponses = false\n private delegatedSelectors: Set<string> = new Set()\n private debug = false\n private log = createLogger('[CacheManager]', () => this.debug)\n\n setDebug(debug: boolean): void {\n this.debug = debug\n }\n\n /**\n * FNV-1a hash algorithm for creating consistent hashes\n */\n private hash(inputString: string, desiredLength = 32): string {\n const fnv1aHash = (string: string): string => {\n let hash = 0x811c9dc5\n for (let i = 0; i < string.length; i++) {\n hash ^= string.charCodeAt(i)\n hash = (hash * 0x01000193) >>> 0\n }\n return hash.toString(16)\n }\n\n const base64Encode = (string: string): string => btoa(string)\n\n let hash = fnv1aHash(inputString)\n let combined = base64Encode(hash)\n\n while (combined.length < desiredLength) {\n combined += base64Encode(fnv1aHash(combined))\n }\n\n return combined.substring(0, desiredLength)\n }\n\n /**\n * Get cookie value by name\n */\n getCookies(name: string): any {\n const value = `; ${document.cookie}`\n const parts = value.split(`; ${name}=`)\n if (parts.length === 2) {\n const cookieValue = decodeURIComponent(parts.pop()!.split(';').shift()!)\n\n try {\n return JSON.parse(cookieValue)\n } catch (e) {\n return cookieValue\n }\n }\n return null\n }\n\n /**\n * Track page unload events to cache pageviews before leaving\n */\n trackPageUnload(): void {\n if (typeof window === 'undefined') return\n\n window.addEventListener('beforeunload', () => {\n if (!this.isPageViewSent()) {\n this.push('cached_analytics_page_views', {\n name: window.location.origin + window.location.pathname,\n })\n }\n })\n }\n\n /**\n * Track XMLHttpRequest responses to monitor analytics calls\n */\n trackResponses(): void {\n if (typeof window === 'undefined' || typeof XMLHttpRequest === 'undefined') return\n\n const originalXhrOpen = XMLHttpRequest.prototype.open\n const originalXhrSend = XMLHttpRequest.prototype.send\n\n XMLHttpRequest.prototype.open = function (method: string, url: string | URL) {\n ;(this as any)._url = url\n ;(this as any)._method = method\n return originalXhrOpen.apply(this, arguments as any)\n }\n\n XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null) {\n this.addEventListener('load', function () {\n let parsedPayload = null\n\n if (typeof body === 'string') {\n try {\n parsedPayload = JSON.parse(body)\n } catch (e) {\n parsedPayload = body\n }\n }\n\n const responseData: ResponseData = {\n url: (this as any)._url,\n method: (this as any)._method,\n status: this.status,\n headers: this.getAllResponseHeaders(),\n data: this.responseText,\n payload: parsedPayload,\n }\n cacheTrackEvents.responses.push(responseData)\n })\n\n return originalXhrSend.apply(this, arguments as any)\n }\n\n this.isTrackingResponses = true\n }\n\n /**\n * Resolve the analytics instance from the window object.\n * Supports three usage patterns:\n * - NPM import: analytics.ts sets window.AnalyticsInstance directly\n * - IIFE bundle: tsup sets window.DerivAnalytics = { Analytics, cacheTrackEvents }\n * - Legacy: consumers that explicitly set window.Analytics = window.DerivAnalytics\n */\n private getAnalyticsInstance(): any {\n if (typeof window === 'undefined') return null\n return (\n (window as any).AnalyticsInstance ??\n (window as any).DerivAnalytics?.Analytics ??\n (window as any).Analytics?.Analytics\n )\n }\n\n /**\n * Check if Analytics instance is ready\n */\n isReady(): boolean {\n if (typeof window === 'undefined') return false\n const instance = this.getAnalyticsInstance()\n if (!instance) return false\n return !!instance.getInstances?.()?.tracking\n }\n\n /**\n * Parse a localStorage entry by key.\n */\n private parseFromLocalStorage(key: string): any {\n if (typeof localStorage === 'undefined') return null\n\n try {\n const raw = localStorage.getItem(key)\n if (raw === null) return null\n return JSON.parse(raw)\n } catch {\n return null\n }\n }\n\n /**\n * Check if pageview has been sent\n */\n isPageViewSent(): boolean {\n return !!this.responses.find(e => e.payload?.type === 'page' && e.payload?.anonymousId)\n }\n\n /**\n * Set a cached event\n */\n set(event: CachedEvent): void {\n this.log('set | caching event to localStorage', event)\n this.push('cached_analytics_events', event)\n }\n\n /**\n * Push data to localStorage cache\n */\n push(key: string, data: any): void {\n if (typeof localStorage === 'undefined') return\n\n const existing = this.parseFromLocalStorage(key)\n const stored: any[] = Array.isArray(existing) ? existing : []\n stored.push(data)\n\n try {\n localStorage.setItem(key, JSON.stringify(stored))\n } catch (err) {\n console.warn('AnalyticsCacheManager: Failed to push to localStorage', err)\n }\n }\n\n /**\n * Process event to hash email and add client info\n */\n processEvent(event: CachedEvent): CachedEvent {\n const clientInfo = this.getCookies('client_information')\n\n if (clientInfo) {\n const { email = null } = clientInfo\n\n if (email) {\n event.properties.email_hash = this.hash(email)\n }\n }\n\n if (event?.properties?.email) {\n const email = event.properties.email\n delete event.properties.email\n event.properties.email_hash = this.hash(email)\n }\n\n return event\n }\n\n /**\n * Track an event (either immediately or cache it)\n */\n track(originalEvent: CachedEvent, cache = false): void {\n if (typeof window === 'undefined') return\n\n const event = this.processEvent(originalEvent)\n const instance = this.getAnalyticsInstance()\n\n if (this.isReady() && !cache) {\n this.log('track | analytics ready — calling trackEvent', {\n event: event.name,\n properties: event.properties,\n })\n instance.trackEvent(event.name, event.properties)\n } else {\n this.log('track | analytics not ready or cache=true — storing event', { event: event.name, cache })\n this.set(event)\n }\n }\n\n /**\n * Track pageview with auto-retry until sent\n */\n pageView(): void {\n if (typeof window === 'undefined') return\n\n this.log('pageView | starting page view polling')\n\n if (!this.isTrackingResponses) {\n this.trackResponses()\n this.trackPageUnload()\n }\n\n this.interval = setInterval(() => {\n const Analytics = (window as any).Analytics\n\n if (\n typeof Analytics !== 'undefined' &&\n typeof Analytics.Analytics?.pageView === 'function' &&\n this.isReady()\n ) {\n this.log('pageView | analytics ready — sending page view', { href: window.location.href })\n Analytics.Analytics.pageView(window.location.href, \"Trader's hub\")\n }\n\n if (this.isPageViewSent()) {\n this.log('pageView | page view confirmed sent — clearing interval')\n if (this.interval) clearInterval(this.interval)\n }\n }, 1000)\n }\n\n /**\n * Add click event listener to element(s)\n */\n listen(\n element: Element | NodeList,\n { name = '', properties = {} }: { name: string; properties: Record<string, any> },\n cache = false,\n callback: ((e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }) | null = null\n ): void {\n const addClickListener = (el: Element) => {\n if (!(el as any).dataset?.clickEventTracking) {\n el.addEventListener('click', (e: Event) => {\n let event = {\n name,\n properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n event = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n this.track(event, event.cache ?? false)\n })\n ;(el as any).dataset.clickEventTracking = 'true'\n }\n }\n\n const elements = element instanceof NodeList ? Array.from(element as NodeListOf<Element>) : [element]\n elements.forEach(addClickListener)\n }\n\n /**\n * Add event handlers to multiple elements with auto-retry\n * Alias for backward compatibility with typo\n */\n addEventHandler(items: EventListenerConfig[]): this {\n if (typeof window === 'undefined') return this\n\n items.forEach(({ element, event = { name: '', properties: {} }, cache = false, callback = null }) => {\n // If a selector string is provided, use event delegation on document\n if (typeof element === 'string') {\n const selector = element\n\n if (!this.delegatedSelectors.has(selector)) {\n const delegatedHandler = (e: Event) => {\n const target = e.target as Element | null\n if (!target) return\n\n const matched = target.closest(selector)\n if (matched && !(matched as any).dataset?.clickEventTracking) {\n let evt: any = {\n name: event.name,\n properties: event.properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n evt = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n ;(matched as any).dataset.clickEventTracking = 'true'\n this.track(evt, evt.cache ?? false)\n }\n }\n\n document.addEventListener('click', delegatedHandler)\n this.delegatedSelectors.add(selector)\n }\n } else {\n // Element or NodeList: attach directly to existing elements\n const elements = element instanceof NodeList ? Array.from(element) : [element]\n\n elements.forEach(el => {\n if (el && !(el as any).dataset?.clickEventTracking) {\n this.listen(el as Element, event, cache, callback)\n }\n })\n }\n })\n\n return this\n }\n\n /**\n * Backward compatibility alias (with typo from original)\n */\n addEventhandler = this.addEventHandler.bind(this)\n\n /**\n * Load events immediately\n */\n loadEvent(items: LoadEventConfig[]): this {\n this.log(\n 'loadEvent | firing load events',\n items.map(i => i.event.name)\n )\n items.forEach(({ event }) => {\n const { name, properties } = event\n this.track({\n name,\n properties,\n })\n })\n\n return this\n }\n\n /**\n * Load events on specific pages\n */\n pageLoadEvent(items: PageLoadEventConfig[]): this {\n if (typeof window === 'undefined') return this\n\n const pathname = window.location.pathname.slice(1)\n this.log('pageLoadEvent | checking page load events', { pathname })\n\n items.forEach(({ pages = [], excludedPages = [], event, callback = null }) => {\n let dispatch = false\n if (pages.length) {\n if (pages.includes(pathname)) {\n dispatch = true\n }\n } else if (excludedPages.length) {\n if (!excludedPages.includes(pathname)) {\n dispatch = true\n }\n } else {\n dispatch = true\n }\n\n if (dispatch) {\n const eventData = callback ? callback() : event\n this.log('pageLoadEvent | dispatching event for page', { pathname, event: eventData.name })\n this.loadEvent([{ event: eventData }])\n } else {\n this.log('pageLoadEvent | skipped event for page', {\n pathname,\n event: event.name,\n pages,\n excludedPages,\n })\n }\n })\n\n return this\n }\n\n /**\n * Clear the interval and cleanup\n */\n clearInterval(): void {\n if (this.interval) {\n clearInterval(this.interval)\n this.interval = null\n }\n }\n\n /**\n * Cleanup method for removing event listeners and intervals\n */\n cleanup(): void {\n this.clearInterval()\n this.responses = []\n this.isTrackingResponses = false\n }\n}\n\n// Create singleton instance\nexport const cacheTrackEvents = new AnalyticsCacheManager()\n\n// Export to global scope for backward compatibility\nif (typeof window !== 'undefined') {\n ;(window as any).cacheTrackEvents = cacheTrackEvents\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/rudderstack.ts"],"names":["COOKIE_MAX_AGE_SECONDS","_RudderStack","RUDDERSTACK_KEY","onLoaded","debug","RudderAnalytics","createLogger","hostname","domain_name","domain","uuid","bytes","hex","byte","secureFlag","error","rudderstackDataplane","user_id","payload","currentUserId","current_page","platform","properties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AAiB,CAAA,EAC1B,CAAA,MAASA,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,8BAAA,CAAgCA,CAAK,EACvD,CACJ,CAAA,CAQA,WAAQ,CAA6BS,CAAAA,CAAUN,CAAAA,GAA4D,CACvG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,sCAAA,CAAwC,CAAE,KAAA,CAAAM,CAAAA,CAAO,OAAA,CAAAN,CAAQ,CAAC,CAAA,CAGnE,IAAA,CAAK,SAAA,CAAU,KAAA,CAAMM,CAAAA,CAAiBN,CAAc,EACxD,CAAA,MAASO,CAAAA,CAAK,CACV,OAAA,CAAQ,IAAA,CAAK,oCAAA,CAAsCA,CAAG,EAC1D,CACJ,CAAA,CA7MI,IAAA,CAAK,gBAAA,CAAmBtB,CAAAA,CACxB,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,CAAKF,CAAe,EAC7B,CA2MJ,CAAA,CA1NaD,CAAAA,CAwBK,sBAAA,CAAyB,CACnCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAQ,KAAA,IAEHH,CAAAA,CAAY,SAAA,GACbA,CAAAA,CAAY,SAAA,CAAY,IAAIA,CAAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAUC,CAAK,CAAA,CAAA,CAErEH,CAAAA,CAAY,SAAA,CAAA,KAhCdyB,CAAAA,CAANzB","file":"chunk-GTT7DF4Y.mjs","sourcesContent":["import { RudderAnalytics } from '@rudderstack/analytics-js'\nimport type { TCoreAttributes, TAllEvents } from '../types'\nimport { rudderstackDataplane } from '../utils/urls'\nimport { createLogger } from '../utils/helpers'\n\n// Constants\nconst COOKIE_MAX_AGE_SECONDS = 180 * 24 * 60 * 60 // 180 days (~6 months)\n\n/**\n * RudderStack analytics wrapper with singleton pattern.\n * Handles user tracking, page views, and event analytics.\n */\nexport class RudderStack {\n analytics = new RudderAnalytics()\n has_identified = false\n has_initialized = false\n current_page = ''\n rudderstack_anonymous_cookie_key = 'rudder_anonymous_id'\n private static _instance: RudderStack\n private onLoadedCallback?: () => void\n private debug = false\n private log = createLogger('[RudderStack]', () => this.debug)\n\n constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void, debug = false) {\n this.onLoadedCallback = onLoaded\n this.debug = debug\n this.init(RUDDERSTACK_KEY)\n }\n\n /**\n * Get or create the singleton instance of RudderStack\n * @param RUDDERSTACK_KEY - RudderStack write key\n * @param onLoaded - Optional callback when RudderStack is loaded\n * @param debug - Enable debug logging\n * @returns The RudderStack singleton instance\n */\n public static getRudderStackInstance = (\n RUDDERSTACK_KEY: string,\n onLoaded?: () => void,\n debug = false\n ): RudderStack => {\n if (!RudderStack._instance) {\n RudderStack._instance = new RudderStack(RUDDERSTACK_KEY, onLoaded, debug)\n }\n return RudderStack._instance\n }\n\n /**\n * Get the anonymous ID from cookies\n * @returns The anonymous ID or undefined if not found\n */\n getAnonymousId = (): string | undefined => {\n return document.cookie.match('(^|;)\\\\s*' + this.rudderstack_anonymous_cookie_key + '\\\\s*=\\\\s*([^;]+)')?.pop()\n }\n\n /**\n * Set anonymous ID cookie if it doesn't exist\n * Creates a secure cookie with proper domain and security attributes\n */\n setCookieIfNotExists = (): void => {\n const anonymous_id = this.getAnonymousId()\n\n if (!anonymous_id) {\n try {\n const hostname = window.location.hostname\n const external_domains = ['webflow.io']\n const is_external_domain = external_domains.some(domain => hostname.endsWith(domain))\n const domain_name = is_external_domain ? hostname : hostname.split('.').slice(-2).join('.')\n\n // Generate cryptographically secure UUID\n let uuid: string\n if (crypto?.randomUUID) {\n uuid = crypto.randomUUID()\n } else if (crypto?.getRandomValues) {\n // Fallback: Generate UUID v4 using crypto.getRandomValues\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n // Set version (4) and variant bits\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n // Convert to UUID string format\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n } else {\n // Crypto API not available - this should not happen in modern browsers\n throw new Error('Crypto API not available for secure random UUID generation')\n }\n\n const isSecure = window.location.protocol === 'https:'\n const secureFlag = isSecure ? '; Secure' : ''\n\n document.cookie = `${this.rudderstack_anonymous_cookie_key}=${uuid}; path=/; Domain=${domain_name}; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secureFlag}`\n } catch (error) {\n console.warn('RudderStack: Failed to set anonymous ID cookie', error)\n }\n }\n }\n\n /**\n * Get the current user ID\n * @returns The user ID, null, or undefined if not identified\n */\n getUserId = () => this.analytics.getUserId()\n\n /**\n * Initialize RudderStack with the provided key\n * @param RUDDERSTACK_KEY - RudderStack write key\n */\n init = (RUDDERSTACK_KEY: string): void => {\n if (!RUDDERSTACK_KEY) {\n console.warn('RudderStack: Initialization skipped - no key provided')\n return\n }\n\n this.log('init | loading SDK', { dataplane: rudderstackDataplane })\n\n try {\n this.setCookieIfNotExists()\n\n this.analytics.load(RUDDERSTACK_KEY, rudderstackDataplane, {\n externalAnonymousIdCookieName: this.rudderstack_anonymous_cookie_key,\n storage: { type: 'localStorage' },\n // Performance optimizations\n lockIntegrationsVersion: true,\n onLoaded: () => {\n this.has_initialized = true\n this.has_identified = !!this.getUserId()\n this.log('init | SDK loaded successfully', {\n userId: this.getUserId(),\n anonymousId: this.getAnonymousId(),\n })\n this.onLoadedCallback?.()\n },\n })\n } catch (error) {\n console.error('RudderStack: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with RudderStack\n * Only identifies if user hasn't been identified yet\n * @param user_id - The user ID to identify\n * @param payload - Optional user traits (e.g., language, custom properties)\n */\n identifyEvent = (user_id: string, payload?: Record<string, any>): void => {\n if (!this.has_initialized) {\n console.warn('RudderStack: Cannot identify - not initialized')\n return\n }\n\n const currentUserId = this.getUserId()\n if (!currentUserId || currentUserId !== user_id) {\n try {\n this.log('identifyEvent | identifying user', { user_id, traits: payload })\n this.analytics.identify(user_id, payload || {})\n this.has_identified = true\n } catch (error) {\n console.error('RudderStack: Failed to identify user', error)\n }\n } else {\n this.log('identifyEvent | user already identified', { user_id })\n this.has_identified = true\n }\n }\n\n /**\n * Track a page view event\n * @param current_page - The page name/path\n * @param platform - The platform name (default: 'Deriv App')\n * @param user_id - The user ID\n * @param properties - Additional page properties\n */\n pageView = (\n current_page: string,\n platform = 'Deriv App',\n user_id: string,\n properties?: Record<string, unknown>\n ): void => {\n if (!this.has_initialized || current_page === this.current_page) return\n\n try {\n const pageProperties = {\n ...(user_id && { user_id }),\n ...properties,\n }\n\n this.log('pageView | tracking page view', { platform, current_page, properties: pageProperties })\n // Type assertion needed due to RudderStack's type definitions\n this.analytics.page(platform, current_page, pageProperties as any)\n this.current_page = current_page\n } catch (error) {\n console.error('RudderStack: Failed to track page view', error)\n }\n }\n\n /**\n * Reset the RudderStack instance\n * Clears user identification and resets tracking state\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting RudderStack session')\n this.analytics.reset()\n this.has_identified = false\n } catch (error) {\n console.error('RudderStack: Failed to reset', error)\n }\n }\n\n /**\n * Track a custom event with payload\n * Payload is pre-cleaned by analytics.ts using cleanObject before being passed here\n * @param event - The event name\n * @param payload - The event payload with core attributes\n */\n track = <T extends keyof TAllEvents>(event: T, payload: TAllEvents[T] & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('track | sending event to RudderStack', { event, payload })\n // Type assertion needed to match RudderStack's ApiObject type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.analytics.track(event as string, payload as any)\n } catch (err) {\n console.warn('RudderStack: Failed to track event', err)\n }\n }\n}\n"]}
@@ -1,3 +0,0 @@
1
- 'use strict';var chunkT4BXL6JM_js=require('./chunk-T4BXL6JM.js');/* @deriv-com/analytics - NPM Package - Built with tsup */
2
- var p=class{constructor(){this.interval=null;this.responses=[];this.isTrackingResponses=false;this.delegatedSelectors=new Set;this.debug=false;this.log=chunkT4BXL6JM_js.f("[CacheManager]",()=>this.debug);this.addEventhandler=this.addEventHandler.bind(this);}setDebug(e){this.debug=e;}hash(e,n=32){let t=i=>{let o=2166136261;for(let l=0;l<i.length;l++)o^=i.charCodeAt(l),o=o*16777619>>>0;return o.toString(16)},a=i=>btoa(i),s=t(e),r=a(s);for(;r.length<n;)r+=a(t(r));return r.substring(0,n)}getCookies(e){let t=`; ${document.cookie}`.split(`; ${e}=`);if(t.length===2){let a=decodeURIComponent(t.pop().split(";").shift());try{return JSON.parse(a)}catch{return a}}return null}trackPageUnload(){typeof window>"u"||window.addEventListener("beforeunload",()=>{this.isPageViewSent()||this.push("cached_analytics_page_views",{name:window.location.origin+window.location.pathname});});}trackResponses(){if(typeof window>"u"||typeof XMLHttpRequest>"u")return;let e=XMLHttpRequest.prototype.open,n=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(t,a){return this._url=a,this._method=t,e.apply(this,arguments)},XMLHttpRequest.prototype.send=function(t){return this.addEventListener("load",function(){let a=null;if(typeof t=="string")try{a=JSON.parse(t);}catch{a=t;}let s={url:this._url,method:this._method,status:this.status,headers:this.getAllResponseHeaders(),data:this.responseText,payload:a};f.responses.push(s);}),n.apply(this,arguments)},this.isTrackingResponses=true;}getAnalyticsInstance(){return typeof window>"u"?null:window.AnalyticsInstance??window.DerivAnalytics?.Analytics??window.Analytics?.Analytics}isReady(){if(typeof window>"u")return false;let e=this.getAnalyticsInstance();return e?!!e.getInstances?.()?.tracking:false}parseFromLocalStorage(e){if(typeof localStorage>"u")return null;try{let n=localStorage.getItem(e);return n===null?null:JSON.parse(n)}catch{return null}}isPageViewSent(){return !!this.responses.find(e=>e.payload?.type==="page"&&e.payload?.anonymousId)}set(e){this.log("set | caching event to localStorage",e),this.push("cached_analytics_events",e);}push(e,n){if(typeof localStorage>"u")return;let t=this.parseFromLocalStorage(e),a=Array.isArray(t)?t:[];a.push(n);try{localStorage.setItem(e,JSON.stringify(a));}catch(s){console.warn("AnalyticsCacheManager: Failed to push to localStorage",s);}}processEvent(e){let n=this.getCookies("client_information");if(n){let{email:t=null}=n;t&&(e.properties.email_hash=this.hash(t));}if(e?.properties?.email){let t=e.properties.email;delete e.properties.email,e.properties.email_hash=this.hash(t);}return e}track(e,n=false){if(typeof window>"u")return;let t=this.processEvent(e),a=this.getAnalyticsInstance();this.isReady()&&!n?(this.log("track | analytics ready \u2014 calling trackEvent",{event:t.name,properties:t.properties}),a.trackEvent(t.name,t.properties)):(this.log("track | analytics not ready or cache=true \u2014 storing event",{event:t.name,cache:n}),this.set(t));}pageView(){typeof window>"u"||(this.log("pageView | starting page view polling"),this.isTrackingResponses||(this.trackResponses(),this.trackPageUnload()),this.interval=setInterval(()=>{let e=window.Analytics;typeof e<"u"&&typeof e.Analytics?.pageView=="function"&&this.isReady()&&(this.log("pageView | analytics ready \u2014 sending page view",{href:window.location.href}),e.Analytics.pageView(window.location.href,"Trader's hub")),this.isPageViewSent()&&(this.log("pageView | page view confirmed sent \u2014 clearing interval"),this.interval&&clearInterval(this.interval));},1e3));}listen(e,{name:n="",properties:t={}},a=false,s=null){let r=o=>{o.dataset?.clickEventTracking||(o.addEventListener("click",l=>{let c={name:n,properties:t,cache:a};if(typeof s=="function"){let d=s(l);c={...d,cache:d.cache??a};}this.track(c,c.cache??false);}),o.dataset.clickEventTracking="true");};(e instanceof NodeList?Array.from(e):[e]).forEach(r);}addEventHandler(e){return typeof window>"u"?this:(e.forEach(({element:n,event:t={name:"",properties:{}},cache:a=false,callback:s=null})=>{if(typeof n=="string"){let r=n;if(!this.delegatedSelectors.has(r)){let i=o=>{let l=o.target;if(!l)return;let c=l.closest(r);if(c&&!c.dataset?.clickEventTracking){let d={name:t.name,properties:t.properties,cache:a};if(typeof s=="function"){let h=s(o);d={...h,cache:h.cache??a};}c.dataset.clickEventTracking="true",this.track(d,d.cache??false);}};document.addEventListener("click",i),this.delegatedSelectors.add(r);}}else (n instanceof NodeList?Array.from(n):[n]).forEach(i=>{i&&!i.dataset?.clickEventTracking&&this.listen(i,t,a,s);});}),this)}loadEvent(e){return this.log("loadEvent | firing load events",e.map(n=>n.event.name)),e.forEach(({event:n})=>{let{name:t,properties:a}=n;this.track({name:t,properties:a});}),this}pageLoadEvent(e){if(typeof window>"u")return this;let n=window.location.pathname.slice(1);return this.log("pageLoadEvent | checking page load events",{pathname:n}),e.forEach(({pages:t=[],excludedPages:a=[],event:s,callback:r=null})=>{let i=false;if(t.length?t.includes(n)&&(i=true):a.length&&a.includes(n)||(i=true),i){let o=r?r():s;this.log("pageLoadEvent | dispatching event for page",{pathname:n,event:o.name}),this.loadEvent([{event:o}]);}else this.log("pageLoadEvent | skipped event for page",{pathname:n,event:s.name,pages:t,excludedPages:a});}),this}clearInterval(){this.interval&&(clearInterval(this.interval),this.interval=null);}cleanup(){this.clearInterval(),this.responses=[],this.isTrackingResponses=false;}},f=new p;typeof window<"u"&&(window.cacheTrackEvents=f);exports.a=f;//# sourceMappingURL=chunk-NCHU4435.js.map
3
- //# sourceMappingURL=chunk-NCHU4435.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/analytics-cache.ts"],"names":["AnalyticsCacheManager","createLogger","debug","inputString","desiredLength","fnv1aHash","string","hash","i","base64Encode","combined","name","parts","cookieValue","originalXhrOpen","originalXhrSend","method","url","body","parsedPayload","responseData","cacheTrackEvents","instance","key","raw","event","data","existing","stored","err","clientInfo","email","originalEvent","cache","Analytics","element","properties","callback","addClickListener","el","e","callbackResult","items","selector","delegatedHandler","target","matched","evt","pathname","pages","excludedPages","dispatch","eventData"],"mappings":";AA+CA,IAAMA,CAAAA,CAAN,KAA4B,CAA5B,WAAA,EAAA,CACI,IAAA,CAAQ,QAAA,CAAkC,IAAA,CAC1C,IAAA,CAAQ,SAAA,CAA4B,EAAC,CACrC,IAAA,CAAQ,mBAAA,CAAsB,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,CAAA,GAAM,CAC1E,IAAIc,CAAAA,CAAW,KAAA,CAaf,GAZIF,CAAAA,CAAM,MAAA,CACFA,CAAAA,CAAM,QAAA,CAASD,CAAQ,CAAA,GACvBG,CAAAA,CAAW,IAAA,CAAA,CAERD,CAAAA,CAAc,MAAA,EAChBA,CAAAA,CAAc,QAAA,CAASF,CAAQ,CAAA,GAChCG,CAAAA,CAAW,IAAA,CAAA,CAMfA,CAAAA,CAAU,CACV,IAAMC,CAAAA,CAAYf,CAAAA,CAAWA,CAAAA,EAAS,CAAIZ,CAAAA,CAC1C,IAAA,CAAK,GAAA,CAAI,4CAAA,CAA8C,CAAE,QAAA,CAAAuB,EAAU,KAAA,CAAOI,CAAAA,CAAU,IAAK,CAAC,CAAA,CAC1F,IAAA,CAAK,SAAA,CAAU,CAAC,CAAE,KAAA,CAAOA,CAAU,CAAC,CAAC,EACzC,CAAA,KACI,IAAA,CAAK,GAAA,CAAI,wCAAA,CAA0C,CAC/C,QAAA,CAAAJ,CAAAA,CACA,KAAA,CAAOvB,CAAAA,CAAM,IAAA,CACb,KAAA,CAAAwB,CAAAA,CACA,aAAA,CAAAC,CACJ,CAAC,EAET,CAAC,CAAA,CAEM,IACX,CAKA,aAAA,EAAsB,CACd,IAAA,CAAK,QAAA,GACL,aAAA,CAAc,IAAA,CAAK,QAAQ,CAAA,CAC3B,IAAA,CAAK,QAAA,CAAW,IAAA,EAExB,CAKA,OAAA,EAAgB,CACZ,IAAA,CAAK,eAAc,CACnB,IAAA,CAAK,SAAA,CAAY,EAAC,CAClB,IAAA,CAAK,mBAAA,CAAsB,MAC/B,CACJ,CAAA,CAGa7B,CAAAA,CAAmB,IAAIrB,EAGhC,OAAO,MAAA,CAAW,GAAA,GAChB,OAAe,gBAAA,CAAmBqB,CAAAA,CAAAA","file":"chunk-NCHU4435.js","sourcesContent":["/**\n * Analytics Cache Manager - Version 1.1.0\n * Enhanced TypeScript implementation with better type safety and SSR support\n */\nimport { createLogger } from './helpers'\n\ntype CachedEvent = {\n name: string\n properties: Record<string, any>\n}\n\ntype ResponseData = {\n url: string\n method: string\n status: number\n headers: string\n data: string\n payload: any\n}\n\ntype EventListenerConfig = {\n element: Element | NodeList | string\n event: {\n name: string\n properties: Record<string, any>\n }\n cache?: boolean\n callback?: (e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }\n}\n\ntype LoadEventConfig = {\n event: {\n name: string\n properties: Record<string, any>\n }\n}\n\ntype PageLoadEventConfig = {\n pages?: string[]\n excludedPages?: string[]\n event: {\n name: string\n properties: Record<string, any>\n }\n callback?: () => { name: string; properties: Record<string, any> }\n}\n\nclass AnalyticsCacheManager {\n private interval: NodeJS.Timeout | null = null\n private responses: ResponseData[] = []\n private isTrackingResponses = false\n private delegatedSelectors: Set<string> = new Set()\n private debug = false\n private log = createLogger('[CacheManager]', () => this.debug)\n\n setDebug(debug: boolean): void {\n this.debug = debug\n }\n\n /**\n * FNV-1a hash algorithm for creating consistent hashes\n */\n private hash(inputString: string, desiredLength = 32): string {\n const fnv1aHash = (string: string): string => {\n let hash = 0x811c9dc5\n for (let i = 0; i < string.length; i++) {\n hash ^= string.charCodeAt(i)\n hash = (hash * 0x01000193) >>> 0\n }\n return hash.toString(16)\n }\n\n const base64Encode = (string: string): string => btoa(string)\n\n let hash = fnv1aHash(inputString)\n let combined = base64Encode(hash)\n\n while (combined.length < desiredLength) {\n combined += base64Encode(fnv1aHash(combined))\n }\n\n return combined.substring(0, desiredLength)\n }\n\n /**\n * Get cookie value by name\n */\n getCookies(name: string): any {\n const value = `; ${document.cookie}`\n const parts = value.split(`; ${name}=`)\n if (parts.length === 2) {\n const cookieValue = decodeURIComponent(parts.pop()!.split(';').shift()!)\n\n try {\n return JSON.parse(cookieValue)\n } catch (e) {\n return cookieValue\n }\n }\n return null\n }\n\n /**\n * Track page unload events to cache pageviews before leaving\n */\n trackPageUnload(): void {\n if (typeof window === 'undefined') return\n\n window.addEventListener('beforeunload', () => {\n if (!this.isPageViewSent()) {\n this.push('cached_analytics_page_views', {\n name: window.location.origin + window.location.pathname,\n })\n }\n })\n }\n\n /**\n * Track XMLHttpRequest responses to monitor analytics calls\n */\n trackResponses(): void {\n if (typeof window === 'undefined' || typeof XMLHttpRequest === 'undefined') return\n\n const originalXhrOpen = XMLHttpRequest.prototype.open\n const originalXhrSend = XMLHttpRequest.prototype.send\n\n XMLHttpRequest.prototype.open = function (method: string, url: string | URL) {\n ;(this as any)._url = url\n ;(this as any)._method = method\n return originalXhrOpen.apply(this, arguments as any)\n }\n\n XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null) {\n this.addEventListener('load', function () {\n let parsedPayload = null\n\n if (typeof body === 'string') {\n try {\n parsedPayload = JSON.parse(body)\n } catch (e) {\n parsedPayload = body\n }\n }\n\n const responseData: ResponseData = {\n url: (this as any)._url,\n method: (this as any)._method,\n status: this.status,\n headers: this.getAllResponseHeaders(),\n data: this.responseText,\n payload: parsedPayload,\n }\n cacheTrackEvents.responses.push(responseData)\n })\n\n return originalXhrSend.apply(this, arguments as any)\n }\n\n this.isTrackingResponses = true\n }\n\n /**\n * Resolve the analytics instance from the window object.\n * Supports three usage patterns:\n * - NPM import: analytics.ts sets window.AnalyticsInstance directly\n * - IIFE bundle: tsup sets window.DerivAnalytics = { Analytics, cacheTrackEvents }\n * - Legacy: consumers that explicitly set window.Analytics = window.DerivAnalytics\n */\n private getAnalyticsInstance(): any {\n if (typeof window === 'undefined') return null\n return (\n (window as any).AnalyticsInstance ??\n (window as any).DerivAnalytics?.Analytics ??\n (window as any).Analytics?.Analytics\n )\n }\n\n /**\n * Check if Analytics instance is ready\n */\n isReady(): boolean {\n if (typeof window === 'undefined') return false\n const instance = this.getAnalyticsInstance()\n if (!instance) return false\n return !!instance.getInstances?.()?.tracking\n }\n\n /**\n * Parse a localStorage entry by key.\n */\n private parseFromLocalStorage(key: string): any {\n if (typeof localStorage === 'undefined') return null\n\n try {\n const raw = localStorage.getItem(key)\n if (raw === null) return null\n return JSON.parse(raw)\n } catch {\n return null\n }\n }\n\n /**\n * Check if pageview has been sent\n */\n isPageViewSent(): boolean {\n return !!this.responses.find(e => e.payload?.type === 'page' && e.payload?.anonymousId)\n }\n\n /**\n * Set a cached event\n */\n set(event: CachedEvent): void {\n this.log('set | caching event to localStorage', event)\n this.push('cached_analytics_events', event)\n }\n\n /**\n * Push data to localStorage cache\n */\n push(key: string, data: any): void {\n if (typeof localStorage === 'undefined') return\n\n const existing = this.parseFromLocalStorage(key)\n const stored: any[] = Array.isArray(existing) ? existing : []\n stored.push(data)\n\n try {\n localStorage.setItem(key, JSON.stringify(stored))\n } catch (err) {\n console.warn('AnalyticsCacheManager: Failed to push to localStorage', err)\n }\n }\n\n /**\n * Process event to hash email and add client info\n */\n processEvent(event: CachedEvent): CachedEvent {\n const clientInfo = this.getCookies('client_information')\n\n if (clientInfo) {\n const { email = null } = clientInfo\n\n if (email) {\n event.properties.email_hash = this.hash(email)\n }\n }\n\n if (event?.properties?.email) {\n const email = event.properties.email\n delete event.properties.email\n event.properties.email_hash = this.hash(email)\n }\n\n return event\n }\n\n /**\n * Track an event (either immediately or cache it)\n */\n track(originalEvent: CachedEvent, cache = false): void {\n if (typeof window === 'undefined') return\n\n const event = this.processEvent(originalEvent)\n const instance = this.getAnalyticsInstance()\n\n if (this.isReady() && !cache) {\n this.log('track | analytics ready — calling trackEvent', {\n event: event.name,\n properties: event.properties,\n })\n instance.trackEvent(event.name, event.properties)\n } else {\n this.log('track | analytics not ready or cache=true — storing event', { event: event.name, cache })\n this.set(event)\n }\n }\n\n /**\n * Track pageview with auto-retry until sent\n */\n pageView(): void {\n if (typeof window === 'undefined') return\n\n this.log('pageView | starting page view polling')\n\n if (!this.isTrackingResponses) {\n this.trackResponses()\n this.trackPageUnload()\n }\n\n this.interval = setInterval(() => {\n const Analytics = (window as any).Analytics\n\n if (\n typeof Analytics !== 'undefined' &&\n typeof Analytics.Analytics?.pageView === 'function' &&\n this.isReady()\n ) {\n this.log('pageView | analytics ready — sending page view', { href: window.location.href })\n Analytics.Analytics.pageView(window.location.href, \"Trader's hub\")\n }\n\n if (this.isPageViewSent()) {\n this.log('pageView | page view confirmed sent — clearing interval')\n if (this.interval) clearInterval(this.interval)\n }\n }, 1000)\n }\n\n /**\n * Add click event listener to element(s)\n */\n listen(\n element: Element | NodeList,\n { name = '', properties = {} }: { name: string; properties: Record<string, any> },\n cache = false,\n callback: ((e: Event) => { name: string; properties: Record<string, any>; cache?: boolean }) | null = null\n ): void {\n const addClickListener = (el: Element) => {\n if (!(el as any).dataset?.clickEventTracking) {\n el.addEventListener('click', (e: Event) => {\n let event = {\n name,\n properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n event = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n this.track(event, event.cache ?? false)\n })\n ;(el as any).dataset.clickEventTracking = 'true'\n }\n }\n\n const elements = element instanceof NodeList ? Array.from(element as NodeListOf<Element>) : [element]\n elements.forEach(addClickListener)\n }\n\n /**\n * Add event handlers to multiple elements with auto-retry\n * Alias for backward compatibility with typo\n */\n addEventHandler(items: EventListenerConfig[]): this {\n if (typeof window === 'undefined') return this\n\n items.forEach(({ element, event = { name: '', properties: {} }, cache = false, callback = null }) => {\n // If a selector string is provided, use event delegation on document\n if (typeof element === 'string') {\n const selector = element\n\n if (!this.delegatedSelectors.has(selector)) {\n const delegatedHandler = (e: Event) => {\n const target = e.target as Element | null\n if (!target) return\n\n const matched = target.closest(selector)\n if (matched && !(matched as any).dataset?.clickEventTracking) {\n let evt: any = {\n name: event.name,\n properties: event.properties,\n cache,\n }\n\n if (typeof callback === 'function') {\n const callbackResult = callback(e)\n evt = {\n ...callbackResult,\n cache: callbackResult.cache ?? cache,\n }\n }\n\n ;(matched as any).dataset.clickEventTracking = 'true'\n this.track(evt, evt.cache ?? false)\n }\n }\n\n document.addEventListener('click', delegatedHandler)\n this.delegatedSelectors.add(selector)\n }\n } else {\n // Element or NodeList: attach directly to existing elements\n const elements = element instanceof NodeList ? Array.from(element) : [element]\n\n elements.forEach(el => {\n if (el && !(el as any).dataset?.clickEventTracking) {\n this.listen(el as Element, event, cache, callback)\n }\n })\n }\n })\n\n return this\n }\n\n /**\n * Backward compatibility alias (with typo from original)\n */\n addEventhandler = this.addEventHandler.bind(this)\n\n /**\n * Load events immediately\n */\n loadEvent(items: LoadEventConfig[]): this {\n this.log(\n 'loadEvent | firing load events',\n items.map(i => i.event.name)\n )\n items.forEach(({ event }) => {\n const { name, properties } = event\n this.track({\n name,\n properties,\n })\n })\n\n return this\n }\n\n /**\n * Load events on specific pages\n */\n pageLoadEvent(items: PageLoadEventConfig[]): this {\n if (typeof window === 'undefined') return this\n\n const pathname = window.location.pathname.slice(1)\n this.log('pageLoadEvent | checking page load events', { pathname })\n\n items.forEach(({ pages = [], excludedPages = [], event, callback = null }) => {\n let dispatch = false\n if (pages.length) {\n if (pages.includes(pathname)) {\n dispatch = true\n }\n } else if (excludedPages.length) {\n if (!excludedPages.includes(pathname)) {\n dispatch = true\n }\n } else {\n dispatch = true\n }\n\n if (dispatch) {\n const eventData = callback ? callback() : event\n this.log('pageLoadEvent | dispatching event for page', { pathname, event: eventData.name })\n this.loadEvent([{ event: eventData }])\n } else {\n this.log('pageLoadEvent | skipped event for page', {\n pathname,\n event: event.name,\n pages,\n excludedPages,\n })\n }\n })\n\n return this\n }\n\n /**\n * Clear the interval and cleanup\n */\n clearInterval(): void {\n if (this.interval) {\n clearInterval(this.interval)\n this.interval = null\n }\n }\n\n /**\n * Cleanup method for removing event listeners and intervals\n */\n cleanup(): void {\n this.clearInterval()\n this.responses = []\n this.isTrackingResponses = false\n }\n}\n\n// Create singleton instance\nexport const cacheTrackEvents = new AnalyticsCacheManager()\n\n// Export to global scope for backward compatibility\nif (typeof window !== 'undefined') {\n ;(window as any).cacheTrackEvents = cacheTrackEvents\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/rudderstack.ts"],"names":["COOKIE_MAX_AGE_SECONDS","_RudderStack","RUDDERSTACK_KEY","onLoaded","debug","RudderAnalytics","createLogger","hostname","domain_name","domain","uuid","bytes","hex","byte","secureFlag","error","rudderstackDataplane","user_id","payload","currentUserId","current_page","platform","properties","pageProperties","event","err","RudderStack"],"mappings":";AAMA,IAAMA,CAAAA,CAAyB,IAAA,CAAW,EAAA,CAAK,EAAA,CAMlCC,CAAAA,CAAN,MAAMA,CAAY,CAWrB,WAAA,CAAYC,CAAAA,CAAyBC,CAAAA,CAAuBC,CAAAA,CAAQ,KAAA,CAAO,CAV3E,IAAA,CAAA,SAAA,CAAY,IAAIC,2BAAAA,CAChB,IAAA,CAAA,cAAA,CAAiB,KAAA,CACjB,IAAA,CAAA,eAAA,CAAkB,KAAA,CAClB,IAAA,CAAA,YAAA,CAAe,EAAA,CACf,IAAA,CAAA,gCAAA,CAAmC,sBAGnC,IAAA,CAAQ,KAAA,CAAQ,KAAA,CAChB,IAAA,CAAQ,GAAA,CAAMC,kBAAAA,CAAa,eAAA,CAAiB,IAAM,IAAA,CAAK,KAAK,CAAA,CA8B5D,IAAA,CAAA,cAAA,CAAiB,IACN,QAAA,CAAS,MAAA,CAAO,KAAA,CAAM,YAAc,IAAA,CAAK,gCAAA,CAAmC,kBAAkB,CAAA,EAAG,GAAA,EAAI,CAOhH,IAAA,CAAA,oBAAA,CAAuB,IAAY,CAG/B,GAAI,CAFiB,IAAA,CAAK,cAAA,EAAe,CAGrC,GAAI,CACA,IAAMC,CAAAA,CAAW,MAAA,CAAO,QAAA,CAAS,QAAA,CAG3BC,CAAAA,CAFmB,CAAC,YAAY,CAAA,CACM,IAAA,CAAKC,CAAAA,EAAUF,CAAAA,CAAS,QAAA,CAASE,CAAM,CAAC,CAAA,CAC3CF,CAAAA,CAAWA,CAAAA,CAAS,KAAA,CAAM,GAAG,CAAA,CAAE,KAAA,CAAM,CAAA,CAAE,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA,CAGtFG,CAAAA,CACJ,GAAI,MAA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AY,CAChB,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,uCAAuC,CAAA,CAChD,KAAK,SAAA,CAAU,KAAA,EAAM,CACrB,IAAA,CAAK,cAAA,CAAiB,CAAA,EAC1B,CAAA,MAASA,CAAAA,CAAO,CACZ,OAAA,CAAQ,KAAA,CAAM,8BAAA,CAAgCA,CAAK,EACvD,CACJ,CAAA,CAQA,WAAQ,CAA6BS,CAAAA,CAAUN,CAAAA,GAA4D,CACvG,GAAK,IAAA,CAAK,eAAA,CAEV,GAAI,CACA,IAAA,CAAK,GAAA,CAAI,sCAAA,CAAwC,CAAE,KAAA,CAAAM,CAAAA,CAAO,OAAA,CAAAN,CAAQ,CAAC,CAAA,CAGnE,IAAA,CAAK,SAAA,CAAU,KAAA,CAAMM,CAAAA,CAAiBN,CAAc,EACxD,CAAA,MAASO,CAAAA,CAAK,CACV,OAAA,CAAQ,IAAA,CAAK,oCAAA,CAAsCA,CAAG,EAC1D,CACJ,CAAA,CA7MI,IAAA,CAAK,gBAAA,CAAmBtB,CAAAA,CACxB,IAAA,CAAK,KAAA,CAAQC,CAAAA,CACb,IAAA,CAAK,IAAA,CAAKF,CAAe,EAC7B,CA2MJ,CAAA,CA1NaD,CAAAA,CAwBK,sBAAA,CAAyB,CACnCC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CAAQ,KAAA,IAEHH,CAAAA,CAAY,SAAA,GACbA,CAAAA,CAAY,SAAA,CAAY,IAAIA,CAAAA,CAAYC,CAAAA,CAAiBC,CAAAA,CAAUC,CAAK,CAAA,CAAA,CAErEH,CAAAA,CAAY,SAAA,CAAA,KAhCdyB,CAAAA,CAANzB","file":"chunk-YZ34YKBW.js","sourcesContent":["import { RudderAnalytics } from '@rudderstack/analytics-js'\nimport type { TCoreAttributes, TAllEvents } from '../types'\nimport { rudderstackDataplane } from '../utils/urls'\nimport { createLogger } from '../utils/helpers'\n\n// Constants\nconst COOKIE_MAX_AGE_SECONDS = 180 * 24 * 60 * 60 // 180 days (~6 months)\n\n/**\n * RudderStack analytics wrapper with singleton pattern.\n * Handles user tracking, page views, and event analytics.\n */\nexport class RudderStack {\n analytics = new RudderAnalytics()\n has_identified = false\n has_initialized = false\n current_page = ''\n rudderstack_anonymous_cookie_key = 'rudder_anonymous_id'\n private static _instance: RudderStack\n private onLoadedCallback?: () => void\n private debug = false\n private log = createLogger('[RudderStack]', () => this.debug)\n\n constructor(RUDDERSTACK_KEY: string, onLoaded?: () => void, debug = false) {\n this.onLoadedCallback = onLoaded\n this.debug = debug\n this.init(RUDDERSTACK_KEY)\n }\n\n /**\n * Get or create the singleton instance of RudderStack\n * @param RUDDERSTACK_KEY - RudderStack write key\n * @param onLoaded - Optional callback when RudderStack is loaded\n * @param debug - Enable debug logging\n * @returns The RudderStack singleton instance\n */\n public static getRudderStackInstance = (\n RUDDERSTACK_KEY: string,\n onLoaded?: () => void,\n debug = false\n ): RudderStack => {\n if (!RudderStack._instance) {\n RudderStack._instance = new RudderStack(RUDDERSTACK_KEY, onLoaded, debug)\n }\n return RudderStack._instance\n }\n\n /**\n * Get the anonymous ID from cookies\n * @returns The anonymous ID or undefined if not found\n */\n getAnonymousId = (): string | undefined => {\n return document.cookie.match('(^|;)\\\\s*' + this.rudderstack_anonymous_cookie_key + '\\\\s*=\\\\s*([^;]+)')?.pop()\n }\n\n /**\n * Set anonymous ID cookie if it doesn't exist\n * Creates a secure cookie with proper domain and security attributes\n */\n setCookieIfNotExists = (): void => {\n const anonymous_id = this.getAnonymousId()\n\n if (!anonymous_id) {\n try {\n const hostname = window.location.hostname\n const external_domains = ['webflow.io']\n const is_external_domain = external_domains.some(domain => hostname.endsWith(domain))\n const domain_name = is_external_domain ? hostname : hostname.split('.').slice(-2).join('.')\n\n // Generate cryptographically secure UUID\n let uuid: string\n if (crypto?.randomUUID) {\n uuid = crypto.randomUUID()\n } else if (crypto?.getRandomValues) {\n // Fallback: Generate UUID v4 using crypto.getRandomValues\n const bytes = new Uint8Array(16)\n crypto.getRandomValues(bytes)\n // Set version (4) and variant bits\n bytes[6] = (bytes[6]! & 0x0f) | 0x40\n bytes[8] = (bytes[8]! & 0x3f) | 0x80\n // Convert to UUID string format\n const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')\n uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`\n } else {\n // Crypto API not available - this should not happen in modern browsers\n throw new Error('Crypto API not available for secure random UUID generation')\n }\n\n const isSecure = window.location.protocol === 'https:'\n const secureFlag = isSecure ? '; Secure' : ''\n\n document.cookie = `${this.rudderstack_anonymous_cookie_key}=${uuid}; path=/; Domain=${domain_name}; max-age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax${secureFlag}`\n } catch (error) {\n console.warn('RudderStack: Failed to set anonymous ID cookie', error)\n }\n }\n }\n\n /**\n * Get the current user ID\n * @returns The user ID, null, or undefined if not identified\n */\n getUserId = () => this.analytics.getUserId()\n\n /**\n * Initialize RudderStack with the provided key\n * @param RUDDERSTACK_KEY - RudderStack write key\n */\n init = (RUDDERSTACK_KEY: string): void => {\n if (!RUDDERSTACK_KEY) {\n console.warn('RudderStack: Initialization skipped - no key provided')\n return\n }\n\n this.log('init | loading SDK', { dataplane: rudderstackDataplane })\n\n try {\n this.setCookieIfNotExists()\n\n this.analytics.load(RUDDERSTACK_KEY, rudderstackDataplane, {\n externalAnonymousIdCookieName: this.rudderstack_anonymous_cookie_key,\n storage: { type: 'localStorage' },\n // Performance optimizations\n lockIntegrationsVersion: true,\n onLoaded: () => {\n this.has_initialized = true\n this.has_identified = !!this.getUserId()\n this.log('init | SDK loaded successfully', {\n userId: this.getUserId(),\n anonymousId: this.getAnonymousId(),\n })\n this.onLoadedCallback?.()\n },\n })\n } catch (error) {\n console.error('RudderStack: Failed to initialize', error)\n }\n }\n\n /**\n * Identify a user with RudderStack\n * Only identifies if user hasn't been identified yet\n * @param user_id - The user ID to identify\n * @param payload - Optional user traits (e.g., language, custom properties)\n */\n identifyEvent = (user_id: string, payload?: Record<string, any>): void => {\n if (!this.has_initialized) {\n console.warn('RudderStack: Cannot identify - not initialized')\n return\n }\n\n const currentUserId = this.getUserId()\n if (!currentUserId || currentUserId !== user_id) {\n try {\n this.log('identifyEvent | identifying user', { user_id, traits: payload })\n this.analytics.identify(user_id, payload || {})\n this.has_identified = true\n } catch (error) {\n console.error('RudderStack: Failed to identify user', error)\n }\n } else {\n this.log('identifyEvent | user already identified', { user_id })\n this.has_identified = true\n }\n }\n\n /**\n * Track a page view event\n * @param current_page - The page name/path\n * @param platform - The platform name (default: 'Deriv App')\n * @param user_id - The user ID\n * @param properties - Additional page properties\n */\n pageView = (\n current_page: string,\n platform = 'Deriv App',\n user_id: string,\n properties?: Record<string, unknown>\n ): void => {\n if (!this.has_initialized || current_page === this.current_page) return\n\n try {\n const pageProperties = {\n ...(user_id && { user_id }),\n ...properties,\n }\n\n this.log('pageView | tracking page view', { platform, current_page, properties: pageProperties })\n // Type assertion needed due to RudderStack's type definitions\n this.analytics.page(platform, current_page, pageProperties as any)\n this.current_page = current_page\n } catch (error) {\n console.error('RudderStack: Failed to track page view', error)\n }\n }\n\n /**\n * Reset the RudderStack instance\n * Clears user identification and resets tracking state\n */\n reset = (): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('reset | resetting RudderStack session')\n this.analytics.reset()\n this.has_identified = false\n } catch (error) {\n console.error('RudderStack: Failed to reset', error)\n }\n }\n\n /**\n * Track a custom event with payload\n * Payload is pre-cleaned by analytics.ts using cleanObject before being passed here\n * @param event - The event name\n * @param payload - The event payload with core attributes\n */\n track = <T extends keyof TAllEvents>(event: T, payload: TAllEvents[T] & Partial<TCoreAttributes>): void => {\n if (!this.has_initialized) return\n\n try {\n this.log('track | sending event to RudderStack', { event, payload })\n // Type assertion needed to match RudderStack's ApiObject type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.analytics.track(event as string, payload as any)\n } catch (err) {\n console.warn('RudderStack: Failed to track event', err)\n }\n }\n}\n"]}