humanbehavior-js 0.5.18 → 0.5.20

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 (72) hide show
  1. package/package.json +8 -43
  2. package/packages/browser/dist/{index.mjs → cjs/index.js} +134 -5
  3. package/packages/browser/dist/cjs/index.js.map +1 -0
  4. package/packages/browser/dist/{index.js → esm/index.js} +114 -23
  5. package/packages/browser/dist/esm/index.js.map +1 -0
  6. package/packages/browser/dist/index.min.js +1 -1
  7. package/packages/browser/dist/index.min.js.map +1 -1
  8. package/packages/browser/dist/types/index.d.ts.map +1 -0
  9. package/packages/core/dist/api.d.ts +30 -0
  10. package/packages/core/dist/api.d.ts.map +1 -0
  11. package/packages/core/dist/index.d.ts +13 -0
  12. package/packages/core/dist/index.d.ts.map +1 -0
  13. package/packages/core/dist/index.js +2 -0
  14. package/packages/core/dist/index.js.map +1 -0
  15. package/packages/core/dist/index.mjs +2 -0
  16. package/packages/core/dist/index.mjs.map +1 -0
  17. package/packages/core/dist/redact.d.ts +88 -0
  18. package/packages/core/dist/redact.d.ts.map +1 -0
  19. package/packages/core/dist/tracker.d.ts +338 -0
  20. package/packages/core/dist/tracker.d.ts.map +1 -0
  21. package/packages/core/dist/utils/global-tracker.d.ts +23 -0
  22. package/packages/core/dist/utils/global-tracker.d.ts.map +1 -0
  23. package/packages/core/dist/utils/logger.d.ts +34 -0
  24. package/packages/core/dist/utils/logger.d.ts.map +1 -0
  25. package/packages/core/dist/utils/property-detector.d.ts +59 -0
  26. package/packages/core/dist/utils/property-detector.d.ts.map +1 -0
  27. package/packages/core/dist/utils/property-manager.d.ts +112 -0
  28. package/packages/core/dist/utils/property-manager.d.ts.map +1 -0
  29. package/packages/react/dist/index.js +1 -1
  30. package/packages/react/dist/index.js.map +1 -1
  31. package/packages/react/dist/index.mjs +1 -1
  32. package/packages/react/dist/index.mjs.map +1 -1
  33. package/packages/angular/dist/index.d.ts +0 -46
  34. package/packages/angular/dist/index.d.ts.map +0 -1
  35. package/packages/angular/dist/index.js +0 -2
  36. package/packages/angular/dist/index.js.map +0 -1
  37. package/packages/angular/dist/index.mjs +0 -2
  38. package/packages/angular/dist/index.mjs.map +0 -1
  39. package/packages/browser/dist/cdn.d.ts +0 -8
  40. package/packages/browser/dist/cdn.d.ts.map +0 -1
  41. package/packages/browser/dist/cdn.js +0 -2
  42. package/packages/browser/dist/cdn.js.map +0 -1
  43. package/packages/browser/dist/index.d.ts.map +0 -1
  44. package/packages/browser/dist/index.js.map +0 -1
  45. package/packages/browser/dist/index.mjs.map +0 -1
  46. package/packages/browser/dist/index.umd.js +0 -12113
  47. package/packages/browser/dist/index.umd.js.map +0 -1
  48. package/packages/browser/dist/module.cjs.d.ts +0 -10
  49. package/packages/browser/dist/module.cjs.d.ts.map +0 -1
  50. package/packages/browser/dist/module.es.d.ts +0 -10
  51. package/packages/browser/dist/module.es.d.ts.map +0 -1
  52. package/packages/browser/dist/module.js +0 -2
  53. package/packages/browser/dist/module.js.map +0 -1
  54. package/packages/remix/dist/index.d.ts +0 -8
  55. package/packages/remix/dist/index.d.ts.map +0 -1
  56. package/packages/remix/dist/index.js +0 -2
  57. package/packages/remix/dist/index.js.map +0 -1
  58. package/packages/remix/dist/index.mjs +0 -2
  59. package/packages/remix/dist/index.mjs.map +0 -1
  60. package/packages/svelte/dist/index.d.ts +0 -11
  61. package/packages/svelte/dist/index.d.ts.map +0 -1
  62. package/packages/svelte/dist/index.js +0 -2
  63. package/packages/svelte/dist/index.js.map +0 -1
  64. package/packages/svelte/dist/index.mjs +0 -2
  65. package/packages/svelte/dist/index.mjs.map +0 -1
  66. package/packages/vue/dist/index.d.ts +0 -14
  67. package/packages/vue/dist/index.d.ts.map +0 -1
  68. package/packages/vue/dist/index.js +0 -2
  69. package/packages/vue/dist/index.js.map +0 -1
  70. package/packages/vue/dist/index.mjs +0 -2
  71. package/packages/vue/dist/index.mjs.map +0 -1
  72. /package/packages/browser/dist/{index.d.ts → types/index.d.ts} +0 -0
@@ -1,5 +1,3 @@
1
- 'use strict';
2
-
3
1
  var __defProp = Object.defineProperty;
4
2
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
3
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
@@ -12063,7 +12061,117 @@ var n$1;
12063
12061
  t2[t2.NotStarted = 0] = "NotStarted", t2[t2.Running = 1] = "Running", t2[t2.Stopped = 2] = "Stopped";
12064
12062
  }(n$1 || (n$1 = {}));
12065
12063
 
