@log-drop/web 1.0.0-alpha2 → 1.0.0-alpha4
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.
- package/README.md +1 -3
- package/dist/index.cjs +334 -23
- package/dist/index.cjs.map +3 -3
- package/dist/index.d.ts +0 -1
- package/dist/index.js +334 -23
- package/dist/index.js.map +3 -3
- package/dist/logdrop-sw.js +2 -2
- package/dist/logdrop.min.js +2 -2
- package/dist/logdrop.min.js.map +4 -4
- package/package.json +1 -1
package/dist/logdrop.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var LogDropSDK=(()=>{var H=Object.defineProperty;var Ye=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var et=(n,e,t)=>e in n?H(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var tt=(n,e)=>{for(var t in e)H(n,t,{get:e[t],enumerable:!0})},it=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Qe(e))!Ze.call(n,s)&&s!==t&&H(n,s,{get:()=>e[s],enumerable:!(i=Ye(e,s))||i.enumerable});return n};var st=n=>it(H({},"__esModule",{value:!0}),n);var A=(n,e,t)=>et(n,typeof e!="symbol"?e+"":e,t);var jt={};tt(jt,{LogDrop:()=>qt,LogDropClient:()=>ie,LogFlow:()=>P,LogLevel:()=>I,capturePageState:()=>Xe,fingerprintStack:()=>zt,generateUUID:()=>Je});var h=class{};h.DEFAULT_BASE_URL="https://server.logdrop.io";h.DEFAULT_WEB_SECRET_KEY="xuM9w0BAQEFx";h.FILE_EXPORT_INTERVAL_MS=3e5;h.DEVICE_INFO_INTERVAL_MS=1e4;h.SDK_VERSION="1.0.0-alpha2";h.STORAGE_CHECK_INTERVAL_MS=12e4;h.MAX_LOCAL_STORAGE_SIZE=5242880;h.DATABASE_MAX_STORAGE_LIMIT=16e6;h.DEBUG_LOGS_ENABLED=!0;h.DEVTOOLS_CONSOLE_PROBE_ENABLED=!1;h.DEVTOOLS_PROBE_INTERVAL_MS=1500;h.INIT_PATH="/logdrop/init";h.LOGS_PATH="/logs";h.CRASH_PATH="/crash";h.USERS_UPDATE_PATH="/users/update";h.PUSH_SW_PATH="/_logdrop/logdrop-sw.js";h.PUSH_SW_SCOPE="/";h.EVENTS_PATH="/events/collect";h.EVENT_FLUSH_INTERVAL_MS=1e4;h.EVENT_CODES=Object.freeze({APP_INSTALL:"ai",APP_OPEN:"ao",APP_FOREGROUNDED:"af",APP_BACKGROUNDED:"ab",APP_PERMISSIONS:"ap",APP_UPDATE:"au",DEEPLINK_OPEN:"do",TIME_IN_APP:"ta",PUSH_RECEIVED:"pr",PUSH_CLICK:"pc",WHITELIST_DOMAIN_DETECTED:"wd",RISK_DETECTED:"rd",SDK_ACTION_CLEARED:"sac"});h.VALID_EVENT_CODES=Object.freeze(Object.values(h.EVENT_CODES));h.EVENT_NAMES=Object.freeze({ai:"app_install",ao:"app_open",af:"app_foregrounded",ab:"app_backgrounded",ap:"app_permissions",au:"app_update",do:"deeplink_open",ta:"time_in_app",pr:"push_received",pc:"push_click",wd:"whitelist_domain_detected",rd:"risk_detected",sac:"sdk_action_cleared"});h.EVENT_REQUIRED_PROPS=Object.freeze({ai:[],ao:[],af:[],ab:[],ap:["pt","ps"],au:["pv","nv"],do:["ol"],ta:["ed"],pr:["pn"],pc:["pn"],wd:["rs","dm"],rd:["rt","rs"],sac:["as","cr"]});h.DEFAULT_INITIAL_REMAINING_LIMIT=15728640;function be(){return Math.random().toString(16).slice(2)+Date.now().toString(16)}function F(){return typeof window<"u"}function O(){return F()&&window.performance&&typeof window.performance.now=="function"?window.performance.now():Date.now()}function nt(n){try{return typeof n=="string"?n:n&&typeof n.url=="string"?n.url:String(n??"unknown")}catch{return"unknown"}}function ae(n){try{return JSON.parse(n)}catch{return null}}function rt(n){try{if(!n||typeof n!="string")return null;let e={},t=n.trim().split(/[\r\n]+/);for(let i of t){let s=i.indexOf(":");if(s===-1)continue;let r=i.slice(0,s).trim().toLowerCase(),o=i.slice(s+1).trim();r&&(e[r]=o)}return Object.keys(e).length?e:null}catch{return null}}function ne(n){if(n==null)return null;if(typeof n=="string")return ae(n)??n;if(typeof n=="object"){if(typeof FormData<"u"&&n instanceof FormData)return"[FormData]";if(typeof Blob<"u"&&n instanceof Blob)return`[Blob ${n.type||"unknown"} ${n.size} bytes]`;if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return`[ArrayBuffer ${n.byteLength} bytes]`}try{return String(n)}catch{return"[unserializable]"}}function re({requestId:n,method:e,url:t,status:i,tookMs:s,requestHeaders:r,requestBody:o,responseHeaders:l,responseBody:a,errorType:c,errorMessage:u,didComplete:d}){let f=d===!0,p={isSuccess:f,uuid:String(n||""),method:String(e||""),url:String(t||""),requestHeaders:r||{},requestBody:o??null,status:typeof i=="number"?i:0,responseHeaders:l||{},responseBody:a??null,tookMs:typeof s=="number"?s:0};return f||(p.errorType=c??"network_error",p.errorMessage=u??"network_error"),p}function ve(n,e,{stripQuery:t=!0,stripHash:i=!0}={}){try{let s=new URL(n,e);return t&&(s.search=""),i&&(s.hash=""),s.toString()}catch{return String(n||"unknown")}}function ot(n,e){try{return new URL(String(n||""),e).toString()}catch{return String(n||"")}}function Se(n,e=[]){let t=String(n||"");return e.some(i=>i?i instanceof RegExp?i.test(t):t.includes(String(i)):!1)}function oe(n){return typeof n!="number"?!0:n<=0?!1:n>=1?!0:Math.random()<n}function at(n,e){try{if(e&&e.method)return String(e.method).toUpperCase();if(n&&typeof n.method=="string")return String(n.method).toUpperCase()}catch{}return"GET"}function lt(n){try{if(!n||!n.headers)return null;let e={};return n.headers.forEach((t,i)=>{e[String(i).toLowerCase()]=String(t)}),Object.keys(e).length?e:null}catch{return null}}function ct(n,e){let t={},i=e?.headers??n?.headers;try{if(!i)return null;if(typeof Headers<"u"&&i instanceof Headers)return i.forEach((s,r)=>{t[String(r).toLowerCase()]=String(s)}),Object.keys(t).length?t:null;if(Array.isArray(i)){for(let[s,r]of i)t[String(s).toLowerCase()]=String(r);return Object.keys(t).length?t:null}if(typeof i=="object"){for(let s of Object.keys(i))t[String(s).toLowerCase()]=String(i[s]);return Object.keys(t).length?t:null}}catch{}return null}var V=class{constructor(e){this._onEvent=e.onEvent,this._getBaseHref=e.getBaseHref||(()=>F()?window.location.href:"http://localhost/"),this._excludeUrls=e.excludeUrls||[],this._redaction=e.redaction||{stripQuery:!0,stripHash:!0},this._sampling=e.sampling||{rate:1,onlyErrors:!1,slowThresholdMs:void 0},this._capture=e.capture||{fetch:!0,xhr:!0},this._shouldBlockRequest=typeof e.shouldBlockRequest=="function"?e.shouldBlockRequest:()=>!1,this._fetchInstalled=!1,this._originalFetch=null,this._xhrInstalled=!1,this._xhrProto=null,this._xhrOrigOpen=null,this._xhrOrigSend=null,this._xhrOrigSetHeader=null}install(){F()&&(this._capture.fetch&&this._installFetch(),this._capture.xhr&&this._installXHR())}uninstall(){F()&&(this._uninstallFetch(),this._uninstallXHR())}_shouldExclude(e){let t=this._getBaseHref(),i=ot(e,t);return Se(e,this._excludeUrls)||Se(i,this._excludeUrls)}_shouldBlock(e){try{return this._shouldBlockRequest(String(e||""))===!0}catch{return!1}}_emit(e,t){try{this._onEvent(e,t)}catch{}}_installFetch(){this._fetchInstalled||typeof window.fetch=="function"&&(this._fetchInstalled=!0,this._originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{let i=at(e,t),s=nt(e);if(this._shouldBlock(s))throw new TypeError("Request blocked by LogDrop risk policy");if(this._shouldExclude(s))return this._originalFetch(e,t);let r=this._getBaseHref(),o=ve(s,r,this._redaction),l=be(),a=O(),c={};try{let u=new Request(e,t),d={};u.headers.forEach((f,p)=>{d[String(p).toLowerCase()]=String(f)}),c=d}catch{c=ct(e,t)||{}}try{let u=ne(t?.body),d=await this._originalFetch(e,t),f=Math.round(O()-a),p=d?.status??0,_=!d||p>=400||p===0,m=typeof this._sampling.slowThresholdMs=="number"&&f>=this._sampling.slowThresholdMs;if((!this._sampling.onlyErrors||_||m)&&oe(this._sampling.rate)){let S=null;try{let R=d?.headers?.get?.("content-type")||"",b=await d.clone().text();S=(R.includes("application/json")?ae(b):null)??b}catch{}let k=lt(d)||{},w=re({requestId:l,method:i,url:o,status:p,tookMs:f,requestHeaders:c,requestBody:u,responseHeaders:k,responseBody:S,errorType:null,errorMessage:null,didComplete:!0});this._emit("network_activity",w)}return d}catch(u){let d=Math.round(O()-a);if(oe(this._sampling.rate)){let f=ne(t?.body),p=re({requestId:l,method:i,url:o,status:0,tookMs:d,requestHeaders:c,requestBody:f,responseHeaders:{},responseBody:null,errorType:u?.name??"fetch_error",errorMessage:String(u),didComplete:!1});this._emit("network_activity",p)}throw u}})}_uninstallFetch(){this._fetchInstalled&&this._originalFetch&&(window.fetch=this._originalFetch,this._fetchInstalled=!1,this._originalFetch=null)}_installXHR(){if(this._xhrInstalled||typeof window.XMLHttpRequest!="function")return;this._xhrInstalled=!0;let e=window.XMLHttpRequest.prototype;this._xhrProto=e,this._xhrOrigOpen=e.open,this._xhrOrigSend=e.send,this._xhrOrigSetHeader=e.setRequestHeader,e.__ld_open_orig=this._xhrOrigOpen,e.__ld_send_orig=this._xhrOrigSend,e.__ld_setheader_orig=this._xhrOrigSetHeader,e.open=function(i,s,r,o,l){return this.__ld={requestId:be(),method:String(i||"GET").toUpperCase(),rawUrl:String(s||"unknown"),start:0,headers:{}},e.__ld_open_orig.call(this,i,s,r,o,l)},e.setRequestHeader=function(i,s){try{this.__ld&&i&&(this.__ld.headers[String(i).toLowerCase()]=String(s))}catch{}return e.__ld_setheader_orig.call(this,i,s)};let t=this;e.send=function(i){let s=this.__ld;if(!s)return e.__ld_send_orig.call(this,i);if(t._shouldBlock(s.rawUrl)){try{this.abort()}catch{}return}if(t._shouldExclude(s.rawUrl))return e.__ld_send_orig.call(this,i);let r=t._getBaseHref(),o=ve(s.rawUrl,r,t._redaction),l=s.headers||{};s.start=O();let a=async c=>{let u=Math.round(O()-s.start),d=this.status??0,f=c!=="loadend"||d>=400||d===0,p=typeof t._sampling.slowThresholdMs=="number"&&u>=t._sampling.slowThresholdMs;if((!t._sampling.onlyErrors||f||p)&&oe(t._sampling.rate)){let _=ne(i),m=null;try{if(!this.responseType||this.responseType==="text"){let R=this.responseText;m=ae(R)??R}else m=this.response??null}catch{}let S={};try{let R=this.getAllResponseHeaders?.(),U=rt(R);U&&(S=U)}catch{}let k=c==="loadend",w=re({requestId:s.requestId,method:s.method,url:o,status:k?d:0,tookMs:u,requestHeaders:l,requestBody:_,responseHeaders:S,responseBody:k?m:null,errorType:k?null:c,errorMessage:k?null:c,didComplete:k});t._emit("network_activity",w)}};return this.addEventListener("loadend",()=>{a("loadend")},{once:!0}),this.addEventListener("error",()=>{a("error")},{once:!0}),this.addEventListener("abort",()=>{a("abort")},{once:!0}),this.addEventListener("timeout",()=>{a("timeout")},{once:!0}),e.__ld_send_orig.call(this,i)}}_uninstallXHR(){if(this._xhrInstalled&&this._xhrProto){this._xhrOrigOpen&&(this._xhrProto.open=this._xhrOrigOpen),this._xhrOrigSend&&(this._xhrProto.send=this._xhrOrigSend),this._xhrOrigSetHeader&&(this._xhrProto.setRequestHeader=this._xhrOrigSetHeader);try{delete this._xhrProto.__ld_open_orig,delete this._xhrProto.__ld_send_orig,delete this._xhrProto.__ld_setheader_orig}catch{}this._xhrInstalled=!1,this._xhrProto=null,this._xhrOrigOpen=null,this._xhrOrigSend=null,this._xhrOrigSetHeader=null}}};function le(){return typeof window<"u"}function ut(n){let e="=".repeat((4-n.length%4)%4),t=(n+e).replace(/-/g,"+").replace(/_/g,"/"),i=atob(t),s=new Uint8Array(i.length);for(let r=0;r<i.length;r++)s[r]=i.charCodeAt(r);return s}function T(n,e){let t=new Error(e);return t.code=n,t}var W=class{constructor(e){let t=e??{};this.vapidPublicKey=t.vapidPublicKey??null,this.manualServiceWorkerRegistration=t.manualServiceWorkerRegistration===!0,this.serviceWorkerUrl=t.serviceWorkerUrl??h.PUSH_SW_PATH,this.serviceWorkerScope=t.serviceWorkerScope??h.PUSH_SW_SCOPE,this.serviceWorkerRegistration=t.serviceWorkerRegistration??null,this.isPushEnabled=t.isPushEnabled!==!1,this.onRemoteMessageReceived=typeof t.onRemoteMessageReceived=="function"?t.onRemoteMessageReceived:null,this.apiKey=t.apiKey??null,this.apiBase=t.apiBase??"",this.deviceId=t.deviceId??null,this.getSessionToken=typeof t.getSessionToken=="function"?t.getSessionToken:null,this.onPushReceived=typeof t.onPushReceived=="function"?t.onPushReceived:null,this.onNotificationClick=typeof t.onNotificationClick=="function"?t.onNotificationClick:null,this.onSubscriptionChanged=typeof t.onSubscriptionChanged=="function"?t.onSubscriptionChanged:null,this._messageHandler=null,this._installed=!1,this._tornDown=!1}install(){if(this._installed||this._tornDown||!le())return;let e=this._getServiceWorkerContainer();!e||typeof e.addEventListener!="function"||(this._messageHandler=t=>{try{let i=t&&t.data;if(!i||typeof i!="object")return;if(i.type==="logdrop:push-received"&&this.onPushReceived)try{this.onPushReceived(i.payload)}catch{}else if(i.type==="logdrop:notification-click"){if(this.onNotificationClick)try{this.onNotificationClick(i.payload)}catch{}else if(typeof this.onRemoteMessageReceived=="function")try{this.onRemoteMessageReceived(i.payload)}catch{}}}catch{}},e.addEventListener("message",this._messageHandler),this._installed=!0)}uninstall(){if(!this._installed){this._messageHandler=null;return}if(le()){let e=this._getServiceWorkerContainer();if(e&&typeof e.removeEventListener=="function"&&this._messageHandler)try{e.removeEventListener("message",this._messageHandler)}catch{}}this._messageHandler=null,this._installed=!1}teardown(){this.uninstall(),this._tornDown=!0}getPermissionState(){if(typeof Notification>"u")return"unsupported";try{return Notification.permission??"unsupported"}catch{return"unsupported"}}updateServerConfig({isPushEnabled:e,vapidPublicKey:t}={}){typeof e=="boolean"&&(this.isPushEnabled=e),(typeof t=="string"||t===null)&&(this.vapidPublicKey=t),this._syncServiceWorkerConfig(),this._syncGrantedSubscription()}requestPendingMessages(){let e=this._getServiceWorkerContainer();try{e?.controller&&typeof e.controller.postMessage=="function"&&e.controller.postMessage({type:"logdrop:drain-pending"})}catch{}}async subscribe(){if(this._tornDown)throw T("TEARDOWN","PushModule has been torn down; subscribe() is no longer available");if(le()&&window.isSecureContext===!1)throw T("INSECURE_CONTEXT","Push requires a secure context (HTTPS). window.isSecureContext is false.");let e=typeof Notification<"u";if(!(typeof navigator<"u"&&!!navigator.serviceWorker)||!e)throw T("PUSH_UNSUPPORTED","Push notifications are not supported in this browser (serviceWorker or Notification API unavailable).");if(this.isPushEnabled===!1)return null;if(!this.vapidPublicKey)throw T("MISSING_VAPID_KEY","vapidPublicKey is required to subscribe to push notifications");let i=this.getPermissionState();if(i==="denied")throw T("PERMISSION_DENIED","Notification permission has been denied by the user");if(i==="default"){if(await Notification.requestPermission()!=="granted")throw T("PERMISSION_DENIED","Notification permission was not granted")}else if(i!=="granted")throw T("PUSH_UNSUPPORTED",`Unsupported Notification.permission state: ${i}`);let s=this._getServiceWorkerContainer();if(!s)throw T("PUSH_UNSUPPORTED","navigator.serviceWorker is not available");let r;if(this.serviceWorkerRegistration?r=this.serviceWorkerRegistration:this.manualServiceWorkerRegistration?r=await s.ready:(await s.register(this.serviceWorkerUrl,{scope:this.serviceWorkerScope}),r=this.serviceWorkerRegistration||await s.ready),!r)throw T("PUSH_UNSUPPORTED","Failed to obtain a service worker registration");if(!r.pushManager)throw T("PUSH_UNSUPPORTED","ServiceWorkerRegistration.pushManager is not available");await this._handshake(s,r);let o=ut(this.vapidPublicKey),l=await r.pushManager.getSubscription(),a=l?.options?.applicationServerKey;l&&a&&!this._keysEqual(a,o)&&await l.unsubscribe();let c;try{c=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:o})}catch(d){let f=d&&d.message?d.message:String(d);if(f.includes("applicationServerKey")||f.includes("gcm_sender_id")){let p=await r.pushManager.getSubscription();p&&await p.unsubscribe(),c=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:o})}else throw d}let u=typeof c.toJSON=="function"?c.toJSON():c;return this.onSubscriptionChanged&&await this.onSubscriptionChanged(u),await this._syncServiceWorkerConfig(r),c}async unsubscribe(){if(this._tornDown)throw T("TEARDOWN","PushModule has been torn down; unsubscribe() is no longer available");let e=this._getServiceWorkerContainer();if(!e)return null;let t;try{t=await e.ready}catch{return null}if(!t||!t.pushManager)return null;let i=null;try{i=await t.pushManager.getSubscription()}catch{i=null}if(!i)return null;try{await i.unsubscribe()}catch{}return null}_getServiceWorkerContainer(){return typeof navigator>"u"?null:navigator.serviceWorker??null}_handshake(e,t){return new Promise(i=>{let s=!1,r=()=>{if(!s){s=!0;try{typeof e.removeEventListener=="function"&&e.removeEventListener("message",o)}catch{}clearTimeout(l),i()}},o=a=>{try{let c=a&&a.data;c&&c.type==="logdrop:pong"&&r()}catch{}};try{typeof e.addEventListener=="function"&&e.addEventListener("message",o)}catch{}let l=setTimeout(r,500);if(l&&typeof l.unref=="function")try{l.unref()}catch{}try{t&&t.active&&typeof t.active.postMessage=="function"?t.active.postMessage({type:"logdrop:ping"}):r()}catch{r()}})}async _syncServiceWorkerConfig(e=null){let t=this._getServiceWorkerContainer();if(!t)return;let i=e||this.serviceWorkerRegistration;if(!i)try{i=await t.ready}catch{return}let s=i?.active||t.controller;!s||typeof s.postMessage!="function"||s.postMessage({type:"logdrop:push-config",config:{vapidPublicKey:this.vapidPublicKey,apiBase:this.apiBase,apiKey:this.apiKey,sessionToken:this.getSessionToken?this.getSessionToken():null,deviceUuid:this.deviceId}})}async _syncGrantedSubscription(){if(!(this.isPushEnabled!==!0||!this.vapidPublicKey||this.getPermissionState()!=="granted"||!this.deviceId||!this.getSessionToken?.()))try{await this.subscribe()}catch{}}reconcileGrantedSubscription(){return this._syncGrantedSubscription()}_keysEqual(e,t){let i=new Uint8Array(e),s=new Uint8Array(t);if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r]!==s[r])return!1;return!0}};function ke(n){return!n||typeof n!="object"?{}:n.data&&typeof n.data=="object"?n.data:n}function dt(n){if(!n||String(n.kind||"").toUpperCase()!=="OPEN_DEEPLINK")return!1;let e=String(n.target||n.fallbackTarget||"").trim();if(!e||typeof window>"u")return!1;try{return String(n.deeplinkMode||"").toUpperCase()==="EXTERNAL_BROWSER"?window.open(e,"_blank","noopener,noreferrer"):window.location.assign(e),!0}catch{let t=String(n.fallbackTarget||"").trim();if(!t||t===e)return!1;try{return window.location.assign(t),!0}catch{return!1}}}var K=class{constructor({onAction:e}={}){this.onAction=typeof e=="function"?e:null,this.queue=[],this.active=null,this._visibilityHandler=()=>this._showNext(),typeof document<"u"&&document.addEventListener?.("visibilitychange",this._visibilityHandler)}enqueue(e){let t=ke(e);if(String(t.messageKind||"").toUpperCase()!=="IN_APP"||!t.inApp||typeof t.inApp!="object")return!1;let i=String(t.notificationId||"").trim();if(i&&(this.active?.notificationId===i||this.queue.some(r=>r.notificationId===i)))return!1;let s=Number(t.inApp.ttlSeconds);return this.queue.push({payload:e,notificationId:i,expiresAt:Number.isFinite(s)&&s>0?Date.now()+s*1e3:null}),this._showNext(),!0}teardown(){typeof document<"u"&&document.removeEventListener?.("visibilitychange",this._visibilityHandler),this.queue=[],this._finish(!1)}_showNext(){if(this.active||typeof document>"u"||!document.body||document.visibilityState==="hidden")return;for(;this.queue.length&&this.queue[0].expiresAt&&this.queue[0].expiresAt<=Date.now();)this.queue.shift();let e=this.queue.shift();e&&(this.active={...e,element:this._render(e)})}_render(e){let i=ke(e.payload).inApp,s=String(i.template||"").toUpperCase()==="BANNER",r=document.createElement("div");r.setAttribute("data-logdrop-in-app","true"),r.setAttribute("role","dialog"),r.setAttribute("aria-modal",s?"false":"true"),r.style.cssText=s?`position:fixed;${String(i.position).toUpperCase()==="BOTTOM"?"bottom":"top"}:16px;left:50%;transform:translateX(-50%);z-index:2147483646;width:min(560px,calc(100% - 32px));font-family:system-ui,sans-serif`:"position:fixed;inset:0;z-index:2147483646;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(15,23,42,.62);font-family:system-ui,sans-serif";let o=document.createElement("div");if(o.style.cssText=`position:relative;box-sizing:border-box;width:100%;max-width:${s?"560px":"520px"};${i.isFullHeight===!0&&!s?"height:calc(100vh - 48px);":"max-height:calc(100vh - 48px);"}overflow:auto;background:#fff;color:#111827;border-radius:14px;padding:20px;box-shadow:0 20px 55px rgba(0,0,0,.3)`,i.dismissible!==!1){let a=document.createElement("button");a.type="button",a.setAttribute("aria-label","Close"),a.textContent="\xD7",a.style.cssText="position:absolute;top:8px;right:10px;border:0;background:transparent;font-size:24px;line-height:1;color:#6b7280;cursor:pointer",a.addEventListener("click",()=>this._finish(!0),{once:!0}),o.appendChild(a)}if(i.imageUrl){let a=document.createElement("img");a.src=String(i.imageUrl),a.alt="",a.style.cssText="display:block;width:100%;max-height:280px;object-fit:cover;border-radius:10px;margin-bottom:16px",o.appendChild(a)}if(i.headline){let a=document.createElement("h2");a.textContent=String(i.headline),a.style.cssText="margin:0 28px 8px 0;font-size:20px;line-height:1.3",o.appendChild(a)}if(i.body){let a=document.createElement("p");a.textContent=String(i.body),a.style.cssText="margin:0;color:#4b5563;line-height:1.5;white-space:pre-wrap",o.appendChild(a)}let l=[i.secondaryButton,i.primaryButton].filter(a=>a?.label);if(l.length){let a=document.createElement("div");a.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:18px",l.forEach((c,u)=>{let d=document.createElement("button");d.type="button",d.textContent=String(c.label);let f=u===l.length-1&&i.primaryButton===c;d.style.cssText=f?"padding:9px 15px;border:0;border-radius:8px;background:#111827;color:#fff;cursor:pointer":"padding:9px 15px;border:1px solid #d1d5db;border-radius:8px;background:#fff;color:#111827;cursor:pointer",d.addEventListener("click",()=>{try{this.onAction?.(e.payload,c.action||null)}catch{}dt(c.action),this._finish(!0)},{once:!0}),a.appendChild(d)}),o.appendChild(a)}return r.appendChild(o),!s&&i.dismissible!==!1&&r.addEventListener("click",a=>{a.target===r&&this._finish(!0)}),document.body.appendChild(r),r}_finish(e){this.active?.element?.parentNode&&this.active.element.parentNode.removeChild(this.active.element),this.active=null,e&&this._showNext()}};var D=class n{constructor(){this._buf=[]}_writeVarint(e){let t=e>>>0;if(e<=127){this._buf.push(t);return}for(;t>127;)this._buf.push(t&127|128),t>>>=7;this._buf.push(t)}_writeTag(e,t){this._writeVarint(e<<3|t)}writeString(e,t){if(!t)return;let i=new TextEncoder().encode(t);this._writeTag(e,2),this._writeVarint(i.length);for(let s=0;s<i.length;s++)this._buf.push(i[s])}writeBytes(e,t){if(!(!t||t.length===0)){this._writeTag(e,2),this._writeVarint(t.length);for(let i=0;i<t.length;i++)this._buf.push(t[i])}}writeInt64(e,t){t&&(this._writeTag(e,0),this._writeVarint(t))}_writeVarintLong(e){let t=Math.floor(e);for(;t>127;)this._buf.push(t%128|128),t=Math.floor(t/128);this._buf.push(t%128)}writeInt64Long(e,t){t&&(this._writeTag(e,0),this._writeVarintLong(t))}writeDouble(e,t){this._writeTag(e,1);let i=new ArrayBuffer(8);new DataView(i).setFloat64(0,t,!0);let s=new Uint8Array(i);for(let r=0;r<8;r++)this._buf.push(s[r])}writeStringForce(e,t){let i=new TextEncoder().encode(t??"");this._writeTag(e,2),this._writeVarint(i.length);for(let s=0;s<i.length;s++)this._buf.push(i[s])}writeBoolForce(e,t){this._writeTag(e,0),this._buf.push(t?1:0)}writeBool(e,t){t&&(this._writeTag(e,0),this._buf.push(1))}writeEnum(e,t){this.writeInt64(e,t)}writeRepeatedString(e,t){if(!(!t||!t.length))for(let i of t)this.writeString(e,i)}writeMessage(e,t){let i=new n;t(i);let s=i.finish();if(s.length!==0){this._writeTag(e,2),this._writeVarint(s.length);for(let r=0;r<s.length;r++)this._buf.push(s[r])}}finish(){return new Uint8Array(this._buf)}},v=class{constructor(e){this._buf=e,this._pos=0}hasMore(){return this._pos<this._buf.length}_readVarint(){let e=0,t=0;for(;this._pos<this._buf.length;){let i=this._buf[this._pos++];if(e|=(i&127)<<t,(i&128)===0)return e>>>0;if(t+=7,t>35){for(;this._pos<this._buf.length&&(this._buf[this._pos++]&128)!==0;);return e>>>0}}return e>>>0}readTag(){if(!this.hasMore())return null;let e=this._readVarint();return{fieldNumber:e>>>3,wireType:e&7}}readBytes(){let e=this._pos,t=this._readVarint();if(!Number.isInteger(t)||t<0||this._pos+t>this._buf.length)throw this._pos=e,new Error("Unexpected end of buffer in readBytes");let i=this._buf.slice(this._pos,this._pos+t);return this._pos+=t,i}readString(){let e=this.readBytes();return new TextDecoder().decode(e)}readVarint(){return this._readVarint()}readVarintLong(){let e=0,t=1;for(;this._pos<this._buf.length;){let i=this._buf[this._pos++];if(e+=(i&127)*t,(i&128)===0)break;t*=128}return e}readDouble(){if(this._pos+8>this._buf.length)throw new Error("Unexpected end of buffer in readDouble");let t=new DataView(this._buf.buffer,this._buf.byteOffset+this._pos,8).getFloat64(0,!0);return this._pos+=8,t}readBool(){return this._readVarint()!==0}skip(e){switch(e){case 0:this._readVarint();break;case 1:if(this._pos+8>this._buf.length)throw new Error("Unexpected end of buffer while skipping 64-bit field");this._pos+=8;break;case 2:{let t=this._readVarint();if(!Number.isInteger(t)||t<0||this._pos+t>this._buf.length)throw new Error("Unexpected end of buffer while skipping length-delimited field");this._pos+=t}break;case 5:if(this._pos+4>this._buf.length)throw new Error("Unexpected end of buffer while skipping 32-bit field");this._pos+=4;break;default:throw new Error(`Unknown wire type: ${e}`)}}};function ht(n,e){n.writeString(1,e.deviceUuid),n.writeString(3,e.iosApnsDeviceToken),n.writeString(4,e.androidFirebaseToken),n.writeString(5,e.huaweiToken),n.writeString(6,e.osName),n.writeString(7,e.osVersion),n.writeString(8,e.deviceBrand),n.writeString(9,e.deviceModel),n.writeString(10,e.appVersion),n.writeString(11,e.sdkVersion),n.writeString(12,e.sdkType),n.writeString(13,e.bridgeSdkType);for(let[t,i]of Object.entries(e.customAttributes||{}))n.writeMessage(14,s=>{s.writeString(1,t),s.writeString(2,i)});for(let t of e.removedCustomAttributeKeys||[])n.writeString(15,t);e.webPushSubscription&&n.writeMessage(16,t=>{t.writeString(1,e.webPushSubscription.endpoint),t.writeString(2,e.webPushSubscription.p256dh),t.writeString(3,e.webPushSubscription.auth),t.writeInt64Long(4,e.webPushSubscription.expirationTime)})}function Re(n){let e=new D;return e.writeString(1,n.userUuid),n.device&&e.writeMessage(2,t=>ht(t,n.device)),e.finish()}function ce(n){let e=new v(n),t={accessToken:"",refreshToken:""};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.accessToken=e.readString();break;case 2:t.refreshToken=e.readString();break;default:e.skip(i.wireType)}}return t}function Ue(n){let e=new D;return e.writeString(2,n.refreshToken),e.writeString(3,n.deviceUuid),e.finish()}function E(n){return n||null}function ft(n){let e=new v(n),t={domain:"",path:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.domain=e.readString();break;case 2:t.path=E(e.readString());break;default:e.skip(i.wireType)}}return t}function Ee(n){let e=new v(n),t={showPopupEnabled:!1,appBlockEnabled:!1,networkBlockEnabled:!1,blockedRequestPaths:[],blockedDomains:[],title:null,message:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.showPopupEnabled=e.readBool();break;case 2:t.appBlockEnabled=e.readBool();break;case 3:t.networkBlockEnabled=e.readBool();break;case 4:t.blockedRequestPaths.push(e.readString());break;case 5:t.blockedDomains.push(e.readString());break;case 6:t.title=E(e.readString());break;case 7:t.message=E(e.readString());break;case 8:t.buttonText=E(e.readString());break;default:e.skip(i.wireType)}}return t}function Ie(n){let e=new v(n),t={enabled:!1,whitelist:[],actions:Ee(new Uint8Array)};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.whitelist.push(ft(e.readBytes()));break;case 3:t.actions=Ee(e.readBytes());break;default:e.skip(i.wireType)}}return t}function _t(n){let e=new v(n),t={enabled:!1,priority:0,matchType:"ANY",eventIds:[],actionIds:[],message:null,title:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.priority=e.readVarint();break;case 3:t.matchType=e.readVarint()===1?"ALL":"ANY";break;case 4:i.wireType===2?t.eventIds.push(...M(e.readBytes())):t.eventIds.push(e.readVarint());break;case 5:i.wireType===2?t.actionIds.push(...M(e.readBytes())):t.actionIds.push(e.readVarint());break;case 6:t.message=E(e.readString());break;case 7:t.title=E(e.readString());break;case 8:t.buttonText=E(e.readString());break;default:e.skip(i.wireType)}}return t}function M(n){let e=new v(n),t=[];for(;e.hasMore();)t.push(e.readVarint());return t}function pt(n){let e=new v(n),t={version:0,rules:[]};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.version=e.readVarint();break;case 2:t.rules.push(_t(e.readBytes()));break;default:e.skip(i.wireType)}}return t}function Te(n){let e=new v(n),t={riskPolicy:{version:0,rules:[]},enabled:!1,botDetectionEnabled:!1,otherRiskTypesEnabled:!1};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.riskPolicy=pt(e.readBytes());break;case 2:t.enabled=e.readBool();break;case 3:t.botDetectionEnabled=e.readBool();break;case 4:t.otherRiskTypesEnabled=e.readBool();break;default:e.skip(i.wireType)}}return t}function xe(n){switch(n){case 1:return"MEDIUM";case 2:return"HIGH";case 3:return"CRITICAL";default:return"UNSPECIFIED"}}function gt(n){let e=new v(n),t={enabled:!1,priority:0,threatLevels:[],actionIds:[],message:null,title:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.priority=e.readVarint();break;case 3:{let s=i.wireType===2?M(e.readBytes()):[e.readVarint()];t.threatLevels.push(...s.map(xe));break}case 4:i.wireType===2?t.actionIds.push(...M(e.readBytes())):t.actionIds.push(e.readVarint());break;case 5:t.message=E(e.readString());break;case 6:t.title=E(e.readString());break;case 7:t.buttonText=E(e.readString());break;default:e.skip(i.wireType)}}return t}function mt(n){let e=new v(n),t={version:0,rules:[]};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.version=e.readVarint();break;case 2:t.rules.push(gt(e.readBytes()));break;default:e.skip(i.wireType)}}return t}function Pe(n){let e=new v(n),t={riskPolicy:{version:0,rules:[]}};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.riskPolicy=mt(e.readBytes());break;default:e.skip(i.wireType)}}return t}function yt(n){let e=new v(n),t={signature:"",eventId:"",threatLevel:"UNSPECIFIED",riskScore:0,actionIds:[],expireAtEpochMillis:0,message:null,title:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.signature=e.readString();break;case 2:t.eventId=e.readString();break;case 3:t.threatLevel=xe(e.readVarint());break;case 4:t.riskScore=e.readVarint();break;case 5:i.wireType===2?t.actionIds.push(...M(e.readBytes())):t.actionIds.push(e.readVarint());break;case 6:t.expireAtEpochMillis=e.readVarintLong();break;case 7:t.message=E(e.readString());break;case 8:t.title=E(e.readString());break;case 9:t.buttonText=E(e.readString());break;default:e.skip(i.wireType)}}return t}function wt(n){let e=new v(n),t={enabled:!1,vapidPublicKey:""};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.vapidPublicKey=e.readString();break;default:e.skip(i.wireType)}}return t}function bt(n){let e=new v(n),t={httpWhitelist:Ie(new Uint8Array),riskDetected:Te(new Uint8Array),ipReputationDetected:Pe(new Uint8Array)};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.httpWhitelist=Ie(e.readBytes());break;case 2:t.riskDetected=Te(e.readBytes());break;case 3:t.ipReputationDetected=Pe(e.readBytes());break;default:e.skip(i.wireType)}}return t}function ue(n){let e=new v(n),t={perUserMaxFileSizeLimitInBytes:0,perUserMinFileSizeLimitInBytes:0,databaseMaxStorageLimitInBytes:0,isSDKDisabled:!1,isHttpLoggingEnabled:!1,isCrashTrackingEnabled:!1,isEventTrackingEnabled:!1,httpDomainBlackList:[],sensitiveInfoFilter:[],sslPinning:null,accessToken:"",limitType:0,riskConfig:null,activeIpReputationAction:null,serverNowEpochMillis:0,webPushConfig:{enabled:!1,vapidPublicKey:""}};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.perUserMaxFileSizeLimitInBytes=e.readVarintLong();break;case 2:t.perUserMinFileSizeLimitInBytes=e.readVarintLong();break;case 3:t.databaseMaxStorageLimitInBytes=e.readVarintLong();break;case 4:t.isSDKDisabled=e.readBool();break;case 5:t.isHttpLoggingEnabled=e.readBool();break;case 6:t.isCrashTrackingEnabled=e.readBool();break;case 7:t.httpDomainBlackList.push(e.readString());break;case 8:t.sensitiveInfoFilter.push(e.readString());break;case 9:e.skip(i.wireType);break;case 10:t.accessToken=e.readString();break;case 11:t.limitType=e.readVarint();break;case 12:t.riskConfig=bt(e.readBytes());break;case 13:t.activeIpReputationAction=yt(e.readBytes());break;case 14:t.serverNowEpochMillis=e.readVarintLong();break;case 15:t.isEventTrackingEnabled=e.readBool();break;case 18:t.webPushConfig=wt(e.readBytes());break;default:e.skip(i.wireType)}}return t}function Le(n){let e=new D;return e.writeBytes(1,n.content),e.writeString(2,n.deviceUuid),e.writeString(4,n.appVersion),e.writeString(5,n.sdkVersion),e.writeString(6,n.osVersion),e.writeString(7,n.errorCount),e.writeString(8,n.firstRealUserUuid),e.writeString(9,n.uploadId),e.finish()}function de(n){let e=new v(n),t={remainingLimit:0};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.remainingLimit=e.readVarint();break;default:e.skip(i.wireType)}}return t}function De(n){let e=new D;return e.writeBytes(1,n.content),e.writeString(2,n.deviceUuid),e.writeString(4,n.sdkVersion),e.finish()}function Ae(n,e){if(e==null){n._writeTag(1,0),n._writeVarint(0);return}let t=typeof e;if(t==="number"){Number.isFinite(e)?n.writeDouble(2,e):(n._writeTag(1,0),n._writeVarint(0));return}if(t==="boolean"){n.writeBoolForce(4,e);return}if(t==="string"){n.writeStringForce(3,e);return}if(Array.isArray(e)){n.writeMessage(6,i=>{for(let s of e)i.writeMessage(1,r=>Ae(r,s))});return}if(t==="object"){n.writeMessage(5,i=>Ne(i,e));return}n.writeStringForce(3,String(e))}function Ne(n,e){for(let t of Object.keys(e))n.writeMessage(1,i=>{i.writeStringForce(1,t),i.writeMessage(2,s=>Ae(s,e[t]))})}function vt(n,e){n.writeString(1,e.eventId),n.writeString(2,e.eventCode),n.writeInt64Long(3,e.timestamp),e.properties&&typeof e.properties=="object"&&Object.keys(e.properties).length>0&&n.writeMessage(4,t=>Ne(t,e.properties))}function St(n,e){if(n.writeString(1,e.sessionId),n.writeString(2,e.userUuid),Array.isArray(e.events))for(let t of e.events)n.writeMessage(3,i=>vt(i,t))}function Ce(n){let e=new D;if(e.writeString(1,n.deviceUuid),Array.isArray(n.sessions))for(let t of n.sessions)e.writeMessage(2,i=>St(i,t));return e.writeString(3,n.firstRealUserUuid),e.writeString(4,n.uploadId),e.finish()}function Oe(n){let e=new v(n),t={count:0};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.count=e.readVarint();break;default:e.skip(i.wireType)}}return t}function B(){return typeof window<"u"}function kt(){return B()&&typeof window.fetch=="function"?window.fetch.bind(window):typeof fetch=="function"?fetch:null}function he(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Et(){return typeof navigation<"u"&&typeof navigation.addEventListener=="function"}var z=class{constructor(e){let t=e??{};this._deviceId=t.deviceId??"",this._getSessionId=typeof t.getSessionId=="function"?t.getSessionId:()=>"",this._getUserUuid=typeof t.getUserUuid=="function"?t.getUserUuid:()=>null,this._getRealUserUuid=typeof t.getRealUserUuid=="function"?t.getRealUserUuid:()=>null,this._logEvent=typeof t.logEvent=="function"?t.logEvent:null,this._getSessionToken=typeof t.getSessionToken=="function"?t.getSessionToken:null,this._release=t.release??void 0,this._apiKey=t.apiKey??"",this._apiBase=t.apiBase??"",this._isEventTrackingEnabled=t.isEventTrackingEnabled===!0,this._isFirstVisit=t.isFirstVisit===!0,this._isSdkUpdated=t.isSdkUpdated===!0,this._previousRelease=t.previousRelease??null,this._dbPromise=t.dbPromise??null,this._eventQueue=[],this._eventPersistPromises=new Set,this._activeMemoryBatch=null,this._eventFlushInProgress=!1,this._installed=!1,this._tornDown=!1,this._visibilityHandler=null,this._pageHideHandler=null,this._navigateHandler=null,this._popstateHandler=null,this._originalPushState=null,this._originalReplaceState=null,this._usesNavigationApi=!1,this._lastUrl=null,this._permissionStatuses=[]}install(){this._installed||this._tornDown||(this._installed=!0,this._lastUrl=this._getCurrentUrl(),this._enqueueEventUnconditional("ao",{}),this._isFirstVisit&&this._enqueueEventUnconditional("ai",{}),this._isSdkUpdated&&this._enqueueEventUnconditional("au",{pv:this._previousRelease,nv:this._release}),this._sessionStartTime=Date.now(),this._visibilityHandler=()=>{try{if(typeof document>"u")return;document.visibilityState==="hidden"?(this._enqueueEvent("ab",{}),this._sessionStartTime!=null&&this._enqueueEvent("ta",{ed:Date.now()-this._sessionStartTime}),this._sessionStartTime=null):document.visibilityState==="visible"&&(this._enqueueEvent("af",{}),this._sessionStartTime=Date.now())}catch{}},typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",this._visibilityHandler),this._pageHideHandler=()=>{try{this._flush(!0)}catch{}},B()&&typeof window.addEventListener=="function"&&window.addEventListener("pagehide",this._pageHideHandler),this._installSpaDetection(),this._installPermissionTracking())}uninstall(){if(this._installed){if(this._visibilityHandler&&typeof document<"u"&&typeof document.removeEventListener=="function")try{document.removeEventListener("visibilitychange",this._visibilityHandler)}catch{}if(this._visibilityHandler=null,this._pageHideHandler&&B()&&typeof window.removeEventListener=="function")try{window.removeEventListener("pagehide",this._pageHideHandler)}catch{}this._pageHideHandler=null,this._uninstallSpaDetection(),this._uninstallPermissionTracking(),this._installed=!1}}teardown(){this.uninstall(),this._tornDown=!0}setEnabled(e){this._isEventTrackingEnabled=e===!0}_enqueueEvent(e,t){!this._isEventTrackingEnabled||this._tornDown||this._enqueueEventUnconditional(e,t)}trackEvent(e,t){this._enqueueEvent(e,t)}_isValidEvent(e,t){if(!h.VALID_EVENT_CODES.includes(e))return!1;let i=h.EVENT_REQUIRED_PROPS[e]??[],s=t??{};for(let r of i){let o=s[r];if(o==null||o==="")return!1}return!0}_enqueueEventUnconditional(e,t){if(this._tornDown||!this._isValidEvent(e,t))return;let i={eventId:he(),eventCode:e,timestamp:Date.now(),properties:t??{},_sessionId:this._getSessionId(),userUuid:this._getUserUuid()};this._eventQueue.push(i);let s=this._persistEvent(i);this._eventPersistPromises.add(s),s.finally(()=>this._eventPersistPromises.delete(s)),this._eventQueue.length>=30&&this._flush()}async _persistEvent(e){if(!this._dbPromise)return null;try{let i=(await this._dbPromise).transaction("events","readwrite"),s=i.objectStore("events").add({...e});return await new Promise((r,o)=>{i.oncomplete=r,i.onerror=()=>o(i.error)}),e._dbId=s.result,s.result}catch{return null}}async _readStore(e){if(!this._dbPromise)return[];let s=(await this._dbPromise).transaction(e,"readonly").objectStore(e).getAll();return new Promise((r,o)=>{s.onsuccess=()=>r(s.result||[]),s.onerror=()=>o(s.error)})}async _replaceEventBatch(e){let i=(await this._dbPromise).transaction("event_upload_batch","readwrite"),s=i.objectStore("event_upload_batch");s.clear(),e&&s.add(e),await new Promise((r,o)=>{i.oncomplete=r,i.onerror=()=>o(i.error)})}async _getOrCreateEventBatch(){if(await Promise.all([...this._eventPersistPromises]),this._dbPromise)try{let e=await this._readStore("events"),i=(await this._readStore("event_upload_batch"))[0]??null;if(i){let s=e.filter(r=>r.id<=i.lastEventId);if(s.length>0)return{uploadId:i.uploadId,events:s,persisted:!0};await this._replaceEventBatch(null)}if(e.length>0){let s={uploadId:he(),lastEventId:e[e.length-1].id};return await this._replaceEventBatch(s),{uploadId:s.uploadId,events:e,persisted:!0}}}catch{}return!this._activeMemoryBatch&&this._eventQueue.length>0&&(this._activeMemoryBatch={uploadId:he(),events:[...this._eventQueue],persisted:!1}),this._activeMemoryBatch}async _acknowledgeEventBatch(e){let t=new Set(e.events.map(i=>i.eventId));if(e.persisted&&this._dbPromise){let s=(await this._dbPromise).transaction("events","readwrite"),r=s.objectStore("events");e.events.forEach(o=>r.delete(o.id)),await new Promise((o,l)=>{s.oncomplete=o,s.onerror=()=>l(s.error)}),await this._replaceEventBatch(null)}else this._activeMemoryBatch=null;this._eventQueue=this._eventQueue.filter(i=>!t.has(i.eventId))}async _flush(e=!1){if(this._tornDown||!this._isEventTrackingEnabled||this._eventFlushInProgress||this._eventQueue.length===0&&!this._dbPromise)return;this._eventFlushInProgress=!0;let t=kt();if(!t){this._eventFlushInProgress=!1;return}let i=null;if(this._getSessionToken)try{i=await this._getSessionToken()}catch{i=null}if(!i){this._eventFlushInProgress=!1;return}try{let s=await this._getOrCreateEventBatch();if(!s||s.events.length===0)return;let r=s.events,o=new Map;for(let _ of r){let m=_._sessionId;o.has(m)||o.set(m,{userUuid:_.userUuid,events:[]}),o.get(m).events.push({eventId:_.eventId,eventCode:_.eventCode,timestamp:_.timestamp,properties:_.properties})}let l=[];for(let[_,m]of o)l.push({sessionId:_,userUuid:m.userUuid,events:m.events});let a=this._getRealUserUuid()??"",c={deviceUuid:this._deviceId,sessions:l,firstRealUserUuid:a,uploadId:s.uploadId},u=Ce(c),d=`${this._apiBase}${h.EVENTS_PATH}`,f={method:"POST",headers:{"Content-Type":"application/x-protobuf",Accept:"application/x-protobuf","x-api-key":this._apiKey,"x-session-token":i},body:new Blob([u],{type:"application/x-protobuf"})};e&&(f.keepalive=!0);let p=await t(d,f);if(p.ok){if(this._logEvent)for(let _ of c.sessions)for(let m of _.events)try{this._logEvent({eventId:m.eventId,eventCode:m.eventCode,eventName:h.EVENT_NAMES[m.eventCode]??m.eventCode,timestamp:m.timestamp,sessionId:_.sessionId,properties:m.properties??{}})}catch{}try{let _=new Uint8Array(await p.arrayBuffer());_.length>0&&Oe(_)}catch{}await this._acknowledgeEventBatch(s)}}catch(s){throw s}finally{this._eventFlushInProgress=!1}}_installSpaDetection(){Et()?(this._usesNavigationApi=!0,this._navigateHandler=e=>{try{let t=e&&e.destination&&e.destination.url?e.destination.url:this._getCurrentUrl();queueMicrotask(()=>{this._lastUrl=t})}catch{}},navigation.addEventListener("navigate",this._navigateHandler)):(this._usesNavigationApi=!1,this._installHistoryPatches())}_uninstallSpaDetection(){if(this._usesNavigationApi){if(this._navigateHandler&&typeof navigation<"u"&&typeof navigation.removeEventListener=="function")try{navigation.removeEventListener("navigate",this._navigateHandler)}catch{}this._navigateHandler=null}else this._restoreHistoryPatches();if(this._popstateHandler&&B()&&typeof window.removeEventListener=="function")try{window.removeEventListener("popstate",this._popstateHandler)}catch{}this._popstateHandler=null}_installHistoryPatches(){if(typeof history>"u")return;this._originalPushState=history.pushState,this._originalReplaceState=history.replaceState;let e=this;history.pushState=function(...t){e._originalPushState.apply(this,t),e._lastUrl=e._getCurrentUrl()},history.replaceState=function(...t){e._originalReplaceState.apply(this,t),e._lastUrl=e._getCurrentUrl()},this._popstateHandler=()=>{try{this._lastUrl=this._getCurrentUrl()}catch{}},B()&&typeof window.addEventListener=="function"&&window.addEventListener("popstate",this._popstateHandler)}_restoreHistoryPatches(){typeof history>"u"||(this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null))}async _installPermissionTracking(){let e=[{pt:"notification",apiName:"notifications"},{pt:"geolocation",apiName:"geolocation"},{pt:"camera",apiName:"camera"},{pt:"microphone",apiName:"microphone"}];if(typeof navigator<"u"&&navigator.permissions&&typeof navigator.permissions.query=="function")for(let{pt:i,apiName:s}of e)try{let r=await navigator.permissions.query({name:s});this._enqueueEvent("ap",{pt:i,ps:r.state}),r.onchange=()=>{try{if(!this._installed)return;this._enqueueEvent("ap",{pt:i,ps:r.state})}catch{}},this._permissionStatuses.push(r)}catch{let r=i==="notification"?this._getNotificationPermission():"unsupported";this._enqueueEvent("ap",{pt:i,ps:r})}else{this._enqueueEvent("ap",{pt:"notification",ps:this._getNotificationPermission()});for(let i of["geolocation","camera","microphone"])this._enqueueEvent("ap",{pt:i,ps:"unsupported"})}}_getNotificationPermission(){try{if(typeof Notification<"u"&&Notification.permission){let e=Notification.permission;return e==="default"?"prompt":e}}catch{}return"unsupported"}_uninstallPermissionTracking(){for(let e of this._permissionStatuses)try{e.onchange=null}catch{}this._permissionStatuses=[]}_getCurrentUrl(){try{if(typeof location<"u"&&location.href)return location.href}catch{}return""}_getReferrer(){try{if(typeof document<"u"&&document.referrer!=null)return document.referrer}catch{}return""}_getTitle(){try{if(typeof document<"u"&&document.title!=null)return document.title}catch{}return""}};function Me(){return typeof window<"u"}var q=class{detect(){if(typeof navigator>"u")return null;let e=[];if(navigator.webdriver===!0&&e.push("webdriver"),typeof navigator.userAgent=="string"&&navigator.userAgent.toLowerCase().includes("chrome")&&Me()&&!window.chrome&&e.push("missing_chrome_api"),Me()){(window.__playwright__binding__!==void 0||window.__pwInitScripts__!==void 0)&&e.push("playwright_binding");for(let t of Object.keys(window))if(t.startsWith("cdc_")){e.push("cdp_marker");break}}return e.length===0?null:{id:"headless_browser_detected",weight:.9,severity:1,confidence:.9,evidence:{indicators:e.join(",")}}}};var j=class{detect(){if(typeof window>"u")return null;let e=[];return(window.__playwright__binding__!==void 0||window.__pwInitScripts__!==void 0)&&e.push("playwright"),window.__puppeteer_evaluation_script__!==void 0&&e.push("puppeteer"),typeof document<"u"&&(document.$wdc_!==void 0||document.__webdriver_evaluate!==void 0)&&e.push("selenium"),e.length===0?null:{id:"automation_environment_detected",weight:.6,severity:1,confidence:1,evidence:{indicators:e.join(",")}}}};function It(n){if(n.length<2)return 0;let e=n.reduce((i,s)=>i+s,0)/n.length,t=n.reduce((i,s)=>i+(s-e)**2,0)/(n.length-1);return Math.sqrt(t)}function Tt(n){return n.length===0?0:n.reduce((e,t)=>e+t,0)/n.length}var G=class{constructor(){this._samples=[]}recordSample(e,t,i){this._samples.push({x:e,y:t,time:i}),this._samples.length>60&&this._samples.shift()}_injectSamples(e){this._samples=e.slice(-60)}detect(){let t=(this._samples.length>0?this._samples[this._samples.length-1].time:0)-4e3,i=this._samples.filter(b=>b.time>=t);if(i.length<8)return null;let s=[];for(let b=1;b<i.length;b++)s.push(i[b].time-i[b-1].time);let r=Tt(s),o=It(s),l=o<18&&r<120,a=0;for(let b=1;b<i.length;b++){let se=i[b].x-i[b-1].x,we=i[b].y-i[b-1].y;a+=Math.sqrt(se*se+we*we)}let c=i[0],u=i[i.length-1],d=u.x-c.x,f=u.y-c.y,p=Math.sqrt(d*d+f*f),_=a>0?p/a:0,m=_>.985,S=u.time-c.time,k=i.length>=10&&S<2500,w=o<30&&r<180;return l||k&&m&&w||m&&k?{id:"automation_pointer_pattern",weight:.6,severity:1,confidence:1,evidence:{stddev:o.toFixed(2),mean_interval:r.toFixed(2),straight:_.toFixed(4),span:S.toFixed(0),samples:i.length.toString()}}:null}};function Pt(n){if(n.length<2)return 0;let e=n.reduce((i,s)=>i+s,0)/n.length,t=n.reduce((i,s)=>i+(s-e)**2,0)/(n.length-1);return Math.sqrt(t)}var $=class{constructor(){this._timestamps=[]}recordTimestamp(e){this._timestamps.push(e),this._timestamps.length>20&&this._timestamps.shift()}_injectTimestamps(e){this._timestamps=e.slice(-20)}detect(){if(this._timestamps.length<6)return null;let e=[];for(let i=1;i<this._timestamps.length;i++)e.push(this._timestamps[i]-this._timestamps[i-1]);let t=Pt(e);return t>=20?null:{id:"keyboard_too_uniform",weight:.55,severity:1,confidence:.8,evidence:{stddev:t.toFixed(2),samples:this._timestamps.length.toString()}}}};function Rt(n){return typeof n=="string"&&n.toLowerCase().includes("chrome")&&!n.toLowerCase().includes("firefox")}var J=class{detect(){if(typeof navigator>"u")return null;let e=navigator.userAgent,t=Rt(e),i=[],s=navigator.plugins;t&&s!==void 0&&s.length===0&&i.push("empty_plugins");let r=navigator.languages;return(!r||r.length===0)&&i.push("missing_languages"),t&&navigator.deviceMemory===void 0&&i.push("missing_device_memory"),i.length===0?null:{id:"hardware_inconsistency",weight:.4,severity:.7,confidence:.6,evidence:{indicators:i.join(",")}}}};var X=class{detect(){if(typeof window>"u")return null;let e=(window.outerWidth??0)-(window.innerWidth??0),t=(window.outerHeight??0)-(window.innerHeight??0);return e<=200&&t<=200?null:{id:"devtools_open",weight:.4,severity:.7,confidence:.75,evidence:{width_diff:e.toString(),height_diff:t.toString()}}}};var Y=class{constructor(){this._triggered=!1,this._bait=this._makeBait()}_makeBait(){let e=this,t={};return Object.defineProperty(t,"id",{enumerable:!0,configurable:!0,get(){return e._triggered=!0,""}}),t}probe(){if(!(typeof console>"u"||typeof console.log!="function")){this._triggered=!1;try{console.log("%c%o","font-size:0;color:transparent",this._bait)}catch{}}}detect(){return this._triggered?{id:"devtools_open",weight:.4,severity:.7,confidence:.6,evidence:{method:"console_getter"}}:null}};var Q=class{constructor(){this._detected=null,this._method=null,this._checkPromise=this._check()}async _check(){let e=typeof window<"u"?window:null,t=e&&(e.RequestFileSystem||e.webkitRequestFileSystem);if(t&&await new Promise(s=>{try{t(0,100,()=>s(!1),()=>s(!0))}catch{s(!1)}})){this._detected=!0,this._method="filesystem_api";return}if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.estimate=="function")try{let{quota:i}=await navigator.storage.estimate();if(typeof i=="number"&&i<10485760){this._detected=!0,this._method="storage_quota";return}this._detected=!1;return}catch{}if(typeof localStorage<"u"){try{localStorage.setItem("_ld_priv_test","1"),localStorage.removeItem("_ld_priv_test"),this._detected=!1}catch{this._detected=!0,this._method="localstorage_throw"}return}this._detected=!1}detect(){return this._detected?{id:"private_browsing_detected",weight:.3,severity:.5,confidence:.7,evidence:{method:this._method??"unknown"}}:null}};var Be="_ld_cv",He="_ld_sm";function Ut(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function xt(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}var Z=class{detect(){let e=Ut(),t=xt();if(!e||!t||t.getItem(He)==="1")return null;t.setItem(He,"1");let i=null;try{let r=e.getItem(Be);r&&(i=JSON.parse(r))}catch{i=null}let s=(i?.n??0)+1;return e.setItem(Be,JSON.stringify({t:Date.now(),n:s})),i!==null?null:{id:"session_not_persistent",weight:.25,severity:.6,confidence:.5,evidence:{method:"localstorage_persistence",sessions:s}}}};var x=Object.freeze({JAILBREAK_DETECTED:1,DEBUGGER_ATTACHED:2,HOOKING_SUSPECTED:3,PROXY_CONFIGURED:4,VPN_SUSPECTED:5,SIMULATOR_IN_USE:6,AUTOMATION_ENVIRONMENT_DETECTED:7,AUTOMATION_TOUCH_PATTERN:8,DEVICE_CLOCK_MISMATCH:9,DEVTOOLS_OPEN:10,HEADLESS_BROWSER_DETECTED:11,AUTOMATION_POINTER_PATTERN:12,KEYBOARD_TOO_UNIFORM:13,PRIVATE_BROWSING_DETECTED:14,SESSION_NOT_PERSISTENT:15,HARDWARE_INCONSISTENCY:16}),y=Object.freeze({BLOCK_ALL_NETWORK:1,SHOW_WARNING:2,BLOCK_APP:3}),Lt=new Set(Object.values(x)),Dt=new Set(Object.values(y)),At=Object.freeze({devtools_open:x.DEVTOOLS_OPEN,headless_browser_detected:x.HEADLESS_BROWSER_DETECTED,automation_environment_detected:x.AUTOMATION_ENVIRONMENT_DETECTED,automation_pointer_pattern:x.AUTOMATION_POINTER_PATTERN,keyboard_too_uniform:x.KEYBOARD_TOO_UNIFORM,private_browsing_detected:x.PRIVATE_BROWSING_DETECTED,session_not_persistent:x.SESSION_NOT_PERSISTENT,hardware_inconsistency:x.HARDWARE_INCONSISTENCY});function Ve(n){return At[n]??null}function N(n){switch(n){case y.BLOCK_ALL_NETWORK:return"block_all_network";case y.SHOW_WARNING:return"show_warning";case y.BLOCK_APP:return"block_app";default:return null}}function We(n,e){let t=new Set(e??[]),i=Array.isArray(n?.rules)?n.rules:[];if(i.length===0||t.size===0)return Fe();let s=i.filter(l=>l?.enabled===!0).map(l=>{let a=(l.eventIds??[]).filter(u=>Lt.has(u)),c=(l.actionIds??[]).filter(u=>Dt.has(u));return{...l,eventIds:a,actionIds:c}}).filter(l=>{if(l.eventIds.length===0||l.actionIds.length===0)return!1;let a=String(l.matchType||"ANY").toUpperCase();return a==="ANY"?l.eventIds.some(c=>t.has(c)):a==="ALL"?l.eventIds.every(c=>t.has(c)):!1}).sort((l,a)=>(a.priority??0)-(l.priority??0));if(s.length===0)return Fe();let r=[...new Set(s.flatMap(l=>l.actionIds))],o=l=>s.map(a=>typeof a[l]=="string"?a[l].trim():"").find(Boolean)||null;return{matchedRules:s,actionIds:r,title:o("title"),message:o("message"),buttonText:o("buttonText")}}function Ke(n){return!n||n.actionIds.length===0?null:JSON.stringify({actions:[...n.actionIds].sort((e,t)=>e-t),rules:n.matchedRules.map(e=>e.priority??0)})}function Fe(){return{matchedRules:[],actionIds:[],title:null,message:null,buttonText:null}}function fe(n){let e=1;for(let t of n)e*=1-t.weight*t.severity*t.confidence;return Math.round(Math.min(100,Math.max(0,100*(1-e))))}function ze(n,e){return e?"collecting":n>=60?"automation_suspected":n>=30?"uncertain":"likely_human"}function _e(n){return n>=75?"critical":n>=50?"high":n>=25?"medium":"low"}function qe(n,e){return n>=75?"critical":n>=50||e>=60?"at_risk":n>=25||e>=30?"elevated":"safe"}var Nt=new Set(["headless_browser_detected","automation_environment_detected","automation_pointer_pattern","keyboard_too_uniform"]),Ct=new Set(["devtools_open","private_browsing_detected","session_not_persistent","hardware_inconsistency"]),Ot=3e4,Mt=3e3,je=8,Bt=3,L=class{constructor(e={}){let t=e??{};this._onThreatChanged=typeof t.onThreatChanged=="function"?t.onThreatChanged:null,this._onRiskEvent=typeof t.onRiskEvent=="function"?t.onRiskEvent:null,this._onPolicyChanged=typeof t.onPolicyChanged=="function"?t.onPolicyChanged:null,this._intervalMs=t.checkIntervalMs??Ot,this._botDetectionEnabled=t.botDetectionEnabled!==!1,this._otherRiskTypesEnabled=t.otherRiskTypesEnabled!==!1,this._riskPolicy=t.riskPolicy??{version:0,rules:[]},this._installed=!1,this._tornDown=!1,this._snapshot=null,this._lastPosture=null,this._lastReportedSignals=new Map,this._lastPolicySignature=null,this._installTime=null,this._devtoolsOpen=!1,this._stickyLabel=null,this._consecutiveNonSuspected=0,this._headless=new q,this._automation=new j,this._pointer=new G,this._keyboard=new $,this._hardware=new J,this._devtools=new X,this._devtoolsConsole=new Y,this._incognito=new Q,this._sessionPersistence=new Z,this._mousemoveHandler=null,this._keydownHandler=null,this._resizeHandler=null,this._timer=null,this._devtoolsProbeTimer=null}install(){if(!(this._installed||this._tornDown)&&(this._installed=!0,this._installTime=Date.now(),this._botDetectionEnabled&&typeof window<"u"&&typeof window.addEventListener=="function"&&(this._mousemoveHandler=e=>{try{let t=typeof performance<"u"?performance.now():Date.now();this._pointer.recordSample(e.clientX,e.clientY,t)}catch{}},window.addEventListener("mousemove",this._mousemoveHandler,{passive:!0})),this._botDetectionEnabled&&typeof document<"u"&&typeof document.addEventListener=="function"&&(this._keydownHandler=e=>{try{if(["Shift","Control","Alt","Meta"].includes(e.key))return;this._keyboard.recordTimestamp(typeof performance<"u"?performance.now():Date.now())}catch{}},document.addEventListener("keydown",this._keydownHandler,{passive:!0})),this._otherRiskTypesEnabled&&typeof window<"u"&&typeof window.addEventListener=="function"&&(this._resizeHandler=()=>{try{this._checkDevtools()}catch{}},window.addEventListener("resize",this._resizeHandler,{passive:!0})),this.evaluate(),this._otherRiskTypesEnabled&&this._checkDevtools(),this._timer=setInterval(()=>{try{this.evaluate()}catch{}},this._intervalMs),this._timer&&typeof this._timer.unref=="function"&&this._timer.unref(),h.DEVTOOLS_CONSOLE_PROBE_ENABLED&&this._otherRiskTypesEnabled&&typeof window<"u"&&typeof console<"u"&&typeof console.log=="function")){try{this._devtoolsConsole.probe(),this._checkDevtools()}catch{}this._devtoolsProbeTimer=setInterval(()=>{try{this._devtoolsConsole.probe(),this._checkDevtools()}catch{}},h.DEVTOOLS_PROBE_INTERVAL_MS),this._devtoolsProbeTimer&&typeof this._devtoolsProbeTimer.unref=="function"&&this._devtoolsProbeTimer.unref()}}_detectDevtoolsSignal(){return this._devtools.detect()||this._devtoolsConsole.detect()}_checkDevtools(){if(!this._installed||this._tornDown)return;let t=this._detectDevtoolsSignal()!==null;t&&!this._devtoolsOpen?(this._devtoolsOpen=!0,this.evaluate()):!t&&this._devtoolsOpen&&(this._devtoolsOpen=!1,this.evaluate())}teardown(){if(this._installed){if(this._tornDown=!0,this._timer!==null&&(clearInterval(this._timer),this._timer=null),this._devtoolsProbeTimer!==null&&(clearInterval(this._devtoolsProbeTimer),this._devtoolsProbeTimer=null),this._mousemoveHandler&&typeof window<"u"){try{window.removeEventListener("mousemove",this._mousemoveHandler)}catch{}this._mousemoveHandler=null}if(this._keydownHandler&&typeof document<"u"){try{document.removeEventListener("keydown",this._keydownHandler)}catch{}this._keydownHandler=null}if(this._resizeHandler&&typeof window<"u"){try{window.removeEventListener("resize",this._resizeHandler)}catch{}this._resizeHandler=null}}}evaluate(){if(!this._installed)return;let e=[...this._botDetectionEnabled?[this._headless.detect(),this._automation.detect(),this._pointer._samples.length>=je?this._pointer.detect():null,this._keyboard._timestamps.length>=6?this._keyboard.detect():null]:[],...this._otherRiskTypesEnabled?[this._hardware.detect(),this._detectDevtoolsSignal(),this._incognito.detect(),this._sessionPersistence.detect()]:[]].filter(Boolean),t=this._botDetectionEnabled?e.filter(_=>Nt.has(_.id)):[],i=this._otherRiskTypesEnabled?e.filter(_=>Ct.has(_.id)):[],s=fe(t),r=fe(i),o=this._installTime!=null?Date.now()-this._installTime:1/0,l=this._pointer._samples.length>=je,a=o<Mt&&!l&&e.length===0,c=this._botDetectionEnabled?ze(s,a):"disabled",u=_e(r),d=qe(r,s);this._botDetectionEnabled&&c==="automation_suspected"?(this._stickyLabel="automation_suspected",this._consecutiveNonSuspected=0):this._botDetectionEnabled&&this._stickyLabel==="automation_suspected"&&(this._consecutiveNonSuspected++,this._consecutiveNonSuspected<Bt?c="automation_suspected":(this._stickyLabel=null,this._consecutiveNonSuspected=0));let f={};for(let _ of e)for(let[m,S]of Object.entries(_.evidence??{}))f[`${_.id}.${m}`]=S;let p=i.map(_=>_.id);if((c==="automation_suspected"||c==="uncertain")&&p.push(c),p.length===0&&p.push(d==="safe"?"no_local_threats_detected":"local_heuristics_triggered"),this._snapshot={botScore:s,riskScore:r,label:c,riskLevel:u,posture:d,reasons:p,riskSignals:i.map(_=>_.id),botSignals:t.map(_=>_.id),evidence:f,timestamp:Date.now()},this._evaluatePolicy([...i,...t]),this._reportDetectedSignals(i,t),d!==this._lastPosture&&(this._lastPosture=d,this._onThreatChanged))try{this._onThreatChanged(this.getSessionThreat())}catch{}}_reportDetectedSignals(e,t){if(!this._onRiskEvent)return;let i=(s,r,o)=>{if(o==="bot"&&r<30||o==="risk"&&r<=0)return;let l=`${o}:${s.id}`;if(this._lastReportedSignals.get(l)!==r){this._lastReportedSignals.set(l,r);try{this._onRiskEvent({type:s.id,score:r,category:o,evidence:s.evidence??{},snapshot:this.getBotSnapshot()})}catch{}}};for(let s of e)i(s,this._snapshot.riskScore,"risk");for(let s of t)i(s,this._snapshot.botScore,"bot")}_evaluatePolicy(e){let t=e.map(r=>Ve(r.id)).filter(r=>r!==null),i=We(this._riskPolicy,t),s=Ke(i);if(s!==this._lastPolicySignature&&(this._lastPolicySignature=s,this._onPolicyChanged))try{this._onPolicyChanged(i)}catch{}}getBotSnapshot(){return this._installed?this._snapshot?{...this._snapshot}:{botScore:0,riskScore:0,label:"collecting",riskLevel:"low",posture:"safe",reasons:["no_local_threats_detected"],riskSignals:[],botSignals:[],evidence:{},timestamp:Date.now()}:null}getSessionThreat(){if(!this._installed)return null;let e=this.getBotSnapshot();return{botScore:e.botScore,botLabel:e.label,riskScore:e.riskScore,riskLevel:e.riskLevel,posture:e.posture,reasons:[...e.reasons],timestamp:e.timestamp}}};A(L,"_computeScore",fe),A(L,"_scoreToLabel",ze),A(L,"_scoreToRiskLevel",_e),A(L,"_scoresToPosture",qe),A(L,"_scoreToPosture",_e);var I=Object.freeze({ERROR:"ERROR",WARNING:"WARNING",INFO:"INFO",DEBUG:"DEBUG",CRASH:"CRASH",DEVICEINFO:"DEVICEINFO",NETWORK_ACTIVITY:"NETWORK_ACTIVITY",REMOTE_MESSAGE:"REMOTE_MESSAGE",EVENT:"EVENT"}),ee=Object.values(I),P=class{constructor(e,t,i=null){this.name=String(e||""),this.id=String(t||""),this.customAttributes=i||null}},Ht=/(^https?:\/\/([^/]+\.)?logdrop\.io(\/|$))/i,Ge="logdrop_init_cache",C="logdrop_token_recovery_identity",pe="logdrop_ip_reputation_active_action",ge="logdrop_ip_reputation_processed_signatures",te="logdrop_last_user_update",me="[REDACTED]",Ft=new Set(["accesstoken","refreshtoken","token","auth"]);function ye(){let n=new Date,e=u=>String(u).padStart(2,"0"),t=u=>String(u).padStart(3,"0"),i=n.getUTCFullYear(),s=e(n.getUTCMonth()+1),r=e(n.getUTCDate()),o=e(n.getUTCHours()),l=e(n.getUTCMinutes()),a=e(n.getUTCSeconds()),c=t(n.getUTCMilliseconds());return`${i}-${s}-${r} ${o}:${l}:${a}:${c}`}function Vt(n){try{return n instanceof Error?JSON.stringify({name:n.name,message:n.message,stack:n.stack}):JSON.stringify(n)}catch{return'"[unserializable]"'}}function g(){return typeof window<"u"}function $e(){return g()&&window.location&&typeof window.location.href=="string"?window.location.href:"http://localhost/"}function Wt(n){let t=String(n||"").trim().replace(/\/+$/,""),i=h.DEFAULT_BASE_URL,s=t||i;return s.endsWith("/api/v2/sdk")?s:s.endsWith("/api")?`${s}/v2/sdk`:`${s}/api/v2/sdk`}function Kt(n){let e=4294967295;for(let t=0;t<n.length;t+=1){let i=(e^n[t])&255;for(let s=0;s<8;s+=1)i=i&1?3988292384^i>>>1:i>>>1;e=e>>>8^i}return(e^4294967295)>>>0}function Je(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n).map(t=>t.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function zt(n){let t=(typeof n=="string"?n:"").trim().split(`
|
|
2
|
-
`),i=t[0]?t[0].trim():"",o=t.slice(1).filter(c=>/^\s*at /.test(c)||/@/.test(c)).slice(0,5).map(c=>{if(/^\s*at /.test(c)){let u=c.trim().match(/^at\s+([^\s(]+)/);return(u?u[1]:"").split("/").pop()||"anonymous"}else{let u=c.match(/^([^@]*)@/);return(u?u[1].trim():"").split("/").pop()||"anonymous"}}),l=i+":"+o.join(","),a=new TextEncoder().encode(l);return Kt(a)}function Xe(){return{url:typeof location<"u"&&location.href||"",referrer:typeof document<"u"&&document.referrer||"",visibilityState:typeof document<"u"&&document.visibilityState||"visible",onLine:typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0,viewportWidth:typeof window<"u"&&window.innerWidth||0,viewportHeight:typeof window<"u"&&window.innerHeight||0,heapUsed:typeof performance<"u"&&performance.memory?performance.memory.usedJSHeapSize:null}}var ie=class{constructor(){this._config=null,this._debugLogEnabled=!1,this._queue=[],this._flushTimer=null,this._fileFlushTimer=null,this._fileFlushInProgress=!1,this._crashFlushTimer=null,this._crashFlushDelayMs=5e3,this._crashFlushInProgress=!1,this._deviceInfoTimer=null,this._storageCheckTimer=null,this._dbPromise=null,this._initialized=!1,this._initResponse=null,this._tokenRecoveryPromise=null,this._tokenValidationState={logdrop_access_token:null,logdrop_refresh_token:null},this._sessionId=this._generateUUID(),this._sessionCreateDate=ye(),this._deviceId=this._getOrCreateDeviceId(),this._serverConfig={isSDKDisabled:!1,isHttpLoggingEnabled:!0,isCrashTrackingEnabled:!0,isEventTrackingEnabled:!1,riskConfig:null,webPushConfig:null},this._activeIpReputationAction=this._loadStoredIpReputationAction(),this._ipReputationExpiryTimer=null,this._loadCachedServerConfig(),this._user=this._loadPersistedExternalUser(),this._errorHandlersInstalled=!1,this._net=null,this._pushModule=null,this._inAppMessagePresenter=null,this.push=null,this._desiredWebPushSubscription=void 0,this._lastSentUserUpdate=this._loadLastSentUserUpdate(),this._activeUserUpdate=null,this._pendingUserUpdate=null,this._drainingUserUpdates=!1,this._eventModule=null,this._eventFlushTimer=null,this._riskModule=null,this._activeRiskPolicyEvaluation=null,this._riskPolicyOverlay=null,this._seenCrashes=new Set,this._crashTrackingOverride=null,this._originalFetch=null}_generateUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}_isInternalLoggingEnabled(){return this._debugLogEnabled===!0}_logInternal(...e){this._isInternalLoggingEnabled()&&console.log(...e)}_warnInternal(...e){this._isInternalLoggingEnabled()&&console.warn(...e)}_errorInternal(...e){this._isInternalLoggingEnabled()&&console.error(...e)}_getProtoHexPreview(e,t=64){if(!(e instanceof Uint8Array)||e.length===0)return"empty";let i=Array.from(e.slice(0,t)).map(s=>s.toString(16).padStart(2,"0")).join(" ");return e.length>t?`${i} ...`:i}_isSensitiveProtoFieldName(e){if(typeof e!="string"||e.length===0)return!1;let t=e.replace(/[^a-z0-9]/gi,"").toLowerCase();return Ft.has(t)}_summarizeProtoPayloadEntry(e,t=null){if(this._isSensitiveProtoFieldName(t))return{containsSensitiveData:!0,summary:me};if(e instanceof Uint8Array)return{containsSensitiveData:!1,summary:{byteLength:e.length,hexPreview:this._getProtoHexPreview(e)}};if(Array.isArray(e)){let i=!1,s=e.map(r=>{let o=this._summarizeProtoPayloadEntry(r);return i=i||o.containsSensitiveData,o.summary});return{containsSensitiveData:i,summary:s}}if(e&&typeof e=="object"){let i={},s=!1;for(let[r,o]of Object.entries(e)){let l=this._summarizeProtoPayloadEntry(o,r);i[r]=l.summary,s=s||l.containsSensitiveData}return{containsSensitiveData:s,summary:i}}return{containsSensitiveData:!1,summary:e}}_summarizeProtoPayload(e){return this._summarizeProtoPayloadEntry(e).summary}_debugLogProtoBody(e,t,i){if(!this._isInternalLoggingEnabled())return;let s=this._summarizeProtoPayloadEntry(t);this._logInternal(`[LogDrop DEBUG] ${e} payload:`,s.summary),this._logInternal(`[LogDrop DEBUG] ${e} protobuf bytes (${i.length} B): ${s.containsSensitiveData?me:this._getProtoHexPreview(i)}`)}_debugLogProtoResponse(e,t,i=null){if(!this._isInternalLoggingEnabled())return;if(!(t instanceof Uint8Array)||t.length===0){this._logInternal(`[LogDrop DEBUG] ${e} response body: empty`);return}let s=!1;if(typeof i=="function")try{let r=this._summarizeProtoPayloadEntry(i(t));s=r.containsSensitiveData,this._logInternal(`[LogDrop DEBUG] ${e} decoded response:`,r.summary)}catch(r){this._warnInternal(`[LogDrop DEBUG] ${e} response decode failed:`,r?.message||r)}this._logInternal(`[LogDrop DEBUG] ${e} response protobuf bytes (${t.length} B): ${s?me:this._getProtoHexPreview(t)}`)}_getOrCreateDeviceId(){if(this._isNewDevice=!1,!g()||typeof localStorage>"u")return this._isNewDevice=!0,this._generateUUID().replace(/-/g,"");let e="logdrop_device_id",t=localStorage.getItem(e),i=t?t.replace(/-/g,""):"";if(i.length===32){if(i!==t){t=i,this._isNewDevice=!0;try{localStorage.setItem(e,t),localStorage.removeItem("logdrop_access_token"),localStorage.removeItem("logdrop_refresh_token"),localStorage.removeItem(C),localStorage.removeItem(te)}catch{}}return t}t=this._generateUUID().replace(/-/g,""),this._isNewDevice=!0;try{localStorage.setItem(e,t),i&&(localStorage.removeItem("logdrop_access_token"),localStorage.removeItem("logdrop_refresh_token"),localStorage.removeItem(C),localStorage.removeItem(te))}catch{}return t}_getEffectiveUserUuid(){return this._user?.userUuid??this._deviceId}_loadPersistedExternalUser(){if(!g()||typeof localStorage>"u")return null;try{let e=localStorage.getItem("logdrop_external_user_uuid");return e?{userUuid:e}:null}catch{return null}}_persistExternalUser(e){if(!(!g()||typeof localStorage>"u"))try{localStorage.setItem("logdrop_external_user_uuid",e)}catch{}}_clearPersistedExternalUser(){if(!(!g()||typeof localStorage>"u"))try{localStorage.removeItem("logdrop_external_user_uuid")}catch{}}_isUserRegistered(){return!g()||typeof localStorage>"u"?!1:localStorage.getItem("logdrop_user_registered")==="true"}_markUserRegistered(){if(!(!g()||typeof localStorage>"u"))try{localStorage.setItem("logdrop_user_registered","true")}catch{}}_loadLastSentUserUpdate(){if(!g()||typeof localStorage>"u")return null;try{let e=localStorage.getItem(te);if(!e)return null;let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}_saveLastSentUserUpdate(e){if(this._lastSentUserUpdate=e,!(!g()||typeof localStorage>"u"))try{localStorage.setItem(te,JSON.stringify(e))}catch{}}_normalizeWebPushSubscription(e){if(e==null)return null;let t=e.keys||{},i=String(e.endpoint||"").trim(),s=String(t.p256dh||e.p256dh||"").trim(),r=String(t.auth||e.auth||"").trim();if(!i||!s||!r)return null;let o=Number(e.expirationTime);return{endpoint:i,p256dh:s,auth:r,expirationTime:Number.isSafeInteger(o)&&o>0?o:null}}_webPushSubscriptionFingerprint(e){return e==null?null:JSON.stringify(e)}_handleWebPushSubscriptionChanged(e){if(e==null)return this._desiredWebPushSubscription=null,Promise.resolve(!0);let t=this._normalizeWebPushSubscription(e);return t==null?(console.warn("[LogDrop] Ignoring invalid Web Push subscription"),Promise.resolve(!1)):(this._desiredWebPushSubscription=t,this._sendUserUpdate(this._getEffectiveUserUuid(),!!this._user,{reason:"web_push_subscription_changed"}))}_normalizeTokenValue(e){if(typeof e!="string")return null;let t=e.trim();return!t||t==="null"||t==="undefined"?null:t}_normalizeTokenRecoveryIdentity(e){if(!e||typeof e!="object")return null;let t=this._normalizeTokenValue(e.userUuid);return t?{userUuid:t,isExternalUser:e.isExternalUser===!0}:null}_getPersistedTokenRecoveryIdentity(){if(!g()||typeof localStorage>"u")return null;let e=localStorage.getItem(C);if(e==null)return null;try{let t=this._normalizeTokenRecoveryIdentity(JSON.parse(e));if(t)return t}catch{}try{localStorage.removeItem(C)}catch{}return null}_clearPersistedTokenRecoveryIdentity(){if(!(!g()||typeof localStorage>"u"))try{localStorage.removeItem(C)}catch{}}_clearStoredTokens(){if(!(!g()||typeof localStorage>"u"))try{localStorage.removeItem("logdrop_access_token"),localStorage.removeItem("logdrop_refresh_token"),this._clearPersistedTokenRecoveryIdentity(),this._tokenValidationState.logdrop_access_token=null,this._tokenValidationState.logdrop_refresh_token=null}catch(e){this._warnInternal("[LogDrop] Failed to clear stored auth state:",e?.message||e)}}_getTokenRecoveryTarget(){if(this._user?.userUuid)return{userUuid:this._user.userUuid,isExternalUser:!0};let e=this._getPersistedTokenRecoveryIdentity();return e||(this._deviceId?{userUuid:this._deviceId,isExternalUser:!1}:null)}async _recoverSessionTokens(e){if(!this._config)return this._warnInternal(`[LogDrop] ${e}; cannot recover tokens before init`),!1;if(!this._config.webSecretKey)return this._warnInternal(`[LogDrop] ${e}; cannot recover tokens without webSecretKey`),!1;let t=this._getTokenRecoveryTarget();if(!t)return this._warnInternal(`[LogDrop] ${e}; no recovery identity is available`),!1;if(this._tokenRecoveryPromise)return this._tokenRecoveryPromise;this._warnInternal(`[LogDrop] ${e}; attempting signature-based re-auth`),this._tokenRecoveryPromise=(async()=>{let i=await this._sendUserUpdate(t.userUuid,t.isExternalUser);return i||this._warnInternal("[LogDrop] Signature-based re-auth did not recover session tokens"),i})();try{return await this._tokenRecoveryPromise}finally{this._tokenRecoveryPromise=null}}_getStoredToken(e,t){if(!g()||typeof localStorage>"u")return null;let i=localStorage.getItem(e),s=this._normalizeTokenValue(i);if(s)return this._tokenValidationState[e]=null,s;let r=i==null?"missing":"invalid";if(i!=null)try{localStorage.removeItem(e)}catch{}return this._tokenValidationState[e]!==r&&(this._tokenValidationState[e]=r,this._warnInternal(`[LogDrop] Stored ${t} is ${r}; treating it as a deleted token`)),null}async _ensureSessionToken(e){let t=this._getAccessToken();return t||(await this._recoverSessionTokens(e)?(t=this._getAccessToken(),t||this._warnInternal(`[LogDrop] ${e}; re-auth succeeded but no access token was persisted`),t):null)}_getAccessToken(){return this._getStoredToken("logdrop_access_token","access token")}_getRefreshToken(){return this._getStoredToken("logdrop_refresh_token","refresh token")}_saveTokens(e,t,i=null){if(!g()||typeof localStorage>"u")return this._warnInternal("[LogDrop] Failed to persist session tokens: localStorage is unavailable"),!1;let s=this._normalizeTokenValue(e),r=this._normalizeTokenValue(t),o=this._normalizeTokenRecoveryIdentity(i||this._getTokenRecoveryTarget());if(!s&&!r)return this._warnInternal("[LogDrop] Failed to persist session tokens: no valid tokens were provided"),!1;try{return o?localStorage.setItem(C,JSON.stringify(o)):this._clearPersistedTokenRecoveryIdentity(),s&&(localStorage.setItem("logdrop_access_token",s),this._tokenValidationState.logdrop_access_token=null),r&&(localStorage.setItem("logdrop_refresh_token",r),this._tokenValidationState.logdrop_refresh_token=null),!0}catch(l){return this._warnInternal("[LogDrop] Failed to persist session tokens:",l?.message||l),!1}}async _computeSignature(e,t){let i=new TextEncoder().encode(e+t),s=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}_getOsInfo(){if(!g()||!navigator)return{osName:"Unknown",osVersion:"Unknown"};let e=navigator.userAgent,t="Unknown",i="Unknown";if(e.includes("Windows")){t="Windows";let s=e.match(/Windows NT (\d+\.\d+)/);s&&(i=s[1])}else if(e.includes("iPhone")||e.includes("iPad")){t="iOS";let s=e.match(/OS (\d+[._]\d+)/);s&&(i=s[1].replace(/_/g,"."))}else if(e.includes("Mac OS X")){t="macOS";let s=e.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);s&&(i=s[1].replace(/_/g,"."))}else if(e.includes("Android")){t="Android";let s=e.match(/Android (\d+(\.\d+)?)/);s&&(i=s[1])}else e.includes("Linux")&&(t="Linux");return{osName:t,osVersion:i}}_getDeviceBrand(){if(!g()||!navigator)return"Unknown";let e=navigator.userAgent;return e.includes("Samsung")?"Samsung":e.includes("Huawei")?"Huawei":e.includes("Xiaomi")||e.includes("Redmi")?"Xiaomi":e.includes("OPPO")?"OPPO":e.includes("Vivo")?"Vivo":e.includes("OnePlus")?"OnePlus":e.includes("LG")?"LG":e.includes("Sony")?"Sony":e.includes("HTC")?"HTC":e.includes("Motorola")?"Motorola":e.includes("Nokia")?"Nokia":e.includes("Google")||e.includes("Pixel")?"Google":e.includes("iPhone")||e.includes("iPad")||e.includes("Macintosh")?"Apple":e.includes("Chrome")?"Google":e.includes("Firefox")?"Mozilla":e.includes("Safari")?"Apple":e.includes("Edge")?"Microsoft":"Unknown"}_createUserUpdateTask(e,t,i={}){let s=this._desiredWebPushSubscription===void 0?void 0:this._normalizeWebPushSubscription(this._desiredWebPushSubscription),r={userUuid:String(e||this._deviceId),isExternalUser:t===!0,webPushSubscription:s,reason:i.reason||"user_update"};return{...r,key:JSON.stringify(r),waiters:[]}}_sendUserUpdate(e,t=!1,i={}){if(!this._config)return Promise.resolve(!1);let s=this._createUserUpdateTask(e,t,i);return new Promise(r=>{if(this._activeUserUpdate?.key===s.key){this._activeUserUpdate.waiters.push(r);return}this._pendingUserUpdate?.key===s.key?this._pendingUserUpdate.waiters.push(r):this._pendingUserUpdate?(s.waiters.push(...this._pendingUserUpdate.waiters,r),this._pendingUserUpdate=s):(s.waiters.push(r),this._pendingUserUpdate=s),this._drainUserUpdates()})}async _drainUserUpdates(){if(!this._drainingUserUpdates){this._drainingUserUpdates=!0;try{for(;this._pendingUserUpdate;){let e=this._pendingUserUpdate;this._pendingUserUpdate=null,this._activeUserUpdate=e;let t=!1;try{t=await this._performUserUpdate(e)}catch(i){console.warn("[LogDrop] User update failed:",i?.message||i)}for(let i of e.waiters)i(t);this._activeUserUpdate=null}}finally{this._activeUserUpdate=null,this._drainingUserUpdates=!1,this._pendingUserUpdate&&this._drainUserUpdates()}}}async _performUserUpdate(e){let t=this._config;if(!t)return!1;let i=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof i!="function")return!1;let s=this._getOsInfo(),r=this._lastSentUserUpdate?.apiKey===t.apiKey?this._lastSentUserUpdate:null,o={apiKey:t.apiKey,userUuid:e.userUuid,osName:s.osName,osVersion:s.osVersion,deviceBrand:this._getDeviceBrand(),deviceModel:this._parseDeviceModel(navigator?.userAgent||"")||"Web Browser",appVersion:t.release||"1.0",sdkVersion:h.SDK_VERSION,webPushFingerprint:e.webPushSubscription===void 0?r?.webPushFingerprint:this._webPushSubscriptionFingerprint(e.webPushSubscription)},l={deviceUuid:this._deviceId,sdkType:"WEB"},a=["osName","osVersion","deviceBrand","deviceModel","appVersion","sdkVersion"];for(let w of a)(!r||o[w]!==r[w])&&(l[w]=o[w]);let c=e.webPushSubscription!==void 0&&(!r||o.webPushFingerprint!==r.webPushFingerprint);e.webPushSubscription&&c&&(l.webPushSubscription=e.webPushSubscription);let u=!r||o.userUuid!==r.userUuid,d=Object.keys(l).some(w=>!["deviceUuid","sdkType"].includes(w)),f=this._getAccessToken(),p=this._getRefreshToken();if(!u&&!d&&f&&p)return this._logInternal(`[LogDrop] User update skipped; no changes (${e.reason})`),!0;let _={"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":t.apiKey},m=!1;if(f)_["x-session-token"]=f;else if(t.webSecretKey)_["x-logdrop-signature"]=await this._computeSignature(t.webSecretKey,this._deviceId),m=!0;else return!1;let S={userUuid:e.userUuid,device:l},k=Re(S);this._debugLogProtoBody("User update request",S,k);try{if(this._config!==t)return!1;let w=`${t.baseUrl}${h.USERS_UPDATE_PATH}`,R=await i(w,{method:"POST",headers:_,body:new Blob([k],{type:"application/x-protobuf"})});if(!R.ok||this._config!==t)return!1;if(m)try{let U=new Uint8Array(await R.arrayBuffer());if(this._debugLogProtoResponse("User update",U,ce),U.length>0){let b=ce(U);this._saveTokens(b.accessToken,b.refreshToken,{userUuid:e.userUuid,isExternalUser:e.isExternalUser})}}catch{}return this._saveLastSentUserUpdate(o),e.isExternalUser||this._markUserRegistered(),this._logInternal(`[LogDrop] User update successful (${e.reason})`),m&&this._desiredWebPushSubscription===void 0&&this._pushModule?.reconcileGrantedSubscription(),!0}catch(w){return console.warn("[LogDrop] User update failed:",w.message||w),this._warnInternal("[LogDrop] User update failed:",w.message||w),!1}}async _getDeviceInfo(){let e={sessionID:this._sessionId,session_create_date:this._sessionCreateDate,device_id:this._deviceId,userUuid:this._getEffectiveUserUuid(),gmt:-new Date().getTimezoneOffset()};if(this._riskModule){let t=this._riskModule.getBotSnapshot();t&&(e.bot_score=t.botScore,e.bot_label=t.label,e.risk_score=t.riskScore,e.posture=t.posture)}if(g()&&navigator){if(navigator.language&&(e.locale=navigator.language),typeof navigator.onLine=="boolean"&&(e.network_available=navigator.onLine),navigator.deviceMemory&&(e.ram_size=`${navigator.deviceMemory} GB`),navigator.hardwareConcurrency&&(e.cpu_cores=navigator.hardwareConcurrency),navigator.platform&&(e.os_version=navigator.platform),navigator.userAgent){e.user_agent=navigator.userAgent;let t=this._parseDeviceModel(navigator.userAgent);t&&(e.device_model=t)}navigator.connection&&(navigator.connection.effectiveType&&(e.connection_type=navigator.connection.effectiveType),typeof navigator.connection.downlink=="number"&&(e.connection_downlink_mbps=navigator.connection.downlink),typeof navigator.connection.rtt=="number"&&(e.connection_rtt_ms=navigator.connection.rtt),typeof navigator.connection.saveData=="boolean"&&(e.save_data_mode=navigator.connection.saveData));try{if(navigator.getBattery){let t=await navigator.getBattery();typeof t.level=="number"&&(e.battery_level=`${Math.round(t.level*100)}%`),typeof t.charging=="boolean"&&(e.low_power_mode=!t.charging&&t.level<.2,e.is_charging=t.charging)}}catch{}try{if(navigator.storage&&navigator.storage.estimate){let t=await navigator.storage.estimate();if(t.quota&&t.usage){let i=t.quota-t.usage;e.free_disk_space=this._formatBytes(i),e.total_disk_quota=this._formatBytes(t.quota)}}}catch{}}return g()&&window.screen&&(e.screen_width=window.screen.width,e.screen_height=window.screen.height,e.screen_color_depth=window.screen.colorDepth,window.devicePixelRatio&&(e.device_pixel_ratio=window.devicePixelRatio)),g()&&document.visibilityState&&(e.visibility_state=document.visibilityState),g()&&window.location&&(e.page_url=window.location.href,document.referrer&&(e.referrer=document.referrer)),this._config&&this._config.release&&(e.app_version=this._config.release),e}_getUserAgentData(){if(!g()||!navigator)return null;let e=navigator.userAgentData;return!e||typeof e!="object"?null:e}_parseDeviceModel(e){if(!g()||!navigator)return null;let t=this._getUserAgentData();if(t&&typeof t.model=="string"&&t.model.trim())return t.model.trim();let i=e.match(/\(([^)]+)\)/);if(i){let a=i[1].split(";").map(u=>u.trim()),c=a.find(u=>/^(SM-|Pixel|Nexus|LG-|HTC|Huawei|Xiaomi|OPPO|Vivo|OnePlus)/i.test(u));if(c)return c;if(a.some(u=>u.includes("iPhone")))return"iPhone";if(a.some(u=>u.includes("iPad")))return"iPad"}let s=this._getOsInfo(),r=this._getBrowserInfo(),o=`${s.osName} ${s.osVersion}`.trim(),l=`${r.name} ${r.version}`.trim();return`${o} - ${l}`.trim()}_getBrowserInfo(){if(!g()||!navigator)return{name:"Unknown",version:"Unknown"};let e=this._getUserAgentData();if(e&&Array.isArray(e.brands)){let l=e.brands.find(a=>/Chrome/i.test(a.brand))||e.brands.find(a=>/Chromium/i.test(a.brand))||e.brands[0];return{name:l?.brand||"Unknown",version:l?.version||"Unknown"}}let t=navigator.userAgent,i=t.match(/Edg\/(\d+)/);if(i)return{name:"Edge",version:i[1]};let s=t.match(/Chrome\/(\d+)/);if(s)return{name:"Chrome",version:s[1]};let r=t.match(/Firefox\/(\d+)/);if(r)return{name:"Firefox",version:r[1]};let o=t.match(/Version\/(\d+).+Safari/);return o&&!t.includes("Chrome")?{name:"Safari",version:o[1]}:{name:"Unknown",version:"Unknown"}}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB","TB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+i[s]}_scheduleDeviceInfoCollection(){this._deviceInfoTimer&&clearInterval(this._deviceInfoTimer),this._collectAndLogDeviceInfo(),this._deviceInfoTimer=setInterval(()=>{this._collectAndLogDeviceInfo()},h.DEVICE_INFO_INTERVAL_MS),this._deviceInfoTimer&&typeof this._deviceInfoTimer.unref=="function"&&this._deviceInfoTimer.unref()}async _collectAndLogDeviceInfo(){if(this._config)try{let e=await this._getDeviceInfo();this._enqueue(I.DEVICEINFO,e)}catch{}}_loadCachedServerConfig(){if(!(!g()||typeof localStorage>"u"))try{let e=localStorage.getItem(Ge);if(e){let t=JSON.parse(e);t&&t.data&&typeof t.data.isSDKDisabled=="boolean"&&(this._serverConfig.isSDKDisabled=t.data.isSDKDisabled)}}catch{}}_saveServerConfigToCache(e){if(!(!g()||typeof localStorage>"u"))try{localStorage.setItem(Ge,JSON.stringify(e))}catch{}}_applyServerConfig(e,t=!1){if(!e)return;let i=this._serverConfig.isHttpLoggingEnabled;if(typeof e.isSDKDisabled=="boolean"&&(this._serverConfig.isSDKDisabled=e.isSDKDisabled),typeof e.isHttpLoggingEnabled=="boolean"&&(this._serverConfig.isHttpLoggingEnabled=e.isHttpLoggingEnabled),typeof e.isCrashTrackingEnabled=="boolean"&&this._crashTrackingOverride===null&&(this._serverConfig.isCrashTrackingEnabled=e.isCrashTrackingEnabled),this._pushModule&&typeof e.isPushEnabled=="boolean"&&(this._pushModule.isPushEnabled=e.isPushEnabled),typeof e.isEventTrackingEnabled=="boolean"&&(this._serverConfig.isEventTrackingEnabled=e.isEventTrackingEnabled,this._eventModule?.setEnabled(e.isEventTrackingEnabled)),e.riskConfig&&typeof e.riskConfig=="object"&&(this._serverConfig.riskConfig=e.riskConfig),e.webPushConfig&&typeof e.webPushConfig=="object"&&(this._serverConfig.webPushConfig=e.webPushConfig,this._pushModule&&this._pushModule.updateServerConfig({isPushEnabled:e.webPushConfig.enabled===!0,vapidPublicKey:e.webPushConfig.vapidPublicKey||null})),this._serverConfig.isSDKDisabled&&this._initialized){this._warnInternal("[LogDrop] SDK disabled by server, clearing all logs and shutting down"),this._clearLogs().catch(()=>{}),this._initialized=!1,this._config=null,this.teardown();return}e.riskConfig&&typeof e.riskConfig=="object"&&this._syncRiskModuleFromServerConfig(),Object.prototype.hasOwnProperty.call(e,"activeIpReputationAction")&&this._applyIpReputationActionFromInit(e.activeIpReputationAction,e.serverNowEpochMillis),t&&this._config&&(this._serverConfig.isHttpLoggingEnabled&&!i?this._installNetworkInstrumentation():!this._serverConfig.isHttpLoggingEnabled&&i&&(this._logInternal("[LogDrop] HTTP logging disabled by server, clearing network logs"),this._uninstallNetworkInstrumentation(),this._clearNetworkLogs()),this._activeRiskPolicyEvaluation?.actionIds?.includes(y.BLOCK_ALL_NETWORK)&&this._refreshNetworkInstrumentationForRiskPolicy())}_installNetworkInstrumentation(e=!1){!this._config||this._net||(this._net=new V({onEvent:(t,i)=>{t==="network_activity"&&(!this._serverConfig.isHttpLoggingEnabled||!this._config?.network?.enabled||this._enqueue(I.NETWORK_ACTIVITY,i,new P("NetworkActivity",i.uuid)))},getBaseHref:$e,excludeUrls:this._config.network.excludeUrls,shouldBlockRequest:t=>this._shouldBlockNetworkRequest(t),redaction:{stripQuery:this._config.network.stripQuery,stripHash:this._config.network.stripHash},sampling:{rate:this._config.network.sampleRate,onlyErrors:this._config.network.onlyErrors,slowThresholdMs:this._config.network.slowThresholdMs},capture:{fetch:e||this._config.network.captureFetch,xhr:e||this._config.network.captureXHR,headersAllowlist:this._config.network.headersAllowlist}}),this._net.install())}_uninstallNetworkInstrumentation(){this._net&&(this._net.uninstall(),this._net=null)}_shouldBlockNetworkRequest(e){let t=this._activeRiskPolicyEvaluation?.actionIds?.includes(y.BLOCK_ALL_NETWORK)===!0,i=this._getActiveIpReputationAction()?.actionIds?.includes(y.BLOCK_ALL_NETWORK)===!0;if(!t&&!i)return!1;try{let s=new URL(e,$e()),r=new URL(this._config?.baseUrl??h.DEFAULT_BASE_URL);if(s.origin.toLowerCase()!==r.origin.toLowerCase())return!0;let o=r.pathname.replace(/\/+$/,""),l=s.pathname.replace(/\/+$/,"");return!(l===o||l.startsWith(`${o}/`))}catch{return!0}}_loadStoredIpReputationAction(){if(!g()||typeof localStorage>"u")return null;try{let e=localStorage.getItem(pe),t=e?JSON.parse(e):null;return t&&typeof t.signature=="string"&&t.signature?t:null}catch{return null}}_persistIpReputationAction(e){if(!(!g()||typeof localStorage>"u"))try{e?localStorage.setItem(pe,JSON.stringify(e)):localStorage.removeItem(pe)}catch{}}_trustedNowForIpReputation(e){let t=Number(e?.receivedServerEpochMillis),i=Number(e?.receivedAtClientEpochMillis),s=Number(e?.receivedAtMonotonicMillis),r=Number(e?.receivedPerformanceTimeOrigin),o=typeof performance<"u"?Number(performance.now?.()):NaN,l=typeof performance<"u"?Number(performance.timeOrigin):NaN;return Number.isFinite(t)&&t>0&&Number.isFinite(s)&&Number.isFinite(o)&&Number.isFinite(r)&&r===l?t+Math.max(0,o-s):Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0?t+Math.max(0,Date.now()-i):Date.now()}_isIpReputationActionExpired(e){let t=Number(e?.expireAtEpochMillis);return!Number.isFinite(t)||t<=this._trustedNowForIpReputation(e)}_getActiveIpReputationAction(){let e=this._activeIpReputationAction;return e?this._isIpReputationActionExpired(e)?(this._clearIpReputationAction("expired"),null):e:null}_resolveIpReputationPresentation(e){let i=(this._serverConfig.riskConfig?.ipReputationDetected?.riskPolicy?.rules??[]).filter(s=>s?.enabled===!0&&(s.threatLevels??[]).includes(e.threatLevel)).sort((s,r)=>(r.priority??0)-(s.priority??0))[0];return{...e,title:e.title||i?.title||null,message:e.message||i?.message||null,buttonText:e.buttonText||i?.buttonText||null}}_hasProcessedIpReputationSignature(e){if(!g()||typeof localStorage>"u")return!1;try{let t=JSON.parse(localStorage.getItem(ge)||"[]");return Array.isArray(t)&&t.includes(e)}catch{return!1}}_markIpReputationSignatureProcessed(e){if(!(!g()||typeof localStorage>"u"||!e))try{let t=JSON.parse(localStorage.getItem(ge)||"[]"),s=[...(Array.isArray(t)?t.filter(r=>typeof r=="string"):[]).filter(r=>r!==e),e].slice(-100);localStorage.setItem(ge,JSON.stringify(s))}catch{}}_scheduleIpReputationExpiry(){this._ipReputationExpiryTimer&&clearTimeout(this._ipReputationExpiryTimer),this._ipReputationExpiryTimer=null;let e=this._activeIpReputationAction;if(!e)return;let t=Number(e.expireAtEpochMillis)-this._trustedNowForIpReputation(e);if(t<=0){this._clearIpReputationAction("expired");return}this._ipReputationExpiryTimer=setTimeout(()=>this._scheduleIpReputationExpiry(),Math.min(t,2147e6)),typeof this._ipReputationExpiryTimer?.unref=="function"&&this._ipReputationExpiryTimer.unref()}_applyIpReputationActionFromInit(e,t){if(!e||typeof e.signature!="string"||!e.signature.trim()){this._clearIpReputationAction("cleared");return}let i=Date.now(),s=this._resolveIpReputationPresentation({...e,signature:e.signature.trim(),eventId:String(e.eventId||e.signature),actionIds:[...new Set((e.actionIds??[]).filter(o=>N(o)))],receivedServerEpochMillis:Number(t)||i,receivedAtClientEpochMillis:i,receivedAtMonotonicMillis:typeof performance<"u"?Number(performance.now?.()):null,receivedPerformanceTimeOrigin:typeof performance<"u"?Number(performance.timeOrigin):null});if(this._isIpReputationActionExpired(s)){this._clearIpReputationAction("expired");return}let r=!this._hasProcessedIpReputationSignature(s.signature);this._activeIpReputationAction=s,this._persistIpReputationAction(s),this._markIpReputationSignatureProcessed(s.signature),this._scheduleIpReputationExpiry(),this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation,r)}_restoreIpReputationActionIfNeeded(){this._getActiveIpReputationAction()&&(this._scheduleIpReputationExpiry(),this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation,!1))}_clearIpReputationAction(e="cleared"){let t=this._activeIpReputationAction;if(this._ipReputationExpiryTimer&&clearTimeout(this._ipReputationExpiryTimer),this._ipReputationExpiryTimer=null,this._activeIpReputationAction=null,this._persistIpReputationAction(null),t&&this._eventModule){let i=t.actionIds??[];this._eventModule.trackEvent(h.EVENT_CODES.SDK_ACTION_CLEARED,{as:"ip_reputation",cr:e,bl:i.includes(y.BLOCK_APP)||i.includes(y.BLOCK_ALL_NETWORK),sig:t.signature,saa:i.map(N).filter(Boolean).join(",")||"none"}),Promise.resolve(this._eventModule._flush()).catch(()=>{})}this._config&&(this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation))}_syncRiskModuleFromServerConfig(){let e=this._serverConfig.riskConfig?.riskDetected,t=e?.enabled===!0&&(e.botDetectionEnabled===!0||e.otherRiskTypesEnabled===!0);this._riskModule?.teardown(),this._riskModule=null,this._activeRiskPolicyEvaluation?this._handleRiskPolicyChanged({matchedRules:[],actionIds:[],title:null,message:null,buttonText:null}):(this._activeRiskPolicyEvaluation=null,this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(null)),!(!t||!this._initialized||!this._config)&&(this._riskModule=new L({botDetectionEnabled:e.botDetectionEnabled===!0,otherRiskTypesEnabled:e.otherRiskTypesEnabled===!0,riskPolicy:e.riskPolicy,onThreatChanged:this._config.onSessionThreatChanged??null,onRiskEvent:i=>this._handleRiskEvent(i),onPolicyChanged:i=>this._handleRiskPolicyChanged(i),checkIntervalMs:3e4}),this._riskModule.install())}init(e){if(this._debugLogEnabled=e?.debugLogEnabled===!0||e?.isDebugLogEnabled===!0,this._initialized)return;if(this._serverConfig.isSDKDisabled){this._warnInternal("[LogDrop] SDK is disabled by server configuration");return}if(!e||!e.appId)throw new Error("LogDrop.init requires config.appId");let t=String(e.apiKey||"").trim();if(!t)throw new Error("LogDrop.init requires config.apiKey");let i=e.webSecretKey==null?h.DEFAULT_WEB_SECRET_KEY:e.webSecretKey,s=String(i||"").trim()||null,r=Wt(e.baseUrl),o=r,l={enabled:e.network?.enabled!==!1,captureFetch:e.network?.captureFetch!==!1,captureXHR:e.network?.captureXHR!==!1,stripQuery:e.network?.stripQuery!==!1,stripHash:e.network?.stripHash!==!1,sampleRate:typeof e.network?.sampleRate=="number"?e.network.sampleRate:1,onlyErrors:e.network?.onlyErrors===!0,slowThresholdMs:typeof e.network?.slowThresholdMs=="number"?e.network.slowThresholdMs:void 0,headersAllowlist:Array.isArray(e.network?.headersAllowlist)?e.network.headersAllowlist:[],excludeUrls:[Ht,r,o,h.DEFAULT_BASE_URL,...Array.isArray(e.network?.excludeUrls)?e.network.excludeUrls:[]]};this._config={appId:String(e.appId),apiKey:t,webSecretKey:s,baseUrl:r,endpoint:o,env:e.env?String(e.env):"prod",release:e.release?String(e.release):void 0,debugLogEnabled:this._debugLogEnabled,flushIntervalMs:typeof e.flushIntervalMs=="number"?e.flushIntervalMs:6e4,maxBatchSize:typeof e.maxBatchSize=="number"?e.maxBatchSize:50,network:l,vapidPublicKey:e.vapidPublicKey?String(e.vapidPublicKey):null,manualServiceWorkerRegistration:e.manualServiceWorkerRegistration===!0,serviceWorkerUrl:e.serviceWorkerUrl?String(e.serviceWorkerUrl):h.PUSH_SW_PATH,serviceWorkerScope:e.serviceWorkerScope?String(e.serviceWorkerScope):h.PUSH_SW_SCOPE,serviceWorkerRegistration:e.serviceWorkerRegistration??null,onRemoteMessageReceived:typeof e.onRemoteMessageReceived=="function"?e.onRemoteMessageReceived:null,onSessionThreatChanged:typeof e.onSessionThreatChanged=="function"?e.onSessionThreatChanged:null,onRiskPolicyActionTaken:typeof e.onRiskPolicyActionTaken=="function"?e.onRiskPolicyActionTaken:null},typeof e.crashTracking=="boolean"?(this._serverConfig.isCrashTrackingEnabled=e.crashTracking,this._crashTrackingOverride=e.crashTracking):this._crashTrackingOverride=null,h.DEBUG_LOGS_ENABLED=!["prod","production"].includes(this._config.env),this._installGlobalErrorHandlers(),this._initDb(),this._inAppMessagePresenter=new K({onAction:d=>this._handleWebPushClick(d)}),this._pushModule=new W({vapidPublicKey:this._config.vapidPublicKey,manualServiceWorkerRegistration:this._config.manualServiceWorkerRegistration,serviceWorkerUrl:this._config.serviceWorkerUrl,serviceWorkerScope:this._config.serviceWorkerScope,serviceWorkerRegistration:this._config.serviceWorkerRegistration,isPushEnabled:!0,onRemoteMessageReceived:this._config.onRemoteMessageReceived,apiKey:this._config.apiKey,apiBase:this._config.baseUrl,deviceId:this._deviceId,getSessionToken:()=>this._getAccessToken(),onPushReceived:d=>this._handleWebPushReceived(d),onNotificationClick:d=>this._handleWebPushClick(d),onSubscriptionChanged:d=>this._handleWebPushSubscriptionChanged(d)}),this._pushModule.install(),this.push={subscribe:()=>this._pushModule.subscribe(),unsubscribe:()=>this._pushModule.unsubscribe(),getPermissionState:()=>this._pushModule.getPermissionState()};let a=g()&&localStorage?localStorage.getItem("logdrop_last_release"):null,c=!!(this._config.release&&a&&this._config.release!==a),u=a;if(this._config.release&&g()&&localStorage)try{localStorage.setItem("logdrop_last_release",this._config.release)}catch{}this._eventModule=new z({deviceId:this._deviceId,getSessionId:()=>this._sessionId,getUserUuid:()=>this._getEffectiveUserUuid(),getRealUserUuid:()=>this._user?.userUuid??null,getSessionToken:()=>this._ensureSessionToken("Event upload requires a valid access token"),logEvent:d=>this._enqueue(I.EVENT,d),release:this._config.release,apiKey:this._config.apiKey,apiBase:this._config.baseUrl,isEventTrackingEnabled:this._serverConfig.isEventTrackingEnabled,isFirstVisit:this._isNewDevice,isSdkUpdated:c,previousRelease:u,dbPromise:this._dbPromise}),this._eventModule.install(),this._pushModule?.requestPendingMessages(),this._scheduleEventFlush(),this._initialized=!0,this._sendInitRequest(),this._uninstallNetworkInstrumentation(),this._config.network.enabled&&this._serverConfig.isHttpLoggingEnabled&&this._installNetworkInstrumentation(),this._restoreIpReputationActionIfNeeded(),this._scheduleFlush(),this._scheduleFileFlush(),this._scheduleDeviceInfoCollection(),this._scheduleStorageCheck(),this.i("LogDrop initialized",{appId:this._config.appId,env:this._config.env,release:this._config.release,networkEnabled:this._config.network.enabled})}async updateUser(e,t){if(!e){this._user=null,this._clearPersistedExternalUser(),this._clearStoredTokens(),this.i("User cleared"),typeof t=="function"&&t(!0);return}let i=String(e);this._user?.userUuid&&this._user.userUuid!==i&&(this._sessionId=this._generateUUID(),this._sessionCreateDate=ye()),this._user={userUuid:i},this._persistExternalUser(i);let s=await this._sendUserUpdate(i,!0,{reason:"developer_user_update"});this.i("User updated",{userUuid:i,success:s}),typeof t=="function"&&t(s)}e(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!ee.includes(e);this._enqueue(I.ERROR,s?t:e,s?i:t instanceof P?t:null,s?e:null)}w(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!ee.includes(e);this._enqueue(I.WARNING,s?t:e,s?i:t instanceof P?t:null,s?e:null)}i(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!ee.includes(e);this._enqueue(I.INFO,s?t:e,s?i:t instanceof P?t:null,s?e:null)}d(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!ee.includes(e);this._enqueue(I.DEBUG,s?t:e,s?i:t instanceof P?t:null,s?e:null)}log(e,t,i,s=null){this._enqueue(i,t,s,e)}onRemoteMessageReceived(e){this._config&&typeof this._config.onRemoteMessageReceived=="function"&&this._config.onRemoteMessageReceived(e)}saveCustomCrashReport(e,t,i="CUSTOM"){this._serverConfig.isCrashTrackingEnabled&&this._recordCrash({threadName:e||"MainThread",stackTrace:String(t||""),crashType:i||"CUSTOM",isCustomCrash:!0})}_handleRiskEvent(e){if(!this._config||!e||!this._eventModule)return;let t=e.score??e.snapshot?.riskScore??e.snapshot?.score??0,i=this._activeRiskPolicyEvaluation?.actionIds??[],s=i.map(N).filter(Boolean),r=i.includes(y.BLOCK_APP)||i.includes(y.BLOCK_ALL_NETWORK);this._eventModule.trackEvent(h.EVENT_CODES.RISK_DETECTED,{rt:e.type,rs:t,bl:r,ev:e.evidence??{},saa:s.join(",")||"none"}),Promise.resolve(this._eventModule._flush()).catch(()=>{})}_webPushData(e){return!e||typeof e!="object"?{}:e.data&&typeof e.data=="object"?e.data:e}_handleWebPushReceived(e){let t=this._webPushData(e),i=typeof t.action=="string"?t.action:t.rawExtras?.action,s=String(t.notificationId||t.receiveEvent?.properties?.pn||"").trim();if(s&&this._eventModule&&(this._eventModule.trackEvent(h.EVENT_CODES.PUSH_RECEIVED,{pn:s}),Promise.resolve(this._eventModule._flush()).catch(()=>{})),this._inAppMessagePresenter?.enqueue(e),i==="ip_reputation_action"?this._applyIpReputationActionFromInit({signature:t.signature||"",eventId:t.eventId||t.signature||"",threatLevel:t.threatLevel||"UNSPECIFIED",riskScore:Number(t.riskScore)||0,actionIds:String(t.actionIds||"").split(",").map(r=>Number(r.trim())).filter(Number.isInteger),expireAtEpochMillis:Number(t.expireAt)||0,title:t.title||null,message:t.message||null,buttonText:t.buttonText||null},Number(t.serverNow)||Date.now()):i==="send_log"&&(this.sendLogs().catch(()=>{}),Promise.resolve(this._eventModule?._flush()).catch(()=>{})),typeof this._config?.onRemoteMessageReceived=="function")try{this._config.onRemoteMessageReceived(e)}catch{}}_handleWebPushClick(e){let t=this._webPushData(e),i=String(t.notificationId||t.clickEvent?.properties?.pn||"").trim();if(i&&this._eventModule&&(this._eventModule.trackEvent(h.EVENT_CODES.PUSH_CLICK,{pn:i}),Promise.resolve(this._eventModule._flush()).catch(()=>{})),typeof this._config?.onRemoteMessageReceived=="function")try{this._config.onRemoteMessageReceived(e)}catch{}}_handleRiskPolicyChanged(e){let t=this._activeRiskPolicyEvaluation;if(this._activeRiskPolicyEvaluation=e?.actionIds?.length?e:null,t&&!this._activeRiskPolicyEvaluation&&this._eventModule){let s=t.actionIds.map(N).filter(Boolean);this._eventModule.trackEvent(h.EVENT_CODES.SDK_ACTION_CLEARED,{as:"risk_detected",cr:"cleared",bl:t.actionIds.includes(y.BLOCK_APP)||t.actionIds.includes(y.BLOCK_ALL_NETWORK),saa:s.join(",")||"none"}),Promise.resolve(this._eventModule._flush()).catch(()=>{})}if(this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation),!this._activeRiskPolicyEvaluation||!this._config?.onRiskPolicyActionTaken)return;let i=[...new Set(e.matchedRules.flatMap(s=>s.eventIds??[]))];try{this._config.onRiskPolicyActionTaken({actionIds:[...e.actionIds],actionNames:e.actionIds.map(N).filter(Boolean),matchedEventIds:i,matchedRulePriorities:e.matchedRules.map(s=>s.priority??0),title:e.title,message:e.message,buttonText:e.buttonText})}catch{}}_refreshNetworkInstrumentationForRiskPolicy(){if(!this._config)return;let e=this._activeRiskPolicyEvaluation?.actionIds?.includes(y.BLOCK_ALL_NETWORK)===!0,t=this._getActiveIpReputationAction()?.actionIds?.includes(y.BLOCK_ALL_NETWORK)===!0,i=e||t,s=this._config.network?.enabled===!0&&this._serverConfig.isHttpLoggingEnabled;this._uninstallNetworkInstrumentation(),(s||i)&&this._installNetworkInstrumentation(i)}_applyRiskPolicyUi(e,t=!1){if(this._riskPolicyOverlay?.parentNode)try{this._riskPolicyOverlay.parentNode.removeChild(this._riskPolicyOverlay)}catch{}this._riskPolicyOverlay=null;let i=this._activeIpReputationAction,s=i?.actionIds?.includes(y.BLOCK_APP)===!0,r=e?.actionIds?.includes(y.BLOCK_APP)===!0;if((s||!r&&t&&i?.actionIds?.includes(y.SHOW_WARNING))&&(e=i),!e||typeof document>"u"||!document.body||typeof document.createElement!="function")return;let o=e.actionIds.includes(y.BLOCK_APP),l=e.actionIds.includes(y.SHOW_WARNING);if(!o&&!l)return;let a=document.createElement("div");a.setAttribute("role","alertdialog"),a.setAttribute("aria-modal","true"),a.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:24px","background:rgba(15,23,42,.72)","font-family:system-ui,sans-serif"].join(";");let c=document.createElement("div");c.style.cssText="max-width:520px;width:100%;background:white;border-radius:12px;padding:24px;box-shadow:0 24px 64px rgba(0,0,0,.35);color:#111827";let u=document.createElement("h2");u.textContent=e.title||(o?"Security block":"Security warning"),u.style.cssText="margin:0 0 12px;font-size:20px";let d=document.createElement("p");if(d.textContent=e.message||"A security risk was detected.",d.style.cssText="margin:0;line-height:1.5",c.append(u,d),!o){let f=document.createElement("button");f.type="button",f.textContent=e.buttonText||"OK",f.style.cssText="margin-top:20px;padding:9px 16px;border:0;border-radius:8px;background:#111827;color:white;cursor:pointer",f.addEventListener("click",()=>{try{a.remove()}catch{}this._riskPolicyOverlay===a&&(this._riskPolicyOverlay=null)},{once:!0}),c.appendChild(f)}a.appendChild(c),document.body.appendChild(a),this._riskPolicyOverlay=a}getBotSnapshot(){return this._riskModule?.getBotSnapshot()??null}refreshBotSnapshot(){return this._riskModule?.evaluate(),this._riskModule?.getBotSnapshot()??null}getSessionThreat(){return this._riskModule?.getSessionThreat()??null}async sendLogs(e){if(!this._config){typeof e=="function"&&e(!1);return}let[t,i]=await Promise.all([this._flushLogs(),this._flushCrashes()]);typeof e=="function"&&e(t&&i)}_enqueue(e,t,i=null,s=null){if(!this._config)return;let r={ts:ye(),level:e,message:typeof t=="string"?t:Vt(t)};s&&(r.tag=s),i&&i instanceof P&&(r.flowId=i.id,r.flowName=i.name,i.customAttributes&&(r.flowAttributes=i.customAttributes)),this._queue.push(r);let o=this._persistLogEntry(r,i);return this._queue.length>2e3&&this._queue.splice(0,this._queue.length-2e3),this._queue.length>=this._config.maxBatchSize&&this.sendLogs(),this._logInternal(`[LogDrop:${e}] ${r.message}`),o}_scheduleFlush(){this._config&&(this._flushTimer&&clearInterval(this._flushTimer),this._flushTimer=setInterval(()=>this.sendLogs(),this._config.flushIntervalMs),this._flushTimer&&typeof this._flushTimer.unref=="function"&&this._flushTimer.unref())}_scheduleEventFlush(){this._eventFlushTimer&&clearInterval(this._eventFlushTimer),this._eventFlushTimer=setInterval(()=>{this._eventModule?._flush()},h.EVENT_FLUSH_INTERVAL_MS),this._eventFlushTimer&&typeof this._eventFlushTimer.unref=="function"&&this._eventFlushTimer.unref()}_scheduleFileFlush(){this._config&&(this._fileFlushTimer&&clearInterval(this._fileFlushTimer),this._fileFlushTimer=setInterval(()=>{this._flushDbToZip()},h.FILE_EXPORT_INTERVAL_MS),this._fileFlushTimer&&typeof this._fileFlushTimer.unref=="function"&&this._fileFlushTimer.unref())}_initDb(){!g()||!window.indexedDB||this._dbPromise||(this._dbPromise=new Promise((e,t)=>{let i=window.indexedDB.open("logdrop",3);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains("logs")||s.createObjectStore("logs",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("crashes")||s.createObjectStore("crashes",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("events")||s.createObjectStore("events",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("event_upload_batch")||s.createObjectStore("event_upload_batch",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("log_upload_batch")||s.createObjectStore("log_upload_batch",{keyPath:"id",autoIncrement:!0})},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)}))}async _persistLogEntry(e,t=null){if(this._dbPromise)try{await this._enforceStorageLimit();let s=(await this._dbPromise).transaction("logs","readwrite"),r={sessionId:this._sessionId,userUuid:this._getEffectiveUserUuid(),ts:e.ts,level:e.level,message:e.message};e.tag&&(r.tag=e.tag),t&&t instanceof P&&(r.flowId=t.id,r.flowName=t.name,t.customAttributes&&(r.flowAttributes=t.customAttributes)),await new Promise((o,l)=>{s.objectStore("logs").add(r),s.oncomplete=()=>o(),s.onerror=()=>l(s.error)})}catch{}}async _readAllLogs(){if(!this._dbPromise)return[];let e=await this._dbPromise;return new Promise((t,i)=>{let o=e.transaction("logs","readonly").objectStore("logs").getAll();o.onsuccess=()=>t(o.result||[]),o.onerror=()=>i(o.error)})}async _readLogUploadBatch(){if(!this._dbPromise)return null;let i=(await this._dbPromise).transaction("log_upload_batch","readonly").objectStore("log_upload_batch").getAll();return new Promise((s,r)=>{i.onsuccess=()=>s((i.result||[])[0]??null),i.onerror=()=>r(i.error)})}async _replaceLogUploadBatch(e){if(!this._dbPromise)return;let i=(await this._dbPromise).transaction("log_upload_batch","readwrite"),s=i.objectStore("log_upload_batch");s.clear(),e&&s.add(e),await new Promise((r,o)=>{i.oncomplete=r,i.onerror=()=>o(i.error)})}async _persistCrash(e){if(this._dbPromise)try{let i=(await this._dbPromise).transaction("crashes","readwrite");i.objectStore("crashes").add(e),await new Promise((s,r)=>{i.oncomplete=()=>s(),i.onerror=()=>r(i.error)})}catch{}}async _readAllCrashes(){if(!this._dbPromise)return[];try{let i=(await this._dbPromise).transaction("crashes","readonly").objectStore("crashes").getAll();return await new Promise((s,r)=>{i.onsuccess=()=>s(i.result||[]),i.onerror=()=>r(i.error)})}catch{return[]}}async _deleteCrashesByIds(e){if(!(!this._dbPromise||!e.length))try{let i=(await this._dbPromise).transaction("crashes","readwrite"),s=i.objectStore("crashes");e.forEach(r=>s.delete(r)),await new Promise((r,o)=>{i.oncomplete=()=>r(),i.onerror=()=>o(i.error)})}catch{}}_buildCrashData({threadName:e,stackTrace:t,crashType:i,isCustomCrash:s,sourceUrl:r="",line:o=0,column:l=0}){let a=Xe(),c=Date.parse(this._sessionCreateDate);return{timestamp:Date.now(),threadName:e,stackTrace:t.slice(0,5e5),sessionId:this._sessionId,userUuid:this._getEffectiveUserUuid(),crashType:i,appVersion:this._config?.release||"UNKNOWN",buildNumber:"",isAppOnBackground:a.visibilityState!=="visible",sessionTime:Number.isFinite(c)?Math.max(0,Date.now()-c):0,uuid:Je().replace(/-/g,""),isCustomCrash:s,url:a.url,sourceUrl:r,line:o,column:l}}_recordCrash(e){let t=String(e.stackTrace||""),i=e.errorIdentity;if(i&&(typeof i=="object"||typeof i=="function")){if(this._seenCrashes.has(i))return;this._seenCrashes.add(i)}let s=this._buildCrashData({...e,stackTrace:t}),r=this._enqueue(I.CRASH,t,new P("Crash",s.uuid),"LogDropCrashTracker"),o=this._persistCrash(s);Promise.allSettled([Promise.resolve(r),o]).then(()=>this._scheduleCrashFlush()).catch(()=>{})}_scheduleCrashFlush(){this._crashFlushTimer&&clearTimeout(this._crashFlushTimer),this._crashFlushTimer=setTimeout(()=>{this._crashFlushTimer=null,this._flushCrashes().catch(()=>{})},this._crashFlushDelayMs),this._crashFlushTimer&&typeof this._crashFlushTimer.unref=="function"&&this._crashFlushTimer.unref()}async _clearLogs(){if(!this._dbPromise)return;let e=await this._dbPromise;return new Promise((t,i)=>{let o=e.transaction("logs","readwrite").objectStore("logs").clear();o.onsuccess=()=>t(),o.onerror=()=>i(o.error)})}async _clearNetworkLogs(){if(this._dbPromise)try{let s=(await this._dbPromise).transaction("logs","readwrite").objectStore("logs").openCursor();return new Promise((r,o)=>{s.onsuccess=l=>{let a=l.target.result;a?(a.value&&a.value.level===I.NETWORK_ACTIVITY&&a.delete(),a.continue()):r()},s.onerror=()=>o(s.error)})}catch{}}async _getStorageSize(){if(!this._dbPromise)return 0;try{let e=await this._readAllLogs(),t=JSON.stringify(e);return new Blob([t]).size}catch{return 0}}_getMaxStorageLimit(){return this._initResponse?.databaseMaxStorageLimitInBytes??h.DATABASE_MAX_STORAGE_LIMIT}async _enforceStorageLimit(){if(this._dbPromise)try{let e=await this._getStorageSize(),t=this._getMaxStorageLimit();e>=t&&(await this._flushLogs()||await this._deleteOldestLogs(e-t+h.MAX_LOCAL_STORAGE_SIZE))}catch{}}async _deleteOldestLogs(e){if(!(!this._dbPromise||e<=0))try{let t=await this._readAllLogs();if(!t.length)return;t.sort((r,o)=>new Date(r.ts)-new Date(o.ts));let i=[],s=0;for(let r of t){if(s>=e)break;let o=new Blob([JSON.stringify(r)]).size;i.push(r.id),s+=o}i.length>0&&(await this._deleteLogsByIds(i),this._logInternal(`[LogDrop] Deleted ${i.length} oldest logs to free storage`))}catch{}}_scheduleStorageCheck(){this._storageCheckTimer&&clearInterval(this._storageCheckTimer),this._storageCheckTimer=setInterval(async()=>{await this._checkStorageAndFlush()},h.STORAGE_CHECK_INTERVAL_MS),this._storageCheckTimer&&typeof this._storageCheckTimer.unref=="function"&&this._storageCheckTimer.unref()}async _checkStorageAndFlush(){if(this._config)try{let e=await this._getStorageSize();e>=h.MAX_LOCAL_STORAGE_SIZE&&(this._logInternal(`[LogDrop] Storage size ${this._formatBytes(e)} exceeds limit, triggering upload`),await this._flushLogs())}catch{}}_getCachedRemainingLimit(){return this._cachedRemainingLimit!=null?this._cachedRemainingLimit:h.DEFAULT_INITIAL_REMAINING_LIMIT}_getMaxFileSize(){return this._initResponse?.perUserMaxFileSizeLimitInBytes??5242880}_getMinFileSize(){return this._initResponse?.perUserMinFileSizeLimitInBytes??524288}_groupLogsBySession(e){let t={};for(let i of e){let s=i.sessionId||"unknown";t[s]||(t[s]=[]),t[s].push(i)}return t}async _getDeviceInfoForSession(e){let i=(await this._readAllLogs()).filter(s=>s.sessionId===e&&s.level===I.DEVICEINFO);if(i.length>0){let r=i[i.length-1]?.message;if(typeof r=="string"&&r.trim())try{let o=JSON.parse(r);if(o&&typeof o=="object")return o}catch{}}return await this._getDeviceInfo()}_buildLogChunk(e,t,i){let s=Math.min(t,i);if(s<=0)return null;let r={sessions:[],size:0,logIds:[],droppedLogIds:[]},o=(l,a)=>{a.length&&r.sessions.push({sessionId:l,logs:a})};for(let[l,a]of Object.entries(e)){let c=[];for(let u of a){let d={id:u.id,ts:u.ts,level:u.level,message:u.message,flowId:u.flowId,flowName:u.flowName,flowAttributes:u.flowAttributes},f=JSON.stringify(d).length;if(f>s){r.droppedLogIds.push(u.id),this._warnInternal(`[LogDrop] Dropping oversized log ${u.id} for session ${l}; entry size ${this._formatBytes(f)} exceeds chunk limit ${this._formatBytes(s)}`);continue}if(r.size+f>s&&r.size>0)return o(l,c),r.sessions.length>0||r.droppedLogIds.length>0?r:null;c.push(d),r.logIds.push(u.id),r.size+=f}o(l,c)}return r.sessions.length>0||r.droppedLogIds.length>0?r:null}async _compressToGzip(e){let t=JSON.stringify(e),s=new TextEncoder().encode(t);if(typeof CompressionStream<"u")try{let o=new Blob([s]).stream().pipeThrough(new CompressionStream("gzip")),l=await new Response(o).blob();return new Uint8Array(await l.arrayBuffer())}catch{}return s}async _sendLogFile(e,t=""){if(!this._config)return{success:!1,remainingLimit:this._cachedRemainingLimit};let i=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof i!="function")return{success:!1,remainingLimit:this._cachedRemainingLimit};let s=await this._ensureSessionToken("Log upload requires a valid access token");if(!s)return this._warnInternal("[LogDrop] No valid session token after recovery attempt, skipping log upload"),{success:!1,remainingLimit:this._cachedRemainingLimit};try{let r=this._getOsInfo(),o=this._cachedRemainingLimit,l={content:e,deviceUuid:this._deviceId,appVersion:this._config.release||"1.0",sdkVersion:h.SDK_VERSION,osVersion:r.osVersion,errorCount:"0",uploadId:t},a=Le(l);this._debugLogProtoBody("Log upload request",l,a);let c=`${this._config.baseUrl}${h.LOGS_PATH}`,u=await i(c,{method:"POST",headers:{"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":this._config.apiKey,"x-session-token":s},body:new Blob([a],{type:"application/x-protobuf"})});if(u.ok){try{let d=new Uint8Array(await u.arrayBuffer());if(this._debugLogProtoResponse("Log upload",d,de),d.length>0){let f=de(d);this._cachedRemainingLimit=f.remainingLimit,o=this._cachedRemainingLimit}}catch{}return{success:!0,remainingLimit:o}}return{success:!1,remainingLimit:this._cachedRemainingLimit}}catch{return{success:!1,remainingLimit:this._cachedRemainingLimit}}}async _sendCrashReport(e){if(!this._config)return!1;let t=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof t!="function")return!1;let i=await this._ensureSessionToken("Crash upload requires a valid access token");if(!i)return this._warnInternal("[LogDrop] No valid session token after recovery attempt, skipping crash upload"),!1;try{let s={content:e,deviceUuid:this._deviceId,sdkVersion:h.SDK_VERSION},r=De(s);this._debugLogProtoBody("Crash upload request",s,r);let o=`${this._config.baseUrl}${h.CRASH_PATH}`;return(await t(o,{method:"POST",headers:{"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":this._config.apiKey,"x-session-token":i},body:new Blob([r],{type:"application/x-protobuf"})})).ok}catch{return!1}}async _flushCrashes(){if(!this._config||!this._dbPromise||this._crashFlushInProgress)return!1;this._crashFlushInProgress=!0;try{let e=await this._readAllCrashes();if(!e.length)return this._seenCrashes.clear(),!0;let t=e.map(o=>o.id).filter(o=>o!==void 0),i={crashes:e.map(({id:o,...l})=>l)},s=await this._compressToGzip(i),r=await this._sendCrashReport(s);return r&&(await this._deleteCrashesByIds(t),this._seenCrashes.clear()),r}finally{this._crashFlushInProgress=!1}}async _deleteLogsByIds(e){if(!(!this._dbPromise||!e.length))try{let i=(await this._dbPromise).transaction("logs","readwrite"),s=i.objectStore("logs");for(let r of e)s.delete(r);return new Promise((r,o)=>{i.oncomplete=()=>r(),i.onerror=()=>o(i.error)})}catch{}}_formatLogForExport(e){let t={level:e.level||"",message:e.message||"",timestamp:e.ts||"",file_and_line:""};return e.flowId&&(t.id=e.flowId),e.flowName&&(t.flow_name=e.flowName),e.tag&&(t.tag=e.tag),t}_formatDeviceInfoForExport(e){let t=e&&typeof e=="object"?e:{};return{sessionID:t.sessionID||"",session_create_date:t.session_create_date||"",os_version:t.os_version||"",app_version:t.app_version||"",device_model:t.device_model||"",locale:t.locale||"",free_disk_space:t.free_disk_space||"",battery_level:t.battery_level||"",low_power_mode:t.low_power_mode||"",ram_size:t.ram_size||"",device_id:t.device_id||"",userUuid:t.userUuid??null,sim_operator_name:"",network_available:t.network_available??!0,gmt:t.gmt??0,...t.bot_score!==void 0&&{bot_score:t.bot_score,bot_label:t.bot_label,posture:t.posture}}}async _flushLogs(){if(!this._config||this._fileFlushInProgress||!this._dbPromise)return!1;this._fileFlushInProgress=!0;try{let e=await this._readAllLogs();if(this._isInternalLoggingEnabled()&&this._logInternal(`[LogDrop DEBUG] _flushLogs called. DB log count: ${e.length}`),!e.length)return this._isInternalLoggingEnabled()&&this._logInternal("[LogDrop DEBUG] No logs in DB, skipping flush (no API call made)"),!0;this._isInternalLoggingEnabled()&&this._logInternal("[LogDrop DEBUG] Logs from DB:",e),this._cachedRemainingLimit==null&&this._logInternal(`[LogDrop] Remaining upload quota unknown; using conservative default limit of ${this._formatBytes(h.DEFAULT_INITIAL_REMAINING_LIMIT)} until a successful upload response updates the cache`);let t=this._getMaxFileSize(),i=e,s=!1;for(;i.length>0;){let r=this._getCachedRemainingLimit();if(r<=0){this._logInternal("[LogDrop] Remaining limit reached, stopping upload");break}let o=await this._readLogUploadBatch(),l=o?.uploadId??null,a;if(o){let f=new Set(o.logIds||[]),p=i.filter(_=>f.has(_.id));if(p.length===0){await this._replaceLogUploadBatch(null);continue}a=this._buildLogChunk(this._groupLogsBySession(p),Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)}else{let f=this._groupLogsBySession(i);a=this._buildLogChunk(f,t,r)}if(!a)break;if(a.droppedLogIds.length>0){await this._deleteLogsByIds(a.droppedLogIds);let f=new Set(a.droppedLogIds);i=i.filter(p=>!f.has(p.id)),s=!0}if(!a.sessions.length)continue;l||(l=this._generateUUID(),await this._replaceLogUploadBatch({uploadId:l,logIds:a.logIds}));let c=[];for(let f of a.sessions){let p=await this._getDeviceInfoForSession(f.sessionId),_=this._formatDeviceInfoForExport(p),m=f.logs.map(S=>this._formatLogForExport(S));c.push({device_info:_,logs:m})}if(this._isInternalLoggingEnabled()){let f=JSON.stringify(c),p=new Blob([f]).size;this._logInternal(`[LogDrop DEBUG] Payload before gzip - Size: ${this._formatBytes(p)}, Log IDs: ${a.logIds.join(", ")}`),this._logInternal("[LogDrop DEBUG] Payload content:",c)}let u=await this._compressToGzip(c);this._isInternalLoggingEnabled()&&this._logInternal(`[LogDrop DEBUG] After gzip - Size: ${this._formatBytes(u.length)}`);let d=await this._sendLogFile(u,l);if(d.success){this._logInternal(`[LogDrop] Successfully sent ${a.logIds.length} logs`),await this._deleteLogsByIds(a.logIds),await this._replaceLogUploadBatch(null);let f=new Set(a.logIds);if(i=i.filter(p=>!f.has(p.id)),s=!0,d.remainingLimit!=null&&d.remainingLimit<=0){this._logInternal("[LogDrop] Remaining limit exhausted after upload, stopping flush");break}}else{this._warnInternal("[LogDrop] Failed to send log chunk, will retry later");break}}return s}catch(e){return this._warnInternal("[LogDrop] Flush failed:",e.message||e),!1}finally{this._fileFlushInProgress=!1}}async _flushDbToZip(){return this._flushLogs()}async _sendInitRequest(e=1){if(!this._config){this._failInit("LogDrop init failed: no config");return}let i=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof i!="function"){this._failInit("LogDrop init failed: fetch not available");return}try{let s={"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":this._config.apiKey},r=this._getAccessToken(),o=this._getRefreshToken();if(!r||!o){let f=[];r||f.push(`Stored access token is ${this._tokenValidationState.logdrop_access_token||"unavailable"}`),o||f.push(`Stored refresh token is ${this._tokenValidationState.logdrop_refresh_token||"unavailable"}`),this._recoverSessionTokens(f.join("; "))}r&&(s["x-session-token"]=r);let l={refreshToken:o||"",deviceUuid:this._deviceId},a=Ue(l);this._debugLogProtoBody("Init request",l,a);let c=`${this._config.baseUrl}${h.INIT_PATH}`,u=await i(c,{method:"POST",headers:s,body:new Blob([a],{type:"application/x-protobuf"})});if(!u.ok)throw new Error(`HTTP ${u.status}`);let d=new Uint8Array(await u.arrayBuffer());this._debugLogProtoResponse("Init",d,ue),d.length>0&&(this._initResponse=ue(d),this._saveServerConfigToCache({data:this._initResponse}),this._initResponse.accessToken&&this._saveTokens(this._initResponse.accessToken,null,this._getTokenRecoveryTarget()),this._applyServerConfig(this._initResponse,!0)),this._logInternal("[LogDrop] Init successful"),this._isNewDevice&&!this._isUserRegistered()&&this._sendUserUpdate(this._deviceId,!1,{reason:"automatic_device_registration"})}catch(s){if(e<3)return this._warnInternal(`[LogDrop] Init attempt ${e} failed, retrying... (${s.message||s})`),await new Promise(r=>setTimeout(r,e*1e3)),this._sendInitRequest(e+1);this._failInit(`LogDrop init failed after 3 attempts: ${s.message||s}`)}}_failInit(e){this._errorInternal(e),this._initialized=!1,this._config=null,this.teardown()}_installGlobalErrorHandlers(){g()&&(this._errorHandlersInstalled||(this._errorHandlersInstalled=!0,window.addEventListener("error",e=>{if(!this._serverConfig.isCrashTrackingEnabled)return;let t=e.error,i=t&&t.stack?String(t.stack):e.message||"";this._recordCrash({threadName:"window",stackTrace:i,crashType:t?.name||"Error",isCustomCrash:!1,sourceUrl:e.filename||"",line:e.lineno||0,column:e.colno||0,errorIdentity:t})}),window.addEventListener("unhandledrejection",e=>{if(!this._serverConfig.isCrashTrackingEnabled)return;let t=e.reason,i=t instanceof Error&&t.stack?String(t.stack):String(t||"");this._recordCrash({threadName:"unhandledrejection",stackTrace:i,crashType:t instanceof Error?t.name:"UnhandledRejection",isCustomCrash:!1,errorIdentity:t instanceof Error?t:null})})))}restoreFetch(){g()&&(this._originalFetch&&(window.fetch=this._originalFetch),this._fetchInstrumented=!1,this._originalFetch=null)}teardown(){if(this._flushTimer&&clearInterval(this._flushTimer),this._flushTimer=null,this._fileFlushTimer&&clearInterval(this._fileFlushTimer),this._fileFlushTimer=null,this._crashFlushTimer&&clearTimeout(this._crashFlushTimer),this._crashFlushTimer=null,this._deviceInfoTimer&&clearInterval(this._deviceInfoTimer),this._deviceInfoTimer=null,this._storageCheckTimer&&clearInterval(this._storageCheckTimer),this._storageCheckTimer=null,this._seenCrashes.clear(),this._uninstallNetworkInstrumentation(),this._pushModule?.teardown(),this._pushModule=null,this._inAppMessagePresenter?.teardown(),this._inAppMessagePresenter=null,this.push=null,this._eventFlushTimer&&clearInterval(this._eventFlushTimer),this._eventFlushTimer=null,this._eventModule?.teardown(),this._eventModule=null,this._riskModule?.teardown(),this._riskModule=null,this._activeRiskPolicyEvaluation=null,this._ipReputationExpiryTimer&&clearTimeout(this._ipReputationExpiryTimer),this._ipReputationExpiryTimer=null,this._riskPolicyOverlay?.parentNode)try{this._riskPolicyOverlay.parentNode.removeChild(this._riskPolicyOverlay)}catch{}this._riskPolicyOverlay=null,this.restoreFetch(),this._debugLogEnabled=!1}},qt=new ie;return st(jt);})();
|
|
1
|
+
var LogDropSDK=(()=>{var F=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var ht=Object.prototype.hasOwnProperty;var ft=(n,e,t)=>e in n?F(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var pt=(n,e)=>{for(var t in e)F(n,t,{get:e[t],enumerable:!0})},_t=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dt(e))!ht.call(n,s)&&s!==t&&F(n,s,{get:()=>e[s],enumerable:!(i=ut(e,s))||i.enumerable});return n};var gt=n=>_t(F({},"__esModule",{value:!0}),n);var C=(n,e,t)=>ft(n,typeof e!="symbol"?e+"":e,t);var _i={};pt(_i,{LogDrop:()=>pi,LogDropClient:()=>ae,LogFlow:()=>P,LogLevel:()=>S,capturePageState:()=>ct,fingerprintStack:()=>fi,generateUUID:()=>lt});var h=class{};h.DEFAULT_BASE_URL="https://server.logdrop.io";h.DEFAULT_WEB_SECRET_KEY="xuM9w0BAQEFx";h.FILE_EXPORT_INTERVAL_MS=3e5;h.DEVICE_INFO_INTERVAL_MS=1e4;h.SDK_VERSION="1.0.0-alpha4";h.STORAGE_CHECK_INTERVAL_MS=12e4;h.MAX_LOCAL_STORAGE_SIZE=5242880;h.DATABASE_MAX_STORAGE_LIMIT=16e6;h.DEBUG_LOGS_ENABLED=!0;h.DEVTOOLS_CONSOLE_PROBE_ENABLED=!1;h.DEVTOOLS_PROBE_INTERVAL_MS=1500;h.INIT_PATH="/logdrop/init";h.LOGS_PATH="/logs";h.CRASH_PATH="/crash";h.USERS_UPDATE_PATH="/users/update";h.PUSH_SW_PATH="/_logdrop/logdrop-sw.js";h.PUSH_SW_SCOPE="/";h.EVENTS_PATH="/events/collect";h.EVENT_FLUSH_INTERVAL_MS=1e4;h.EVENT_CODES=Object.freeze({APP_INSTALL:"ai",APP_OPEN:"ao",APP_FOREGROUNDED:"af",APP_BACKGROUNDED:"ab",APP_PERMISSIONS:"ap",APP_UPDATE:"au",DEEPLINK_OPEN:"do",TIME_IN_APP:"ta",PUSH_RECEIVED:"pr",PUSH_CLICK:"pc",WHITELIST_DOMAIN_DETECTED:"wd",RISK_DETECTED:"rd",SDK_ACTION_CLEARED:"sac"});h.VALID_EVENT_CODES=Object.freeze(Object.values(h.EVENT_CODES));h.EVENT_NAMES=Object.freeze({ai:"app_install",ao:"app_open",af:"app_foregrounded",ab:"app_backgrounded",ap:"app_permissions",au:"app_update",do:"deeplink_open",ta:"time_in_app",pr:"push_received",pc:"push_click",wd:"whitelist_domain_detected",rd:"risk_detected",sac:"sdk_action_cleared"});h.EVENT_REQUIRED_PROPS=Object.freeze({ai:[],ao:[],af:[],ab:[],ap:["pt","ps"],au:["pv","nv"],do:["ol"],ta:["ed"],pr:["pn"],pc:["pn"],wd:["rs","dm"],rd:["rt","rs"],sac:["as","cr"]});h.DEFAULT_INITIAL_REMAINING_LIMIT=15728640;function Re(){return Math.random().toString(16).slice(2)+Date.now().toString(16)}function V(){return typeof window<"u"}function B(){return V()&&window.performance&&typeof window.performance.now=="function"?window.performance.now():Date.now()}function mt(n){try{return typeof n=="string"?n:n&&typeof n.url=="string"?n.url:String(n??"unknown")}catch{return"unknown"}}function he(n){try{return JSON.parse(n)}catch{return null}}function yt(n){try{if(!n||typeof n!="string")return null;let e={},t=n.trim().split(/[\r\n]+/);for(let i of t){let s=i.indexOf(":");if(s===-1)continue;let r=i.slice(0,s).trim().toLowerCase(),o=i.slice(s+1).trim();r&&(e[r]=o)}return Object.keys(e).length?e:null}catch{return null}}function ce(n){if(n==null)return null;if(typeof n=="string")return he(n)??n;if(typeof n=="object"){if(typeof FormData<"u"&&n instanceof FormData)return"[FormData]";if(typeof Blob<"u"&&n instanceof Blob)return`[Blob ${n.type||"unknown"} ${n.size} bytes]`;if(typeof ArrayBuffer<"u"&&n instanceof ArrayBuffer)return`[ArrayBuffer ${n.byteLength} bytes]`}try{return String(n)}catch{return"[unserializable]"}}function ue({requestId:n,method:e,url:t,status:i,tookMs:s,requestHeaders:r,requestBody:o,responseHeaders:a,responseBody:l,errorType:c,errorMessage:u,didComplete:d}){let p=d===!0,_={isSuccess:p,uuid:String(n||""),method:String(e||""),url:String(t||""),requestHeaders:r||{},requestBody:o??null,status:typeof i=="number"?i:0,responseHeaders:a||{},responseBody:l??null,tookMs:typeof s=="number"?s:0};return p||(_.errorType=c??"network_error",_.errorMessage=u??"network_error"),_}function Ue(n,e,{stripQuery:t=!0,stripHash:i=!0}={}){try{let s=new URL(n,e);return t&&(s.search=""),i&&(s.hash=""),s.toString()}catch{return String(n||"unknown")}}function bt(n,e){try{return new URL(String(n||""),e).toString()}catch{return String(n||"")}}function xe(n,e=[]){let t=String(n||"");return e.some(i=>i?i instanceof RegExp?i.test(t):t.includes(String(i)):!1)}function de(n){return typeof n!="number"?!0:n<=0?!1:n>=1?!0:Math.random()<n}function wt(n,e){try{if(e&&e.method)return String(e.method).toUpperCase();if(n&&typeof n.method=="string")return String(n.method).toUpperCase()}catch{}return"GET"}function vt(n){try{if(!n||!n.headers)return null;let e={};return n.headers.forEach((t,i)=>{e[String(i).toLowerCase()]=String(t)}),Object.keys(e).length?e:null}catch{return null}}function St(n,e){let t={},i=e?.headers??n?.headers;try{if(!i)return null;if(typeof Headers<"u"&&i instanceof Headers)return i.forEach((s,r)=>{t[String(r).toLowerCase()]=String(s)}),Object.keys(t).length?t:null;if(Array.isArray(i)){for(let[s,r]of i)t[String(s).toLowerCase()]=String(r);return Object.keys(t).length?t:null}if(typeof i=="object"){for(let s of Object.keys(i))t[String(s).toLowerCase()]=String(i[s]);return Object.keys(t).length?t:null}}catch{}return null}var W=class{constructor(e){this._onEvent=e.onEvent,this._getBaseHref=e.getBaseHref||(()=>V()?window.location.href:"http://localhost/"),this._excludeUrls=e.excludeUrls||[],this._redaction=e.redaction||{stripQuery:!0,stripHash:!0},this._sampling=e.sampling||{rate:1,onlyErrors:!1,slowThresholdMs:void 0},this._capture=e.capture||{fetch:!0,xhr:!0},this._shouldBlockRequest=typeof e.shouldBlockRequest=="function"?e.shouldBlockRequest:()=>!1,this._fetchInstalled=!1,this._originalFetch=null,this._xhrInstalled=!1,this._xhrProto=null,this._xhrOrigOpen=null,this._xhrOrigSend=null,this._xhrOrigSetHeader=null}install(){V()&&(this._capture.fetch&&this._installFetch(),this._capture.xhr&&this._installXHR())}uninstall(){V()&&(this._uninstallFetch(),this._uninstallXHR())}_shouldExclude(e){let t=this._getBaseHref(),i=bt(e,t);return xe(e,this._excludeUrls)||xe(i,this._excludeUrls)}_shouldBlock(e){try{return this._shouldBlockRequest(String(e||""))===!0}catch{return!1}}_emit(e,t){try{this._onEvent(e,t)}catch{}}_installFetch(){this._fetchInstalled||typeof window.fetch=="function"&&(this._fetchInstalled=!0,this._originalFetch=window.fetch.bind(window),window.fetch=async(e,t)=>{let i=wt(e,t),s=mt(e);if(this._shouldBlock(s))throw new TypeError("Request blocked by LogDrop risk policy");if(this._shouldExclude(s))return this._originalFetch(e,t);let r=this._getBaseHref(),o=Ue(s,r,this._redaction),a=Re(),l=B(),c={};try{let u=new Request(e,t),d={};u.headers.forEach((p,_)=>{d[String(_).toLowerCase()]=String(p)}),c=d}catch{c=St(e,t)||{}}try{let u=ce(t?.body),d=await this._originalFetch(e,t),p=Math.round(B()-l),_=d?.status??0,f=!d||_>=400||_===0,m=typeof this._sampling.slowThresholdMs=="number"&&p>=this._sampling.slowThresholdMs;if((!this._sampling.onlyErrors||f||m)&&de(this._sampling.rate)){let k=null;try{let R=d?.headers?.get?.("content-type")||"",v=await d.clone().text();k=(R.includes("application/json")?he(v):null)??v}catch{}let E=vt(d)||{},w=ue({requestId:a,method:i,url:o,status:_,tookMs:p,requestHeaders:c,requestBody:u,responseHeaders:E,responseBody:k,errorType:null,errorMessage:null,didComplete:!0});this._emit("network_activity",w)}return d}catch(u){let d=Math.round(B()-l);if(de(this._sampling.rate)){let p=ce(t?.body),_=ue({requestId:a,method:i,url:o,status:0,tookMs:d,requestHeaders:c,requestBody:p,responseHeaders:{},responseBody:null,errorType:u?.name??"fetch_error",errorMessage:String(u),didComplete:!1});this._emit("network_activity",_)}throw u}})}_uninstallFetch(){this._fetchInstalled&&this._originalFetch&&(window.fetch=this._originalFetch,this._fetchInstalled=!1,this._originalFetch=null)}_installXHR(){if(this._xhrInstalled||typeof window.XMLHttpRequest!="function")return;this._xhrInstalled=!0;let e=window.XMLHttpRequest.prototype;this._xhrProto=e,this._xhrOrigOpen=e.open,this._xhrOrigSend=e.send,this._xhrOrigSetHeader=e.setRequestHeader,e.__ld_open_orig=this._xhrOrigOpen,e.__ld_send_orig=this._xhrOrigSend,e.__ld_setheader_orig=this._xhrOrigSetHeader,e.open=function(i,s,r,o,a){return this.__ld={requestId:Re(),method:String(i||"GET").toUpperCase(),rawUrl:String(s||"unknown"),start:0,headers:{}},e.__ld_open_orig.call(this,i,s,r,o,a)},e.setRequestHeader=function(i,s){try{this.__ld&&i&&(this.__ld.headers[String(i).toLowerCase()]=String(s))}catch{}return e.__ld_setheader_orig.call(this,i,s)};let t=this;e.send=function(i){let s=this.__ld;if(!s)return e.__ld_send_orig.call(this,i);if(t._shouldBlock(s.rawUrl)){try{this.abort()}catch{}return}if(t._shouldExclude(s.rawUrl))return e.__ld_send_orig.call(this,i);let r=t._getBaseHref(),o=Ue(s.rawUrl,r,t._redaction),a=s.headers||{};s.start=B();let l=async c=>{let u=Math.round(B()-s.start),d=this.status??0,p=c!=="loadend"||d>=400||d===0,_=typeof t._sampling.slowThresholdMs=="number"&&u>=t._sampling.slowThresholdMs;if((!t._sampling.onlyErrors||p||_)&&de(t._sampling.rate)){let f=ce(i),m=null;try{if(!this.responseType||this.responseType==="text"){let R=this.responseText;m=he(R)??R}else m=this.response??null}catch{}let k={};try{let R=this.getAllResponseHeaders?.(),U=yt(R);U&&(k=U)}catch{}let E=c==="loadend",w=ue({requestId:s.requestId,method:s.method,url:o,status:E?d:0,tookMs:u,requestHeaders:a,requestBody:f,responseHeaders:k,responseBody:E?m:null,errorType:E?null:c,errorMessage:E?null:c,didComplete:E});t._emit("network_activity",w)}};return this.addEventListener("loadend",()=>{l("loadend")},{once:!0}),this.addEventListener("error",()=>{l("error")},{once:!0}),this.addEventListener("abort",()=>{l("abort")},{once:!0}),this.addEventListener("timeout",()=>{l("timeout")},{once:!0}),e.__ld_send_orig.call(this,i)}}_uninstallXHR(){if(this._xhrInstalled&&this._xhrProto){this._xhrOrigOpen&&(this._xhrProto.open=this._xhrOrigOpen),this._xhrOrigSend&&(this._xhrProto.send=this._xhrOrigSend),this._xhrOrigSetHeader&&(this._xhrProto.setRequestHeader=this._xhrOrigSetHeader);try{delete this._xhrProto.__ld_open_orig,delete this._xhrProto.__ld_send_orig,delete this._xhrProto.__ld_setheader_orig}catch{}this._xhrInstalled=!1,this._xhrProto=null,this._xhrOrigOpen=null,this._xhrOrigSend=null,this._xhrOrigSetHeader=null}}};var kt=new Set(["authorization","proxy-authorization","x-auth-token","x-api-key","x-session-token","cookie","set-cookie"]),z="***",Et=500,It=/(a\+)\+|\(\.\*\)\+|\(\.\+\)\+/;function K(n){let e=String(n??"").trim().replace(/\.+$/,"").toLowerCase();return!e||/[/:?#@]/.test(e)||e.length>253?null:e}function pe(n){let e=String(n??"").trim();if(!e)return"/";let t=e.startsWith("/")?e:`/${e}`;return t.length>1?t.replace(/\/+$/,""):t}function fe(n,e){return n===e||n.endsWith(`.${e}`)}function Ae(n,e,t){return t==="EXACT"?n===e:t==="PREFIX"?e==="/"||n===e||n.startsWith(`${e}/`):!1}function De(n){try{let e=new URL(String(n??"")),t=K(e.hostname);return t?{host:t,path:pe(e.pathname)}:null}catch{return null}}function Tt(n){let e=[];for(let t of Array.isArray(n)?n:[]){let i=String(t??"");if(!i||i.length>Et)continue;let s=i.match(/^\/(.+)\/([gimsuy]*)$/),r=s?s[1]:i;if(It.test(r))continue;let o=s?s[2]:"";o.includes("g")||(o+="g"),o.includes("i")||(o+="i");try{e.push(new RegExp(r,o))}catch{}}return e}function Pt(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return(e>>>0).toString(16)}function $(n){let e={domainBlacklist:(n?.httpDomainBlackList??[]).map(K).filter(Boolean),pathBlacklist:Array.isArray(n?.httpPathBlackList)?n.httpPathBlackList:[],captureConfig:n?.httpPayloadCaptureConfig??null,sensitivePatterns:Tt(n?.sensitiveInfoFilter)};return e.fingerprint=Pt(JSON.stringify([e.domainBlacklist,e.pathBlacklist,e.captureConfig,e.sensitivePatterns.map(t=>`${t.source}/${t.flags}`)])),e}function Rt(n,e){let t=De(n);return!t||!e?!1:e.domainBlacklist.some(i=>fe(t.host,i))?!0:e.pathBlacklist.some(i=>{let s=K(i?.host);return!s||!fe(t.host,s)?!1:Ae(t.path,pe(i.path),i.matchType)})}function Ut(n,e){let t={requestHeaders:e?.disableRequestHeaders===!0,requestBody:e?.disableRequestBody===!0,responseHeaders:e?.disableResponseHeaders===!0,responseBody:e?.disableResponseBody===!0},i=De(n);if(!e||!i)return t;for(let s of e.rules??[]){let r=K(s?.host);!r||!fe(i.host,r)||s.path&&String(s.path).trim()&&!Ae(i.path,pe(s.path),s.matchType)||(t.requestHeaders||(t.requestHeaders=s.disableRequestHeaders===!0),t.requestBody||(t.requestBody=s.disableRequestBody===!0),t.responseHeaders||(t.responseHeaders=s.disableResponseHeaders===!0),t.responseBody||(t.responseBody=s.disableResponseBody===!0))}return t}function A(n,e){if(typeof n!="string"||!e?.length)return n;let t=n;for(let i of e)i.lastIndex=0,t=t.replace(i,(...s)=>{let r=s.slice(1,-2).filter(a=>typeof a=="string"||a===void 0),o=r.filter(a=>a!==void 0&&a!=="");return o.length===3?`${r[0]}${z}${r[2]}`:o.length===2?`${r[0]}${z}`:z});return t}function q(n,e){if(n==null||!e.length)return n;if(typeof n=="string")return A(n,e);try{return JSON.parse(A(JSON.stringify(n),e))}catch{return n}}function Le(n){if(!n||typeof n!="object")return{};let e={};for(let[t,i]of Object.entries(n))e[t]=kt.has(String(t).toLowerCase())?z:i;return e}function _e(n,e){if(!n)return null;let t=e??$(null);if(Rt(n.url,t))return null;let i=Ut(n.url,t.captureConfig),s=t.sensitivePatterns;return{...n,url:A(String(n.url??""),s),requestHeaders:i.requestHeaders?{}:q(Le(n.requestHeaders),s),requestBody:i.requestBody?null:q(n.requestBody??null,s),responseHeaders:i.responseHeaders?{}:q(Le(n.responseHeaders),s),responseBody:i.responseBody?null:q(n.responseBody??null,s)}}function ge(){return typeof window<"u"}function xt(n){let e="=".repeat((4-n.length%4)%4),t=(n+e).replace(/-/g,"+").replace(/_/g,"/"),i=atob(t),s=new Uint8Array(i.length);for(let r=0;r<i.length;r++)s[r]=i.charCodeAt(r);return s}function T(n,e){let t=new Error(e);return t.code=n,t}var j=class{constructor(e){let t=e??{};this.vapidPublicKey=t.vapidPublicKey??null,this.manualServiceWorkerRegistration=t.manualServiceWorkerRegistration===!0,this.serviceWorkerUrl=t.serviceWorkerUrl??h.PUSH_SW_PATH,this.serviceWorkerScope=t.serviceWorkerScope??h.PUSH_SW_SCOPE,this.serviceWorkerRegistration=t.serviceWorkerRegistration??null,this.isPushEnabled=t.isPushEnabled!==!1,this.onRemoteMessageReceived=typeof t.onRemoteMessageReceived=="function"?t.onRemoteMessageReceived:null,this.appId=t.appId??null,this.apiBase=t.apiBase??"",this.deviceId=t.deviceId??null,this.getSessionToken=typeof t.getSessionToken=="function"?t.getSessionToken:null,this.onPushReceived=typeof t.onPushReceived=="function"?t.onPushReceived:null,this.onNotificationClick=typeof t.onNotificationClick=="function"?t.onNotificationClick:null,this.onSubscriptionChanged=typeof t.onSubscriptionChanged=="function"?t.onSubscriptionChanged:null,this._messageHandler=null,this._installed=!1,this._tornDown=!1}install(){if(this._installed||this._tornDown||!ge())return;let e=this._getServiceWorkerContainer();!e||typeof e.addEventListener!="function"||(this._messageHandler=t=>{try{let i=t&&t.data;if(!i||typeof i!="object")return;if(i.type==="logdrop:push-received"&&this.onPushReceived)try{this.onPushReceived(i.payload)}catch{}else if(i.type==="logdrop:notification-click"){if(this.onNotificationClick)try{this.onNotificationClick(i.payload)}catch{}else if(typeof this.onRemoteMessageReceived=="function")try{this.onRemoteMessageReceived(i.payload)}catch{}}}catch{}},e.addEventListener("message",this._messageHandler),this._installed=!0)}uninstall(){if(!this._installed){this._messageHandler=null;return}if(ge()){let e=this._getServiceWorkerContainer();if(e&&typeof e.removeEventListener=="function"&&this._messageHandler)try{e.removeEventListener("message",this._messageHandler)}catch{}}this._messageHandler=null,this._installed=!1}teardown(){this.uninstall(),this._tornDown=!0}getPermissionState(){if(typeof Notification>"u")return"unsupported";try{return Notification.permission??"unsupported"}catch{return"unsupported"}}updateServerConfig({isPushEnabled:e,vapidPublicKey:t}={}){typeof e=="boolean"&&(this.isPushEnabled=e),(typeof t=="string"||t===null)&&(this.vapidPublicKey=t),this._syncServiceWorkerConfig(),this._syncGrantedSubscription()}requestPendingMessages(){let e=this._getServiceWorkerContainer();try{e?.controller&&typeof e.controller.postMessage=="function"&&e.controller.postMessage({type:"logdrop:drain-pending"})}catch{}}async subscribe(){if(this._tornDown)throw T("TEARDOWN","PushModule has been torn down; subscribe() is no longer available");if(ge()&&window.isSecureContext===!1)throw T("INSECURE_CONTEXT","Push requires a secure context (HTTPS). window.isSecureContext is false.");let e=typeof Notification<"u";if(!(typeof navigator<"u"&&!!navigator.serviceWorker)||!e)throw T("PUSH_UNSUPPORTED","Push notifications are not supported in this browser (serviceWorker or Notification API unavailable).");if(this.isPushEnabled===!1)return null;if(!this.vapidPublicKey)throw T("MISSING_VAPID_KEY","vapidPublicKey is required to subscribe to push notifications");let i=this.getPermissionState();if(i==="denied")throw T("PERMISSION_DENIED","Notification permission has been denied by the user");if(i==="default"){if(await Notification.requestPermission()!=="granted")throw T("PERMISSION_DENIED","Notification permission was not granted")}else if(i!=="granted")throw T("PUSH_UNSUPPORTED",`Unsupported Notification.permission state: ${i}`);let s=this._getServiceWorkerContainer();if(!s)throw T("PUSH_UNSUPPORTED","navigator.serviceWorker is not available");let r;if(this.serviceWorkerRegistration?r=this.serviceWorkerRegistration:this.manualServiceWorkerRegistration?r=await s.ready:(await s.register(this.serviceWorkerUrl,{scope:this.serviceWorkerScope}),r=this.serviceWorkerRegistration||await s.ready),!r)throw T("PUSH_UNSUPPORTED","Failed to obtain a service worker registration");if(!r.pushManager)throw T("PUSH_UNSUPPORTED","ServiceWorkerRegistration.pushManager is not available");await this._handshake(s,r);let o=xt(this.vapidPublicKey),a=await r.pushManager.getSubscription(),l=a?.options?.applicationServerKey;a&&l&&!this._keysEqual(l,o)&&await a.unsubscribe();let c;try{c=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:o})}catch(d){let p=d&&d.message?d.message:String(d);if(p.includes("applicationServerKey")||p.includes("gcm_sender_id")){let _=await r.pushManager.getSubscription();_&&await _.unsubscribe(),c=await r.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:o})}else throw d}let u=typeof c.toJSON=="function"?c.toJSON():c;return this.onSubscriptionChanged&&await this.onSubscriptionChanged(u),await this._syncServiceWorkerConfig(r),c}async unsubscribe(){if(this._tornDown)throw T("TEARDOWN","PushModule has been torn down; unsubscribe() is no longer available");let e=this._getServiceWorkerContainer();if(!e)return null;let t;try{t=await e.ready}catch{return null}if(!t||!t.pushManager)return null;let i=null;try{i=await t.pushManager.getSubscription()}catch{i=null}if(!i)return null;try{await i.unsubscribe()}catch{}return null}_getServiceWorkerContainer(){return typeof navigator>"u"?null:navigator.serviceWorker??null}_handshake(e,t){return new Promise(i=>{let s=!1,r=()=>{if(!s){s=!0;try{typeof e.removeEventListener=="function"&&e.removeEventListener("message",o)}catch{}clearTimeout(a),i()}},o=l=>{try{let c=l&&l.data;c&&c.type==="logdrop:pong"&&r()}catch{}};try{typeof e.addEventListener=="function"&&e.addEventListener("message",o)}catch{}let a=setTimeout(r,500);if(a&&typeof a.unref=="function")try{a.unref()}catch{}try{t&&t.active&&typeof t.active.postMessage=="function"?t.active.postMessage({type:"logdrop:ping"}):r()}catch{r()}})}async _syncServiceWorkerConfig(e=null){let t=this._getServiceWorkerContainer();if(!t)return;let i=e||this.serviceWorkerRegistration;if(!i)try{i=await t.ready}catch{return}let s=i?.active||t.controller;!s||typeof s.postMessage!="function"||s.postMessage({type:"logdrop:push-config",config:{vapidPublicKey:this.vapidPublicKey,apiBase:this.apiBase,appId:this.appId,sessionToken:this.getSessionToken?this.getSessionToken():null,deviceUuid:this.deviceId}})}async _syncGrantedSubscription(){if(!(this.isPushEnabled!==!0||!this.vapidPublicKey||this.getPermissionState()!=="granted"||!this.deviceId||!this.getSessionToken?.()))try{await this.subscribe()}catch{}}reconcileGrantedSubscription(){return this._syncGrantedSubscription()}_keysEqual(e,t){let i=new Uint8Array(e),s=new Uint8Array(t);if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r]!==s[r])return!1;return!0}};function Ce(n){return!n||typeof n!="object"?{}:n.data&&typeof n.data=="object"?n.data:n}function Lt(n){if(!n||String(n.kind||"").toUpperCase()!=="OPEN_DEEPLINK")return!1;let e=String(n.target||n.fallbackTarget||"").trim();if(!e||typeof window>"u")return!1;try{return String(n.deeplinkMode||"").toUpperCase()==="EXTERNAL_BROWSER"?window.open(e,"_blank","noopener,noreferrer"):window.location.assign(e),!0}catch{let t=String(n.fallbackTarget||"").trim();if(!t||t===e)return!1;try{return window.location.assign(t),!0}catch{return!1}}}var G=class{constructor({onAction:e}={}){this.onAction=typeof e=="function"?e:null,this.queue=[],this.active=null,this._visibilityHandler=()=>this._showNext(),typeof document<"u"&&document.addEventListener?.("visibilitychange",this._visibilityHandler)}enqueue(e){let t=Ce(e);if(String(t.messageKind||"").toUpperCase()!=="IN_APP"||!t.inApp||typeof t.inApp!="object")return!1;let i=String(t.notificationId||"").trim();if(i&&(this.active?.notificationId===i||this.queue.some(r=>r.notificationId===i)))return!1;let s=Number(t.inApp.ttlSeconds);return this.queue.push({payload:e,notificationId:i,expiresAt:Number.isFinite(s)&&s>0?Date.now()+s*1e3:null}),this._showNext(),!0}teardown(){typeof document<"u"&&document.removeEventListener?.("visibilitychange",this._visibilityHandler),this.queue=[],this._finish(!1)}_showNext(){if(this.active||typeof document>"u"||!document.body||document.visibilityState==="hidden")return;for(;this.queue.length&&this.queue[0].expiresAt&&this.queue[0].expiresAt<=Date.now();)this.queue.shift();let e=this.queue.shift();e&&(this.active={...e,element:this._render(e)})}_render(e){let i=Ce(e.payload).inApp,s=String(i.template||"").toUpperCase()==="BANNER",r=document.createElement("div");r.setAttribute("data-logdrop-in-app","true"),r.setAttribute("role","dialog"),r.setAttribute("aria-modal",s?"false":"true"),r.style.cssText=s?`position:fixed;${String(i.position).toUpperCase()==="BOTTOM"?"bottom":"top"}:16px;left:50%;transform:translateX(-50%);z-index:2147483646;width:min(560px,calc(100% - 32px));font-family:system-ui,sans-serif`:"position:fixed;inset:0;z-index:2147483646;display:flex;align-items:center;justify-content:center;padding:24px;background:rgba(15,23,42,.62);font-family:system-ui,sans-serif";let o=document.createElement("div");if(o.style.cssText=`position:relative;box-sizing:border-box;width:100%;max-width:${s?"560px":"520px"};${i.isFullHeight===!0&&!s?"height:calc(100vh - 48px);":"max-height:calc(100vh - 48px);"}overflow:auto;background:#fff;color:#111827;border-radius:14px;padding:20px;box-shadow:0 20px 55px rgba(0,0,0,.3)`,i.dismissible!==!1){let l=document.createElement("button");l.type="button",l.setAttribute("aria-label","Close"),l.textContent="\xD7",l.style.cssText="position:absolute;top:8px;right:10px;border:0;background:transparent;font-size:24px;line-height:1;color:#6b7280;cursor:pointer",l.addEventListener("click",()=>this._finish(!0),{once:!0}),o.appendChild(l)}if(i.imageUrl){let l=document.createElement("img");l.src=String(i.imageUrl),l.alt="",l.style.cssText="display:block;width:100%;max-height:280px;object-fit:cover;border-radius:10px;margin-bottom:16px",o.appendChild(l)}if(i.headline){let l=document.createElement("h2");l.textContent=String(i.headline),l.style.cssText="margin:0 28px 8px 0;font-size:20px;line-height:1.3",o.appendChild(l)}if(i.body){let l=document.createElement("p");l.textContent=String(i.body),l.style.cssText="margin:0;color:#4b5563;line-height:1.5;white-space:pre-wrap",o.appendChild(l)}let a=[i.secondaryButton,i.primaryButton].filter(l=>l?.label);if(a.length){let l=document.createElement("div");l.style.cssText="display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:18px",a.forEach((c,u)=>{let d=document.createElement("button");d.type="button",d.textContent=String(c.label);let p=u===a.length-1&&i.primaryButton===c;d.style.cssText=p?"padding:9px 15px;border:0;border-radius:8px;background:#111827;color:#fff;cursor:pointer":"padding:9px 15px;border:1px solid #d1d5db;border-radius:8px;background:#fff;color:#111827;cursor:pointer",d.addEventListener("click",()=>{try{this.onAction?.(e.payload,c.action||null)}catch{}Lt(c.action),this._finish(!0)},{once:!0}),l.appendChild(d)}),o.appendChild(l)}return r.appendChild(o),!s&&i.dismissible!==!1&&r.addEventListener("click",l=>{l.target===r&&this._finish(!0)}),document.body.appendChild(r),r}_finish(e){this.active?.element?.parentNode&&this.active.element.parentNode.removeChild(this.active.element),this.active=null,e&&this._showNext()}};var D=class n{constructor(){this._buf=[]}_writeVarint(e){let t=e>>>0;if(e<=127){this._buf.push(t);return}for(;t>127;)this._buf.push(t&127|128),t>>>=7;this._buf.push(t)}_writeTag(e,t){this._writeVarint(e<<3|t)}writeString(e,t){if(!t)return;let i=new TextEncoder().encode(t);this._writeTag(e,2),this._writeVarint(i.length);for(let s=0;s<i.length;s++)this._buf.push(i[s])}writeBytes(e,t){if(!(!t||t.length===0)){this._writeTag(e,2),this._writeVarint(t.length);for(let i=0;i<t.length;i++)this._buf.push(t[i])}}writeInt64(e,t){t&&(this._writeTag(e,0),this._writeVarint(t))}_writeVarintLong(e){let t=Math.floor(e);for(;t>127;)this._buf.push(t%128|128),t=Math.floor(t/128);this._buf.push(t%128)}writeInt64Long(e,t){t&&(this._writeTag(e,0),this._writeVarintLong(t))}writeDouble(e,t){this._writeTag(e,1);let i=new ArrayBuffer(8);new DataView(i).setFloat64(0,t,!0);let s=new Uint8Array(i);for(let r=0;r<8;r++)this._buf.push(s[r])}writeStringForce(e,t){let i=new TextEncoder().encode(t??"");this._writeTag(e,2),this._writeVarint(i.length);for(let s=0;s<i.length;s++)this._buf.push(i[s])}writeBoolForce(e,t){this._writeTag(e,0),this._buf.push(t?1:0)}writeBool(e,t){t&&(this._writeTag(e,0),this._buf.push(1))}writeEnum(e,t){this.writeInt64(e,t)}writeRepeatedString(e,t){if(!(!t||!t.length))for(let i of t)this.writeString(e,i)}writeMessage(e,t){let i=new n;t(i);let s=i.finish();if(s.length!==0){this._writeTag(e,2),this._writeVarint(s.length);for(let r=0;r<s.length;r++)this._buf.push(s[r])}}finish(){return new Uint8Array(this._buf)}},y=class{constructor(e){this._buf=e,this._pos=0}hasMore(){return this._pos<this._buf.length}_readVarint(){let e=0,t=0;for(;this._pos<this._buf.length;){let i=this._buf[this._pos++];if(e|=(i&127)<<t,(i&128)===0)return e>>>0;if(t+=7,t>35){for(;this._pos<this._buf.length&&(this._buf[this._pos++]&128)!==0;);return e>>>0}}return e>>>0}readTag(){if(!this.hasMore())return null;let e=this._readVarint();return{fieldNumber:e>>>3,wireType:e&7}}readBytes(){let e=this._pos,t=this._readVarint();if(!Number.isInteger(t)||t<0||this._pos+t>this._buf.length)throw this._pos=e,new Error("Unexpected end of buffer in readBytes");let i=this._buf.slice(this._pos,this._pos+t);return this._pos+=t,i}readString(){let e=this.readBytes();return new TextDecoder().decode(e)}readVarint(){return this._readVarint()}readVarintLong(){let e=0,t=1;for(;this._pos<this._buf.length;){let i=this._buf[this._pos++];if(e+=(i&127)*t,(i&128)===0)break;t*=128}return e}readDouble(){if(this._pos+8>this._buf.length)throw new Error("Unexpected end of buffer in readDouble");let t=new DataView(this._buf.buffer,this._buf.byteOffset+this._pos,8).getFloat64(0,!0);return this._pos+=8,t}readBool(){return this._readVarint()!==0}skip(e){switch(e){case 0:this._readVarint();break;case 1:if(this._pos+8>this._buf.length)throw new Error("Unexpected end of buffer while skipping 64-bit field");this._pos+=8;break;case 2:{let t=this._readVarint();if(!Number.isInteger(t)||t<0||this._pos+t>this._buf.length)throw new Error("Unexpected end of buffer while skipping length-delimited field");this._pos+=t}break;case 5:if(this._pos+4>this._buf.length)throw new Error("Unexpected end of buffer while skipping 32-bit field");this._pos+=4;break;default:throw new Error(`Unknown wire type: ${e}`)}}};function At(n,e){n.writeString(1,e.deviceUuid),n.writeString(3,e.iosApnsDeviceToken),n.writeString(4,e.androidFirebaseToken),n.writeString(5,e.huaweiToken),n.writeString(6,e.osName),n.writeString(7,e.osVersion),n.writeString(8,e.deviceBrand),n.writeString(9,e.deviceModel),n.writeString(10,e.appVersion),n.writeString(11,e.sdkVersion),n.writeString(12,e.sdkType),n.writeString(13,e.bridgeSdkType);for(let[t,i]of Object.entries(e.customAttributes||{}))n.writeMessage(14,s=>{s.writeString(1,t),s.writeString(2,i)});for(let t of e.removedCustomAttributeKeys||[])n.writeString(15,t);e.webPushSubscription&&n.writeMessage(16,t=>{t.writeString(1,e.webPushSubscription.endpoint),t.writeString(2,e.webPushSubscription.p256dh),t.writeString(3,e.webPushSubscription.auth),t.writeInt64Long(4,e.webPushSubscription.expirationTime)})}function He(n){let e=new D;return e.writeString(1,n.userUuid),n.device&&e.writeMessage(2,t=>At(t,n.device)),e.finish()}function me(n){let e=new y(n),t={accessToken:"",refreshToken:""};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.accessToken=e.readString();break;case 2:t.refreshToken=e.readString();break;default:e.skip(i.wireType)}}return t}function Fe(n){let e=new D;return e.writeString(2,n.refreshToken),e.writeString(3,n.deviceUuid),e.finish()}function I(n){return n||null}function Dt(n){let e=new y(n),t={domain:"",path:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.domain=e.readString();break;case 2:t.path=I(e.readString());break;default:e.skip(i.wireType)}}return t}function Ne(n){let e=new y(n),t={showPopupEnabled:!1,appBlockEnabled:!1,networkBlockEnabled:!1,blockedRequestPaths:[],blockedDomains:[],title:null,message:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.showPopupEnabled=e.readBool();break;case 2:t.appBlockEnabled=e.readBool();break;case 3:t.networkBlockEnabled=e.readBool();break;case 4:t.blockedRequestPaths.push(e.readString());break;case 5:t.blockedDomains.push(e.readString());break;case 6:t.title=I(e.readString());break;case 7:t.message=I(e.readString());break;case 8:t.buttonText=I(e.readString());break;default:e.skip(i.wireType)}}return t}function Oe(n){let e=new y(n),t={enabled:!1,whitelist:[],actions:Ne(new Uint8Array)};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.whitelist.push(Dt(e.readBytes()));break;case 3:t.actions=Ne(e.readBytes());break;default:e.skip(i.wireType)}}return t}function Ct(n){let e=new y(n),t={enabled:!1,priority:0,matchType:"ANY",eventIds:[],actionIds:[],message:null,title:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.priority=e.readVarint();break;case 3:t.matchType=e.readVarint()===1?"ALL":"ANY";break;case 4:i.wireType===2?t.eventIds.push(...M(e.readBytes())):t.eventIds.push(e.readVarint());break;case 5:i.wireType===2?t.actionIds.push(...M(e.readBytes())):t.actionIds.push(e.readVarint());break;case 6:t.message=I(e.readString());break;case 7:t.title=I(e.readString());break;case 8:t.buttonText=I(e.readString());break;default:e.skip(i.wireType)}}return t}function M(n){let e=new y(n),t=[];for(;e.hasMore();)t.push(e.readVarint());return t}function Nt(n){let e=new y(n),t={version:0,rules:[]};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.version=e.readVarint();break;case 2:t.rules.push(Ct(e.readBytes()));break;default:e.skip(i.wireType)}}return t}function Be(n){let e=new y(n),t={riskPolicy:{version:0,rules:[]},enabled:!1,botDetectionEnabled:!1,otherRiskTypesEnabled:!1};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.riskPolicy=Nt(e.readBytes());break;case 2:t.enabled=e.readBool();break;case 3:t.botDetectionEnabled=e.readBool();break;case 4:t.otherRiskTypesEnabled=e.readBool();break;default:e.skip(i.wireType)}}return t}function Ve(n){switch(n){case 1:return"MEDIUM";case 2:return"HIGH";case 3:return"CRITICAL";default:return"UNSPECIFIED"}}function Ot(n){let e=new y(n),t={enabled:!1,priority:0,threatLevels:[],actionIds:[],message:null,title:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.priority=e.readVarint();break;case 3:{let s=i.wireType===2?M(e.readBytes()):[e.readVarint()];t.threatLevels.push(...s.map(Ve));break}case 4:i.wireType===2?t.actionIds.push(...M(e.readBytes())):t.actionIds.push(e.readVarint());break;case 5:t.message=I(e.readString());break;case 6:t.title=I(e.readString());break;case 7:t.buttonText=I(e.readString());break;default:e.skip(i.wireType)}}return t}function Bt(n){let e=new y(n),t={version:0,rules:[]};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.version=e.readVarint();break;case 2:t.rules.push(Ot(e.readBytes()));break;default:e.skip(i.wireType)}}return t}function Me(n){let e=new y(n),t={riskPolicy:{version:0,rules:[]}};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.riskPolicy=Bt(e.readBytes());break;default:e.skip(i.wireType)}}return t}function Mt(n){let e=new y(n),t={signature:"",eventId:"",threatLevel:"UNSPECIFIED",riskScore:0,actionIds:[],expireAtEpochMillis:0,message:null,title:null,buttonText:null};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.signature=e.readString();break;case 2:t.eventId=e.readString();break;case 3:t.threatLevel=Ve(e.readVarint());break;case 4:t.riskScore=e.readVarint();break;case 5:i.wireType===2?t.actionIds.push(...M(e.readBytes())):t.actionIds.push(e.readVarint());break;case 6:t.expireAtEpochMillis=e.readVarintLong();break;case 7:t.message=I(e.readString());break;case 8:t.title=I(e.readString());break;case 9:t.buttonText=I(e.readString());break;default:e.skip(i.wireType)}}return t}function Ht(n){let e=new y(n),t={enabled:!1,vapidPublicKey:""};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.enabled=e.readBool();break;case 2:t.vapidPublicKey=e.readString();break;default:e.skip(i.wireType)}}return t}var Ft=["EXACT","PREFIX"];function We(n){return Ft[n]??null}function Vt(n){let e=new y(n),t={host:"",path:"",matchType:"EXACT"};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.host=e.readString();break;case 2:t.path=e.readString();break;case 3:t.matchType=We(e.readVarint());break;default:e.skip(i.wireType)}}return t}function Wt(n){let e=new y(n),t={host:"",path:null,matchType:"EXACT",disableRequestHeaders:!1,disableRequestBody:!1,disableResponseHeaders:!1,disableResponseBody:!1};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.host=e.readString();break;case 2:t.path=e.readString();break;case 3:t.matchType=We(e.readVarint());break;case 4:t.disableRequestHeaders=e.readBool();break;case 5:t.disableRequestBody=e.readBool();break;case 6:t.disableResponseHeaders=e.readBool();break;case 7:t.disableResponseBody=e.readBool();break;default:e.skip(i.wireType)}}return t}function qt(n){let e=new y(n),t={disableRequestHeaders:!1,disableRequestBody:!1,disableResponseHeaders:!1,disableResponseBody:!1,rules:[]};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.disableRequestHeaders=e.readBool();break;case 2:t.disableRequestBody=e.readBool();break;case 3:t.disableResponseHeaders=e.readBool();break;case 4:t.disableResponseBody=e.readBool();break;case 5:t.rules.push(Wt(e.readBytes()));break;default:e.skip(i.wireType)}}return t}function zt(n){let e=new y(n),t={httpWhitelist:Oe(new Uint8Array),riskDetected:Be(new Uint8Array),ipReputationDetected:Me(new Uint8Array)};for(;e.hasMore();){let i=e.readTag();switch(i.fieldNumber){case 1:t.httpWhitelist=Oe(e.readBytes());break;case 2:t.riskDetected=Be(e.readBytes());break;case 3:t.ipReputationDetected=Me(e.readBytes());break;default:e.skip(i.wireType)}}return t}function ye(n){let e=new y(n),t={perUserMaxFileSizeLimitInBytes:0,perUserMinFileSizeLimitInBytes:0,databaseMaxStorageLimitInBytes:0,isSDKDisabled:!1,isHttpLoggingEnabled:!1,isCrashTrackingEnabled:!1,isEventTrackingEnabled:!1,httpDomainBlackList:[],httpPathBlackList:[],httpPayloadCaptureConfig:null,sensitiveInfoFilter:[],sslPinning:null,accessToken:"",limitType:0,riskConfig:null,activeIpReputationAction:null,serverNowEpochMillis:0,webPushConfig:{enabled:!1,vapidPublicKey:""}};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.perUserMaxFileSizeLimitInBytes=e.readVarintLong();break;case 2:t.perUserMinFileSizeLimitInBytes=e.readVarintLong();break;case 3:t.databaseMaxStorageLimitInBytes=e.readVarintLong();break;case 4:t.isSDKDisabled=e.readBool();break;case 5:t.isHttpLoggingEnabled=e.readBool();break;case 6:t.isCrashTrackingEnabled=e.readBool();break;case 7:t.httpDomainBlackList.push(e.readString());break;case 8:t.sensitiveInfoFilter.push(e.readString());break;case 9:e.skip(i.wireType);break;case 10:t.accessToken=e.readString();break;case 11:t.limitType=e.readVarint();break;case 12:t.riskConfig=zt(e.readBytes());break;case 13:t.activeIpReputationAction=Mt(e.readBytes());break;case 14:t.serverNowEpochMillis=e.readVarintLong();break;case 15:t.isEventTrackingEnabled=e.readBool();break;case 16:t.httpPathBlackList.push(Vt(e.readBytes()));break;case 17:t.httpPayloadCaptureConfig=qt(e.readBytes());break;case 18:t.webPushConfig=Ht(e.readBytes());break;default:e.skip(i.wireType)}}return t}function qe(n){let e=new D;return e.writeBytes(1,n.content),e.writeString(2,n.deviceUuid),e.writeString(4,n.appVersion),e.writeString(5,n.sdkVersion),e.writeString(6,n.osVersion),e.writeString(7,n.errorCount),e.writeString(8,n.firstRealUserUuid),e.writeString(9,n.uploadId),e.finish()}function be(n){let e=new y(n),t={remainingLimit:0};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.remainingLimit=e.readVarint();break;default:e.skip(i.wireType)}}return t}function ze(n){let e=new D;return e.writeBytes(1,n.content),e.writeString(2,n.deviceUuid),e.writeString(4,n.sdkVersion),e.finish()}function Ke(n,e){if(e==null){n._writeTag(1,0),n._writeVarint(0);return}let t=typeof e;if(t==="number"){Number.isFinite(e)?n.writeDouble(2,e):(n._writeTag(1,0),n._writeVarint(0));return}if(t==="boolean"){n.writeBoolForce(4,e);return}if(t==="string"){n.writeStringForce(3,e);return}if(Array.isArray(e)){n.writeMessage(6,i=>{for(let s of e)i.writeMessage(1,r=>Ke(r,s))});return}if(t==="object"){n.writeMessage(5,i=>$e(i,e));return}n.writeStringForce(3,String(e))}function $e(n,e){for(let t of Object.keys(e))n.writeMessage(1,i=>{i.writeStringForce(1,t),i.writeMessage(2,s=>Ke(s,e[t]))})}function Kt(n,e){n.writeString(1,e.eventId),n.writeString(2,e.eventCode),n.writeInt64Long(3,e.timestamp),e.properties&&typeof e.properties=="object"&&Object.keys(e.properties).length>0&&n.writeMessage(4,t=>$e(t,e.properties))}function $t(n,e){if(n.writeString(1,e.sessionId),n.writeString(2,e.userUuid),Array.isArray(e.events))for(let t of e.events)n.writeMessage(3,i=>Kt(i,t))}function je(n){let e=new D;if(e.writeString(1,n.deviceUuid),Array.isArray(n.sessions))for(let t of n.sessions)e.writeMessage(2,i=>$t(i,t));return e.writeString(3,n.firstRealUserUuid),e.writeString(4,n.uploadId),e.finish()}function Ge(n){let e=new y(n),t={count:0};for(;e.hasMore();){let i=e.readTag();if(!i)break;switch(i.fieldNumber){case 1:t.count=e.readVarint();break;default:e.skip(i.wireType)}}return t}function H(){return typeof window<"u"}function jt(){return H()&&typeof window.fetch=="function"?window.fetch.bind(window):typeof fetch=="function"?fetch:null}function we(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function Gt(){return typeof navigation<"u"&&typeof navigation.addEventListener=="function"}var X=class{constructor(e){let t=e??{};this._deviceId=t.deviceId??"",this._getSessionId=typeof t.getSessionId=="function"?t.getSessionId:()=>"",this._getUserUuid=typeof t.getUserUuid=="function"?t.getUserUuid:()=>null,this._getRealUserUuid=typeof t.getRealUserUuid=="function"?t.getRealUserUuid:()=>null,this._logEvent=typeof t.logEvent=="function"?t.logEvent:null,this._getSessionToken=typeof t.getSessionToken=="function"?t.getSessionToken:null,this._release=t.release??void 0,this._appId=t.appId??"",this._apiBase=t.apiBase??"",this._isEventTrackingEnabled=t.isEventTrackingEnabled===!0,this._isFirstVisit=t.isFirstVisit===!0,this._isSdkUpdated=t.isSdkUpdated===!0,this._previousRelease=t.previousRelease??null,this._dbPromise=t.dbPromise??null,this._eventQueue=[],this._eventPersistPromises=new Set,this._activeMemoryBatch=null,this._eventFlushInProgress=!1,this._installed=!1,this._tornDown=!1,this._visibilityHandler=null,this._pageHideHandler=null,this._navigateHandler=null,this._popstateHandler=null,this._originalPushState=null,this._originalReplaceState=null,this._usesNavigationApi=!1,this._lastUrl=null,this._permissionStatuses=[]}install(){this._installed||this._tornDown||(this._installed=!0,this._lastUrl=this._getCurrentUrl(),this._enqueueEventUnconditional("ao",{}),this._isFirstVisit&&this._enqueueEventUnconditional("ai",{}),this._isSdkUpdated&&this._enqueueEventUnconditional("au",{pv:this._previousRelease,nv:this._release}),this._sessionStartTime=Date.now(),this._visibilityHandler=()=>{try{if(typeof document>"u")return;document.visibilityState==="hidden"?(this._enqueueEvent("ab",{}),this._sessionStartTime!=null&&this._enqueueEvent("ta",{ed:Date.now()-this._sessionStartTime}),this._sessionStartTime=null):document.visibilityState==="visible"&&(this._enqueueEvent("af",{}),this._sessionStartTime=Date.now())}catch{}},typeof document<"u"&&typeof document.addEventListener=="function"&&document.addEventListener("visibilitychange",this._visibilityHandler),this._pageHideHandler=()=>{try{this._flush(!0)}catch{}},H()&&typeof window.addEventListener=="function"&&window.addEventListener("pagehide",this._pageHideHandler),this._installSpaDetection(),this._installPermissionTracking())}uninstall(){if(this._installed){if(this._visibilityHandler&&typeof document<"u"&&typeof document.removeEventListener=="function")try{document.removeEventListener("visibilitychange",this._visibilityHandler)}catch{}if(this._visibilityHandler=null,this._pageHideHandler&&H()&&typeof window.removeEventListener=="function")try{window.removeEventListener("pagehide",this._pageHideHandler)}catch{}this._pageHideHandler=null,this._uninstallSpaDetection(),this._uninstallPermissionTracking(),this._installed=!1}}teardown(){this.uninstall(),this._tornDown=!0}setEnabled(e){this._isEventTrackingEnabled=e===!0}_enqueueEvent(e,t){!this._isEventTrackingEnabled||this._tornDown||this._enqueueEventUnconditional(e,t)}trackEvent(e,t){this._enqueueEvent(e,t)}_isValidEvent(e,t){if(!h.VALID_EVENT_CODES.includes(e))return!1;let i=h.EVENT_REQUIRED_PROPS[e]??[],s=t??{};for(let r of i){let o=s[r];if(o==null||o==="")return!1}return!0}_enqueueEventUnconditional(e,t){if(this._tornDown||!this._isValidEvent(e,t))return;let i={eventId:we(),eventCode:e,timestamp:Date.now(),properties:t??{},_sessionId:this._getSessionId(),userUuid:this._getUserUuid()};this._eventQueue.push(i);let s=this._persistEvent(i);this._eventPersistPromises.add(s),s.finally(()=>this._eventPersistPromises.delete(s)),this._eventQueue.length>=30&&this._flush()}async _persistEvent(e){if(!this._dbPromise)return null;try{let i=(await this._dbPromise).transaction("events","readwrite"),s=i.objectStore("events").add({...e});return await new Promise((r,o)=>{i.oncomplete=r,i.onerror=()=>o(i.error)}),e._dbId=s.result,s.result}catch{return null}}async _readStore(e){if(!this._dbPromise)return[];let s=(await this._dbPromise).transaction(e,"readonly").objectStore(e).getAll();return new Promise((r,o)=>{s.onsuccess=()=>r(s.result||[]),s.onerror=()=>o(s.error)})}async _replaceEventBatch(e){let i=(await this._dbPromise).transaction("event_upload_batch","readwrite"),s=i.objectStore("event_upload_batch");s.clear(),e&&s.add(e),await new Promise((r,o)=>{i.oncomplete=r,i.onerror=()=>o(i.error)})}async _getOrCreateEventBatch(){if(await Promise.all([...this._eventPersistPromises]),this._dbPromise)try{let e=await this._readStore("events"),i=(await this._readStore("event_upload_batch"))[0]??null;if(i){let s=e.filter(r=>r.id<=i.lastEventId);if(s.length>0)return{uploadId:i.uploadId,events:s,persisted:!0};await this._replaceEventBatch(null)}if(e.length>0){let s={uploadId:we(),lastEventId:e[e.length-1].id};return await this._replaceEventBatch(s),{uploadId:s.uploadId,events:e,persisted:!0}}}catch{}return!this._activeMemoryBatch&&this._eventQueue.length>0&&(this._activeMemoryBatch={uploadId:we(),events:[...this._eventQueue],persisted:!1}),this._activeMemoryBatch}async _acknowledgeEventBatch(e){let t=new Set(e.events.map(i=>i.eventId));if(e.persisted&&this._dbPromise){let s=(await this._dbPromise).transaction("events","readwrite"),r=s.objectStore("events");e.events.forEach(o=>r.delete(o.id)),await new Promise((o,a)=>{s.oncomplete=o,s.onerror=()=>a(s.error)}),await this._replaceEventBatch(null)}else this._activeMemoryBatch=null;this._eventQueue=this._eventQueue.filter(i=>!t.has(i.eventId))}async _flush(e=!1){if(this._tornDown||!this._isEventTrackingEnabled||this._eventFlushInProgress||this._eventQueue.length===0&&!this._dbPromise)return;this._eventFlushInProgress=!0;let t=jt();if(!t){this._eventFlushInProgress=!1;return}let i=null;if(this._getSessionToken)try{i=await this._getSessionToken()}catch{i=null}if(!i){this._eventFlushInProgress=!1;return}try{let s=await this._getOrCreateEventBatch();if(!s||s.events.length===0)return;let r=s.events,o=new Map;for(let f of r){let m=f._sessionId;o.has(m)||o.set(m,{userUuid:f.userUuid,events:[]}),o.get(m).events.push({eventId:f.eventId,eventCode:f.eventCode,timestamp:f.timestamp,properties:f.properties})}let a=[];for(let[f,m]of o)a.push({sessionId:f,userUuid:m.userUuid,events:m.events});let l=this._getRealUserUuid()??"",c={deviceUuid:this._deviceId,sessions:a,firstRealUserUuid:l,uploadId:s.uploadId},u=je(c),d=`${this._apiBase}${h.EVENTS_PATH}`,p={method:"POST",headers:{"Content-Type":"application/x-protobuf",Accept:"application/x-protobuf","x-api-key":this._appId,"x-session-token":i},body:new Blob([u],{type:"application/x-protobuf"})};e&&(p.keepalive=!0);let _=await t(d,p);if(_.ok){if(this._logEvent)for(let f of c.sessions)for(let m of f.events)try{this._logEvent({eventId:m.eventId,eventCode:m.eventCode,eventName:h.EVENT_NAMES[m.eventCode]??m.eventCode,timestamp:m.timestamp,sessionId:f.sessionId,properties:m.properties??{}})}catch{}try{let f=new Uint8Array(await _.arrayBuffer());f.length>0&&Ge(f)}catch{}await this._acknowledgeEventBatch(s)}}catch(s){throw s}finally{this._eventFlushInProgress=!1}}_installSpaDetection(){Gt()?(this._usesNavigationApi=!0,this._navigateHandler=e=>{try{let t=e&&e.destination&&e.destination.url?e.destination.url:this._getCurrentUrl();queueMicrotask(()=>{this._lastUrl=t})}catch{}},navigation.addEventListener("navigate",this._navigateHandler)):(this._usesNavigationApi=!1,this._installHistoryPatches())}_uninstallSpaDetection(){if(this._usesNavigationApi){if(this._navigateHandler&&typeof navigation<"u"&&typeof navigation.removeEventListener=="function")try{navigation.removeEventListener("navigate",this._navigateHandler)}catch{}this._navigateHandler=null}else this._restoreHistoryPatches();if(this._popstateHandler&&H()&&typeof window.removeEventListener=="function")try{window.removeEventListener("popstate",this._popstateHandler)}catch{}this._popstateHandler=null}_installHistoryPatches(){if(typeof history>"u")return;this._originalPushState=history.pushState,this._originalReplaceState=history.replaceState;let e=this;history.pushState=function(...t){e._originalPushState.apply(this,t),e._lastUrl=e._getCurrentUrl()},history.replaceState=function(...t){e._originalReplaceState.apply(this,t),e._lastUrl=e._getCurrentUrl()},this._popstateHandler=()=>{try{this._lastUrl=this._getCurrentUrl()}catch{}},H()&&typeof window.addEventListener=="function"&&window.addEventListener("popstate",this._popstateHandler)}_restoreHistoryPatches(){typeof history>"u"||(this._originalPushState&&(history.pushState=this._originalPushState,this._originalPushState=null),this._originalReplaceState&&(history.replaceState=this._originalReplaceState,this._originalReplaceState=null))}async _installPermissionTracking(){let e=[{pt:"notification",apiName:"notifications"},{pt:"geolocation",apiName:"geolocation"},{pt:"camera",apiName:"camera"},{pt:"microphone",apiName:"microphone"}];if(typeof navigator<"u"&&navigator.permissions&&typeof navigator.permissions.query=="function")for(let{pt:i,apiName:s}of e)try{let r=await navigator.permissions.query({name:s});this._enqueueEvent("ap",{pt:i,ps:r.state}),r.onchange=()=>{try{if(!this._installed)return;this._enqueueEvent("ap",{pt:i,ps:r.state})}catch{}},this._permissionStatuses.push(r)}catch{let r=i==="notification"?this._getNotificationPermission():"unsupported";this._enqueueEvent("ap",{pt:i,ps:r})}else{this._enqueueEvent("ap",{pt:"notification",ps:this._getNotificationPermission()});for(let i of["geolocation","camera","microphone"])this._enqueueEvent("ap",{pt:i,ps:"unsupported"})}}_getNotificationPermission(){try{if(typeof Notification<"u"&&Notification.permission){let e=Notification.permission;return e==="default"?"prompt":e}}catch{}return"unsupported"}_uninstallPermissionTracking(){for(let e of this._permissionStatuses)try{e.onchange=null}catch{}this._permissionStatuses=[]}_getCurrentUrl(){try{if(typeof location<"u"&&location.href)return location.href}catch{}return""}_getReferrer(){try{if(typeof document<"u"&&document.referrer!=null)return document.referrer}catch{}return""}_getTitle(){try{if(typeof document<"u"&&document.title!=null)return document.title}catch{}return""}};function Xe(){return typeof window<"u"}var J=class{detect(){if(typeof navigator>"u")return null;let e=[];if(navigator.webdriver===!0&&e.push("webdriver"),typeof navigator.userAgent=="string"&&navigator.userAgent.toLowerCase().includes("chrome")&&Xe()&&!window.chrome&&e.push("missing_chrome_api"),Xe()){(window.__playwright__binding__!==void 0||window.__pwInitScripts__!==void 0)&&e.push("playwright_binding");for(let t of Object.keys(window))if(t.startsWith("cdc_")){e.push("cdp_marker");break}}return e.length===0?null:{id:"headless_browser_detected",weight:.9,severity:1,confidence:.9,evidence:{indicators:e.join(",")}}}};var Y=class{detect(){if(typeof window>"u")return null;let e=[];return(window.__playwright__binding__!==void 0||window.__pwInitScripts__!==void 0)&&e.push("playwright"),window.__puppeteer_evaluation_script__!==void 0&&e.push("puppeteer"),typeof document<"u"&&(document.$wdc_!==void 0||document.__webdriver_evaluate!==void 0)&&e.push("selenium"),e.length===0?null:{id:"automation_environment_detected",weight:.6,severity:1,confidence:1,evidence:{indicators:e.join(",")}}}};function Xt(n){if(n.length<2)return 0;let e=n.reduce((i,s)=>i+s,0)/n.length,t=n.reduce((i,s)=>i+(s-e)**2,0)/(n.length-1);return Math.sqrt(t)}function Jt(n){return n.length===0?0:n.reduce((e,t)=>e+t,0)/n.length}var Q=class{constructor(){this._samples=[]}recordSample(e,t,i){this._samples.push({x:e,y:t,time:i}),this._samples.length>60&&this._samples.shift()}_injectSamples(e){this._samples=e.slice(-60)}detect(){let t=(this._samples.length>0?this._samples[this._samples.length-1].time:0)-4e3,i=this._samples.filter(v=>v.time>=t);if(i.length<8)return null;let s=[];for(let v=1;v<i.length;v++)s.push(i[v].time-i[v-1].time);let r=Jt(s),o=Xt(s),a=o<18&&r<120,l=0;for(let v=1;v<i.length;v++){let le=i[v].x-i[v-1].x,Pe=i[v].y-i[v-1].y;l+=Math.sqrt(le*le+Pe*Pe)}let c=i[0],u=i[i.length-1],d=u.x-c.x,p=u.y-c.y,_=Math.sqrt(d*d+p*p),f=l>0?_/l:0,m=f>.985,k=u.time-c.time,E=i.length>=10&&k<2500,w=o<30&&r<180;return a||E&&m&&w||m&&E?{id:"automation_pointer_pattern",weight:.6,severity:1,confidence:1,evidence:{stddev:o.toFixed(2),mean_interval:r.toFixed(2),straight:f.toFixed(4),span:k.toFixed(0),samples:i.length.toString()}}:null}};function Yt(n){if(n.length<2)return 0;let e=n.reduce((i,s)=>i+s,0)/n.length,t=n.reduce((i,s)=>i+(s-e)**2,0)/(n.length-1);return Math.sqrt(t)}var Z=class{constructor(){this._timestamps=[]}recordTimestamp(e){this._timestamps.push(e),this._timestamps.length>20&&this._timestamps.shift()}_injectTimestamps(e){this._timestamps=e.slice(-20)}detect(){if(this._timestamps.length<6)return null;let e=[];for(let i=1;i<this._timestamps.length;i++)e.push(this._timestamps[i]-this._timestamps[i-1]);let t=Yt(e);return t>=20?null:{id:"keyboard_too_uniform",weight:.55,severity:1,confidence:.8,evidence:{stddev:t.toFixed(2),samples:this._timestamps.length.toString()}}}};function Qt(n){return typeof n=="string"&&n.toLowerCase().includes("chrome")&&!n.toLowerCase().includes("firefox")}var ee=class{detect(){if(typeof navigator>"u")return null;let e=navigator.userAgent,t=Qt(e),i=[],s=navigator.plugins;t&&s!==void 0&&s.length===0&&i.push("empty_plugins");let r=navigator.languages;return(!r||r.length===0)&&i.push("missing_languages"),t&&navigator.deviceMemory===void 0&&i.push("missing_device_memory"),i.length===0?null:{id:"hardware_inconsistency",weight:.4,severity:.7,confidence:.6,evidence:{indicators:i.join(",")}}}};var te=class{detect(){if(typeof window>"u")return null;let e=(window.outerWidth??0)-(window.innerWidth??0),t=(window.outerHeight??0)-(window.innerHeight??0);return e<=200&&t<=200?null:{id:"devtools_open",weight:.4,severity:.7,confidence:.75,evidence:{width_diff:e.toString(),height_diff:t.toString()}}}};var ie=class{constructor(){this._triggered=!1,this._bait=this._makeBait()}_makeBait(){let e=this,t={};return Object.defineProperty(t,"id",{enumerable:!0,configurable:!0,get(){return e._triggered=!0,""}}),t}probe(){if(!(typeof console>"u"||typeof console.log!="function")){this._triggered=!1;try{console.log("%c%o","font-size:0;color:transparent",this._bait)}catch{}}}detect(){return this._triggered?{id:"devtools_open",weight:.4,severity:.7,confidence:.6,evidence:{method:"console_getter"}}:null}};var se=class{constructor(){this._detected=null,this._method=null,this._checkPromise=this._check()}async _check(){let e=typeof window<"u"?window:null,t=e&&(e.RequestFileSystem||e.webkitRequestFileSystem);if(t&&await new Promise(s=>{try{t(0,100,()=>s(!1),()=>s(!0))}catch{s(!1)}})){this._detected=!0,this._method="filesystem_api";return}if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.estimate=="function")try{let{quota:i}=await navigator.storage.estimate();if(typeof i=="number"&&i<10485760){this._detected=!0,this._method="storage_quota";return}this._detected=!1;return}catch{}if(typeof localStorage<"u"){try{localStorage.setItem("_ld_priv_test","1"),localStorage.removeItem("_ld_priv_test"),this._detected=!1}catch{this._detected=!0,this._method="localstorage_throw"}return}this._detected=!1}detect(){return this._detected?{id:"private_browsing_detected",weight:.3,severity:.5,confidence:.7,evidence:{method:this._method??"unknown"}}:null}};var Je="_ld_cv",Ye="_ld_sm";function Zt(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function ei(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}var ne=class{detect(){let e=Zt(),t=ei();if(!e||!t||t.getItem(Ye)==="1")return null;t.setItem(Ye,"1");let i=null;try{let r=e.getItem(Je);r&&(i=JSON.parse(r))}catch{i=null}let s=(i?.n??0)+1;return e.setItem(Je,JSON.stringify({t:Date.now(),n:s})),i!==null?null:{id:"session_not_persistent",weight:.25,severity:.6,confidence:.5,evidence:{method:"localstorage_persistence",sessions:s}}}};var x=Object.freeze({JAILBREAK_DETECTED:1,DEBUGGER_ATTACHED:2,HOOKING_SUSPECTED:3,PROXY_CONFIGURED:4,VPN_SUSPECTED:5,SIMULATOR_IN_USE:6,AUTOMATION_ENVIRONMENT_DETECTED:7,AUTOMATION_TOUCH_PATTERN:8,DEVICE_CLOCK_MISMATCH:9,DEVTOOLS_OPEN:10,HEADLESS_BROWSER_DETECTED:11,AUTOMATION_POINTER_PATTERN:12,KEYBOARD_TOO_UNIFORM:13,PRIVATE_BROWSING_DETECTED:14,SESSION_NOT_PERSISTENT:15,HARDWARE_INCONSISTENCY:16}),b=Object.freeze({BLOCK_ALL_NETWORK:1,SHOW_WARNING:2,BLOCK_APP:3}),ti=new Set(Object.values(x)),ii=new Set(Object.values(b)),si=Object.freeze({devtools_open:x.DEVTOOLS_OPEN,headless_browser_detected:x.HEADLESS_BROWSER_DETECTED,automation_environment_detected:x.AUTOMATION_ENVIRONMENT_DETECTED,automation_pointer_pattern:x.AUTOMATION_POINTER_PATTERN,keyboard_too_uniform:x.KEYBOARD_TOO_UNIFORM,private_browsing_detected:x.PRIVATE_BROWSING_DETECTED,session_not_persistent:x.SESSION_NOT_PERSISTENT,hardware_inconsistency:x.HARDWARE_INCONSISTENCY});function Ze(n){return si[n]??null}function N(n){switch(n){case b.BLOCK_ALL_NETWORK:return"block_all_network";case b.SHOW_WARNING:return"show_warning";case b.BLOCK_APP:return"block_app";default:return null}}function et(n,e){let t=new Set(e??[]),i=Array.isArray(n?.rules)?n.rules:[];if(i.length===0||t.size===0)return Qe();let s=i.filter(a=>a?.enabled===!0).map(a=>{let l=(a.eventIds??[]).filter(u=>ti.has(u)),c=(a.actionIds??[]).filter(u=>ii.has(u));return{...a,eventIds:l,actionIds:c}}).filter(a=>{if(a.eventIds.length===0||a.actionIds.length===0)return!1;let l=String(a.matchType||"ANY").toUpperCase();return l==="ANY"?a.eventIds.some(c=>t.has(c)):l==="ALL"?a.eventIds.every(c=>t.has(c)):!1}).sort((a,l)=>(l.priority??0)-(a.priority??0));if(s.length===0)return Qe();let r=[...new Set(s.flatMap(a=>a.actionIds))],o=a=>s.map(l=>typeof l[a]=="string"?l[a].trim():"").find(Boolean)||null;return{matchedRules:s,actionIds:r,title:o("title"),message:o("message"),buttonText:o("buttonText")}}function tt(n){return!n||n.actionIds.length===0?null:JSON.stringify({actions:[...n.actionIds].sort((e,t)=>e-t),rules:n.matchedRules.map(e=>e.priority??0)})}function Qe(){return{matchedRules:[],actionIds:[],title:null,message:null,buttonText:null}}function ve(n){let e=1;for(let t of n)e*=1-t.weight*t.severity*t.confidence;return Math.round(Math.min(100,Math.max(0,100*(1-e))))}function it(n,e){return e?"collecting":n>=60?"automation_suspected":n>=30?"uncertain":"likely_human"}function Se(n){return n>=75?"critical":n>=50?"high":n>=25?"medium":"low"}function st(n,e){return n>=75?"critical":n>=50||e>=60?"at_risk":n>=25||e>=30?"elevated":"safe"}var ni=new Set(["headless_browser_detected","automation_environment_detected","automation_pointer_pattern","keyboard_too_uniform"]),ri=new Set(["devtools_open","private_browsing_detected","session_not_persistent","hardware_inconsistency"]),oi=3e4,ai=3e3,nt=8,li=3,L=class{constructor(e={}){let t=e??{};this._onThreatChanged=typeof t.onThreatChanged=="function"?t.onThreatChanged:null,this._onRiskEvent=typeof t.onRiskEvent=="function"?t.onRiskEvent:null,this._onPolicyChanged=typeof t.onPolicyChanged=="function"?t.onPolicyChanged:null,this._intervalMs=t.checkIntervalMs??oi,this._botDetectionEnabled=t.botDetectionEnabled!==!1,this._otherRiskTypesEnabled=t.otherRiskTypesEnabled!==!1,this._riskPolicy=t.riskPolicy??{version:0,rules:[]},this._installed=!1,this._tornDown=!1,this._snapshot=null,this._lastPosture=null,this._lastReportedSignals=new Map,this._lastPolicySignature=null,this._installTime=null,this._devtoolsOpen=!1,this._stickyLabel=null,this._consecutiveNonSuspected=0,this._headless=new J,this._automation=new Y,this._pointer=new Q,this._keyboard=new Z,this._hardware=new ee,this._devtools=new te,this._devtoolsConsole=new ie,this._incognito=new se,this._sessionPersistence=new ne,this._mousemoveHandler=null,this._keydownHandler=null,this._resizeHandler=null,this._timer=null,this._devtoolsProbeTimer=null}install(){if(!(this._installed||this._tornDown)&&(this._installed=!0,this._installTime=Date.now(),this._botDetectionEnabled&&typeof window<"u"&&typeof window.addEventListener=="function"&&(this._mousemoveHandler=e=>{try{let t=typeof performance<"u"?performance.now():Date.now();this._pointer.recordSample(e.clientX,e.clientY,t)}catch{}},window.addEventListener("mousemove",this._mousemoveHandler,{passive:!0})),this._botDetectionEnabled&&typeof document<"u"&&typeof document.addEventListener=="function"&&(this._keydownHandler=e=>{try{if(["Shift","Control","Alt","Meta"].includes(e.key))return;this._keyboard.recordTimestamp(typeof performance<"u"?performance.now():Date.now())}catch{}},document.addEventListener("keydown",this._keydownHandler,{passive:!0})),this._otherRiskTypesEnabled&&typeof window<"u"&&typeof window.addEventListener=="function"&&(this._resizeHandler=()=>{try{this._checkDevtools()}catch{}},window.addEventListener("resize",this._resizeHandler,{passive:!0})),this.evaluate(),this._otherRiskTypesEnabled&&this._checkDevtools(),this._timer=setInterval(()=>{try{this.evaluate()}catch{}},this._intervalMs),this._timer&&typeof this._timer.unref=="function"&&this._timer.unref(),h.DEVTOOLS_CONSOLE_PROBE_ENABLED&&this._otherRiskTypesEnabled&&typeof window<"u"&&typeof console<"u"&&typeof console.log=="function")){try{this._devtoolsConsole.probe(),this._checkDevtools()}catch{}this._devtoolsProbeTimer=setInterval(()=>{try{this._devtoolsConsole.probe(),this._checkDevtools()}catch{}},h.DEVTOOLS_PROBE_INTERVAL_MS),this._devtoolsProbeTimer&&typeof this._devtoolsProbeTimer.unref=="function"&&this._devtoolsProbeTimer.unref()}}_detectDevtoolsSignal(){return this._devtools.detect()||this._devtoolsConsole.detect()}_checkDevtools(){if(!this._installed||this._tornDown)return;let t=this._detectDevtoolsSignal()!==null;t&&!this._devtoolsOpen?(this._devtoolsOpen=!0,this.evaluate()):!t&&this._devtoolsOpen&&(this._devtoolsOpen=!1,this.evaluate())}teardown(){if(this._installed){if(this._tornDown=!0,this._timer!==null&&(clearInterval(this._timer),this._timer=null),this._devtoolsProbeTimer!==null&&(clearInterval(this._devtoolsProbeTimer),this._devtoolsProbeTimer=null),this._mousemoveHandler&&typeof window<"u"){try{window.removeEventListener("mousemove",this._mousemoveHandler)}catch{}this._mousemoveHandler=null}if(this._keydownHandler&&typeof document<"u"){try{document.removeEventListener("keydown",this._keydownHandler)}catch{}this._keydownHandler=null}if(this._resizeHandler&&typeof window<"u"){try{window.removeEventListener("resize",this._resizeHandler)}catch{}this._resizeHandler=null}}}evaluate(){if(!this._installed)return;let e=[...this._botDetectionEnabled?[this._headless.detect(),this._automation.detect(),this._pointer._samples.length>=nt?this._pointer.detect():null,this._keyboard._timestamps.length>=6?this._keyboard.detect():null]:[],...this._otherRiskTypesEnabled?[this._hardware.detect(),this._detectDevtoolsSignal(),this._incognito.detect(),this._sessionPersistence.detect()]:[]].filter(Boolean),t=this._botDetectionEnabled?e.filter(f=>ni.has(f.id)):[],i=this._otherRiskTypesEnabled?e.filter(f=>ri.has(f.id)):[],s=ve(t),r=ve(i),o=this._installTime!=null?Date.now()-this._installTime:1/0,a=this._pointer._samples.length>=nt,l=o<ai&&!a&&e.length===0,c=this._botDetectionEnabled?it(s,l):"disabled",u=Se(r),d=st(r,s);this._botDetectionEnabled&&c==="automation_suspected"?(this._stickyLabel="automation_suspected",this._consecutiveNonSuspected=0):this._botDetectionEnabled&&this._stickyLabel==="automation_suspected"&&(this._consecutiveNonSuspected++,this._consecutiveNonSuspected<li?c="automation_suspected":(this._stickyLabel=null,this._consecutiveNonSuspected=0));let p={};for(let f of e)for(let[m,k]of Object.entries(f.evidence??{}))p[`${f.id}.${m}`]=k;let _=i.map(f=>f.id);if((c==="automation_suspected"||c==="uncertain")&&_.push(c),_.length===0&&_.push(d==="safe"?"no_local_threats_detected":"local_heuristics_triggered"),this._snapshot={botScore:s,riskScore:r,label:c,riskLevel:u,posture:d,reasons:_,riskSignals:i.map(f=>f.id),botSignals:t.map(f=>f.id),evidence:p,timestamp:Date.now()},this._evaluatePolicy([...i,...t]),this._reportDetectedSignals(i,t),d!==this._lastPosture&&(this._lastPosture=d,this._onThreatChanged))try{this._onThreatChanged(this.getSessionThreat())}catch{}}_reportDetectedSignals(e,t){if(!this._onRiskEvent)return;let i=(s,r,o)=>{if(o==="bot"&&r<30||o==="risk"&&r<=0)return;let a=`${o}:${s.id}`;if(this._lastReportedSignals.get(a)!==r){this._lastReportedSignals.set(a,r);try{this._onRiskEvent({type:s.id,score:r,category:o,evidence:s.evidence??{},snapshot:this.getBotSnapshot()})}catch{}}};for(let s of e)i(s,this._snapshot.riskScore,"risk");for(let s of t)i(s,this._snapshot.botScore,"bot")}_evaluatePolicy(e){let t=e.map(r=>Ze(r.id)).filter(r=>r!==null),i=et(this._riskPolicy,t),s=tt(i);if(s!==this._lastPolicySignature&&(this._lastPolicySignature=s,this._onPolicyChanged))try{this._onPolicyChanged(i)}catch{}}getBotSnapshot(){return this._installed?this._snapshot?{...this._snapshot}:{botScore:0,riskScore:0,label:"collecting",riskLevel:"low",posture:"safe",reasons:["no_local_threats_detected"],riskSignals:[],botSignals:[],evidence:{},timestamp:Date.now()}:null}getSessionThreat(){if(!this._installed)return null;let e=this.getBotSnapshot();return{botScore:e.botScore,botLabel:e.label,riskScore:e.riskScore,riskLevel:e.riskLevel,posture:e.posture,reasons:[...e.reasons],timestamp:e.timestamp}}};C(L,"_computeScore",ve),C(L,"_scoreToLabel",it),C(L,"_scoreToRiskLevel",Se),C(L,"_scoresToPosture",st),C(L,"_scoreToPosture",Se);var S=Object.freeze({ERROR:"ERROR",WARNING:"WARNING",INFO:"INFO",DEBUG:"DEBUG",CRASH:"CRASH",DEVICEINFO:"DEVICEINFO",NETWORK_ACTIVITY:"NETWORK_ACTIVITY",REMOTE_MESSAGE:"REMOTE_MESSAGE",EVENT:"EVENT"}),re=Object.values(S),P=class{constructor(e,t,i=null){this.name=String(e||""),this.id=String(t||""),this.customAttributes=i||null}},ci=/(^https?:\/\/([^/]+\.)?logdrop\.io(\/|$))/i,rt="logdrop_init_cache",O="logdrop_token_recovery_identity",ke="logdrop_ip_reputation_active_action",Ee="logdrop_ip_reputation_processed_signatures",oe="logdrop_last_user_update",Ie="[REDACTED]",ui=new Set(["accesstoken","refreshtoken","token","auth"]);function Te(){let n=new Date,e=u=>String(u).padStart(2,"0"),t=u=>String(u).padStart(3,"0"),i=n.getUTCFullYear(),s=e(n.getUTCMonth()+1),r=e(n.getUTCDate()),o=e(n.getUTCHours()),a=e(n.getUTCMinutes()),l=e(n.getUTCSeconds()),c=t(n.getUTCMilliseconds());return`${i}-${s}-${r} ${o}:${a}:${l}:${c}`}function ot(n){try{return n instanceof Error?JSON.stringify({name:n.name,message:n.message,stack:n.stack}):JSON.stringify(n)}catch{return'"[unserializable]"'}}function g(){return typeof window<"u"}function at(){return g()&&window.location&&typeof window.location.href=="string"?window.location.href:"http://localhost/"}function di(n){let t=String(n||"").trim().replace(/\/+$/,""),i=h.DEFAULT_BASE_URL,s=t||i;return s.endsWith("/api/v2/sdk")?s:s.endsWith("/api")?`${s}/v2/sdk`:`${s}/api/v2/sdk`}function hi(n){let e=4294967295;for(let t=0;t<n.length;t+=1){let i=(e^n[t])&255;for(let s=0;s<8;s+=1)i=i&1?3988292384^i>>>1:i>>>1;e=e>>>8^i}return(e^4294967295)>>>0}function lt(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){let n=new Uint8Array(16);crypto.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=Array.from(n).map(t=>t.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return(n==="x"?e:e&3|8).toString(16)})}function fi(n){let t=(typeof n=="string"?n:"").trim().split(`
|
|
2
|
+
`),i=t[0]?t[0].trim():"",o=t.slice(1).filter(c=>/^\s*at /.test(c)||/@/.test(c)).slice(0,5).map(c=>{if(/^\s*at /.test(c)){let u=c.trim().match(/^at\s+([^\s(]+)/);return(u?u[1]:"").split("/").pop()||"anonymous"}else{let u=c.match(/^([^@]*)@/);return(u?u[1].trim():"").split("/").pop()||"anonymous"}}),a=i+":"+o.join(","),l=new TextEncoder().encode(a);return hi(l)}function ct(){return{url:typeof location<"u"&&location.href||"",referrer:typeof document<"u"&&document.referrer||"",visibilityState:typeof document<"u"&&document.visibilityState||"visible",onLine:typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0,viewportWidth:typeof window<"u"&&window.innerWidth||0,viewportHeight:typeof window<"u"&&window.innerHeight||0,heapUsed:typeof performance<"u"&&performance.memory?performance.memory.usedJSHeapSize:null}}var ae=class{constructor(){this._config=null,this._debugLogEnabled=!1,this._queue=[],this._flushTimer=null,this._fileFlushTimer=null,this._fileFlushInProgress=!1,this._crashFlushTimer=null,this._crashFlushDelayMs=5e3,this._crashFlushInProgress=!1,this._deviceInfoTimer=null,this._storageCheckTimer=null,this._dbPromise=null,this._initialized=!1,this._initResponse=null,this._tokenRecoveryPromise=null,this._tokenValidationState={logdrop_access_token:null,logdrop_refresh_token:null},this._sessionId=this._generateUUID(),this._sessionCreateDate=Te(),this._deviceId=this._getOrCreateDeviceId(),this._serverConfig={isSDKDisabled:!1,isHttpLoggingEnabled:!0,isCrashTrackingEnabled:!0,isEventTrackingEnabled:!1,riskConfig:null,webPushConfig:null},this._activeIpReputationAction=this._loadStoredIpReputationAction(),this._ipReputationExpiryTimer=null,this._httpCapturePolicy=null,this._loadCachedServerConfig(),this._user=this._loadPersistedExternalUser(),this._errorHandlersInstalled=!1,this._net=null,this._pushModule=null,this._inAppMessagePresenter=null,this.push=null,this._desiredWebPushSubscription=void 0,this._lastSentUserUpdate=this._loadLastSentUserUpdate(),this._activeUserUpdate=null,this._pendingUserUpdate=null,this._drainingUserUpdates=!1,this._eventModule=null,this._eventFlushTimer=null,this._riskModule=null,this._activeRiskPolicyEvaluation=null,this._riskPolicyOverlay=null,this._seenCrashes=new Set,this._crashTrackingOverride=null,this._originalFetch=null}_generateUUID(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}_isInternalLoggingEnabled(){return this._debugLogEnabled===!0}_logInternal(...e){this._isInternalLoggingEnabled()&&console.log(...e)}_warnInternal(...e){this._isInternalLoggingEnabled()&&console.warn(...e)}_errorInternal(...e){this._isInternalLoggingEnabled()&&console.error(...e)}_getProtoHexPreview(e,t=64){if(!(e instanceof Uint8Array)||e.length===0)return"empty";let i=Array.from(e.slice(0,t)).map(s=>s.toString(16).padStart(2,"0")).join(" ");return e.length>t?`${i} ...`:i}_isSensitiveProtoFieldName(e){if(typeof e!="string"||e.length===0)return!1;let t=e.replace(/[^a-z0-9]/gi,"").toLowerCase();return ui.has(t)}_summarizeProtoPayloadEntry(e,t=null){if(this._isSensitiveProtoFieldName(t))return{containsSensitiveData:!0,summary:Ie};if(e instanceof Uint8Array)return{containsSensitiveData:!1,summary:{byteLength:e.length,hexPreview:this._getProtoHexPreview(e)}};if(Array.isArray(e)){let i=!1,s=e.map(r=>{let o=this._summarizeProtoPayloadEntry(r);return i=i||o.containsSensitiveData,o.summary});return{containsSensitiveData:i,summary:s}}if(e&&typeof e=="object"){let i={},s=!1;for(let[r,o]of Object.entries(e)){let a=this._summarizeProtoPayloadEntry(o,r);i[r]=a.summary,s=s||a.containsSensitiveData}return{containsSensitiveData:s,summary:i}}return{containsSensitiveData:!1,summary:e}}_summarizeProtoPayload(e){return this._summarizeProtoPayloadEntry(e).summary}_debugLogProtoBody(e,t,i){if(!this._isInternalLoggingEnabled())return;let s=this._summarizeProtoPayloadEntry(t);this._logInternal(`[LogDrop DEBUG] ${e} payload:`,s.summary),this._logInternal(`[LogDrop DEBUG] ${e} protobuf bytes (${i.length} B): ${s.containsSensitiveData?Ie:this._getProtoHexPreview(i)}`)}_debugLogProtoResponse(e,t,i=null){if(!this._isInternalLoggingEnabled())return;if(!(t instanceof Uint8Array)||t.length===0){this._logInternal(`[LogDrop DEBUG] ${e} response body: empty`);return}let s=!1;if(typeof i=="function")try{let r=this._summarizeProtoPayloadEntry(i(t));s=r.containsSensitiveData,this._logInternal(`[LogDrop DEBUG] ${e} decoded response:`,r.summary)}catch(r){this._warnInternal(`[LogDrop DEBUG] ${e} response decode failed:`,r?.message||r)}this._logInternal(`[LogDrop DEBUG] ${e} response protobuf bytes (${t.length} B): ${s?Ie:this._getProtoHexPreview(t)}`)}_getOrCreateDeviceId(){if(this._isNewDevice=!1,!g()||typeof localStorage>"u")return this._isNewDevice=!0,this._generateUUID().replace(/-/g,"");let e="logdrop_device_id",t=localStorage.getItem(e),i=t?t.replace(/-/g,""):"";if(i.length===32){if(i!==t){t=i,this._isNewDevice=!0;try{localStorage.setItem(e,t),localStorage.removeItem("logdrop_access_token"),localStorage.removeItem("logdrop_refresh_token"),localStorage.removeItem(O),localStorage.removeItem(oe)}catch{}}return t}t=this._generateUUID().replace(/-/g,""),this._isNewDevice=!0;try{localStorage.setItem(e,t),i&&(localStorage.removeItem("logdrop_access_token"),localStorage.removeItem("logdrop_refresh_token"),localStorage.removeItem(O),localStorage.removeItem(oe))}catch{}return t}_getEffectiveUserUuid(){return this._user?.userUuid??this._deviceId}_loadPersistedExternalUser(){if(!g()||typeof localStorage>"u")return null;try{let e=localStorage.getItem("logdrop_external_user_uuid");return e?{userUuid:e}:null}catch{return null}}_persistExternalUser(e){if(!(!g()||typeof localStorage>"u"))try{localStorage.setItem("logdrop_external_user_uuid",e)}catch{}}_clearPersistedExternalUser(){if(!(!g()||typeof localStorage>"u"))try{localStorage.removeItem("logdrop_external_user_uuid")}catch{}}_isUserRegistered(){return!g()||typeof localStorage>"u"?!1:localStorage.getItem("logdrop_user_registered")==="true"}_markUserRegistered(){if(!(!g()||typeof localStorage>"u"))try{localStorage.setItem("logdrop_user_registered","true")}catch{}}_loadLastSentUserUpdate(){if(!g()||typeof localStorage>"u")return null;try{let e=localStorage.getItem(oe);if(!e)return null;let t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}_saveLastSentUserUpdate(e){if(this._lastSentUserUpdate=e,!(!g()||typeof localStorage>"u"))try{localStorage.setItem(oe,JSON.stringify(e))}catch{}}_normalizeWebPushSubscription(e){if(e==null)return null;let t=e.keys||{},i=String(e.endpoint||"").trim(),s=String(t.p256dh||e.p256dh||"").trim(),r=String(t.auth||e.auth||"").trim();if(!i||!s||!r)return null;let o=Number(e.expirationTime);return{endpoint:i,p256dh:s,auth:r,expirationTime:Number.isSafeInteger(o)&&o>0?o:null}}_webPushSubscriptionFingerprint(e){return e==null?null:JSON.stringify(e)}_handleWebPushSubscriptionChanged(e){if(e==null)return this._desiredWebPushSubscription=null,Promise.resolve(!0);let t=this._normalizeWebPushSubscription(e);return t==null?(console.warn("[LogDrop] Ignoring invalid Web Push subscription"),Promise.resolve(!1)):(this._desiredWebPushSubscription=t,this._sendUserUpdate(this._getEffectiveUserUuid(),!!this._user,{reason:"web_push_subscription_changed"}))}_normalizeTokenValue(e){if(typeof e!="string")return null;let t=e.trim();return!t||t==="null"||t==="undefined"?null:t}_normalizeTokenRecoveryIdentity(e){if(!e||typeof e!="object")return null;let t=this._normalizeTokenValue(e.userUuid);return t?{userUuid:t,isExternalUser:e.isExternalUser===!0}:null}_getPersistedTokenRecoveryIdentity(){if(!g()||typeof localStorage>"u")return null;let e=localStorage.getItem(O);if(e==null)return null;try{let t=this._normalizeTokenRecoveryIdentity(JSON.parse(e));if(t)return t}catch{}try{localStorage.removeItem(O)}catch{}return null}_clearPersistedTokenRecoveryIdentity(){if(!(!g()||typeof localStorage>"u"))try{localStorage.removeItem(O)}catch{}}_clearStoredTokens(){if(!(!g()||typeof localStorage>"u"))try{localStorage.removeItem("logdrop_access_token"),localStorage.removeItem("logdrop_refresh_token"),this._clearPersistedTokenRecoveryIdentity(),this._tokenValidationState.logdrop_access_token=null,this._tokenValidationState.logdrop_refresh_token=null}catch(e){this._warnInternal("[LogDrop] Failed to clear stored auth state:",e?.message||e)}}_getTokenRecoveryTarget(){if(this._user?.userUuid)return{userUuid:this._user.userUuid,isExternalUser:!0};let e=this._getPersistedTokenRecoveryIdentity();return e||(this._deviceId?{userUuid:this._deviceId,isExternalUser:!1}:null)}async _recoverSessionTokens(e){if(!this._config)return this._warnInternal(`[LogDrop] ${e}; cannot recover tokens before init`),!1;if(!this._config.webSecretKey)return this._warnInternal(`[LogDrop] ${e}; cannot recover tokens without webSecretKey`),!1;let t=this._getTokenRecoveryTarget();if(!t)return this._warnInternal(`[LogDrop] ${e}; no recovery identity is available`),!1;if(this._tokenRecoveryPromise)return this._tokenRecoveryPromise;this._warnInternal(`[LogDrop] ${e}; attempting signature-based re-auth`),this._tokenRecoveryPromise=(async()=>{let i=await this._sendUserUpdate(t.userUuid,t.isExternalUser);return i||this._warnInternal("[LogDrop] Signature-based re-auth did not recover session tokens"),i})();try{return await this._tokenRecoveryPromise}finally{this._tokenRecoveryPromise=null}}_getStoredToken(e,t){if(!g()||typeof localStorage>"u")return null;let i=localStorage.getItem(e),s=this._normalizeTokenValue(i);if(s)return this._tokenValidationState[e]=null,s;let r=i==null?"missing":"invalid";if(i!=null)try{localStorage.removeItem(e)}catch{}return this._tokenValidationState[e]!==r&&(this._tokenValidationState[e]=r,this._warnInternal(`[LogDrop] Stored ${t} is ${r}; treating it as a deleted token`)),null}async _ensureSessionToken(e){let t=this._getAccessToken();return t||(await this._recoverSessionTokens(e)?(t=this._getAccessToken(),t||this._warnInternal(`[LogDrop] ${e}; re-auth succeeded but no access token was persisted`),t):null)}_getAccessToken(){return this._getStoredToken("logdrop_access_token","access token")}_getRefreshToken(){return this._getStoredToken("logdrop_refresh_token","refresh token")}_saveTokens(e,t,i=null){if(!g()||typeof localStorage>"u")return this._warnInternal("[LogDrop] Failed to persist session tokens: localStorage is unavailable"),!1;let s=this._normalizeTokenValue(e),r=this._normalizeTokenValue(t),o=this._normalizeTokenRecoveryIdentity(i||this._getTokenRecoveryTarget());if(!s&&!r)return this._warnInternal("[LogDrop] Failed to persist session tokens: no valid tokens were provided"),!1;try{return o?localStorage.setItem(O,JSON.stringify(o)):this._clearPersistedTokenRecoveryIdentity(),s&&(localStorage.setItem("logdrop_access_token",s),this._tokenValidationState.logdrop_access_token=null),r&&(localStorage.setItem("logdrop_refresh_token",r),this._tokenValidationState.logdrop_refresh_token=null),!0}catch(a){return this._warnInternal("[LogDrop] Failed to persist session tokens:",a?.message||a),!1}}async _computeSignature(e,t){let i=new TextEncoder().encode(e+t),s=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(s)).map(o=>o.toString(16).padStart(2,"0")).join("")}_getOsInfo(){if(!g()||!navigator)return{osName:"Unknown",osVersion:"Unknown"};let e=navigator.userAgent,t="Unknown",i="Unknown";if(e.includes("Windows")){t="Windows";let s=e.match(/Windows NT (\d+\.\d+)/);s&&(i=s[1])}else if(e.includes("iPhone")||e.includes("iPad")){t="iOS";let s=e.match(/OS (\d+[._]\d+)/);s&&(i=s[1].replace(/_/g,"."))}else if(e.includes("Mac OS X")){t="macOS";let s=e.match(/Mac OS X (\d+[._]\d+[._]?\d*)/);s&&(i=s[1].replace(/_/g,"."))}else if(e.includes("Android")){t="Android";let s=e.match(/Android (\d+(\.\d+)?)/);s&&(i=s[1])}else e.includes("Linux")&&(t="Linux");return{osName:t,osVersion:i}}_getDeviceBrand(){if(!g()||!navigator)return"Unknown";let e=navigator.userAgent;return e.includes("Samsung")?"Samsung":e.includes("Huawei")?"Huawei":e.includes("Xiaomi")||e.includes("Redmi")?"Xiaomi":e.includes("OPPO")?"OPPO":e.includes("Vivo")?"Vivo":e.includes("OnePlus")?"OnePlus":e.includes("LG")?"LG":e.includes("Sony")?"Sony":e.includes("HTC")?"HTC":e.includes("Motorola")?"Motorola":e.includes("Nokia")?"Nokia":e.includes("Google")||e.includes("Pixel")?"Google":e.includes("iPhone")||e.includes("iPad")||e.includes("Macintosh")?"Apple":e.includes("Chrome")?"Google":e.includes("Firefox")?"Mozilla":e.includes("Safari")?"Apple":e.includes("Edge")?"Microsoft":"Unknown"}_createUserUpdateTask(e,t,i={}){let s=this._desiredWebPushSubscription===void 0?void 0:this._normalizeWebPushSubscription(this._desiredWebPushSubscription),r={userUuid:String(e||this._deviceId),isExternalUser:t===!0,webPushSubscription:s,reason:i.reason||"user_update"};return{...r,key:JSON.stringify(r),waiters:[]}}_sendUserUpdate(e,t=!1,i={}){if(!this._config)return Promise.resolve(!1);let s=this._createUserUpdateTask(e,t,i);return new Promise(r=>{if(this._activeUserUpdate?.key===s.key){this._activeUserUpdate.waiters.push(r);return}this._pendingUserUpdate?.key===s.key?this._pendingUserUpdate.waiters.push(r):this._pendingUserUpdate?(s.waiters.push(...this._pendingUserUpdate.waiters,r),this._pendingUserUpdate=s):(s.waiters.push(r),this._pendingUserUpdate=s),this._drainUserUpdates()})}async _drainUserUpdates(){if(!this._drainingUserUpdates){this._drainingUserUpdates=!0;try{for(;this._pendingUserUpdate;){let e=this._pendingUserUpdate;this._pendingUserUpdate=null,this._activeUserUpdate=e;let t=!1;try{t=await this._performUserUpdate(e)}catch(i){console.warn("[LogDrop] User update failed:",i?.message||i)}for(let i of e.waiters)i(t);this._activeUserUpdate=null}}finally{this._activeUserUpdate=null,this._drainingUserUpdates=!1,this._pendingUserUpdate&&this._drainUserUpdates()}}}async _performUserUpdate(e){let t=this._config;if(!t)return!1;let i=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof i!="function")return!1;let s=this._getOsInfo(),r=this._lastSentUserUpdate?.appId===t.appId?this._lastSentUserUpdate:null,o={appId:t.appId,userUuid:e.userUuid,osName:s.osName,osVersion:s.osVersion,deviceBrand:this._getDeviceBrand(),deviceModel:this._parseDeviceModel(navigator?.userAgent||"")||"Web Browser",appVersion:t.release||"1.0",sdkVersion:h.SDK_VERSION,webPushFingerprint:e.webPushSubscription===void 0?r?.webPushFingerprint:this._webPushSubscriptionFingerprint(e.webPushSubscription)},a={deviceUuid:this._deviceId,sdkType:"WEB"},l=["osName","osVersion","deviceBrand","deviceModel","appVersion","sdkVersion"];for(let w of l)(!r||o[w]!==r[w])&&(a[w]=o[w]);let c=e.webPushSubscription!==void 0&&(!r||o.webPushFingerprint!==r.webPushFingerprint);e.webPushSubscription&&c&&(a.webPushSubscription=e.webPushSubscription);let u=!r||o.userUuid!==r.userUuid,d=Object.keys(a).some(w=>!["deviceUuid","sdkType"].includes(w)),p=this._getAccessToken(),_=this._getRefreshToken();if(!u&&!d&&p&&_)return this._logInternal(`[LogDrop] User update skipped; no changes (${e.reason})`),!0;let f={"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":t.appId},m=!1;if(p)f["x-session-token"]=p;else if(t.webSecretKey)f["x-logdrop-signature"]=await this._computeSignature(t.webSecretKey,this._deviceId),m=!0;else return!1;let k={userUuid:e.userUuid,device:a},E=He(k);this._debugLogProtoBody("User update request",k,E);try{if(this._config!==t)return!1;let w=`${t.baseUrl}${h.USERS_UPDATE_PATH}`,R=await i(w,{method:"POST",headers:f,body:new Blob([E],{type:"application/x-protobuf"})});if(!R.ok||this._config!==t)return!1;if(m)try{let U=new Uint8Array(await R.arrayBuffer());if(this._debugLogProtoResponse("User update",U,me),U.length>0){let v=me(U);this._saveTokens(v.accessToken,v.refreshToken,{userUuid:e.userUuid,isExternalUser:e.isExternalUser})}}catch{}return this._saveLastSentUserUpdate(o),e.isExternalUser||this._markUserRegistered(),this._logInternal(`[LogDrop] User update successful (${e.reason})`),m&&this._desiredWebPushSubscription===void 0&&this._pushModule?.reconcileGrantedSubscription(),!0}catch(w){return console.warn("[LogDrop] User update failed:",w.message||w),this._warnInternal("[LogDrop] User update failed:",w.message||w),!1}}async _getDeviceInfo(){let e={sessionID:this._sessionId,session_create_date:this._sessionCreateDate,device_id:this._deviceId,userUuid:this._getEffectiveUserUuid(),gmt:-new Date().getTimezoneOffset()};if(this._riskModule){let t=this._riskModule.getBotSnapshot();t&&(e.bot_score=t.botScore,e.bot_label=t.label,e.risk_score=t.riskScore,e.posture=t.posture)}if(g()&&navigator){if(navigator.language&&(e.locale=navigator.language),typeof navigator.onLine=="boolean"&&(e.network_available=navigator.onLine),navigator.deviceMemory&&(e.ram_size=`${navigator.deviceMemory} GB`),navigator.hardwareConcurrency&&(e.cpu_cores=navigator.hardwareConcurrency),navigator.platform&&(e.os_version=navigator.platform),navigator.userAgent){e.user_agent=navigator.userAgent;let t=this._parseDeviceModel(navigator.userAgent);t&&(e.device_model=t)}navigator.connection&&(navigator.connection.effectiveType&&(e.connection_type=navigator.connection.effectiveType),typeof navigator.connection.downlink=="number"&&(e.connection_downlink_mbps=navigator.connection.downlink),typeof navigator.connection.rtt=="number"&&(e.connection_rtt_ms=navigator.connection.rtt),typeof navigator.connection.saveData=="boolean"&&(e.save_data_mode=navigator.connection.saveData));try{if(navigator.getBattery){let t=await navigator.getBattery();typeof t.level=="number"&&(e.battery_level=`${Math.round(t.level*100)}%`),typeof t.charging=="boolean"&&(e.low_power_mode=!t.charging&&t.level<.2,e.is_charging=t.charging)}}catch{}try{if(navigator.storage&&navigator.storage.estimate){let t=await navigator.storage.estimate();if(t.quota&&t.usage){let i=t.quota-t.usage;e.free_disk_space=this._formatBytes(i),e.total_disk_quota=this._formatBytes(t.quota)}}}catch{}}return g()&&window.screen&&(e.screen_width=window.screen.width,e.screen_height=window.screen.height,e.screen_color_depth=window.screen.colorDepth,window.devicePixelRatio&&(e.device_pixel_ratio=window.devicePixelRatio)),g()&&document.visibilityState&&(e.visibility_state=document.visibilityState),g()&&window.location&&(e.page_url=window.location.href,document.referrer&&(e.referrer=document.referrer)),this._config&&this._config.release&&(e.app_version=this._config.release),e}_getUserAgentData(){if(!g()||!navigator)return null;let e=navigator.userAgentData;return!e||typeof e!="object"?null:e}_parseDeviceModel(e){if(!g()||!navigator)return null;let t=this._getUserAgentData();if(t&&typeof t.model=="string"&&t.model.trim())return t.model.trim();let i=e.match(/\(([^)]+)\)/);if(i){let l=i[1].split(";").map(u=>u.trim()),c=l.find(u=>/^(SM-|Pixel|Nexus|LG-|HTC|Huawei|Xiaomi|OPPO|Vivo|OnePlus)/i.test(u));if(c)return c;if(l.some(u=>u.includes("iPhone")))return"iPhone";if(l.some(u=>u.includes("iPad")))return"iPad"}let s=this._getOsInfo(),r=this._getBrowserInfo(),o=`${s.osName} ${s.osVersion}`.trim(),a=`${r.name} ${r.version}`.trim();return`${o} - ${a}`.trim()}_getBrowserInfo(){if(!g()||!navigator)return{name:"Unknown",version:"Unknown"};let e=this._getUserAgentData();if(e&&Array.isArray(e.brands)){let a=e.brands.find(l=>/Chrome/i.test(l.brand))||e.brands.find(l=>/Chromium/i.test(l.brand))||e.brands[0];return{name:a?.brand||"Unknown",version:a?.version||"Unknown"}}let t=navigator.userAgent,i=t.match(/Edg\/(\d+)/);if(i)return{name:"Edge",version:i[1]};let s=t.match(/Chrome\/(\d+)/);if(s)return{name:"Chrome",version:s[1]};let r=t.match(/Firefox\/(\d+)/);if(r)return{name:"Firefox",version:r[1]};let o=t.match(/Version\/(\d+).+Safari/);return o&&!t.includes("Chrome")?{name:"Safari",version:o[1]}:{name:"Unknown",version:"Unknown"}}_formatBytes(e){if(e===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB","TB"],s=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,s)).toFixed(2))+" "+i[s]}_scheduleDeviceInfoCollection(){this._deviceInfoTimer&&clearInterval(this._deviceInfoTimer),this._collectAndLogDeviceInfo(),this._deviceInfoTimer=setInterval(()=>{this._collectAndLogDeviceInfo()},h.DEVICE_INFO_INTERVAL_MS),this._deviceInfoTimer&&typeof this._deviceInfoTimer.unref=="function"&&this._deviceInfoTimer.unref()}async _collectAndLogDeviceInfo(){if(this._config)try{let e=await this._getDeviceInfo();this._enqueue(S.DEVICEINFO,e)}catch{}}_loadCachedServerConfig(){if(!(!g()||typeof localStorage>"u"))try{let e=localStorage.getItem(rt);if(e){let t=JSON.parse(e);t&&t.data&&(typeof t.data.isSDKDisabled=="boolean"&&(this._serverConfig.isSDKDisabled=t.data.isSDKDisabled),this._httpCapturePolicy=$(t.data))}}catch{}}_saveServerConfigToCache(e){if(!(!g()||typeof localStorage>"u"))try{localStorage.setItem(rt,JSON.stringify(e))}catch{}}_applyServerConfig(e,t=!1){if(!e)return;let i=this._serverConfig.isHttpLoggingEnabled;if(typeof e.isSDKDisabled=="boolean"&&(this._serverConfig.isSDKDisabled=e.isSDKDisabled),typeof e.isHttpLoggingEnabled=="boolean"&&(this._serverConfig.isHttpLoggingEnabled=e.isHttpLoggingEnabled),("httpDomainBlackList"in e||"httpPayloadCaptureConfig"in e||"sensitiveInfoFilter"in e)&&(this._httpCapturePolicy=$(e)),typeof e.isCrashTrackingEnabled=="boolean"&&this._crashTrackingOverride===null&&(this._serverConfig.isCrashTrackingEnabled=e.isCrashTrackingEnabled),this._pushModule&&typeof e.isPushEnabled=="boolean"&&(this._pushModule.isPushEnabled=e.isPushEnabled),typeof e.isEventTrackingEnabled=="boolean"&&(this._serverConfig.isEventTrackingEnabled=e.isEventTrackingEnabled,this._eventModule?.setEnabled(e.isEventTrackingEnabled)),e.riskConfig&&typeof e.riskConfig=="object"&&(this._serverConfig.riskConfig=e.riskConfig),e.webPushConfig&&typeof e.webPushConfig=="object"&&(this._serverConfig.webPushConfig=e.webPushConfig,this._pushModule&&this._pushModule.updateServerConfig({isPushEnabled:e.webPushConfig.enabled===!0,vapidPublicKey:e.webPushConfig.vapidPublicKey||null})),this._serverConfig.isSDKDisabled&&this._initialized){this._warnInternal("[LogDrop] SDK disabled by server, clearing all logs and shutting down"),this._clearLogs().catch(()=>{}),this._initialized=!1,this._config=null,this.teardown();return}e.riskConfig&&typeof e.riskConfig=="object"&&this._syncRiskModuleFromServerConfig(),Object.prototype.hasOwnProperty.call(e,"activeIpReputationAction")&&this._applyIpReputationActionFromInit(e.activeIpReputationAction,e.serverNowEpochMillis),t&&this._config&&(this._serverConfig.isHttpLoggingEnabled&&!i?this._installNetworkInstrumentation():!this._serverConfig.isHttpLoggingEnabled&&i&&(this._logInternal("[LogDrop] HTTP logging disabled by server, clearing network logs"),this._uninstallNetworkInstrumentation(),this._clearNetworkLogs()),this._activeRiskPolicyEvaluation?.actionIds?.includes(b.BLOCK_ALL_NETWORK)&&this._refreshNetworkInstrumentationForRiskPolicy())}_installNetworkInstrumentation(e=!1){!this._config||this._net||(this._net=new W({onEvent:(t,i)=>{t==="network_activity"&&(!this._serverConfig.isHttpLoggingEnabled||!this._config?.network?.enabled||this._recordNetworkActivity(i))},getBaseHref:at,excludeUrls:this._config.network.excludeUrls,shouldBlockRequest:t=>this._shouldBlockNetworkRequest(t),redaction:{stripQuery:this._config.network.stripQuery,stripHash:this._config.network.stripHash},sampling:{rate:this._config.network.sampleRate,onlyErrors:this._config.network.onlyErrors,slowThresholdMs:this._config.network.slowThresholdMs},capture:{fetch:e||this._config.network.captureFetch,xhr:e||this._config.network.captureXHR,headersAllowlist:this._config.network.headersAllowlist}}),this._net.install())}_recordNetworkActivity(e){let t=_e(e,this._httpCapturePolicy);t&&this._enqueue(S.NETWORK_ACTIVITY,t,new P("NetworkActivity",t.uuid))}_applyHttpCapturePolicyToStoredLog(e){let t=this._httpCapturePolicy;if(!t||e.level===S.DEVICEINFO||e.httpPolicyFingerprint===t.fingerprint)return e.message;if(e.level!==S.NETWORK_ACTIVITY)return A(e.message,t.sensitivePatterns);let i;try{i=JSON.parse(e.message)}catch{return A(e.message,t.sensitivePatterns)}let s=_e(i,t);return s?ot(s):null}_uninstallNetworkInstrumentation(){this._net&&(this._net.uninstall(),this._net=null)}_shouldBlockNetworkRequest(e){let t=this._activeRiskPolicyEvaluation?.actionIds?.includes(b.BLOCK_ALL_NETWORK)===!0,i=this._getActiveIpReputationAction()?.actionIds?.includes(b.BLOCK_ALL_NETWORK)===!0;if(!t&&!i)return!1;try{let s=new URL(e,at()),r=new URL(this._config?.baseUrl??h.DEFAULT_BASE_URL);if(s.origin.toLowerCase()!==r.origin.toLowerCase())return!0;let o=r.pathname.replace(/\/+$/,""),a=s.pathname.replace(/\/+$/,"");return!(a===o||a.startsWith(`${o}/`))}catch{return!0}}_loadStoredIpReputationAction(){if(!g()||typeof localStorage>"u")return null;try{let e=localStorage.getItem(ke),t=e?JSON.parse(e):null;return t&&typeof t.signature=="string"&&t.signature?t:null}catch{return null}}_persistIpReputationAction(e){if(!(!g()||typeof localStorage>"u"))try{e?localStorage.setItem(ke,JSON.stringify(e)):localStorage.removeItem(ke)}catch{}}_trustedNowForIpReputation(e){let t=Number(e?.receivedServerEpochMillis),i=Number(e?.receivedAtClientEpochMillis),s=Number(e?.receivedAtMonotonicMillis),r=Number(e?.receivedPerformanceTimeOrigin),o=typeof performance<"u"?Number(performance.now?.()):NaN,a=typeof performance<"u"?Number(performance.timeOrigin):NaN;return Number.isFinite(t)&&t>0&&Number.isFinite(s)&&Number.isFinite(o)&&Number.isFinite(r)&&r===a?t+Math.max(0,o-s):Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0?t+Math.max(0,Date.now()-i):Date.now()}_isIpReputationActionExpired(e){let t=Number(e?.expireAtEpochMillis);return!Number.isFinite(t)||t<=this._trustedNowForIpReputation(e)}_getActiveIpReputationAction(){let e=this._activeIpReputationAction;return e?this._isIpReputationActionExpired(e)?(this._clearIpReputationAction("expired"),null):e:null}_resolveIpReputationPresentation(e){let i=(this._serverConfig.riskConfig?.ipReputationDetected?.riskPolicy?.rules??[]).filter(s=>s?.enabled===!0&&(s.threatLevels??[]).includes(e.threatLevel)).sort((s,r)=>(r.priority??0)-(s.priority??0))[0];return{...e,title:e.title||i?.title||null,message:e.message||i?.message||null,buttonText:e.buttonText||i?.buttonText||null}}_hasProcessedIpReputationSignature(e){if(!g()||typeof localStorage>"u")return!1;try{let t=JSON.parse(localStorage.getItem(Ee)||"[]");return Array.isArray(t)&&t.includes(e)}catch{return!1}}_markIpReputationSignatureProcessed(e){if(!(!g()||typeof localStorage>"u"||!e))try{let t=JSON.parse(localStorage.getItem(Ee)||"[]"),s=[...(Array.isArray(t)?t.filter(r=>typeof r=="string"):[]).filter(r=>r!==e),e].slice(-100);localStorage.setItem(Ee,JSON.stringify(s))}catch{}}_scheduleIpReputationExpiry(){this._ipReputationExpiryTimer&&clearTimeout(this._ipReputationExpiryTimer),this._ipReputationExpiryTimer=null;let e=this._activeIpReputationAction;if(!e)return;let t=Number(e.expireAtEpochMillis)-this._trustedNowForIpReputation(e);if(t<=0){this._clearIpReputationAction("expired");return}this._ipReputationExpiryTimer=setTimeout(()=>this._scheduleIpReputationExpiry(),Math.min(t,2147e6)),typeof this._ipReputationExpiryTimer?.unref=="function"&&this._ipReputationExpiryTimer.unref()}_applyIpReputationActionFromInit(e,t){if(!e||typeof e.signature!="string"||!e.signature.trim()){this._clearIpReputationAction("cleared");return}let i=Date.now(),s=this._resolveIpReputationPresentation({...e,signature:e.signature.trim(),eventId:String(e.eventId||e.signature),actionIds:[...new Set((e.actionIds??[]).filter(o=>N(o)))],receivedServerEpochMillis:Number(t)||i,receivedAtClientEpochMillis:i,receivedAtMonotonicMillis:typeof performance<"u"?Number(performance.now?.()):null,receivedPerformanceTimeOrigin:typeof performance<"u"?Number(performance.timeOrigin):null});if(this._isIpReputationActionExpired(s)){this._clearIpReputationAction("expired");return}let r=!this._hasProcessedIpReputationSignature(s.signature);this._activeIpReputationAction=s,this._persistIpReputationAction(s),this._markIpReputationSignatureProcessed(s.signature),this._scheduleIpReputationExpiry(),this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation,r)}_restoreIpReputationActionIfNeeded(){this._getActiveIpReputationAction()&&(this._scheduleIpReputationExpiry(),this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation,!1))}_clearIpReputationAction(e="cleared"){let t=this._activeIpReputationAction;if(this._ipReputationExpiryTimer&&clearTimeout(this._ipReputationExpiryTimer),this._ipReputationExpiryTimer=null,this._activeIpReputationAction=null,this._persistIpReputationAction(null),t&&this._eventModule){let i=t.actionIds??[];this._eventModule.trackEvent(h.EVENT_CODES.SDK_ACTION_CLEARED,{as:"ip_reputation",cr:e,bl:i.includes(b.BLOCK_APP)||i.includes(b.BLOCK_ALL_NETWORK),sig:t.signature,saa:i.map(N).filter(Boolean).join(",")||"none"}),Promise.resolve(this._eventModule._flush()).catch(()=>{})}this._config&&(this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation))}_syncRiskModuleFromServerConfig(){let e=this._serverConfig.riskConfig?.riskDetected,t=e?.enabled===!0&&(e.botDetectionEnabled===!0||e.otherRiskTypesEnabled===!0);this._riskModule?.teardown(),this._riskModule=null,this._activeRiskPolicyEvaluation?this._handleRiskPolicyChanged({matchedRules:[],actionIds:[],title:null,message:null,buttonText:null}):(this._activeRiskPolicyEvaluation=null,this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(null)),!(!t||!this._initialized||!this._config)&&(this._riskModule=new L({botDetectionEnabled:e.botDetectionEnabled===!0,otherRiskTypesEnabled:e.otherRiskTypesEnabled===!0,riskPolicy:e.riskPolicy,onThreatChanged:this._config.onSessionThreatChanged??null,onRiskEvent:i=>this._handleRiskEvent(i),onPolicyChanged:i=>this._handleRiskPolicyChanged(i),checkIntervalMs:3e4}),this._riskModule.install())}init(e){if(this._debugLogEnabled=e?.debugLogEnabled===!0||e?.isDebugLogEnabled===!0,this._initialized)return;if(this._serverConfig.isSDKDisabled){this._warnInternal("[LogDrop] SDK is disabled by server configuration");return}let t=String(e?.appId||"").trim();if(!t)throw new Error("LogDrop.init requires config.appId");let i=e.webSecretKey==null?h.DEFAULT_WEB_SECRET_KEY:e.webSecretKey,s=String(i||"").trim()||null,r=di(e.baseUrl),o=r,a={enabled:e.network?.enabled!==!1,captureFetch:e.network?.captureFetch!==!1,captureXHR:e.network?.captureXHR!==!1,stripQuery:e.network?.stripQuery!==!1,stripHash:e.network?.stripHash!==!1,sampleRate:typeof e.network?.sampleRate=="number"?e.network.sampleRate:1,onlyErrors:e.network?.onlyErrors===!0,slowThresholdMs:typeof e.network?.slowThresholdMs=="number"?e.network.slowThresholdMs:void 0,headersAllowlist:Array.isArray(e.network?.headersAllowlist)?e.network.headersAllowlist:[],excludeUrls:[ci,r,o,h.DEFAULT_BASE_URL,...Array.isArray(e.network?.excludeUrls)?e.network.excludeUrls:[]]};this._config={appId:t,webSecretKey:s,baseUrl:r,endpoint:o,env:e.env?String(e.env):"prod",release:e.release?String(e.release):void 0,debugLogEnabled:this._debugLogEnabled,flushIntervalMs:typeof e.flushIntervalMs=="number"?e.flushIntervalMs:6e4,maxBatchSize:typeof e.maxBatchSize=="number"?e.maxBatchSize:50,network:a,vapidPublicKey:e.vapidPublicKey?String(e.vapidPublicKey):null,manualServiceWorkerRegistration:e.manualServiceWorkerRegistration===!0,serviceWorkerUrl:e.serviceWorkerUrl?String(e.serviceWorkerUrl):h.PUSH_SW_PATH,serviceWorkerScope:e.serviceWorkerScope?String(e.serviceWorkerScope):h.PUSH_SW_SCOPE,serviceWorkerRegistration:e.serviceWorkerRegistration??null,onRemoteMessageReceived:typeof e.onRemoteMessageReceived=="function"?e.onRemoteMessageReceived:null,onSessionThreatChanged:typeof e.onSessionThreatChanged=="function"?e.onSessionThreatChanged:null,onRiskPolicyActionTaken:typeof e.onRiskPolicyActionTaken=="function"?e.onRiskPolicyActionTaken:null},typeof e.crashTracking=="boolean"?(this._serverConfig.isCrashTrackingEnabled=e.crashTracking,this._crashTrackingOverride=e.crashTracking):this._crashTrackingOverride=null,h.DEBUG_LOGS_ENABLED=!["prod","production"].includes(this._config.env),this._installGlobalErrorHandlers(),this._initDb(),this._inAppMessagePresenter=new G({onAction:d=>this._handleWebPushClick(d)}),this._pushModule=new j({vapidPublicKey:this._config.vapidPublicKey,manualServiceWorkerRegistration:this._config.manualServiceWorkerRegistration,serviceWorkerUrl:this._config.serviceWorkerUrl,serviceWorkerScope:this._config.serviceWorkerScope,serviceWorkerRegistration:this._config.serviceWorkerRegistration,isPushEnabled:!0,onRemoteMessageReceived:this._config.onRemoteMessageReceived,appId:this._config.appId,apiBase:this._config.baseUrl,deviceId:this._deviceId,getSessionToken:()=>this._getAccessToken(),onPushReceived:d=>this._handleWebPushReceived(d),onNotificationClick:d=>this._handleWebPushClick(d),onSubscriptionChanged:d=>this._handleWebPushSubscriptionChanged(d)}),this._pushModule.install(),this.push={subscribe:()=>this._pushModule.subscribe(),unsubscribe:()=>this._pushModule.unsubscribe(),getPermissionState:()=>this._pushModule.getPermissionState()};let l=g()&&localStorage?localStorage.getItem("logdrop_last_release"):null,c=!!(this._config.release&&l&&this._config.release!==l),u=l;if(this._config.release&&g()&&localStorage)try{localStorage.setItem("logdrop_last_release",this._config.release)}catch{}this._eventModule=new X({deviceId:this._deviceId,getSessionId:()=>this._sessionId,getUserUuid:()=>this._getEffectiveUserUuid(),getRealUserUuid:()=>this._user?.userUuid??null,getSessionToken:()=>this._ensureSessionToken("Event upload requires a valid access token"),logEvent:d=>this._enqueue(S.EVENT,d),release:this._config.release,appId:this._config.appId,apiBase:this._config.baseUrl,isEventTrackingEnabled:this._serverConfig.isEventTrackingEnabled,isFirstVisit:this._isNewDevice,isSdkUpdated:c,previousRelease:u,dbPromise:this._dbPromise}),this._eventModule.install(),this._pushModule?.requestPendingMessages(),this._scheduleEventFlush(),this._initialized=!0,this._sendInitRequest(),this._uninstallNetworkInstrumentation(),this._config.network.enabled&&this._serverConfig.isHttpLoggingEnabled&&this._installNetworkInstrumentation(),this._restoreIpReputationActionIfNeeded(),this._scheduleFlush(),this._scheduleFileFlush(),this._scheduleDeviceInfoCollection(),this._scheduleStorageCheck(),this.i("LogDrop initialized",{appId:this._config.appId,env:this._config.env,release:this._config.release,networkEnabled:this._config.network.enabled})}async updateUser(e,t){if(!e){this._user=null,this._clearPersistedExternalUser(),this._clearStoredTokens(),this.i("User cleared"),typeof t=="function"&&t(!0);return}let i=String(e);this._user?.userUuid&&this._user.userUuid!==i&&(this._sessionId=this._generateUUID(),this._sessionCreateDate=Te()),this._user={userUuid:i},this._persistExternalUser(i);let s=await this._sendUserUpdate(i,!0,{reason:"developer_user_update"});this.i("User updated",{userUuid:i,success:s}),typeof t=="function"&&t(s)}e(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!re.includes(e);this._enqueue(S.ERROR,s?t:e,s?i:t instanceof P?t:null,s?e:null)}w(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!re.includes(e);this._enqueue(S.WARNING,s?t:e,s?i:t instanceof P?t:null,s?e:null)}i(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!re.includes(e);this._enqueue(S.INFO,s?t:e,s?i:t instanceof P?t:null,s?e:null)}d(e,t,i=null){let s=typeof e=="string"&&typeof t=="string"&&!re.includes(e);this._enqueue(S.DEBUG,s?t:e,s?i:t instanceof P?t:null,s?e:null)}log(e,t,i,s=null){this._enqueue(i,t,s,e)}onRemoteMessageReceived(e){this._config&&typeof this._config.onRemoteMessageReceived=="function"&&this._config.onRemoteMessageReceived(e)}saveCustomCrashReport(e,t,i="CUSTOM"){this._serverConfig.isCrashTrackingEnabled&&this._recordCrash({threadName:e||"MainThread",stackTrace:String(t||""),crashType:i||"CUSTOM",isCustomCrash:!0})}_handleRiskEvent(e){if(!this._config||!e||!this._eventModule)return;let t=e.score??e.snapshot?.riskScore??e.snapshot?.score??0,i=this._activeRiskPolicyEvaluation?.actionIds??[],s=i.map(N).filter(Boolean),r=i.includes(b.BLOCK_APP)||i.includes(b.BLOCK_ALL_NETWORK);this._eventModule.trackEvent(h.EVENT_CODES.RISK_DETECTED,{rt:e.type,rs:t,bl:r,ev:e.evidence??{},saa:s.join(",")||"none"}),Promise.resolve(this._eventModule._flush()).catch(()=>{})}_webPushData(e){return!e||typeof e!="object"?{}:e.data&&typeof e.data=="object"?e.data:e}_handleWebPushReceived(e){let t=this._webPushData(e),i=typeof t.action=="string"?t.action:t.rawExtras?.action,s=String(t.notificationId||t.receiveEvent?.properties?.pn||"").trim();if(s&&this._eventModule&&(this._eventModule.trackEvent(h.EVENT_CODES.PUSH_RECEIVED,{pn:s}),Promise.resolve(this._eventModule._flush()).catch(()=>{})),this._inAppMessagePresenter?.enqueue(e),i==="ip_reputation_action"?this._applyIpReputationActionFromInit({signature:t.signature||"",eventId:t.eventId||t.signature||"",threatLevel:t.threatLevel||"UNSPECIFIED",riskScore:Number(t.riskScore)||0,actionIds:String(t.actionIds||"").split(",").map(r=>Number(r.trim())).filter(Number.isInteger),expireAtEpochMillis:Number(t.expireAt)||0,title:t.title||null,message:t.message||null,buttonText:t.buttonText||null},Number(t.serverNow)||Date.now()):i==="send_log"&&(this.sendLogs().catch(()=>{}),Promise.resolve(this._eventModule?._flush()).catch(()=>{})),typeof this._config?.onRemoteMessageReceived=="function")try{this._config.onRemoteMessageReceived(e)}catch{}}_handleWebPushClick(e){let t=this._webPushData(e),i=String(t.notificationId||t.clickEvent?.properties?.pn||"").trim();if(i&&this._eventModule&&(this._eventModule.trackEvent(h.EVENT_CODES.PUSH_CLICK,{pn:i}),Promise.resolve(this._eventModule._flush()).catch(()=>{})),typeof this._config?.onRemoteMessageReceived=="function")try{this._config.onRemoteMessageReceived(e)}catch{}}_handleRiskPolicyChanged(e){let t=this._activeRiskPolicyEvaluation;if(this._activeRiskPolicyEvaluation=e?.actionIds?.length?e:null,t&&!this._activeRiskPolicyEvaluation&&this._eventModule){let s=t.actionIds.map(N).filter(Boolean);this._eventModule.trackEvent(h.EVENT_CODES.SDK_ACTION_CLEARED,{as:"risk_detected",cr:"cleared",bl:t.actionIds.includes(b.BLOCK_APP)||t.actionIds.includes(b.BLOCK_ALL_NETWORK),saa:s.join(",")||"none"}),Promise.resolve(this._eventModule._flush()).catch(()=>{})}if(this._refreshNetworkInstrumentationForRiskPolicy(),this._applyRiskPolicyUi(this._activeRiskPolicyEvaluation),!this._activeRiskPolicyEvaluation||!this._config?.onRiskPolicyActionTaken)return;let i=[...new Set(e.matchedRules.flatMap(s=>s.eventIds??[]))];try{this._config.onRiskPolicyActionTaken({actionIds:[...e.actionIds],actionNames:e.actionIds.map(N).filter(Boolean),matchedEventIds:i,matchedRulePriorities:e.matchedRules.map(s=>s.priority??0),title:e.title,message:e.message,buttonText:e.buttonText})}catch{}}_refreshNetworkInstrumentationForRiskPolicy(){if(!this._config)return;let e=this._activeRiskPolicyEvaluation?.actionIds?.includes(b.BLOCK_ALL_NETWORK)===!0,t=this._getActiveIpReputationAction()?.actionIds?.includes(b.BLOCK_ALL_NETWORK)===!0,i=e||t,s=this._config.network?.enabled===!0&&this._serverConfig.isHttpLoggingEnabled;this._uninstallNetworkInstrumentation(),(s||i)&&this._installNetworkInstrumentation(i)}_applyRiskPolicyUi(e,t=!1){if(this._riskPolicyOverlay?.parentNode)try{this._riskPolicyOverlay.parentNode.removeChild(this._riskPolicyOverlay)}catch{}this._riskPolicyOverlay=null;let i=this._activeIpReputationAction,s=i?.actionIds?.includes(b.BLOCK_APP)===!0,r=e?.actionIds?.includes(b.BLOCK_APP)===!0;if((s||!r&&t&&i?.actionIds?.includes(b.SHOW_WARNING))&&(e=i),!e||typeof document>"u"||!document.body||typeof document.createElement!="function")return;let o=e.actionIds.includes(b.BLOCK_APP),a=e.actionIds.includes(b.SHOW_WARNING);if(!o&&!a)return;let l=document.createElement("div");l.setAttribute("role","alertdialog"),l.setAttribute("aria-modal","true"),l.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:24px","background:rgba(15,23,42,.72)","font-family:system-ui,sans-serif"].join(";");let c=document.createElement("div");c.style.cssText="max-width:520px;width:100%;background:white;border-radius:12px;padding:24px;box-shadow:0 24px 64px rgba(0,0,0,.35);color:#111827";let u=document.createElement("h2");u.textContent=e.title||(o?"Security block":"Security warning"),u.style.cssText="margin:0 0 12px;font-size:20px";let d=document.createElement("p");if(d.textContent=e.message||"A security risk was detected.",d.style.cssText="margin:0;line-height:1.5",c.append(u,d),!o){let p=document.createElement("button");p.type="button",p.textContent=e.buttonText||"OK",p.style.cssText="margin-top:20px;padding:9px 16px;border:0;border-radius:8px;background:#111827;color:white;cursor:pointer",p.addEventListener("click",()=>{try{l.remove()}catch{}this._riskPolicyOverlay===l&&(this._riskPolicyOverlay=null)},{once:!0}),c.appendChild(p)}l.appendChild(c),document.body.appendChild(l),this._riskPolicyOverlay=l}getBotSnapshot(){return this._riskModule?.getBotSnapshot()??null}refreshBotSnapshot(){return this._riskModule?.evaluate(),this._riskModule?.getBotSnapshot()??null}getSessionThreat(){return this._riskModule?.getSessionThreat()??null}async sendLogs(e){if(!this._config){typeof e=="function"&&e(!1);return}let[t,i]=await Promise.all([this._flushLogs(),this._flushCrashes()]);typeof e=="function"&&e(t&&i)}_enqueue(e,t,i=null,s=null){if(!this._config)return;let r={ts:Te(),level:e,message:typeof t=="string"?t:ot(t)},o=this._httpCapturePolicy;o&&e!==S.DEVICEINFO&&(e!==S.NETWORK_ACTIVITY&&(r.message=A(r.message,o.sensitivePatterns)),r.httpPolicyFingerprint=o.fingerprint),s&&(r.tag=s),i&&i instanceof P&&(r.flowId=i.id,r.flowName=i.name,i.customAttributes&&(r.flowAttributes=i.customAttributes)),this._queue.push(r);let a=this._persistLogEntry(r,i);return this._queue.length>2e3&&this._queue.splice(0,this._queue.length-2e3),this._queue.length>=this._config.maxBatchSize&&this.sendLogs(),this._logInternal(`[LogDrop:${e}] ${r.message}`),a}_scheduleFlush(){this._config&&(this._flushTimer&&clearInterval(this._flushTimer),this._flushTimer=setInterval(()=>this.sendLogs(),this._config.flushIntervalMs),this._flushTimer&&typeof this._flushTimer.unref=="function"&&this._flushTimer.unref())}_scheduleEventFlush(){this._eventFlushTimer&&clearInterval(this._eventFlushTimer),this._eventFlushTimer=setInterval(()=>{this._eventModule?._flush()},h.EVENT_FLUSH_INTERVAL_MS),this._eventFlushTimer&&typeof this._eventFlushTimer.unref=="function"&&this._eventFlushTimer.unref()}_scheduleFileFlush(){this._config&&(this._fileFlushTimer&&clearInterval(this._fileFlushTimer),this._fileFlushTimer=setInterval(()=>{this._flushDbToZip()},h.FILE_EXPORT_INTERVAL_MS),this._fileFlushTimer&&typeof this._fileFlushTimer.unref=="function"&&this._fileFlushTimer.unref())}_initDb(){!g()||!window.indexedDB||this._dbPromise||(this._dbPromise=new Promise((e,t)=>{let i=window.indexedDB.open("logdrop",3);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains("logs")||s.createObjectStore("logs",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("crashes")||s.createObjectStore("crashes",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("events")||s.createObjectStore("events",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("event_upload_batch")||s.createObjectStore("event_upload_batch",{keyPath:"id",autoIncrement:!0}),s.objectStoreNames.contains("log_upload_batch")||s.createObjectStore("log_upload_batch",{keyPath:"id",autoIncrement:!0})},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error)}))}async _persistLogEntry(e,t=null){if(this._dbPromise)try{await this._enforceStorageLimit();let s=(await this._dbPromise).transaction("logs","readwrite"),r={sessionId:this._sessionId,userUuid:this._getEffectiveUserUuid(),ts:e.ts,level:e.level,message:e.message};e.tag&&(r.tag=e.tag),e.httpPolicyFingerprint&&(r.httpPolicyFingerprint=e.httpPolicyFingerprint),t&&t instanceof P&&(r.flowId=t.id,r.flowName=t.name,t.customAttributes&&(r.flowAttributes=t.customAttributes)),await new Promise((o,a)=>{s.objectStore("logs").add(r),s.oncomplete=()=>o(),s.onerror=()=>a(s.error)})}catch{}}async _readAllLogs(){if(!this._dbPromise)return[];let e=await this._dbPromise;return new Promise((t,i)=>{let o=e.transaction("logs","readonly").objectStore("logs").getAll();o.onsuccess=()=>t(o.result||[]),o.onerror=()=>i(o.error)})}async _readLogUploadBatch(){if(!this._dbPromise)return null;let i=(await this._dbPromise).transaction("log_upload_batch","readonly").objectStore("log_upload_batch").getAll();return new Promise((s,r)=>{i.onsuccess=()=>s((i.result||[])[0]??null),i.onerror=()=>r(i.error)})}async _replaceLogUploadBatch(e){if(!this._dbPromise)return;let i=(await this._dbPromise).transaction("log_upload_batch","readwrite"),s=i.objectStore("log_upload_batch");s.clear(),e&&s.add(e),await new Promise((r,o)=>{i.oncomplete=r,i.onerror=()=>o(i.error)})}async _persistCrash(e){if(this._dbPromise)try{let i=(await this._dbPromise).transaction("crashes","readwrite");i.objectStore("crashes").add(e),await new Promise((s,r)=>{i.oncomplete=()=>s(),i.onerror=()=>r(i.error)})}catch{}}async _readAllCrashes(){if(!this._dbPromise)return[];try{let i=(await this._dbPromise).transaction("crashes","readonly").objectStore("crashes").getAll();return await new Promise((s,r)=>{i.onsuccess=()=>s(i.result||[]),i.onerror=()=>r(i.error)})}catch{return[]}}async _deleteCrashesByIds(e){if(!(!this._dbPromise||!e.length))try{let i=(await this._dbPromise).transaction("crashes","readwrite"),s=i.objectStore("crashes");e.forEach(r=>s.delete(r)),await new Promise((r,o)=>{i.oncomplete=()=>r(),i.onerror=()=>o(i.error)})}catch{}}_buildCrashData({threadName:e,stackTrace:t,crashType:i,isCustomCrash:s,sourceUrl:r="",line:o=0,column:a=0}){let l=ct(),c=Date.parse(this._sessionCreateDate);return{timestamp:Date.now(),threadName:e,stackTrace:t.slice(0,5e5),sessionId:this._sessionId,userUuid:this._getEffectiveUserUuid(),crashType:i,appVersion:this._config?.release||"UNKNOWN",buildNumber:"",isAppOnBackground:l.visibilityState!=="visible",sessionTime:Number.isFinite(c)?Math.max(0,Date.now()-c):0,uuid:lt().replace(/-/g,""),isCustomCrash:s,url:l.url,sourceUrl:r,line:o,column:a}}_recordCrash(e){let t=String(e.stackTrace||""),i=e.errorIdentity;if(i&&(typeof i=="object"||typeof i=="function")){if(this._seenCrashes.has(i))return;this._seenCrashes.add(i)}let s=this._buildCrashData({...e,stackTrace:t}),r=this._enqueue(S.CRASH,t,new P("Crash",s.uuid),"LogDropCrashTracker"),o=this._persistCrash(s);Promise.allSettled([Promise.resolve(r),o]).then(()=>this._scheduleCrashFlush()).catch(()=>{})}_scheduleCrashFlush(){this._crashFlushTimer&&clearTimeout(this._crashFlushTimer),this._crashFlushTimer=setTimeout(()=>{this._crashFlushTimer=null,this._flushCrashes().catch(()=>{})},this._crashFlushDelayMs),this._crashFlushTimer&&typeof this._crashFlushTimer.unref=="function"&&this._crashFlushTimer.unref()}async _clearLogs(){if(!this._dbPromise)return;let e=await this._dbPromise;return new Promise((t,i)=>{let o=e.transaction("logs","readwrite").objectStore("logs").clear();o.onsuccess=()=>t(),o.onerror=()=>i(o.error)})}async _clearNetworkLogs(){if(this._dbPromise)try{let s=(await this._dbPromise).transaction("logs","readwrite").objectStore("logs").openCursor();return new Promise((r,o)=>{s.onsuccess=a=>{let l=a.target.result;l?(l.value&&l.value.level===S.NETWORK_ACTIVITY&&l.delete(),l.continue()):r()},s.onerror=()=>o(s.error)})}catch{}}async _getStorageSize(){if(!this._dbPromise)return 0;try{let e=await this._readAllLogs(),t=JSON.stringify(e);return new Blob([t]).size}catch{return 0}}_getMaxStorageLimit(){return this._initResponse?.databaseMaxStorageLimitInBytes??h.DATABASE_MAX_STORAGE_LIMIT}async _enforceStorageLimit(){if(this._dbPromise)try{let e=await this._getStorageSize(),t=this._getMaxStorageLimit();e>=t&&(await this._flushLogs()||await this._deleteOldestLogs(e-t+h.MAX_LOCAL_STORAGE_SIZE))}catch{}}async _deleteOldestLogs(e){if(!(!this._dbPromise||e<=0))try{let t=await this._readAllLogs();if(!t.length)return;t.sort((r,o)=>new Date(r.ts)-new Date(o.ts));let i=[],s=0;for(let r of t){if(s>=e)break;let o=new Blob([JSON.stringify(r)]).size;i.push(r.id),s+=o}i.length>0&&(await this._deleteLogsByIds(i),this._logInternal(`[LogDrop] Deleted ${i.length} oldest logs to free storage`))}catch{}}_scheduleStorageCheck(){this._storageCheckTimer&&clearInterval(this._storageCheckTimer),this._storageCheckTimer=setInterval(async()=>{await this._checkStorageAndFlush()},h.STORAGE_CHECK_INTERVAL_MS),this._storageCheckTimer&&typeof this._storageCheckTimer.unref=="function"&&this._storageCheckTimer.unref()}async _checkStorageAndFlush(){if(this._config)try{let e=await this._getStorageSize();e>=h.MAX_LOCAL_STORAGE_SIZE&&(this._logInternal(`[LogDrop] Storage size ${this._formatBytes(e)} exceeds limit, triggering upload`),await this._flushLogs())}catch{}}_getCachedRemainingLimit(){return this._cachedRemainingLimit!=null?this._cachedRemainingLimit:h.DEFAULT_INITIAL_REMAINING_LIMIT}_getMaxFileSize(){return this._initResponse?.perUserMaxFileSizeLimitInBytes??5242880}_getMinFileSize(){return this._initResponse?.perUserMinFileSizeLimitInBytes??524288}_groupLogsBySession(e){let t={};for(let i of e){let s=i.sessionId||"unknown";t[s]||(t[s]=[]),t[s].push(i)}return t}async _getDeviceInfoForSession(e){let i=(await this._readAllLogs()).filter(s=>s.sessionId===e&&s.level===S.DEVICEINFO);if(i.length>0){let r=i[i.length-1]?.message;if(typeof r=="string"&&r.trim())try{let o=JSON.parse(r);if(o&&typeof o=="object")return o}catch{}}return await this._getDeviceInfo()}_buildLogChunk(e,t,i){let s=Math.min(t,i);if(s<=0)return null;let r={sessions:[],size:0,logIds:[],droppedLogIds:[]},o=(a,l)=>{l.length&&r.sessions.push({sessionId:a,logs:l})};for(let[a,l]of Object.entries(e)){let c=[];for(let u of l){let d=this._applyHttpCapturePolicyToStoredLog(u);if(d===null){r.droppedLogIds.push(u.id);continue}let p={id:u.id,ts:u.ts,level:u.level,message:d,flowId:u.flowId,flowName:u.flowName,flowAttributes:u.flowAttributes},_=JSON.stringify(p).length;if(_>s){r.droppedLogIds.push(u.id),this._warnInternal(`[LogDrop] Dropping oversized log ${u.id} for session ${a}; entry size ${this._formatBytes(_)} exceeds chunk limit ${this._formatBytes(s)}`);continue}if(r.size+_>s&&r.size>0)return o(a,c),r.sessions.length>0||r.droppedLogIds.length>0?r:null;c.push(p),r.logIds.push(u.id),r.size+=_}o(a,c)}return r.sessions.length>0||r.droppedLogIds.length>0?r:null}async _compressToGzip(e){let t=JSON.stringify(e),s=new TextEncoder().encode(t);if(typeof CompressionStream<"u")try{let o=new Blob([s]).stream().pipeThrough(new CompressionStream("gzip")),a=await new Response(o).blob();return new Uint8Array(await a.arrayBuffer())}catch{}return s}async _sendLogFile(e,t=""){if(!this._config)return{success:!1,remainingLimit:this._cachedRemainingLimit};let i=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof i!="function")return{success:!1,remainingLimit:this._cachedRemainingLimit};let s=await this._ensureSessionToken("Log upload requires a valid access token");if(!s)return this._warnInternal("[LogDrop] No valid session token after recovery attempt, skipping log upload"),{success:!1,remainingLimit:this._cachedRemainingLimit};try{let r=this._getOsInfo(),o=this._cachedRemainingLimit,a={content:e,deviceUuid:this._deviceId,appVersion:this._config.release||"1.0",sdkVersion:h.SDK_VERSION,osVersion:r.osVersion,errorCount:"0",uploadId:t},l=qe(a);this._debugLogProtoBody("Log upload request",a,l);let c=`${this._config.baseUrl}${h.LOGS_PATH}`,u=await i(c,{method:"POST",headers:{"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":this._config.appId,"x-session-token":s},body:new Blob([l],{type:"application/x-protobuf"})});if(u.ok){try{let d=new Uint8Array(await u.arrayBuffer());if(this._debugLogProtoResponse("Log upload",d,be),d.length>0){let p=be(d);this._cachedRemainingLimit=p.remainingLimit,o=this._cachedRemainingLimit}}catch{}return{success:!0,remainingLimit:o}}return{success:!1,remainingLimit:this._cachedRemainingLimit}}catch{return{success:!1,remainingLimit:this._cachedRemainingLimit}}}async _sendCrashReport(e){if(!this._config)return!1;let t=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof t!="function")return!1;let i=await this._ensureSessionToken("Crash upload requires a valid access token");if(!i)return this._warnInternal("[LogDrop] No valid session token after recovery attempt, skipping crash upload"),!1;try{let s={content:e,deviceUuid:this._deviceId,sdkVersion:h.SDK_VERSION},r=ze(s);this._debugLogProtoBody("Crash upload request",s,r);let o=`${this._config.baseUrl}${h.CRASH_PATH}`;return(await t(o,{method:"POST",headers:{"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":this._config.appId,"x-session-token":i},body:new Blob([r],{type:"application/x-protobuf"})})).ok}catch{return!1}}async _flushCrashes(){if(!this._config||!this._dbPromise||this._crashFlushInProgress)return!1;this._crashFlushInProgress=!0;try{let e=await this._readAllCrashes();if(!e.length)return this._seenCrashes.clear(),!0;let t=e.map(o=>o.id).filter(o=>o!==void 0),i={crashes:e.map(({id:o,...a})=>a)},s=await this._compressToGzip(i),r=await this._sendCrashReport(s);return r&&(await this._deleteCrashesByIds(t),this._seenCrashes.clear()),r}finally{this._crashFlushInProgress=!1}}async _deleteLogsByIds(e){if(!(!this._dbPromise||!e.length))try{let i=(await this._dbPromise).transaction("logs","readwrite"),s=i.objectStore("logs");for(let r of e)s.delete(r);return new Promise((r,o)=>{i.oncomplete=()=>r(),i.onerror=()=>o(i.error)})}catch{}}_formatLogForExport(e){let t={level:e.level||"",message:e.message||"",timestamp:e.ts||"",file_and_line:""};return e.flowId&&(t.id=e.flowId),e.flowName&&(t.flow_name=e.flowName),e.tag&&(t.tag=e.tag),t}_formatDeviceInfoForExport(e){let t=e&&typeof e=="object"?e:{};return{sessionID:t.sessionID||"",session_create_date:t.session_create_date||"",os_version:t.os_version||"",app_version:t.app_version||"",device_model:t.device_model||"",locale:t.locale||"",free_disk_space:t.free_disk_space||"",battery_level:t.battery_level||"",low_power_mode:t.low_power_mode||"",ram_size:t.ram_size||"",device_id:t.device_id||"",userUuid:t.userUuid??null,sim_operator_name:"",network_available:t.network_available??!0,gmt:t.gmt??0,...t.bot_score!==void 0&&{bot_score:t.bot_score,bot_label:t.bot_label,posture:t.posture}}}async _flushLogs(){if(!this._config||this._fileFlushInProgress||!this._dbPromise)return!1;this._fileFlushInProgress=!0;try{let e=await this._readAllLogs(),t=this._httpCapturePolicy?e:e.filter(o=>o.level!==S.NETWORK_ACTIVITY);if(this._isInternalLoggingEnabled()&&this._logInternal(`[LogDrop DEBUG] _flushLogs called. DB log count: ${t.length}`),!t.length)return this._isInternalLoggingEnabled()&&this._logInternal("[LogDrop DEBUG] No logs in DB, skipping flush (no API call made)"),!0;this._isInternalLoggingEnabled()&&this._logInternal("[LogDrop DEBUG] Logs from DB:",t),this._cachedRemainingLimit==null&&this._logInternal(`[LogDrop] Remaining upload quota unknown; using conservative default limit of ${this._formatBytes(h.DEFAULT_INITIAL_REMAINING_LIMIT)} until a successful upload response updates the cache`);let i=this._getMaxFileSize(),s=t,r=!1;for(;s.length>0;){let o=this._getCachedRemainingLimit();if(o<=0){this._logInternal("[LogDrop] Remaining limit reached, stopping upload");break}let a=await this._readLogUploadBatch(),l=a?.uploadId??null,c;if(a){let _=new Set(a.logIds||[]),f=s.filter(m=>_.has(m.id));if(f.length===0){await this._replaceLogUploadBatch(null);continue}c=this._buildLogChunk(this._groupLogsBySession(f),Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER)}else{let _=this._groupLogsBySession(s);c=this._buildLogChunk(_,i,o)}if(!c)break;if(c.droppedLogIds.length>0){await this._deleteLogsByIds(c.droppedLogIds);let _=new Set(c.droppedLogIds);s=s.filter(f=>!_.has(f.id)),r=!0}if(!c.sessions.length)continue;l||(l=this._generateUUID(),await this._replaceLogUploadBatch({uploadId:l,logIds:c.logIds}));let u=[];for(let _ of c.sessions){let f=await this._getDeviceInfoForSession(_.sessionId),m=this._formatDeviceInfoForExport(f),k=_.logs.map(E=>this._formatLogForExport(E));u.push({device_info:m,logs:k})}if(this._isInternalLoggingEnabled()){let _=JSON.stringify(u),f=new Blob([_]).size;this._logInternal(`[LogDrop DEBUG] Payload before gzip - Size: ${this._formatBytes(f)}, Log IDs: ${c.logIds.join(", ")}`),this._logInternal("[LogDrop DEBUG] Payload content:",u)}let d=await this._compressToGzip(u);this._isInternalLoggingEnabled()&&this._logInternal(`[LogDrop DEBUG] After gzip - Size: ${this._formatBytes(d.length)}`);let p=await this._sendLogFile(d,l);if(p.success){this._logInternal(`[LogDrop] Successfully sent ${c.logIds.length} logs`),await this._deleteLogsByIds(c.logIds),await this._replaceLogUploadBatch(null);let _=new Set(c.logIds);if(s=s.filter(f=>!_.has(f.id)),r=!0,p.remainingLimit!=null&&p.remainingLimit<=0){this._logInternal("[LogDrop] Remaining limit exhausted after upload, stopping flush");break}}else{this._warnInternal("[LogDrop] Failed to send log chunk, will retry later");break}}return r}catch(e){return this._warnInternal("[LogDrop] Flush failed:",e.message||e),!1}finally{this._fileFlushInProgress=!1}}async _flushDbToZip(){return this._flushLogs()}async _sendInitRequest(e=1){if(!this._config){this._failInit("LogDrop init failed: no config");return}let i=g()?window.fetch:typeof fetch<"u"?fetch:null;if(typeof i!="function"){this._failInit("LogDrop init failed: fetch not available");return}try{let s={"content-type":"application/x-protobuf",accept:"application/x-protobuf","x-api-key":this._config.appId},r=this._getAccessToken(),o=this._getRefreshToken();if(!r||!o){let p=[];r||p.push(`Stored access token is ${this._tokenValidationState.logdrop_access_token||"unavailable"}`),o||p.push(`Stored refresh token is ${this._tokenValidationState.logdrop_refresh_token||"unavailable"}`),this._recoverSessionTokens(p.join("; "))}r&&(s["x-session-token"]=r);let a={refreshToken:o||"",deviceUuid:this._deviceId},l=Fe(a);this._debugLogProtoBody("Init request",a,l);let c=`${this._config.baseUrl}${h.INIT_PATH}`,u=await i(c,{method:"POST",headers:s,body:new Blob([l],{type:"application/x-protobuf"})});if(!u.ok)throw new Error(`HTTP ${u.status}`);let d=new Uint8Array(await u.arrayBuffer());this._debugLogProtoResponse("Init",d,ye),d.length>0&&(this._initResponse=ye(d),this._saveServerConfigToCache({data:this._initResponse}),this._initResponse.accessToken&&this._saveTokens(this._initResponse.accessToken,null,this._getTokenRecoveryTarget()),this._applyServerConfig(this._initResponse,!0)),this._logInternal("[LogDrop] Init successful"),this._isNewDevice&&!this._isUserRegistered()&&this._sendUserUpdate(this._deviceId,!1,{reason:"automatic_device_registration"})}catch(s){if(e<3)return this._warnInternal(`[LogDrop] Init attempt ${e} failed, retrying... (${s.message||s})`),await new Promise(r=>setTimeout(r,e*1e3)),this._sendInitRequest(e+1);this._failInit(`LogDrop init failed after 3 attempts: ${s.message||s}`)}}_failInit(e){this._errorInternal(e),this._initialized=!1,this._config=null,this.teardown()}_installGlobalErrorHandlers(){g()&&(this._errorHandlersInstalled||(this._errorHandlersInstalled=!0,window.addEventListener("error",e=>{if(!this._serverConfig.isCrashTrackingEnabled)return;let t=e.error,i=t&&t.stack?String(t.stack):e.message||"";this._recordCrash({threadName:"window",stackTrace:i,crashType:t?.name||"Error",isCustomCrash:!1,sourceUrl:e.filename||"",line:e.lineno||0,column:e.colno||0,errorIdentity:t})}),window.addEventListener("unhandledrejection",e=>{if(!this._serverConfig.isCrashTrackingEnabled)return;let t=e.reason,i=t instanceof Error&&t.stack?String(t.stack):String(t||"");this._recordCrash({threadName:"unhandledrejection",stackTrace:i,crashType:t instanceof Error?t.name:"UnhandledRejection",isCustomCrash:!1,errorIdentity:t instanceof Error?t:null})})))}restoreFetch(){g()&&(this._originalFetch&&(window.fetch=this._originalFetch),this._fetchInstrumented=!1,this._originalFetch=null)}teardown(){if(this._flushTimer&&clearInterval(this._flushTimer),this._flushTimer=null,this._fileFlushTimer&&clearInterval(this._fileFlushTimer),this._fileFlushTimer=null,this._crashFlushTimer&&clearTimeout(this._crashFlushTimer),this._crashFlushTimer=null,this._deviceInfoTimer&&clearInterval(this._deviceInfoTimer),this._deviceInfoTimer=null,this._storageCheckTimer&&clearInterval(this._storageCheckTimer),this._storageCheckTimer=null,this._seenCrashes.clear(),this._uninstallNetworkInstrumentation(),this._pushModule?.teardown(),this._pushModule=null,this._inAppMessagePresenter?.teardown(),this._inAppMessagePresenter=null,this.push=null,this._eventFlushTimer&&clearInterval(this._eventFlushTimer),this._eventFlushTimer=null,this._eventModule?.teardown(),this._eventModule=null,this._riskModule?.teardown(),this._riskModule=null,this._activeRiskPolicyEvaluation=null,this._ipReputationExpiryTimer&&clearTimeout(this._ipReputationExpiryTimer),this._ipReputationExpiryTimer=null,this._riskPolicyOverlay?.parentNode)try{this._riskPolicyOverlay.parentNode.removeChild(this._riskPolicyOverlay)}catch{}this._riskPolicyOverlay=null,this.restoreFetch(),this._debugLogEnabled=!1}},pi=new ae;return gt(_i);})();
|
|
3
3
|
globalThis.LogDrop=LogDropSDK.LogDrop;globalThis.LogFlow=LogDropSDK.LogFlow;globalThis.LogLevel=LogDropSDK.LogLevel;
|
|
4
4
|
//# sourceMappingURL=logdrop.min.js.map
|