12066
- const t=[];for(let e=0;e<256;++e)t.push((e+256).toString(16).slice(1));let i;const s=new Uint8Array(16);const r={};function n(e,n,o){let a;{const e=Date.now(),t=function(){if(!i){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");i=crypto.getRandomValues.bind(crypto);}return i(s)}();!function(e,t,i){e.msecs??=-1/0,e.nsecs??=0,t===e.msecs?(e.nsecs++,e.nsecs>=1e4&&(e.node=void 0,e.nsecs=0)):t>e.msecs?e.nsecs=0:t<e.msecs&&(e.node=void 0);e.node||(e.node=i.slice(10,16),e.node[0]|=1,e.clockseq=16383&(i[8]<<8|i[9]));e.msecs=t;}(r,e,t),a=function(e,t,i,s,r,n,o=0){if(e.length<16)throw new Error("Random bytes length must be >= 16");if(n){if(o<0||o+16>n.length)throw new RangeError(`UUID byte range ${o}:${o+15} is out of buffer bounds`)}else n=new Uint8Array(16),o=0;t??=Date.now(),i??=0,s??=16383&(e[8]<<8|e[9]),r??=e.slice(10,16);const a=(1e4*(268435455&(t+=122192928e5))+i)%4294967296;n[o++]=a>>>24&255,n[o++]=a>>>16&255,n[o++]=a>>>8&255,n[o++]=255&a;const d=t/4294967296*1e4&268435455;n[o++]=d>>>8&255,n[o++]=255&d,n[o++]=d>>>24&15|16,n[o++]=d>>>16&255,n[o++]=s>>>8|128,n[o++]=255&s;for(let e=0;e<6;++e)n[o++]=r[e];return n}(t,r.msecs,r.nsecs,r.clockseq,r.node,n,o);}return n??function(e,i=0){return (t[e[i+0]]+t[e[i+1]]+t[e[i+2]]+t[e[i+3]]+"-"+t[e[i+4]]+t[e[i+5]]+"-"+t[e[i+6]]+t[e[i+7]]+"-"+t[e[i+8]]+t[e[i+9]]+"-"+t[e[i+10]]+t[e[i+11]]+t[e[i+12]]+t[e[i+13]]+t[e[i+14]]+t[e[i+15]]).toLowerCase()}(a)}exports.LogLevel = void 0;!function(e){e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG";}(exports.LogLevel||(exports.LogLevel={}));const a=new class{constructor(e){this.config={level:exports.LogLevel.ERROR,enableConsole:true,enableStorage:false},this.isBrowser="undefined"!=typeof window,e&&(this.config={...this.config,...e});}setConfig(e){this.config={...this.config,...e};}shouldLog(e){return e<=this.config.level}formatMessage(e,t,...i){return `[HumanBehavior ${e}] ${(new Date).toISOString()}: ${t}`}error(e,...t){if(!this.shouldLog(exports.LogLevel.ERROR))return;const i=this.formatMessage("ERROR",e);this.config.enableConsole&&console.error(i,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(i,t);}warn(e,...t){if(!this.shouldLog(exports.LogLevel.WARN))return;const i=this.formatMessage("WARN",e);this.config.enableConsole&&console.warn(i,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(i,t);}info(e,...t){if(!this.shouldLog(exports.LogLevel.INFO))return;const i=this.formatMessage("INFO",e);this.config.enableConsole&&console.log(i,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(i,t);}debug(e,...t){if(!this.shouldLog(exports.LogLevel.DEBUG))return;const i=this.formatMessage("DEBUG",e);this.config.enableConsole&&console.log(i,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(i,t);}logToStorage(e,t){try{const i=JSON.parse(localStorage.getItem("human_behavior_logs")||"[]"),s={message:e,args:t.length>0?t:void 0,timestamp:Date.now()};i.push(s),i.length>1e3&&i.splice(0,i.length-1e3),localStorage.setItem("human_behavior_logs",JSON.stringify(i));}catch(e){}}getLogs(){if(!this.isBrowser)return [];try{return JSON.parse(localStorage.getItem("human_behavior_logs")||"[]")}catch(e){return []}}clearLogs(){this.isBrowser&&localStorage.removeItem("human_behavior_logs");}},d=(e,...t)=>a.error(e,...t),c=(e,...t)=>a.warn(e,...t),l=(e,...t)=>a.info(e,...t),h=(e,...t)=>a.debug(e,...t),u=1048576;function p(e,t,i){return (new TextEncoder).encode(JSON.stringify({sessionId:i,events:[...e,t]})).length>u}function g(e,t){if(!e||"object"!=typeof e)return [];if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[e]})).length<=u)return [e];const i={...e},s=["screenshot","html","dom","fullText","innerHTML","outerHTML"];s.forEach(e=>{i[e]&&delete i[e];});if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[i]})).length<=u)return [i];return [{type:e.type,timestamp:e.timestamp,url:e.url,pathname:e.pathname,...Object.fromEntries(Object.entries(e).filter(([e,t])=>!s.includes(e)&&"object"!=typeof t&&"string"!=typeof t||"string"==typeof t&&t.length<1e3))}]}class m{constructor({apiKey:e,ingestionUrl:t}){this.apiKey=e,this.baseUrl=t;}async init(e,t){let i=null,s=null;"undefined"!=typeof window&&(i=window.location.href,s=document.referrer),l("API init called with:",{sessionId:e,userId:t,entryURL:i,referrer:s,baseUrl:this.baseUrl});try{const r=await fetch(`${this.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:e,endUserId:t,entryURL:i,referrer:s})});if(l("API init response status:",r.status),!r.ok){const e=await r.text();throw d("API init failed:",r.status,e),new Error(`Failed to initialize ingestion: ${r.statusText} - ${e}`)}const n=await r.json();return l("API init success:",n),{sessionId:n.sessionId,endUserId:n.endUserId}}catch(e){throw d("API init error:",e),e}}async sendEvents(e,t,i){const s=e.filter(e=>e&&"object"==typeof e),r=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:s,endUserId:i})});if(!r.ok)throw new Error(`Failed to send events: ${r.statusText}`)}async sendEventsChunked(e,t,i){try{const s=[];let r=[];for(const n of e)if(n&&"object"==typeof n)if(p(r,n,t)){if(r.length>0){h(`[SDK] Sending chunk with ${r.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:r,endUserId:i})});if(!e.ok)throw new Error(`Failed to send events: ${e.statusText}`);s.push(await e.json()),r=[];}r=g(n,t);}else r.push(n);if(r.length>0){h(`[SDK] Sending final chunk with ${r.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:r,endUserId:i})});if(!e.ok)throw new Error(`Failed to send events: ${e.statusText}`);s.push(await e.json());}return s.flat()}catch(e){throw d("Error sending events:",e),e}}async sendUserData(e,t,i){try{const s={userId:e,userAttributes:t,sessionId:i,posthogName:t.email||t.name||null};h("Sending user data to server:",s);const r=await fetch(`${this.baseUrl}/api/ingestion/user`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send user data: ${r.statusText} with API key: ${this.apiKey}`);const n=await r.json();return h("Server response:",n),n}catch(e){throw d("Error sending user data:",e),e}}async sendUserAuth(e,t,i,s){try{const r=await fetch(`${this.baseUrl}/api/ingestion/user/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({userId:e,userAttributes:t,sessionId:i,authFields:s})});if(!r.ok)throw new Error(`Failed to authenticate user: ${r.statusText} with API key: ${this.apiKey}`);return await r.json()}catch(e){throw d("Error authenticating user:",e),e}}sendBeaconEvents(e,t){const i={sessionId:t,events:e,endUserId:null,apiKey:this.apiKey},s=new Blob([JSON.stringify(i)],{type:"application/json"});return navigator.sendBeacon(`${this.baseUrl}/api/ingestion/events`,s)}async sendCustomEvent(e,t,i){l("[SDK] Sending custom event",{sessionId:e,eventName:t,eventProperties:i});try{const s=await fetch(`${this.baseUrl}/api/ingestion/customEvent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,eventName:t,eventProperties:i||{}})});if(l("[SDK] Custom event response",{status:s.status,statusText:s.statusText}),!s.ok){const e=await s.text();throw d("[SDK] Failed to send custom event",{status:s.status,statusText:s.statusText,errorText:e}),new Error(`Failed to send custom event: ${s.status} ${s.statusText} - ${e}`)}const r=await s.json();return h("[SDK] Custom event success",r),r}catch(s){throw d("[SDK] Error sending custom event",s,{sessionId:e,eventName:t,eventProperties:i}),s}}async sendCustomEventBatch(e,t){try{const i=await fetch(`${this.baseUrl}/api/ingestion/customEvent/batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,events:t})});if(!i.ok)throw new Error(`Failed to send custom event batch: ${i.statusText}`);return await i.json()}catch(e){throw d("Error sending custom event batch:",e),e}}}class y{constructor(e){this.redactedText="[REDACTED]",this.unredactedFields=new Set,this.redactedFields=new Set,this.redactionMode="privacy-first",this.excludeSelectors=['[data-no-redact="true"]',".human-behavior-no-redact"],e?.redactedText&&(this.redactedText=e.redactedText),e?.excludeSelectors&&(this.excludeSelectors=[...this.excludeSelectors,...e.excludeSelectors]),e?.redactionStrategy&&(this.redactionMode=e.redactionStrategy.mode,"privacy-first"===this.redactionMode?e.redactionStrategy.unredactFields&&this.setFieldsToUnredact(e.redactionStrategy.unredactFields):e.redactionStrategy.redactFields&&this.setFieldsToRedact(e.redactionStrategy.redactFields)),e?.legacyRedactFields&&this.setFieldsToUnredact(e.legacyRedactFields),e?.userFields&&this.setFieldsToUnredact(e.userFields);}setFieldsToRedact(e){this.redactedFields.clear();['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]',...e].forEach(e=>{this.redactedFields.add(e);}),this.redactedFields.size>0?h(`Redaction: Active for ${this.redactedFields.size} field(s):`,Array.from(this.redactedFields)):h("Redaction: No fields to redact"),this.applyRedactionClasses();}setFieldsToUnredact(e){this.unredactedFields.clear();const t=e.filter(e=>!this.isPasswordSelector(e)||(c(`Cannot unredact password field: ${e} - Password fields are always protected`),false));t.forEach(e=>this.unredactedFields.add(e)),t.length>0?h(`Unredaction: Active for ${t.length} field(s):`,t):h("Unredaction: No valid fields to unredact"),this.applyUnredactionClasses();}redactFields(e){e.forEach(e=>{this.unredactedFields.delete(e);}),this.unredactedFields.size>0?h(`Unredaction: Removed ${e.length} field(s), ${this.unredactedFields.size} remaining:`,Array.from(this.unredactedFields)):h("Unredaction: All fields redacted"),this.applyUnredactionClasses();}clearUnredactedFields(){this.unredactedFields.clear(),h("Unredaction: All fields cleared, everything redacted"),this.removeUnredactionClasses();}hasUnredactedFields(){return this.unredactedFields.size>0}getRedactionMode(){return this.redactionMode}getUnredactedFields(){return Array.from(this.unredactedFields)}getMaskTextSelector(){return "privacy-first"===this.redactionMode?0===this.unredactedFields.size?null:Array.from(this.unredactedFields).join(","):0===this.redactedFields.size?null:Array.from(this.redactedFields).join(",")}applyRedactionClasses(){0!==this.redactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.redactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.add("rr-mask");}),h(`Added rr-mask class to ${t.length} element(s) for selector: ${e}`);}catch(t){c(`Invalid selector: ${e}`);}}):h("DOM not ready, deferring redaction class application"));}applyUnredactionClasses(){0!==this.unredactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.unredactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.remove("rr-mask");}),h(`Removed rr-mask class from ${t.length} element(s) for selector: ${e}`);}catch(t){c(`Invalid selector: ${e}`);}}):h("DOM not ready, deferring unredaction class application"));}removeUnredactionClasses(){h("Unredaction classes removed");}isPasswordSelector(e){return ['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]'].some(t=>e.toLowerCase().includes(t.toLowerCase().replace(/[\[\]]/g,"")))}getOriginalValue(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return e.value}isElementUnredacted(e){return this.shouldUnredactElement(e)}shouldUnredactElement(e){if("privacy-first"===this.redactionMode){if(0===this.unredactedFields.size)return false;for(const t of this.unredactedFields)try{if(e.matches(t))return !0}catch(e){c(`Invalid selector: ${t}`);}return false}if(0===this.redactedFields.size)return true;for(const t of this.redactedFields)try{if(e.matches(t))return !1}catch(e){c(`Invalid selector: ${t}`);}return true}}new y;const f="undefined"!=typeof window;function v(){if(!f)return "unknown";const e=navigator.userAgent.toLowerCase(),t=window.screen.width,i=window.screen.height;return /mobile|android|iphone|ipad|ipod|blackberry|windows phone/i.test(e)?/ipad/i.test(e)||t>=768&&i>=1024?"tablet":"mobile":/windows|macintosh|linux/i.test(e)?"desktop":"unknown"}function w(e){try{return new URL(e).hostname}catch{return ""}}function S(){if(!f)return {device_type:"unknown",browser:"unknown",browser_version:"unknown",os:"unknown",os_version:"unknown",screen_resolution:"unknown",viewport_size:"unknown",color_depth:0,timezone:"unknown",language:"unknown",languages:[]};const{browser:e,browser_version:t}=function(){if(!f)return {browser:"unknown",browser_version:"unknown"};const e=navigator.userAgent;if(/chrome/i.test(e)&&!/edge/i.test(e)){const t=e.match(/chrome\/(\d+)/i);return {browser:"chrome",browser_version:t?t[1]:"unknown"}}if(/firefox/i.test(e)){const t=e.match(/firefox\/(\d+)/i);return {browser:"firefox",browser_version:t?t[1]:"unknown"}}if(/safari/i.test(e)&&!/chrome/i.test(e)){const t=e.match(/version\/(\d+)/i);return {browser:"safari",browser_version:t?t[1]:"unknown"}}if(/edge/i.test(e)){const t=e.match(/edge\/(\d+)/i);return {browser:"edge",browser_version:t?t[1]:"unknown"}}if(/msie|trident/i.test(e)){const t=e.match(/msie (\d+)/i)||e.match(/rv:(\d+)/i);return {browser:"ie",browser_version:t?t[1]:"unknown"}}return {browser:"unknown",browser_version:"unknown"}}(),{os:i,os_version:s}=function(){if(!f)return {os:"unknown",os_version:"unknown"};const e=navigator.userAgent;if(/windows/i.test(e)){const t=e.match(/windows nt (\d+\.\d+)/i);let i="unknown";if(t){const e=parseFloat(t[1]);i=10===e?"10":6.3===e?"8.1":6.2===e?"8":6.1===e?"7":t[1];}return {os:"windows",os_version:i}}if(/macintosh|mac os x/i.test(e)){const t=e.match(/mac os x (\d+[._]\d+)/i);return {os:"macos",os_version:t?t[1].replace("_","."):"unknown"}}if(/iphone|ipad|ipod/i.test(e)){const t=e.match(/os (\d+[._]\d+)/i);return {os:"ios",os_version:t?t[1].replace("_","."):"unknown"}}if(/android/i.test(e)){const t=e.match(/android (\d+\.\d+)/i);return {os:"android",os_version:t?t[1]:"unknown"}}return /linux/i.test(e)?{os:"linux",os_version:"unknown"}:{os:"unknown",os_version:"unknown"}}();return {device_type:v(),browser:e,browser_version:t,os:i,os_version:s,screen_resolution:`${window.screen.width}x${window.screen.height}`,viewport_size:`${window.innerWidth}x${window.innerHeight}`,color_depth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,languages:[...navigator.languages||[navigator.language]],raw_user_agent:navigator.userAgent}}function _(){if(!f)return {current_url:"",pathname:"",search:"",hash:"",title:"",referrer:"",referrer_domain:"",initial_referrer:"",initial_referrer_domain:""};const e=window.location.href,t=document.referrer,i=function(e){const t=new URL(e),i={};return ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(e=>{const s=t.searchParams.get(e);s&&(i[e]=s);}),i}(e);return {current_url:e,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,title:document.title,referrer:t,referrer_domain:w(t),initial_referrer:t,initial_referrer_domain:w(t),initial_host:window.location.hostname,...i}}function b(){return {...S(),..._()}}function k(){if(!f)return {};const e=_();return {initial_referrer:e.initial_referrer,initial_referrer_domain:e.initial_referrer_domain,initial_url:e.current_url,initial_pathname:e.pathname,initial_utm_source:e.utm_source,initial_utm_medium:e.utm_medium,initial_utm_campaign:e.utm_campaign,initial_utm_term:e.utm_term,initial_utm_content:e.utm_content}}function I(){if(!f)return {};const e=_();return {current_url:e.current_url,pathname:e.pathname,search:e.search,hash:e.hash,title:e.title,referrer:e.referrer,referrer_domain:e.referrer_domain,utm_source:e.utm_source,utm_medium:e.utm_medium,utm_campaign:e.utm_campaign,utm_term:e.utm_term,utm_content:e.utm_content}}class E{constructor(e={}){this.sessionProperties={},this.userProperties={},this.initialProperties={},this.isInitialized=false,this.config={enableAutomaticProperties:true,enableSessionProperties:true,enableUserProperties:true,propertyDenylist:[],...e},this.automaticProperties=b(),this.initialize();}initialize(){this.isInitialized||(this.initialProperties=k(),this.loadSessionProperties(),this.isInitialized=true);}getEventProperties(e={}){const t={...e};return this.config.enableAutomaticProperties&&Object.assign(t,this.getAutomaticProperties()),this.config.enableSessionProperties&&Object.assign(t,this.sessionProperties),this.config.enableUserProperties&&Object.assign(t,this.userProperties),this.sessionProperties.$initial_properties_captured||(Object.assign(t,this.initialProperties),this.setSessionProperty("$initial_properties_captured",true)),this.applyDenylist(t),t}getAutomaticProperties(){return {...this.automaticProperties,...I()}}getAutomaticPropertiesWithGeoIP(e={}){return {...this.automaticProperties,...I(),...e}}setSessionProperty(e,t){this.sessionProperties[e]=t,this.saveSessionProperties();}setSessionProperties(e){Object.assign(this.sessionProperties,e),this.saveSessionProperties();}getSessionProperty(e){return this.sessionProperties[e]}removeSessionProperty(e){delete this.sessionProperties[e],this.saveSessionProperties();}setUserProperty(e,t){this.userProperties[e]=t;}setUserProperties(e){Object.assign(this.userProperties,e);}getUserProperty(e){return this.userProperties[e]}removeUserProperty(e){delete this.userProperties[e];}setOnce(e,t,i="user"){"session"===i?e in this.sessionProperties||this.setSessionProperty(e,t):e in this.userProperties||this.setUserProperty(e,t);}clearSessionProperties(){this.sessionProperties={},this.saveSessionProperties();}clearUserProperties(){this.userProperties={};}reset(){this.clearSessionProperties(),this.clearUserProperties(),this.initialProperties={},this.isInitialized=false,this.initialize();}loadSessionProperties(){if("undefined"!=typeof sessionStorage)try{const e=sessionStorage.getItem("hb_session_properties");e&&(this.sessionProperties=JSON.parse(e));}catch(e){console.warn("Failed to load session properties:",e);}}saveSessionProperties(){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem("hb_session_properties",JSON.stringify(this.sessionProperties));}catch(e){console.warn("Failed to save session properties:",e);}}applyDenylist(e){this.config.propertyDenylist&&0!==this.config.propertyDenylist.length&&this.config.propertyDenylist.forEach(t=>{delete e[t];});}updateAutomaticProperties(){this.automaticProperties=b();}getAllProperties(){return {automatic:this.getAutomaticProperties(),session:{...this.sessionProperties},user:{...this.userProperties},initial:{...this.initialProperties}}}}const U="undefined"!=typeof window;class P{get isTrackerStarted(){return this.isStarted}setupDomReadyHandler(){if(U)if("complete"===document.readyState||"interactive"===document.readyState)this.onDomReady();else if(document.addEventListener){document.addEventListener("DOMContentLoaded",()=>this.onDomReady(),{capture:false});const e=setInterval(()=>{"interactive"!==document.readyState&&"complete"!==document.readyState||(clearInterval(e),this.onDomReady());},10);setTimeout(()=>clearInterval(e),5e3);}else this.onDomReady();else this.onDomReady();}onDomReady(){this.isDomReady||(this.isDomReady=true,h("🎯 DOM is ready, processing queued requests"),this.requestQueue.forEach(e=>{this.processRequest(e);}),this.requestQueue=[],this.domReadyHandlers.forEach(e=>e()),this.domReadyHandlers=[]);}queueRequest(e){this.isDomReady?this.processRequest(e):this.requestQueue.push(e);}async processRequest(e){switch(h("Processing queued request:",e),e.type){case "addEvent":await this.addEvent(e.event);break;case "identifyUser":await this.identifyUser(e.userProperties);break;case "trackPageView":this.trackPageView();break;default:c("Unknown request type:",e.type);}}registerDomReadyHandler(e){this.isDomReady?e():this.domReadyHandlers.push(e);}static init(e,t){if(U&&false!==t?.suppressConsoleErrors){const e=console.error;console.error=(...t)=>{const i=t.join(" ");i.includes("SecurityError: Failed to execute 'toDataURL'")||i.includes("Tainted canvases may not be exported")||i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("TypeError: NetworkError")||i.includes("HumanBehavior ERROR")||i.includes("Failed to track custom event")||i.includes("Error sending custom event")||e.apply(console,t);};const t=console.warn;console.warn=(...e)=>{const i=e.join(" ");i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("Custom event network error")||i.includes("Request blocked by ad blocker")||t.apply(console,e);},window.addEventListener("error",e=>{const t=e.message||"";if(t.includes("SecurityError")||t.includes("Tainted canvases")||t.includes("toDataURL")||t.includes("Cross-Origin")||t.includes("CORS")||t.includes("NetworkError")||t.includes("Failed to fetch"))return e.preventDefault(),false});}if(U&&window.__humanBehaviorGlobalTracker)return h("Tracker already initialized, returning existing instance"),window.__humanBehaviorGlobalTracker;t?.logLevel&&this.configureLogging({level:t.logLevel});const i=new P(e,t?.ingestionUrl,{enableAutomaticProperties:t?.enableAutomaticProperties,propertyDenylist:t?.propertyDenylist,maxQueueSize:t?.maxQueueSize});return i.recordCanvas=t?.recordCanvas??false,t?.redactFields&&i.setUnredactedFields(t.redactFields),t?.redactionStrategy&&("privacy-first"===t.redactionStrategy.mode?t.redactionStrategy.unredactFields&&i.setUnredactedFields(t.redactionStrategy.unredactFields):t.redactionStrategy.redactFields&&i.setRedactedFields(t.redactionStrategy.redactFields)),i.start(),i}constructor(e,t,i){if(this.eventQueue=[],this.userProperties={},this.isProcessing=false,this.flushInterval=null,this.FLUSH_INTERVAL_MS=3e3,this.endUserId=null,this.initialized=false,this.initializationPromise=null,this.isDomReady=false,this.requestQueue=[],this.domReadyHandlers=[],this.originalConsole=null,this.consoleTrackingEnabled=false,this.navigationTrackingEnabled=false,this.currentUrl="",this.previousUrl="",this.originalPushState=null,this.originalReplaceState=null,this.navigationListeners=[],this._connectionBlocked=false,this.recordInstance=null,this.sessionStartTime=Date.now(),this.rrwebRecord=null,this.fullSnapshotTimeout=null,this.recordCanvas=false,this.isStarted=false,!e)throw new Error("Human Behavior API Key is required");if(this.api=new m({apiKey:e,ingestionUrl:t||"https://ingest.humanbehavior.co"}),this.apiKey=e,this.MAX_QUEUE_SIZE=i?.maxQueueSize??1e3,this.redactionManager=new y({redactionStrategy:i?.redactionStrategy,legacyRedactFields:i?.redactFields}),this.propertyManager=new E({enableAutomaticProperties:false!==i?.enableAutomaticProperties,propertyDenylist:i?.propertyDenylist||[]}),U){const e=localStorage.getItem(`human_behavior_session_id_${this.apiKey}`),t=localStorage.getItem(`human_behavior_last_activity_${this.apiKey}`),i=Date.now()-9e5;e&&t&&parseInt(t)>i?(this.sessionId=e,h(`Reusing existing session: ${this.sessionId}`),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())):(e&&(h(`Session expired, clearing old session: ${e}`),localStorage.removeItem(`human_behavior_session_id_${this.apiKey}`),localStorage.removeItem(`human_behavior_last_activity_${this.apiKey}`)),this.sessionId=n(),h(`Creating new session: ${this.sessionId}`),localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())),this.currentUrl=window.location.href,window.__humanBehaviorGlobalTracker=this;}else this.sessionId=n();this.initializationPromise=this.init().catch(e=>{d("Background initialization failed:",e);});}async init(){try{this.initialized=!0;const e=U?this.getCookie(`human_behavior_end_user_id_${this.apiKey}`):null;h(`Initializing with sessionId: ${this.sessionId}, userId: ${e}`);const t=this.propertyManager.getAutomaticProperties();U?(this.setupPageUnloadHandler(),this.setupNavigationTracking()):l("HumanBehaviorTracker initialized in server environment. Session tracking is disabled."),await this.initServerAsync(e,t),l(`HumanBehaviorTracker initialized with sessionId: ${this.sessionId}`);}catch(e){throw d("Failed to initialize HumanBehaviorTracker:",e),e}}async initServerAsync(e,t){try{h("🚀 Attempting to call /init endpoint..."),h("📡 URL:",`${this.api.baseUrl}/api/ingestion/init`),h("🔑 API Key:",this.apiKey);let i=null,s=null;U&&(i=window.location.href,s=document.referrer),h("📦 Payload:",{sessionId:this.sessionId,endUserId:e,entryURL:i,referrer:s,automaticProperties:t});const r=await fetch(`${this.api.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:this.sessionId,endUserId:e,entryURL:i,referrer:s,automaticProperties:t})});if(!r.ok)throw new Error(`Failed to initialize: ${r.statusText}`);const{sessionId:n,endUserId:o}=await r.json();n!==this.sessionId&&(h(`Server returned different sessionId: ${n} (client had: ${this.sessionId})`),this.sessionId=n,U&&localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId)),this.endUserId=o,this.setCookie(`human_behavior_end_user_id_${this.apiKey}`,o,365),l(`Server initialization completed with endUserId: ${o}`);}catch(e){d("❌ Server initialization failed:",e),d("🔍 Error details:",{message:e?.message||"Unknown error",stack:e?.stack||"No stack trace",type:e?.constructor?.name||"Unknown type"}),c("Server initialization failed, continuing with local session:",e);}}async ensureInitialized(){this.initializationPromise&&await this.initializationPromise;}setupNavigationTracking(){if(!U||this.navigationTrackingEnabled)return;this.navigationTrackingEnabled=true,h("Setting up navigation tracking"),this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState,history.pushState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalPushState.apply(history,e),this.trackNavigationEvent("pushState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();},history.replaceState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalReplaceState.apply(history,e),this.trackNavigationEvent("replaceState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};const e=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("popstate",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};window.addEventListener("popstate",e),this.navigationListeners.push(()=>{window.removeEventListener("popstate",e);});const t=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("hashchange",this.previousUrl,this.currentUrl);};window.addEventListener("hashchange",t),this.navigationListeners.push(()=>{window.removeEventListener("hashchange",t);}),this.trackNavigationEvent("pageLoad","",this.currentUrl);}async trackNavigationEvent(e,t,i){if(this.initialized)try{const s={type:e,from:t,to:i,timestamp:(new Date).toISOString(),pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer};await this.addEvent({type:5,data:{payload:{eventType:"navigation",...s}},timestamp:Date.now()}),h(`Navigation tracked: ${e} from ${t} to ${i}`);}catch(e){d("Failed to track navigation event:",e);}}async trackPageView(e){if(this.initialized){this.propertyManager.updateAutomaticProperties();try{const t={url:e||window.location.href,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer,timestamp:(new Date).toISOString()},i=this.propertyManager.getEventProperties(t);await this.addEvent({type:5,data:{payload:{eventType:"pageview",...i}},timestamp:Date.now()}),h(`Pageview tracked: ${t.url}`);}catch(e){d("Failed to track pageview event:",e);}}}async customEvent(e,t){if(!this.initialized)return;const i=this.propertyManager.getEventProperties(t);try{await this.api.sendCustomEvent(this.sessionId,e,i),h(`Custom event tracked: ${e}`,i);}catch(t){d("Failed to track custom event:",t),t.message?.includes("500")||t.message?.includes("Internal Server Error")||t.message?.includes("Failed to send custom event")?c("Custom event endpoint failed, using fallback"):t.message?.includes("ERR_BLOCKED_BY_CLIENT")?c("Custom event request blocked by ad blocker, using fallback"):t.message?.includes("Failed to fetch")&&c("Custom event network error, using fallback");try{const t={eventName:e,properties:i||{},timestamp:(new Date).toISOString(),url:window.location.href,pathname:window.location.pathname};await this.addEvent({type:5,data:{payload:{eventType:"custom",...t}},timestamp:Date.now()}),h(`Custom event added to event stream as fallback: ${e}`);}catch(e){d("Failed to add custom event to event stream as fallback:",e);}}}setupAutomaticTracking(e){}setupAutomaticButtonTracking(e){}setupAutomaticLinkTracking(e){}setupAutomaticFormTracking(e){}cleanupNavigationTracking(){this.navigationTrackingEnabled&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.navigationListeners.forEach(e=>e()),this.navigationListeners=[],this.navigationTrackingEnabled=false,h("Navigation tracking cleaned up"));}static logToStorage(e){l(e);}static configureLogging(e){a.setConfig({level:{none:0,error:1,warn:2,info:3,debug:4}[e.level||"error"],enableConsole:false!==e.enableConsole,enableStorage:e.enableStorage||false});}enableConsoleTracking(){U&&!this.consoleTrackingEnabled&&(this.originalConsole={log:console.log,warn:console.warn,error:console.error},console.log=(...e)=>{this.trackConsoleEvent("log",e),this.originalConsole.log(...e);},console.warn=(...e)=>{this.trackConsoleEvent("warn",e),this.originalConsole.warn(...e);},console.error=(...e)=>{this.trackConsoleEvent("error",e),this.originalConsole.error(...e);},this.consoleTrackingEnabled=true,h("Console tracking enabled"));}disableConsoleTracking(){U&&this.consoleTrackingEnabled&&(this.originalConsole&&(console.log=this.originalConsole.log,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error),this.consoleTrackingEnabled=false,h("Console tracking disabled"));}trackConsoleEvent(e,t){if(this.initialized)try{const i={level:e,message:t.map(e=>"object"==typeof e?JSON.stringify(e):String(e)).join(" "),timestamp:(new Date).toISOString(),url:window.location.href};this.addEvent({type:5,data:{payload:{eventType:"console",...i}},timestamp:Date.now()}).catch(e=>{d("Failed to track console event:",e);});}catch(e){d("Error in trackConsoleEvent:",e);}}setupPageUnloadHandler(){if(!U)return;h("Setting up page unload handler"),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&(h("Page hidden - sending pending events"),this.flushEvents());}),window.addEventListener("beforeunload",()=>{this.flushEvents();});const e=()=>{localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString());};window.addEventListener("click",e),window.addEventListener("keydown",e),window.addEventListener("scroll",e),window.addEventListener("mousemove",e);}viewLogs(){try{const e=a.getLogs();l("HumanBehavior Logs:",e),a.clearLogs();}catch(e){d("Failed to read logs:",e);}}async identifyUser({userProperties:e}){await this.ensureInitialized();const t=this.endUserId;return this.userProperties=e,h("Identifying user:",{userProperties:e,originalEndUserId:t,sessionId:this.sessionId}),!U||this.propertyManager.getAutomaticProperties(),await this.api.sendUserData(t||"",e,this.sessionId),t||""}getUserAttributes(){return {...this.userProperties}}async start(){if(await this.ensureInitialized(),!U)return;if(this.isStarted)return void h("HumanBehaviorTracker already started, skipping start() call.");this.isStarted=true,this.flushInterval=window.setInterval(()=>{this.flushEvents();},this.FLUSH_INTERVAL_MS);const t=()=>{if(this.recordInstance)return void h("🎯 Recording already started, skipping duplicate start");h("🎯 DOM ready, starting session recording"),this.rrwebRecord=record;const t=record({emit:e=>{this.addRecordingEvent(e),2===e.type&&h(`🎯 FullSnapshot generated at ${(new Date).toISOString()}`);},maskTextSelector:this.redactionManager.getMaskTextSelector()||void 0,maskTextFn:void 0,maskAllInputs:"privacy-first"===this.redactionManager.getRedactionMode(),maskInputOptions:{password:true},maskInputFn:void 0,slimDOMOptions:{},collectFonts:false,inlineStylesheet:true,recordCrossOriginIframes:false,recordCanvas:this.recordCanvas,sampling:this.recordCanvas?{canvas:4}:void 0,dataURLOptions:this.recordCanvas?{type:"image/webp",quality:.4}:void 0});this.recordInstance=t||null;};if(h(`🎯 DOM ready state: ${document.readyState}`),"complete"===document.readyState||"interactive"===document.readyState)h(`🎯 DOM ready (${document.readyState}), starting recording immediately`),t();else {h("🎯 DOM not ready, waiting for DOMContentLoaded event");const e=()=>("interactive"===document.readyState||"complete"===document.readyState)&&(h(`🎯 DOM ready (${document.readyState}), starting recording`),t(),true);if(e())return;document.addEventListener("DOMContentLoaded",()=>{h("🎯 DOMContentLoaded fired, starting recording"),t();},{once:true});const i=setInterval(()=>{e()&&clearInterval(i);},10);setTimeout(()=>clearInterval(i),5e3);}}takeFullSnapshot(){this.fullSnapshotTimeout&&clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=window.setTimeout(()=>{try{requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.rrwebRecord&&"function"==typeof this.rrwebRecord.takeFullSnapshot?(this.rrwebRecord.takeFullSnapshot(),h("✅ FullSnapshot taken for navigation (delayed for animations)")):c("⚠️ takeFullSnapshot not available on record function");});});}catch(e){d("❌ Failed to take FullSnapshot for navigation:",e);}},1e3);}async stop(){await this.ensureInitialized(),U&&(this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.recordInstance&&(this.recordInstance(),this.recordInstance=null),this.fullSnapshotTimeout&&(clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=null),this.rrwebRecord=null,this.disableConsoleTracking(),this.cleanupNavigationTracking());}async addEvent(e){if(await this.ensureInitialized(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);h(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),h("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(h("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(h(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else h("⚠️ Skipping invalid event:",e);}async flushEvents(){if(!this.isProcessing&&this.initialized){this.isProcessing=true;try{const e=this.eventQueue;if(this.eventQueue=[],e.length>0){h("Flushing events:",e);const t=e.filter(e=>2===e.type);t.length>0&&h(`[FIXED] Sending ${t.length} FullSnapshot(s) with valid data`);try{await this.api.sendEventsChunked(e,this.sessionId,this.endUserId);}catch(e){if(e.message?.includes("ERROR: Session already completed"))c("Session expired, events will be lost");else if(e.message?.includes("413")||e.message?.includes("Content Too Large"))c("Payload too large, events will be lost");else {if(!(e.message?.includes("ERR_BLOCKED_BY_CLIENT")||e.message?.includes("Failed to fetch")||e.message?.includes("NetworkError")))throw e;c("Request blocked by ad blocker or network issue, events will be lost");}}}}finally{this.isProcessing=false;}}}async addRecordingEvent(e){if(await this.ensureInitialized(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);h(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),h("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(h("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(h(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else h("⚠️ Skipping invalid recording event:",e);}setCookie(e,t,i){if(U)try{const s=new Date;s.setTime(s.getTime()+24*i*60*60*1e3);const r=`expires=${s.toUTCString()}`;document.cookie=`${e}=${t};${r};path=/;SameSite=Lax`,localStorage.setItem(e,t),h(`Set cookie and localStorage: ${e}`);}catch(i){try{localStorage.setItem(e,t),h(`Cookie blocked, using localStorage: ${e}`);}catch(e){d("Failed to store user ID in both cookie and localStorage:",e);}}}getCookie(e){if(!U)return null;try{const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let r=i[s];for(;" "===r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t)){const i=r.substring(t.length,r.length);return h(`Found cookie: ${e}`),i}}const s=localStorage.getItem(e);return s?(h(`Cookie not found, using localStorage: ${e}`),s):null}catch(t){try{const t=localStorage.getItem(e);if(t)return h(`Cookie access failed, using localStorage: ${e}`),t}catch(e){d("Failed to access both cookie and localStorage:",e);}return null}}deleteCookie(e){if(U){try{document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax`,h(`Deleted cookie: ${e}`);}catch(t){d(`Failed to delete cookie: ${e}`,t);}try{localStorage.removeItem(e),h(`Removed from localStorage: ${e}`);}catch(t){d(`Failed to remove from localStorage: ${e}`,t);}}}logout(){if(U)try{const e=`human_behavior_end_user_id_${this.apiKey}`;this.deleteCookie(e),localStorage.removeItem(`human_behavior_session_id_${this.apiKey}`),localStorage.removeItem(`human_behavior_last_activity_${this.apiKey}`),this.endUserId=null,this.userProperties={},this.sessionId=n(),U&&(localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())),l("User logged out - cleared all user data and started fresh session");}catch(e){d("Error during logout:",e);}}async redact(e){await this.ensureInitialized(),U?this.redactionManager=new y(e):c("Redaction is only available in browser environments");}setRedactedFields(e){this.redactionManager.setFieldsToRedact(e),this.recordInstance&&this.restartWithNewRedaction();}setUnredactedFields(e){this.redactionManager.setFieldsToUnredact(e),this.recordInstance&&this.restartWithNewRedaction();}restartWithNewRedaction(){this.recordInstance&&(this.recordInstance(),this.start());}hasUnredactedFields(){return this.redactionManager.hasUnredactedFields()}getUnredactedFields(){return this.redactionManager.getUnredactedFields()}redactFields(e){this.redactionManager.redactFields(e),this.recordInstance&&this.restartWithNewRedaction();}clearUnredactedFields(){this.redactionManager.clearUnredactedFields(),this.recordInstance&&this.restartWithNewRedaction();}getSessionId(){return this.sessionId}getCurrentUrl(){return this.currentUrl}getSnapshotFrequencyInfo(){return {sessionDuration:Date.now()-this.sessionStartTime,currentInterval:3e5,currentThreshold:1e3,phase:"configured"}}async testConnection(){try{return await this.api.init(this.sessionId,this.endUserId),{success:!0}}catch(e){return {success:false,error:e.message||"Unknown error"}}}getConnectionStatus(){const e=[];let t=false;return this.eventQueue.length>0&&(t=true,e.push("Some requests may be blocked by ad blockers")),this._connectionBlocked&&(t=true,e.push("Initial connection test failed - ad blocker may be active")),"undefined"==typeof window&&e.push("Not running in browser environment"),void 0===navigator.sendBeacon&&e.push("sendBeacon not available, using fetch fallback"),{blocked:t,recommendations:e}}isPreexistingUser(){if(!U)return false;const e=this.getCookie(`human_behavior_end_user_id_${this.apiKey}`);return null!==e&&e!==this.endUserId}getUserInfo(){return {endUserId:this.endUserId,sessionId:this.sessionId,isPreexistingUser:this.isPreexistingUser(),initialized:this.initialized}}setSessionProperty(e,t){this.propertyManager.setSessionProperty(e,t);}setSessionProperties(e){this.propertyManager.setSessionProperties(e);}getSessionProperty(e){return this.propertyManager.getSessionProperty(e)}removeSessionProperty(e){this.propertyManager.removeSessionProperty(e);}setUserProperty(e,t){this.propertyManager.setUserProperty(e,t);}setUserProperties(e){this.propertyManager.setUserProperties(e);}getUserProperty(e){return this.propertyManager.getUserProperty(e)}removeUserProperty(e){this.propertyManager.removeUserProperty(e);}setOnce(e,t,i="user"){this.propertyManager.setOnce(e,t,i);}clearSessionProperties(){this.propertyManager.clearSessionProperties();}clearUserProperties(){this.propertyManager.clearUserProperties();}getAllProperties(){return this.propertyManager.getAllProperties()}}function F(e){const t=globalThis.__humanBehaviorGlobalTracker;return t?.identifyUser?t.identifyUser({userProperties:e}):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function T(e,t){const i=globalThis.__humanBehaviorGlobalTracker;return i?.track?i.track(e,t):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function $(){const e=globalThis.__humanBehaviorGlobalTracker;return !!e?.identifyUser}U&&(window.HumanBehaviorTracker=P);
12064
+ const byteToHex = [];
12065
+ for (let i = 0; i < 256; ++i) {
12066
+ byteToHex.push((i + 0x100).toString(16).slice(1));
12067
+ }
12068
+ function unsafeStringify(arr, offset = 0) {
12069
+ return (byteToHex[arr[offset + 0]] +
12070
+ byteToHex[arr[offset + 1]] +
12071
+ byteToHex[arr[offset + 2]] +
12072
+ byteToHex[arr[offset + 3]] +
12073
+ '-' +
12074
+ byteToHex[arr[offset + 4]] +
12075
+ byteToHex[arr[offset + 5]] +
12076
+ '-' +
12077
+ byteToHex[arr[offset + 6]] +
12078
+ byteToHex[arr[offset + 7]] +
12079
+ '-' +
12080
+ byteToHex[arr[offset + 8]] +
12081
+ byteToHex[arr[offset + 9]] +
12082
+ '-' +
12083
+ byteToHex[arr[offset + 10]] +
12084
+ byteToHex[arr[offset + 11]] +
12085
+ byteToHex[arr[offset + 12]] +
12086
+ byteToHex[arr[offset + 13]] +
12087
+ byteToHex[arr[offset + 14]] +
12088
+ byteToHex[arr[offset + 15]]).toLowerCase();
12089
+ }
12090
+
12091
+ let getRandomValues;
12092
+ const rnds8 = new Uint8Array(16);
12093
+ function rng() {
12094
+ if (!getRandomValues) {
12095
+ if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
12096
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
12097
+ }
12098
+ getRandomValues = crypto.getRandomValues.bind(crypto);
12099
+ }
12100
+ return getRandomValues(rnds8);
12101
+ }
12102
+
12103
+ const _state = {};
12104
+ function v1(options, buf, offset) {
12105
+ let bytes;
12106
+ {
12107
+ const now = Date.now();
12108
+ const rnds = rng();
12109
+ updateV1State(_state, now, rnds);
12110
+ bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, _state.clockseq, _state.node, buf, offset);
12111
+ }
12112
+ return buf ?? unsafeStringify(bytes);
12113
+ }
12114
+ function updateV1State(state, now, rnds) {
12115
+ state.msecs ??= -Infinity;
12116
+ state.nsecs ??= 0;
12117
+ if (now === state.msecs) {
12118
+ state.nsecs++;
12119
+ if (state.nsecs >= 10000) {
12120
+ state.node = undefined;
12121
+ state.nsecs = 0;
12122
+ }
12123
+ }
12124
+ else if (now > state.msecs) {
12125
+ state.nsecs = 0;
12126
+ }
12127
+ else if (now < state.msecs) {
12128
+ state.node = undefined;
12129
+ }
12130
+ if (!state.node) {
12131
+ state.node = rnds.slice(10, 16);
12132
+ state.node[0] |= 0x01;
12133
+ state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff;
12134
+ }
12135
+ state.msecs = now;
12136
+ return state;
12137
+ }
12138
+ function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) {
12139
+ if (rnds.length < 16) {
12140
+ throw new Error('Random bytes length must be >= 16');
12141
+ }
12142
+ if (!buf) {
12143
+ buf = new Uint8Array(16);
12144
+ offset = 0;
12145
+ }
12146
+ else {
12147
+ if (offset < 0 || offset + 16 > buf.length) {
12148
+ throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
12149
+ }
12150
+ }
12151
+ msecs ??= Date.now();
12152
+ nsecs ??= 0;
12153
+ clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff;
12154
+ node ??= rnds.slice(10, 16);
12155
+ msecs += 12219292800000;
12156
+ const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
12157
+ buf[offset++] = (tl >>> 24) & 0xff;
12158
+ buf[offset++] = (tl >>> 16) & 0xff;
12159
+ buf[offset++] = (tl >>> 8) & 0xff;
12160
+ buf[offset++] = tl & 0xff;
12161
+ const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff;
12162
+ buf[offset++] = (tmh >>> 8) & 0xff;
12163
+ buf[offset++] = tmh & 0xff;
12164
+ buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10;
12165
+ buf[offset++] = (tmh >>> 16) & 0xff;
12166
+ buf[offset++] = (clockseq >>> 8) | 0x80;
12167
+ buf[offset++] = clockseq & 0xff;
12168
+ for (let n = 0; n < 6; ++n) {
12169
+ buf[offset++] = node[n];
12170
+ }
12171
+ return buf;
12172
+ }
12173
+
12174
+ var i;!function(e){e[e.NONE=0]="NONE",e[e.ERROR=1]="ERROR",e[e.WARN=2]="WARN",e[e.INFO=3]="INFO",e[e.DEBUG=4]="DEBUG";}(i||(i={}));const s=new class{constructor(e){this.config={level:i.ERROR,enableConsole:true,enableStorage:false},this.isBrowser="undefined"!=typeof window,e&&(this.config={...this.config,...e});}setConfig(e){this.config={...this.config,...e};}shouldLog(e){return e<=this.config.level}formatMessage(e,t,...i){return `[HumanBehavior ${e}] ${(new Date).toISOString()}: ${t}`}error(e,...t){if(!this.shouldLog(i.ERROR))return;const s=this.formatMessage("ERROR",e);this.config.enableConsole&&console.error(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}warn(e,...t){if(!this.shouldLog(i.WARN))return;const s=this.formatMessage("WARN",e);this.config.enableConsole&&console.warn(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}info(e,...t){if(!this.shouldLog(i.INFO))return;const s=this.formatMessage("INFO",e);this.config.enableConsole&&console.log(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}debug(e,...t){if(!this.shouldLog(i.DEBUG))return;const s=this.formatMessage("DEBUG",e);this.config.enableConsole&&console.log(s,...t),this.config.enableStorage&&this.isBrowser&&this.logToStorage(s,t);}logToStorage(e,t){try{const i=JSON.parse(localStorage.getItem("human_behavior_logs")||"[]"),s={message:e,args:t.length>0?t:void 0,timestamp:Date.now()};i.push(s),i.length>1e3&&i.splice(0,i.length-1e3),localStorage.setItem("human_behavior_logs",JSON.stringify(i));}catch(e){}}getLogs(){if(!this.isBrowser)return [];try{return JSON.parse(localStorage.getItem("human_behavior_logs")||"[]")}catch(e){return []}}clearLogs(){this.isBrowser&&localStorage.removeItem("human_behavior_logs");}},r=(e,...t)=>s.error(e,...t),n=(e,...t)=>s.warn(e,...t),o=(e,...t)=>s.info(e,...t),a=(e,...t)=>s.debug(e,...t),d=1048576;function l(e,t,i){return (new TextEncoder).encode(JSON.stringify({sessionId:i,events:[...e,t]})).length>d}function c(e,t){if(!e||"object"!=typeof e)return [];if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[e]})).length<=d)return [e];const i={...e},s=["screenshot","html","dom","fullText","innerHTML","outerHTML"];s.forEach(e=>{i[e]&&delete i[e];});if((new TextEncoder).encode(JSON.stringify({sessionId:t,events:[i]})).length<=d)return [i];return [{type:e.type,timestamp:e.timestamp,url:e.url,pathname:e.pathname,...Object.fromEntries(Object.entries(e).filter(([e,t])=>!s.includes(e)&&"object"!=typeof t&&"string"!=typeof t||"string"==typeof t&&t.length<1e3))}]}class h{constructor({apiKey:e,ingestionUrl:t}){this.apiKey=e,this.baseUrl=t;}async init(e,t){let i=null,s=null;"undefined"!=typeof window&&(i=window.location.href,s=document.referrer),o("API init called with:",{sessionId:e,userId:t,entryURL:i,referrer:s,baseUrl:this.baseUrl});try{const n=await fetch(`${this.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:e,endUserId:t,entryURL:i,referrer:s})});if(o("API init response status:",n.status),!n.ok){const e=await n.text();throw r("API init failed:",n.status,e),new Error(`Failed to initialize ingestion: ${n.statusText} - ${e}`)}const a=await n.json();return o("API init success:",a),{sessionId:a.sessionId,endUserId:a.endUserId}}catch(e){throw r("API init error:",e),e}}async sendEvents(e,t,i){const s=e.filter(e=>e&&"object"==typeof e),r=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:s,endUserId:i})});if(!r.ok)throw new Error(`Failed to send events: ${r.statusText}`)}async sendEventsChunked(e,t,i){try{const s=[];let r=[];for(const n of e)if(n&&"object"==typeof n)if(l(r,n,t)){if(r.length>0){a(`[SDK] Sending chunk with ${r.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:r,endUserId:i})});if(!e.ok)throw new Error(`Failed to send events: ${e.statusText}`);s.push(await e.json()),r=[];}r=c(n,t);}else r.push(n);if(r.length>0){a(`[SDK] Sending final chunk with ${r.length} events`);const e=await fetch(`${this.baseUrl}/api/ingestion/events`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:t,events:r,endUserId:i})});if(!e.ok)throw new Error(`Failed to send events: ${e.statusText}`);s.push(await e.json());}return s.flat()}catch(e){throw r("Error sending events:",e),e}}async sendUserData(e,t,i){try{const s={userId:e,userAttributes:t,sessionId:i,posthogName:t.email||t.name||null};a("Sending user data to server:",s);const r=await fetch(`${this.baseUrl}/api/ingestion/user`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(s)});if(!r.ok)throw new Error(`Failed to send user data: ${r.statusText} with API key: ${this.apiKey}`);const n=await r.json();return a("Server response:",n),n}catch(e){throw r("Error sending user data:",e),e}}async sendUserAuth(e,t,i,s){try{const r=await fetch(`${this.baseUrl}/api/ingestion/user/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({userId:e,userAttributes:t,sessionId:i,authFields:s})});if(!r.ok)throw new Error(`Failed to authenticate user: ${r.statusText} with API key: ${this.apiKey}`);return await r.json()}catch(e){throw r("Error authenticating user:",e),e}}sendBeaconEvents(e,t){const i={sessionId:t,events:e,endUserId:null,apiKey:this.apiKey},s=new Blob([JSON.stringify(i)],{type:"application/json"});return navigator.sendBeacon(`${this.baseUrl}/api/ingestion/events`,s)}async sendCustomEvent(e,t,i){o("[SDK] Sending custom event",{sessionId:e,eventName:t,eventProperties:i});try{const s=await fetch(`${this.baseUrl}/api/ingestion/customEvent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,eventName:t,eventProperties:i||{}})});if(o("[SDK] Custom event response",{status:s.status,statusText:s.statusText}),!s.ok){const e=await s.text();throw r("[SDK] Failed to send custom event",{status:s.status,statusText:s.statusText,errorText:e}),new Error(`Failed to send custom event: ${s.status} ${s.statusText} - ${e}`)}const n=await s.json();return a("[SDK] Custom event success",n),n}catch(s){throw r("[SDK] Error sending custom event",s,{sessionId:e,eventName:t,eventProperties:i}),s}}async sendCustomEventBatch(e,t){try{const i=await fetch(`${this.baseUrl}/api/ingestion/customEvent/batch`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({sessionId:e,events:t})});if(!i.ok)throw new Error(`Failed to send custom event batch: ${i.statusText}`);return await i.json()}catch(e){throw r("Error sending custom event batch:",e),e}}}class u{constructor(e){this.redactedText="[REDACTED]",this.unredactedFields=new Set,this.redactedFields=new Set,this.redactionMode="privacy-first",this.excludeSelectors=['[data-no-redact="true"]',".human-behavior-no-redact"],e?.redactedText&&(this.redactedText=e.redactedText),e?.excludeSelectors&&(this.excludeSelectors=[...this.excludeSelectors,...e.excludeSelectors]),e?.redactionStrategy&&(this.redactionMode=e.redactionStrategy.mode,"privacy-first"===this.redactionMode?e.redactionStrategy.unredactFields&&this.setFieldsToUnredact(e.redactionStrategy.unredactFields):e.redactionStrategy.redactFields&&this.setFieldsToRedact(e.redactionStrategy.redactFields)),e?.legacyRedactFields&&this.setFieldsToUnredact(e.legacyRedactFields),e?.userFields&&this.setFieldsToUnredact(e.userFields);}setFieldsToRedact(e){this.redactedFields.clear();['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]',...e].forEach(e=>{this.redactedFields.add(e);}),this.redactedFields.size>0?a(`Redaction: Active for ${this.redactedFields.size} field(s):`,Array.from(this.redactedFields)):a("Redaction: No fields to redact"),this.applyRedactionClasses();}setFieldsToUnredact(e){this.unredactedFields.clear();const t=e.filter(e=>!this.isPasswordSelector(e)||(n(`Cannot unredact password field: ${e} - Password fields are always protected`),false));t.forEach(e=>this.unredactedFields.add(e)),t.length>0?a(`Unredaction: Active for ${t.length} field(s):`,t):a("Unredaction: No valid fields to unredact"),this.applyUnredactionClasses();}redactFields(e){e.forEach(e=>{this.unredactedFields.delete(e);}),this.unredactedFields.size>0?a(`Unredaction: Removed ${e.length} field(s), ${this.unredactedFields.size} remaining:`,Array.from(this.unredactedFields)):a("Unredaction: All fields redacted"),this.applyUnredactionClasses();}clearUnredactedFields(){this.unredactedFields.clear(),a("Unredaction: All fields cleared, everything redacted"),this.removeUnredactionClasses();}hasUnredactedFields(){return this.unredactedFields.size>0}getRedactionMode(){return this.redactionMode}getUnredactedFields(){return Array.from(this.unredactedFields)}getMaskTextSelector(){return "privacy-first"===this.redactionMode?0===this.unredactedFields.size?null:Array.from(this.unredactedFields).join(","):0===this.redactedFields.size?null:Array.from(this.redactedFields).join(",")}applyRedactionClasses(){0!==this.redactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.redactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.add("rr-mask");}),a(`Added rr-mask class to ${t.length} element(s) for selector: ${e}`);}catch(t){n(`Invalid selector: ${e}`);}}):a("DOM not ready, deferring redaction class application"));}applyUnredactionClasses(){0!==this.unredactedFields.size&&("undefined"!=typeof document&&"loading"!==document.readyState?this.unredactedFields.forEach(e=>{try{const t=document.querySelectorAll(e);t.forEach(e=>{e&&e.classList&&e.classList.remove("rr-mask");}),a(`Removed rr-mask class from ${t.length} element(s) for selector: ${e}`);}catch(t){n(`Invalid selector: ${e}`);}}):a("DOM not ready, deferring unredaction class application"));}removeUnredactionClasses(){a("Unredaction classes removed");}isPasswordSelector(e){return ['input[type="password"]','input[type="password" i]','[type="password"]','[type="password" i]'].some(t=>e.toLowerCase().includes(t.toLowerCase().replace(/[\[\]]/g,"")))}getOriginalValue(e){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return e.value}isElementUnredacted(e){return this.shouldUnredactElement(e)}shouldUnredactElement(e){if("privacy-first"===this.redactionMode){if(0===this.unredactedFields.size)return false;for(const t of this.unredactedFields)try{if(e.matches(t))return !0}catch(e){n(`Invalid selector: ${t}`);}return false}if(0===this.redactedFields.size)return true;for(const t of this.redactedFields)try{if(e.matches(t))return !1}catch(e){n(`Invalid selector: ${t}`);}return true}}new u;const p="undefined"!=typeof window;function g(){if(!p)return "unknown";const e=navigator.userAgent.toLowerCase(),t=window.screen.width,i=window.screen.height;return /mobile|android|iphone|ipad|ipod|blackberry|windows phone/i.test(e)?/ipad/i.test(e)||t>=768&&i>=1024?"tablet":"mobile":/windows|macintosh|linux/i.test(e)?"desktop":"unknown"}function m(e){try{return new URL(e).hostname}catch{return ""}}function y(){if(!p)return {device_type:"unknown",browser:"unknown",browser_version:"unknown",os:"unknown",os_version:"unknown",screen_resolution:"unknown",viewport_size:"unknown",color_depth:0,timezone:"unknown",language:"unknown",languages:[]};const{browser:e,browser_version:t}=function(){if(!p)return {browser:"unknown",browser_version:"unknown"};const e=navigator.userAgent;if(/chrome/i.test(e)&&!/edge/i.test(e)){const t=e.match(/chrome\/(\d+)/i);return {browser:"chrome",browser_version:t?t[1]:"unknown"}}if(/firefox/i.test(e)){const t=e.match(/firefox\/(\d+)/i);return {browser:"firefox",browser_version:t?t[1]:"unknown"}}if(/safari/i.test(e)&&!/chrome/i.test(e)){const t=e.match(/version\/(\d+)/i);return {browser:"safari",browser_version:t?t[1]:"unknown"}}if(/edge/i.test(e)){const t=e.match(/edge\/(\d+)/i);return {browser:"edge",browser_version:t?t[1]:"unknown"}}if(/msie|trident/i.test(e)){const t=e.match(/msie (\d+)/i)||e.match(/rv:(\d+)/i);return {browser:"ie",browser_version:t?t[1]:"unknown"}}return {browser:"unknown",browser_version:"unknown"}}(),{os:i,os_version:s}=function(){if(!p)return {os:"unknown",os_version:"unknown"};const e=navigator.userAgent;if(/windows/i.test(e)){const t=e.match(/windows nt (\d+\.\d+)/i);let i="unknown";if(t){const e=parseFloat(t[1]);i=10===e?"10":6.3===e?"8.1":6.2===e?"8":6.1===e?"7":t[1];}return {os:"windows",os_version:i}}if(/macintosh|mac os x/i.test(e)){const t=e.match(/mac os x (\d+[._]\d+)/i);return {os:"macos",os_version:t?t[1].replace("_","."):"unknown"}}if(/iphone|ipad|ipod/i.test(e)){const t=e.match(/os (\d+[._]\d+)/i);return {os:"ios",os_version:t?t[1].replace("_","."):"unknown"}}if(/android/i.test(e)){const t=e.match(/android (\d+\.\d+)/i);return {os:"android",os_version:t?t[1]:"unknown"}}return /linux/i.test(e)?{os:"linux",os_version:"unknown"}:{os:"unknown",os_version:"unknown"}}();return {device_type:g(),browser:e,browser_version:t,os:i,os_version:s,screen_resolution:`${window.screen.width}x${window.screen.height}`,viewport_size:`${window.innerWidth}x${window.innerHeight}`,color_depth:window.screen.colorDepth,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone,language:navigator.language,languages:[...navigator.languages||[navigator.language]],raw_user_agent:navigator.userAgent}}function f(){if(!p)return {current_url:"",pathname:"",search:"",hash:"",title:"",referrer:"",referrer_domain:"",initial_referrer:"",initial_referrer_domain:""};const e=window.location.href,t=document.referrer,i=function(e){const t=new URL(e),i={};return ["utm_source","utm_medium","utm_campaign","utm_term","utm_content"].forEach(e=>{const s=t.searchParams.get(e);s&&(i[e]=s);}),i}(e);return {current_url:e,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,title:document.title,referrer:t,referrer_domain:m(t),initial_referrer:t,initial_referrer_domain:m(t),initial_host:window.location.hostname,...i}}function v(){return {...y(),...f()}}function w(){if(!p)return {};const e=f();return {initial_referrer:e.initial_referrer,initial_referrer_domain:e.initial_referrer_domain,initial_url:e.current_url,initial_pathname:e.pathname,initial_utm_source:e.utm_source,initial_utm_medium:e.utm_medium,initial_utm_campaign:e.utm_campaign,initial_utm_term:e.utm_term,initial_utm_content:e.utm_content}}function S(){if(!p)return {};const e=f();return {current_url:e.current_url,pathname:e.pathname,search:e.search,hash:e.hash,title:e.title,referrer:e.referrer,referrer_domain:e.referrer_domain,utm_source:e.utm_source,utm_medium:e.utm_medium,utm_campaign:e.utm_campaign,utm_term:e.utm_term,utm_content:e.utm_content}}class _{constructor(e={}){this.sessionProperties={},this.userProperties={},this.initialProperties={},this.isInitialized=false,this.config={enableAutomaticProperties:true,enableSessionProperties:true,enableUserProperties:true,propertyDenylist:[],...e},this.automaticProperties=v(),this.initialize();}initialize(){this.isInitialized||(this.initialProperties=w(),this.loadSessionProperties(),this.isInitialized=true);}getEventProperties(e={}){const t={...e};return this.config.enableAutomaticProperties&&Object.assign(t,this.getAutomaticProperties()),this.config.enableSessionProperties&&Object.assign(t,this.sessionProperties),this.config.enableUserProperties&&Object.assign(t,this.userProperties),this.sessionProperties.$initial_properties_captured||(Object.assign(t,this.initialProperties),this.setSessionProperty("$initial_properties_captured",true)),this.applyDenylist(t),t}getAutomaticProperties(){return {...this.automaticProperties,...S()}}getAutomaticPropertiesWithGeoIP(e={}){return {...this.automaticProperties,...S(),...e}}setSessionProperty(e,t){this.sessionProperties[e]=t,this.saveSessionProperties();}setSessionProperties(e){Object.assign(this.sessionProperties,e),this.saveSessionProperties();}getSessionProperty(e){return this.sessionProperties[e]}removeSessionProperty(e){delete this.sessionProperties[e],this.saveSessionProperties();}setUserProperty(e,t){this.userProperties[e]=t;}setUserProperties(e){Object.assign(this.userProperties,e);}getUserProperty(e){return this.userProperties[e]}removeUserProperty(e){delete this.userProperties[e];}setOnce(e,t,i="user"){"session"===i?e in this.sessionProperties||this.setSessionProperty(e,t):e in this.userProperties||this.setUserProperty(e,t);}clearSessionProperties(){this.sessionProperties={},this.saveSessionProperties();}clearUserProperties(){this.userProperties={};}reset(){this.clearSessionProperties(),this.clearUserProperties(),this.initialProperties={},this.isInitialized=false,this.initialize();}loadSessionProperties(){if("undefined"!=typeof sessionStorage)try{const e=sessionStorage.getItem("hb_session_properties");e&&(this.sessionProperties=JSON.parse(e));}catch(e){console.warn("Failed to load session properties:",e);}}saveSessionProperties(){if("undefined"!=typeof sessionStorage)try{sessionStorage.setItem("hb_session_properties",JSON.stringify(this.sessionProperties));}catch(e){console.warn("Failed to save session properties:",e);}}applyDenylist(e){this.config.propertyDenylist&&0!==this.config.propertyDenylist.length&&this.config.propertyDenylist.forEach(t=>{delete e[t];});}updateAutomaticProperties(){this.automaticProperties=v();}getAllProperties(){return {automatic:this.getAutomaticProperties(),session:{...this.sessionProperties},user:{...this.userProperties},initial:{...this.initialProperties}}}}const b="undefined"!=typeof window;class k{get isTrackerStarted(){return this.isStarted}setupDomReadyHandler(){if(b)if("complete"===document.readyState||"interactive"===document.readyState)this.onDomReady();else if(document.addEventListener){document.addEventListener("DOMContentLoaded",()=>this.onDomReady(),{capture:false});const e=setInterval(()=>{"interactive"!==document.readyState&&"complete"!==document.readyState||(clearInterval(e),this.onDomReady());},10);setTimeout(()=>clearInterval(e),5e3);}else this.onDomReady();else this.onDomReady();}onDomReady(){this.isDomReady||(this.isDomReady=true,a("🎯 DOM is ready, processing queued requests"),this.requestQueue.forEach(e=>{this.processRequest(e);}),this.requestQueue=[],this.domReadyHandlers.forEach(e=>e()),this.domReadyHandlers=[]);}queueRequest(e){this.isDomReady?this.processRequest(e):this.requestQueue.push(e);}async processRequest(e){switch(a("Processing queued request:",e),e.type){case "addEvent":await this.addEvent(e.event);break;case "identifyUser":await this.identifyUser(e.userProperties);break;case "trackPageView":this.trackPageView();break;default:n("Unknown request type:",e.type);}}registerDomReadyHandler(e){this.isDomReady?e():this.domReadyHandlers.push(e);}static init(e,t){if(b&&false!==t?.suppressConsoleErrors){const e=console.error;console.error=(...t)=>{const i=t.join(" ");i.includes("SecurityError: Failed to execute 'toDataURL'")||i.includes("Tainted canvases may not be exported")||i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("TypeError: NetworkError")||i.includes("HumanBehavior ERROR")||i.includes("Failed to track custom event")||i.includes("Error sending custom event")||e.apply(console,t);};const t=console.warn;console.warn=(...e)=>{const i=e.join(" ");i.includes("Cannot inline img src=")||i.includes("Cross-Origin")||i.includes("CORS")||i.includes("Access-Control-Allow-Origin")||i.includes("Failed to load resource")||i.includes("net::ERR_BLOCKED_BY_CLIENT")||i.includes("NetworkError when attempting to fetch resource")||i.includes("Failed to fetch")||i.includes("Custom event network error")||i.includes("Request blocked by ad blocker")||t.apply(console,e);},window.addEventListener("error",e=>{const t=e.message||"";if(t.includes("SecurityError")||t.includes("Tainted canvases")||t.includes("toDataURL")||t.includes("Cross-Origin")||t.includes("CORS")||t.includes("NetworkError")||t.includes("Failed to fetch"))return e.preventDefault(),false});}if(b&&window.__humanBehaviorGlobalTracker)return a("Tracker already initialized, returning existing instance"),window.__humanBehaviorGlobalTracker;t?.logLevel&&this.configureLogging({level:t.logLevel});const i=new k(e,t?.ingestionUrl,{enableAutomaticProperties:t?.enableAutomaticProperties,propertyDenylist:t?.propertyDenylist,maxQueueSize:t?.maxQueueSize});return i.recordCanvas=t?.recordCanvas??false,t?.redactFields&&i.setUnredactedFields(t.redactFields),t?.redactionStrategy&&("privacy-first"===t.redactionStrategy.mode?t.redactionStrategy.unredactFields&&i.setUnredactedFields(t.redactionStrategy.unredactFields):t.redactionStrategy.redactFields&&i.setRedactedFields(t.redactionStrategy.redactFields)),i.start(),i}constructor(e,i,s){if(this.eventQueue=[],this.userProperties={},this.isProcessing=false,this.flushInterval=null,this.FLUSH_INTERVAL_MS=3e3,this.endUserId=null,this.initialized=false,this.initializationPromise=null,this.isDomReady=false,this.requestQueue=[],this.domReadyHandlers=[],this.originalConsole=null,this.consoleTrackingEnabled=false,this.navigationTrackingEnabled=false,this.currentUrl="",this.previousUrl="",this.originalPushState=null,this.originalReplaceState=null,this.navigationListeners=[],this._connectionBlocked=false,this.recordInstance=null,this.sessionStartTime=Date.now(),this.rrwebRecord=null,this.fullSnapshotTimeout=null,this.recordCanvas=false,this.isStarted=false,!e)throw new Error("Human Behavior API Key is required");if(this.api=new h({apiKey:e,ingestionUrl:i||"https://ingest.humanbehavior.co"}),this.apiKey=e,this.MAX_QUEUE_SIZE=s?.maxQueueSize??1e3,this.redactionManager=new u({redactionStrategy:s?.redactionStrategy,legacyRedactFields:s?.redactFields}),this.propertyManager=new _({enableAutomaticProperties:false!==s?.enableAutomaticProperties,propertyDenylist:s?.propertyDenylist||[]}),b){const e=localStorage.getItem(`human_behavior_session_id_${this.apiKey}`),i=localStorage.getItem(`human_behavior_last_activity_${this.apiKey}`),s=Date.now()-9e5;e&&i&&parseInt(i)>s?(this.sessionId=e,a(`Reusing existing session: ${this.sessionId}`),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())):(e&&(a(`Session expired, clearing old session: ${e}`),localStorage.removeItem(`human_behavior_session_id_${this.apiKey}`),localStorage.removeItem(`human_behavior_last_activity_${this.apiKey}`)),this.sessionId=v1(),a(`Creating new session: ${this.sessionId}`),localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())),this.currentUrl=window.location.href,window.__humanBehaviorGlobalTracker=this;}else this.sessionId=v1();this.initializationPromise=this.init().catch(e=>{r("Background initialization failed:",e);});}async init(){try{this.initialized=!0;const e=b?this.getCookie(`human_behavior_end_user_id_${this.apiKey}`):null;a(`Initializing with sessionId: ${this.sessionId}, userId: ${e}`);const t=this.propertyManager.getAutomaticProperties();b?(this.setupPageUnloadHandler(),this.setupNavigationTracking()):o("HumanBehaviorTracker initialized in server environment. Session tracking is disabled."),await this.initServerAsync(e,t),o(`HumanBehaviorTracker initialized with sessionId: ${this.sessionId}`);}catch(e){throw r("Failed to initialize HumanBehaviorTracker:",e),e}}async initServerAsync(e,t){try{a("🚀 Attempting to call /init endpoint..."),a("📡 URL:",`${this.api.baseUrl}/api/ingestion/init`),a("🔑 API Key:",this.apiKey);let i=null,s=null;b&&(i=window.location.href,s=document.referrer),a("📦 Payload:",{sessionId:this.sessionId,endUserId:e,entryURL:i,referrer:s,automaticProperties:t});const r=await fetch(`${this.api.baseUrl}/api/ingestion/init`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,Referer:s||""},body:JSON.stringify({sessionId:this.sessionId,endUserId:e,entryURL:i,referrer:s,automaticProperties:t})});if(!r.ok)throw new Error(`Failed to initialize: ${r.statusText}`);const{sessionId:n,endUserId:d}=await r.json();n!==this.sessionId&&(a(`Server returned different sessionId: ${n} (client had: ${this.sessionId})`),this.sessionId=n,b&&localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId)),this.endUserId=d,this.setCookie(`human_behavior_end_user_id_${this.apiKey}`,d,365),o(`Server initialization completed with endUserId: ${d}`);}catch(e){r("❌ Server initialization failed:",e),r("🔍 Error details:",{message:e?.message||"Unknown error",stack:e?.stack||"No stack trace",type:e?.constructor?.name||"Unknown type"}),n("Server initialization failed, continuing with local session:",e);}}async ensureInitialized(){this.initializationPromise&&await this.initializationPromise;}setupNavigationTracking(){if(!b||this.navigationTrackingEnabled)return;this.navigationTrackingEnabled=true,a("Setting up navigation tracking"),this.originalPushState=history.pushState,this.originalReplaceState=history.replaceState,history.pushState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalPushState.apply(history,e),this.trackNavigationEvent("pushState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();},history.replaceState=(...e)=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.originalReplaceState.apply(history,e),this.trackNavigationEvent("replaceState",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};const e=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("popstate",this.previousUrl,this.currentUrl),this.takeFullSnapshot();};window.addEventListener("popstate",e),this.navigationListeners.push(()=>{window.removeEventListener("popstate",e);});const t=()=>{this.previousUrl=this.currentUrl,this.currentUrl=window.location.href,this.trackNavigationEvent("hashchange",this.previousUrl,this.currentUrl);};window.addEventListener("hashchange",t),this.navigationListeners.push(()=>{window.removeEventListener("hashchange",t);}),this.trackNavigationEvent("pageLoad","",this.currentUrl);}async trackNavigationEvent(e,t,i){if(this.initialized)try{const s={type:e,from:t,to:i,timestamp:(new Date).toISOString(),pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer};await this.addEvent({type:5,data:{payload:{eventType:"navigation",...s}},timestamp:Date.now()}),a(`Navigation tracked: ${e} from ${t} to ${i}`);}catch(e){r("Failed to track navigation event:",e);}}async trackPageView(e){if(this.initialized){this.propertyManager.updateAutomaticProperties();try{const t={url:e||window.location.href,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash,referrer:document.referrer,timestamp:(new Date).toISOString()},i=this.propertyManager.getEventProperties(t);await this.addEvent({type:5,data:{payload:{eventType:"pageview",...i}},timestamp:Date.now()}),a(`Pageview tracked: ${t.url}`);}catch(e){r("Failed to track pageview event:",e);}}}async customEvent(e,t){if(!this.initialized)return;const i=this.propertyManager.getEventProperties(t);try{await this.api.sendCustomEvent(this.sessionId,e,i),a(`Custom event tracked: ${e}`,i);}catch(t){r("Failed to track custom event:",t),t.message?.includes("500")||t.message?.includes("Internal Server Error")||t.message?.includes("Failed to send custom event")?n("Custom event endpoint failed, using fallback"):t.message?.includes("ERR_BLOCKED_BY_CLIENT")?n("Custom event request blocked by ad blocker, using fallback"):t.message?.includes("Failed to fetch")&&n("Custom event network error, using fallback");try{const t={eventName:e,properties:i||{},timestamp:(new Date).toISOString(),url:window.location.href,pathname:window.location.pathname};await this.addEvent({type:5,data:{payload:{eventType:"custom",...t}},timestamp:Date.now()}),a(`Custom event added to event stream as fallback: ${e}`);}catch(e){r("Failed to add custom event to event stream as fallback:",e);}}}setupAutomaticTracking(e){}setupAutomaticButtonTracking(e){}setupAutomaticLinkTracking(e){}setupAutomaticFormTracking(e){}cleanupNavigationTracking(){this.navigationTrackingEnabled&&(this.originalPushState&&(history.pushState=this.originalPushState),this.originalReplaceState&&(history.replaceState=this.originalReplaceState),this.navigationListeners.forEach(e=>e()),this.navigationListeners=[],this.navigationTrackingEnabled=false,a("Navigation tracking cleaned up"));}static logToStorage(e){o(e);}static configureLogging(e){s.setConfig({level:{none:0,error:1,warn:2,info:3,debug:4}[e.level||"error"],enableConsole:false!==e.enableConsole,enableStorage:e.enableStorage||false});}enableConsoleTracking(){b&&!this.consoleTrackingEnabled&&(this.originalConsole={log:console.log,warn:console.warn,error:console.error},console.log=(...e)=>{this.trackConsoleEvent("log",e),this.originalConsole.log(...e);},console.warn=(...e)=>{this.trackConsoleEvent("warn",e),this.originalConsole.warn(...e);},console.error=(...e)=>{this.trackConsoleEvent("error",e),this.originalConsole.error(...e);},this.consoleTrackingEnabled=true,a("Console tracking enabled"));}disableConsoleTracking(){b&&this.consoleTrackingEnabled&&(this.originalConsole&&(console.log=this.originalConsole.log,console.warn=this.originalConsole.warn,console.error=this.originalConsole.error),this.consoleTrackingEnabled=false,a("Console tracking disabled"));}trackConsoleEvent(e,t){if(this.initialized)try{const i={level:e,message:t.map(e=>"object"==typeof e?JSON.stringify(e):String(e)).join(" "),timestamp:(new Date).toISOString(),url:window.location.href};this.addEvent({type:5,data:{payload:{eventType:"console",...i}},timestamp:Date.now()}).catch(e=>{r("Failed to track console event:",e);});}catch(e){r("Error in trackConsoleEvent:",e);}}setupPageUnloadHandler(){if(!b)return;a("Setting up page unload handler"),window.addEventListener("visibilitychange",()=>{"hidden"===document.visibilityState&&(a("Page hidden - sending pending events"),this.flushEvents());}),window.addEventListener("beforeunload",()=>{this.flushEvents();});const e=()=>{localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString());};window.addEventListener("click",e),window.addEventListener("keydown",e),window.addEventListener("scroll",e),window.addEventListener("mousemove",e);}viewLogs(){try{const e=s.getLogs();o("HumanBehavior Logs:",e),s.clearLogs();}catch(e){r("Failed to read logs:",e);}}async identifyUser({userProperties:e}){await this.ensureInitialized();const t=this.endUserId;return this.userProperties=e,a("Identifying user:",{userProperties:e,originalEndUserId:t,sessionId:this.sessionId}),!b||this.propertyManager.getAutomaticProperties(),await this.api.sendUserData(t||"",e,this.sessionId),t||""}getUserAttributes(){return {...this.userProperties}}async start(){if(await this.ensureInitialized(),!b)return;if(this.isStarted)return void a("HumanBehaviorTracker already started, skipping start() call.");this.isStarted=true,this.flushInterval=window.setInterval(()=>{this.flushEvents();},this.FLUSH_INTERVAL_MS);const t=()=>{if(this.recordInstance)return void a("🎯 Recording already started, skipping duplicate start");a("🎯 DOM ready, starting session recording"),this.rrwebRecord=record;const t=record({emit:e=>{this.addRecordingEvent(e),2===e.type&&a(`🎯 FullSnapshot generated at ${(new Date).toISOString()}`);},maskTextSelector:this.redactionManager.getMaskTextSelector()||void 0,maskTextFn:void 0,maskAllInputs:"privacy-first"===this.redactionManager.getRedactionMode(),maskInputOptions:{password:true},maskInputFn:void 0,slimDOMOptions:{},collectFonts:false,inlineStylesheet:true,recordCrossOriginIframes:false,recordCanvas:this.recordCanvas,sampling:this.recordCanvas?{canvas:4}:void 0,dataURLOptions:this.recordCanvas?{type:"image/webp",quality:.4}:void 0});this.recordInstance=t||null;};if(a(`🎯 DOM ready state: ${document.readyState}`),"complete"===document.readyState||"interactive"===document.readyState)a(`🎯 DOM ready (${document.readyState}), starting recording immediately`),t();else {a("🎯 DOM not ready, waiting for DOMContentLoaded event");const e=()=>("interactive"===document.readyState||"complete"===document.readyState)&&(a(`🎯 DOM ready (${document.readyState}), starting recording`),t(),true);if(e())return;document.addEventListener("DOMContentLoaded",()=>{a("🎯 DOMContentLoaded fired, starting recording"),t();},{once:true});const i=setInterval(()=>{e()&&clearInterval(i);},10);setTimeout(()=>clearInterval(i),5e3);}}takeFullSnapshot(){this.fullSnapshotTimeout&&clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=window.setTimeout(()=>{try{requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.rrwebRecord&&"function"==typeof this.rrwebRecord.takeFullSnapshot?(this.rrwebRecord.takeFullSnapshot(),a("✅ FullSnapshot taken for navigation (delayed for animations)")):n("⚠️ takeFullSnapshot not available on record function");});});}catch(e){r("❌ Failed to take FullSnapshot for navigation:",e);}},1e3);}async stop(){await this.ensureInitialized(),b&&(this.flushInterval&&(clearInterval(this.flushInterval),this.flushInterval=null),this.recordInstance&&(this.recordInstance(),this.recordInstance=null),this.fullSnapshotTimeout&&(clearTimeout(this.fullSnapshotTimeout),this.fullSnapshotTimeout=null),this.rrwebRecord=null,this.disableConsoleTracking(),this.cleanupNavigationTracking());}async addEvent(e){if(await this.ensureInitialized(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);a(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),a("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(a("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(a(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else a("⚠️ Skipping invalid event:",e);}async flushEvents(){if(!this.isProcessing&&this.initialized){this.isProcessing=true;try{const e=this.eventQueue;if(this.eventQueue=[],e.length>0){a("Flushing events:",e);const t=e.filter(e=>2===e.type);t.length>0&&a(`[FIXED] Sending ${t.length} FullSnapshot(s) with valid data`);try{await this.api.sendEventsChunked(e,this.sessionId,this.endUserId);}catch(e){if(e.message?.includes("ERROR: Session already completed"))n("Session expired, events will be lost");else if(e.message?.includes("413")||e.message?.includes("Content Too Large"))n("Payload too large, events will be lost");else {if(!(e.message?.includes("ERR_BLOCKED_BY_CLIENT")||e.message?.includes("Failed to fetch")||e.message?.includes("NetworkError")))throw e;n("Request blocked by ad blocker or network issue, events will be lost");}}}}finally{this.isProcessing=false;}}}async addRecordingEvent(e){if(await this.ensureInitialized(),e&&"object"==typeof e){if(2===e.type){const t=!!e.data,i=!(!e.data||!e.data.node);a(t&&i?`✅ Valid FullSnapshot: hasData=${t}, hasNode=${i}, dataType=${e.data?.node?.type}`:`⚠️ Empty FullSnapshot detected: hasData=${t}, hasNode=${i} - continuing session`);}this.eventQueue.length>=this.MAX_QUEUE_SIZE&&(this.eventQueue.shift(),a("Queue is full, the oldest event is dropped.")),this.eventQueue.push(e),2===e.type?(a("FullSnapshot added, triggering immediate flush"),this.flushEvents()):this.eventQueue.length>=.8*this.MAX_QUEUE_SIZE&&(a(`Queue at ${this.eventQueue.length}/${this.MAX_QUEUE_SIZE}, triggering immediate flush`),this.flushEvents());}else a("⚠️ Skipping invalid recording event:",e);}setCookie(e,t,i){if(b)try{const s=new Date;s.setTime(s.getTime()+24*i*60*60*1e3);const r=`expires=${s.toUTCString()}`;document.cookie=`${e}=${t};${r};path=/;SameSite=Lax`,localStorage.setItem(e,t),a(`Set cookie and localStorage: ${e}`);}catch(i){try{localStorage.setItem(e,t),a(`Cookie blocked, using localStorage: ${e}`);}catch(e){r("Failed to store user ID in both cookie and localStorage:",e);}}}getCookie(e){if(!b)return null;try{const t=e+"=",i=document.cookie.split(";");for(let s=0;s<i.length;s++){let r=i[s];for(;" "===r.charAt(0);)r=r.substring(1,r.length);if(0===r.indexOf(t)){const i=r.substring(t.length,r.length);return a(`Found cookie: ${e}`),i}}const s=localStorage.getItem(e);return s?(a(`Cookie not found, using localStorage: ${e}`),s):null}catch(t){try{const t=localStorage.getItem(e);if(t)return a(`Cookie access failed, using localStorage: ${e}`),t}catch(e){r("Failed to access both cookie and localStorage:",e);}return null}}deleteCookie(e){if(b){try{document.cookie=`${e}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=Lax`,a(`Deleted cookie: ${e}`);}catch(t){r(`Failed to delete cookie: ${e}`,t);}try{localStorage.removeItem(e),a(`Removed from localStorage: ${e}`);}catch(t){r(`Failed to remove from localStorage: ${e}`,t);}}}logout(){if(b)try{const e=`human_behavior_end_user_id_${this.apiKey}`;this.deleteCookie(e),localStorage.removeItem(`human_behavior_session_id_${this.apiKey}`),localStorage.removeItem(`human_behavior_last_activity_${this.apiKey}`),this.endUserId=null,this.userProperties={},this.sessionId=v1(),b&&(localStorage.setItem(`human_behavior_session_id_${this.apiKey}`,this.sessionId),localStorage.setItem(`human_behavior_last_activity_${this.apiKey}`,Date.now().toString())),o("User logged out - cleared all user data and started fresh session");}catch(e){r("Error during logout:",e);}}async redact(e){await this.ensureInitialized(),b?this.redactionManager=new u(e):n("Redaction is only available in browser environments");}setRedactedFields(e){this.redactionManager.setFieldsToRedact(e),this.recordInstance&&this.restartWithNewRedaction();}setUnredactedFields(e){this.redactionManager.setFieldsToUnredact(e),this.recordInstance&&this.restartWithNewRedaction();}restartWithNewRedaction(){this.recordInstance&&(this.recordInstance(),this.start());}hasUnredactedFields(){return this.redactionManager.hasUnredactedFields()}getUnredactedFields(){return this.redactionManager.getUnredactedFields()}redactFields(e){this.redactionManager.redactFields(e),this.recordInstance&&this.restartWithNewRedaction();}clearUnredactedFields(){this.redactionManager.clearUnredactedFields(),this.recordInstance&&this.restartWithNewRedaction();}getSessionId(){return this.sessionId}getCurrentUrl(){return this.currentUrl}getSnapshotFrequencyInfo(){return {sessionDuration:Date.now()-this.sessionStartTime,currentInterval:3e5,currentThreshold:1e3,phase:"configured"}}async testConnection(){try{return await this.api.init(this.sessionId,this.endUserId),{success:!0}}catch(e){return {success:false,error:e.message||"Unknown error"}}}getConnectionStatus(){const e=[];let t=false;return this.eventQueue.length>0&&(t=true,e.push("Some requests may be blocked by ad blockers")),this._connectionBlocked&&(t=true,e.push("Initial connection test failed - ad blocker may be active")),"undefined"==typeof window&&e.push("Not running in browser environment"),void 0===navigator.sendBeacon&&e.push("sendBeacon not available, using fetch fallback"),{blocked:t,recommendations:e}}isPreexistingUser(){if(!b)return false;const e=this.getCookie(`human_behavior_end_user_id_${this.apiKey}`);return null!==e&&e!==this.endUserId}getUserInfo(){return {endUserId:this.endUserId,sessionId:this.sessionId,isPreexistingUser:this.isPreexistingUser(),initialized:this.initialized}}setSessionProperty(e,t){this.propertyManager.setSessionProperty(e,t);}setSessionProperties(e){this.propertyManager.setSessionProperties(e);}getSessionProperty(e){return this.propertyManager.getSessionProperty(e)}removeSessionProperty(e){this.propertyManager.removeSessionProperty(e);}setUserProperty(e,t){this.propertyManager.setUserProperty(e,t);}setUserProperties(e){this.propertyManager.setUserProperties(e);}getUserProperty(e){return this.propertyManager.getUserProperty(e)}removeUserProperty(e){this.propertyManager.removeUserProperty(e);}setOnce(e,t,i="user"){this.propertyManager.setOnce(e,t,i);}clearSessionProperties(){this.propertyManager.clearSessionProperties();}clearUserProperties(){this.propertyManager.clearUserProperties();}getAllProperties(){return this.propertyManager.getAllProperties()}}function I(e){const t=globalThis.__humanBehaviorGlobalTracker;return t?.identifyUser?t.identifyUser({userProperties:e}):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function E(e,t){const i=globalThis.__humanBehaviorGlobalTracker;return i?.track?i.track(e,t):(console.warn("HumanBehavior tracker not found. Make sure the SDK is initialized."),null)}function U(){const e=globalThis.__humanBehaviorGlobalTracker;return !!e?.identifyUser}b&&(window.HumanBehaviorTracker=k);
12067
12175
 
12068
12176
  /**
12069
12177
  * Main entry point for the HumanBehavior SDK
@@ -12071,30 +12179,13 @@ const t=[];for(let e=0;e<256;++e)t.push((e+256).toString(16).slice(1));let i;con
12071
12179
  // Import the main tracker first
12072
12180
  // Create an initialization function (similar to PostHog's pattern)
12073
12181
  const init = (apiKey, ingestionUrl, options) => {
12074
- return new P(apiKey, ingestionUrl, options);
12182
+ return new k(apiKey, ingestionUrl, options);
12075
12183
  };
12076
12184
  // For UMD builds, expose the class and init function globally
12077
12185
  if (typeof window !== 'undefined') {
12078
- window.HumanBehaviorTracker = P;
12186
+ window.HumanBehaviorTracker = k;
12079
12187
  window.humanbehavior = { init };
12080
12188
  }
12081
12189
 
12082
- exports.HumanBehaviorAPI = m;
12083
- exports.HumanBehaviorTracker = P;
12084
- exports.PropertyManager = E;
12085
- exports.RedactionManager = y;
12086
- exports.getAutomaticProperties = b;
12087
- exports.getCurrentPageProperties = I;
12088
- exports.getDeviceInfo = S;
12089
- exports.getInitialProperties = k;
12090
- exports.getLocationInfo = _;
12091
- exports.identifyUserGlobally = F;
12092
- exports.init = init;
12093
- exports.isGlobalTrackerAvailable = $;
12094
- exports.logDebug = h;
12095
- exports.logError = d;
12096
- exports.logInfo = l;
12097
- exports.logWarn = c;
12098
- exports.logger = a;
12099
- exports.sendEventGlobally = T;
12190
+ export { h as HumanBehaviorAPI, k as HumanBehaviorTracker, i as LogLevel, _ as PropertyManager, u as RedactionManager, v as getAutomaticProperties, S as getCurrentPageProperties, y as getDeviceInfo, w as getInitialProperties, f as getLocationInfo, I as identifyUserGlobally, init, U as isGlobalTrackerAvailable, a as logDebug, r as logError, o as logInfo, n as logWarn, s as logger, E as sendEventGlobally };
12100
12191
  //# sourceMappingURL=index.js.map