@depsmith/depsmith-sdk 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- function ae(){return import("./autocapture.js")}var z=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]],Ke=Object.fromEntries(z.map(([r])=>[r,!0]));function de(r){let e={...Ke};if(!r)return e;for(let[t]of z)r[t]===!1&&(e[t]=!1);return e}function ue(r,e){let t=r;for(let[i,n,s]of z){if(e[i])continue;if(s===void 0){delete t[n];continue}let o={...t[n]};delete o[s],Object.keys(o).length>0?t[n]=o:delete t[n]}return r}var V={clicks:"interactive",forms:!0,scrolls:!0,pageviews:!0,ignoredSelectors:[],selectorMaxDepth:5};function ze(r){return r===void 0?V.clicks:r===!0?"interactive":r}function ce(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=r.autocapture===!0?V:r.autocapture&&typeof r.autocapture=="object"?{...V,...r.autocapture,clicks:ze(r.autocapture.clicks)}:!1;return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:L(r.batchSize??20,1,500),batchIntervalMs:Math.max(r.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(r.maxQueueSize??1e3,1),maxQueueBytes:Math.max(r.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(r.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(r.sampleRate)?L(r.sampleRate,0,1):1,sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:L(r.maxRetries??5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,trackingOptions:de(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage"}}function L(r,e,t){return Math.min(Math.max(r,e),t)}function F(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function pe(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e>>>0}function Le(r){return pe(r).toString(36)}function le(r){return pe(r)/4294967296}function B(r){return F(r)+Le(r)}var j={},he=!1;function ge(){if(!he){he=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{j=e}).catch(()=>{})}catch{}}}function fe(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=je(e,t);i&&(r.browser=i);let n=Xe(e);if(n){let a=Fe(n.name,j.platformVersion);r.os=a?{...n,version:a}:n}let s=Ge(e,t);s&&(r.deviceType=s);let o=Ve(e,n);return o&&(r.device=o),r}function Ve(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=j.model?.trim();return i?t.model=i:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function Fe(r,e){let t=e?.trim();if(t){if(r==="Windows"){let i=Number.parseInt(t.split(".")[0]??"",10);return!Number.isFinite(i)||i===0?void 0:i>=13?"11":"10"}return me(t)}}var Be=[{pattern:/Edg(?:e|A|iOS)?\/([\d.]+)/,name:"Edge",engine:"Blink"},{pattern:/OPR\/([\d.]+)/,name:"Opera",engine:"Blink"},{pattern:/Firefox\/([\d.]+)/,name:"Firefox",engine:"Gecko"},{pattern:/Chrome\/([\d.]+)/,name:"Chrome",engine:"Blink"},{pattern:/Version\/([\d.]+)/,name:"Safari",engine:"WebKit",requires:/Safari/}];function je(r,e){for(let i of Be){if(i.requires&&!i.requires.test(r))continue;let n=r.match(i.pattern);if(n)return{name:i.name,version:n[1],engine:i.engine}}let t=e?.brands?.find(i=>!/not.?a.?brand/i.test(i.brand));if(t)return{name:t.brand,version:t.version}}var Ye=[{pattern:/Windows NT ([\d.]+)/,name:"Windows"},{pattern:/OS ([\d_]+)/,name:"iOS",requires:/iPhone|iPad|iPod/},{pattern:/Android ([\d.]+)/,name:"Android"},{pattern:/Mac OS X ([\d_]+)/,name:"macOS"}];function Xe(r){for(let e of Ye){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:me((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function me(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function Ge(r,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(r))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(r))return"mobile";if(/Android/.test(r))return"tablet";if(typeof navigator<"u"&&r)return"desktop"}var A=null,E=null;function ve(){return E!==null||(E=We()),E}function O(){return A!==null||(A=B(ve().map(r=>r.value).join("|"))),A}function ye(){let r={};for(let e of ve())r[`$fp_${e.name}`]=e.value;return r}function We(){let r=[];try{if(typeof screen<"u"&&r.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;r.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),r.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),r.push({name:"plat",value:`plat:${navigator.platform??""}`}),r.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}r.push({name:"canvas",value:`canvas:${He()}`})}catch{}return r}function He(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),B(r.toDataURL())):""}catch{return""}}function Se(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};switch(r.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(r.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var P=null,ke=0,be=!1,y=!1,we=null;function xe(){if(!be){be=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let r=navigator.permissions;if(typeof r?.query!="function")return;r.query({name:"geolocation"}).then(e=>{we=e,e.state==="granted"&&Y(),e.onchange=()=>{e.state==="granted"?Y():P=null}}).catch(()=>{})}catch{}}}function Y(){if(!y){y=!0;try{navigator.geolocation.getCurrentPosition(r=>{y=!1;let{latitude:e,longitude:t,accuracy:i}=r.coords;if(!Number.isFinite(e)||!Number.isFinite(t))return;let n={latitude:e,longitude:t,source:"gps"};Number.isFinite(i)&&(n.accuracy=i),P=n,ke=Date.now()},()=>{y=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{y=!1}}}function _e(){if(P)return Date.now()-ke>3e5&&we?.state==="granted"&&Y(),{...P}}var G="@depsmith/depsmith-sdk",f="0.6.0",X=null;function Je(){if(X)return X;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),X=r,r}function b(r={}){let e={library:{name:G,version:f}};S(()=>{typeof window<"u"&&window.location&&(e.page={url:window.location.href,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0})}),S(()=>{typeof window<"u"&&window.screen&&(e.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),S(()=>{let t=Je();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),S(()=>{r.fingerprint&&Qe(e)}),S(()=>{if(r.geolocation){let t=_e();t&&(e.location=t)}});try{if(r.overrides){for(let[t,i]of Object.entries(r.overrides))i!==void 0&&(e[t]=i);e.library={name:G,version:f}}}catch{}return r.tracking&&ue(e,r.tracking),e}function Qe(r){let{browser:e,os:t,deviceType:i,device:n}=fe();e&&(r.browser=e),t&&(r.os=t);let s={};i&&(s.type=i),n?.manufacturer&&(s.manufacturer=n.manufacturer),n?.model&&(s.model=n.model),Object.keys(s).length>0&&(r.device=s);let o=Se();o.type&&(r.network={...r.network,type:o.type})}function S(r){try{r()}catch{}}function Ae(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var W="depsmith_consent",C=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(W);this.state=n==="granted"||n==="denied"||n==="pending"?n:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(W,"granted")}optOut(){this.state="denied",this.storage.set(W,"denied")}};var k=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Ze=r=>r();var T="depsmith_queue",et=512*1024,H=2,tt=new Set(["identify","alias","group"]);function rt(r){return tt.has(r?.event_type)}var I=class{constructor(e,t,i,n={}){this.storage=e;this.maxSize=t;this.logger=i;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=n.maxChars??et,this.schedule=n.schedule??k,this.restore()}restore(){try{let e=this.storage.get(T);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let i=t.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string");this.reset(i),i.length!==t.length&&(this.logger.warn("discarded corrupt queued events on restore"),this.markDirty()),this.trimToBudget()&&this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty"),this.reset([]),this.storage.remove(T)}}reset(e){this.events=e,this.sizes=e.map(t=>Ee(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?H:this.sizeSum+(this.events.length-1)+H}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(T,JSON.stringify(this.events)))}prepend(e){let t=new Set(this.events.map(n=>n.event_id)),i=e.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string"&&!t.has(n.event_id));i.length!==0&&(this.reset([...i,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let t=Ee(e);if(t+H>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let i=this.events.length-this.maxSize;this.dropOldest(i),this.logger.warn(`queue cap reached; dropped ${i} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!rt(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e){return this.events.slice(0,e)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let a=this.events[o];if(t.has(a.event_id))continue;let d=this.sizes[o];i.push(a),n.push(d),s+=d}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(T)}};function Ee(r){return JSON.stringify(r).length}function l(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let i=0;i<16;i++)e[i]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=[];for(let i=0;i<16;i++)t.push(e[i].toString(16).padStart(2,"0"));return`${t[0]}${t[1]}${t[2]}${t[3]}-${t[4]}${t[5]}-${t[6]}${t[7]}-${t[8]}${t[9]}-${t[10]}${t[11]}${t[12]}${t[13]}${t[14]}${t[15]}`}function m(r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r))return null;let e=r.slice(0,8)+r.slice(9,13),t=parseInt(e,16);return Number.isFinite(t)?t:null}var Oe=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker"],v=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},J=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},M=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let i of document.cookie.split("; "))if(i.startsWith(t))return decodeURIComponent(i.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",i=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${i}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},it=new Set(["depsmith_anonymous_id"]),$=class{constructor(e,t,i=it){this.primary=e;this.secondary=t;this.mirrored=i}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let i=this.secondary.get(e);if(t===i)return t;if(t===null&&i!==null)return this.primary.set(e,i),i;if(i===null&&t!==null)return this.secondary.set(e,t),t;let n=nt(t,i)??t;return this.primary.set(e,n),this.secondary.set(e,n),n}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}};function nt(r,e){let t=m(r),i=m(e);return t===null||i===null?null:t<=i?r:e}var w=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let i=indexedDB.open(e,1);i.onupgradeneeded=()=>i.result.createObjectStore("kv"),i.onsuccess=()=>{this.db=i.result;let n=this.db.transaction("kv","readonly").objectStore("kv"),s=n.getAllKeys(),o=n.getAll();o.onsuccess=()=>{let a=s.result;o.result.forEach((d,u)=>{let p=a[u];p!==void 0&&(this.snapshot.set(p,d),this.mirror.has(p)||this.mirror.set(p,d))}),t()},o.onerror=()=>t()},i.onerror=()=>t()}catch{t()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(t,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}},Q=class{constructor(e,t=Oe){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};function Pe(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new J(window.localStorage)}}catch{}return new v}var Z="depsmith_anonymous_id",ee="depsmith_user_id",te="depsmith_group_id",R="depsmith_user_props",D=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(Z);return e||(e=l(this.clock.now()),this.storage.set(Z,e)),e}get userId(){return this.storage.get(ee)}get groupId(){return this.storage.get(te)}identify(e){this.storage.set(ee,e)}setGroup(e){this.storage.set(te,e)}getUserProps(){try{return JSON.parse(this.storage.get(R)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(R,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(R,JSON.stringify(t))}reset(){this.storage.remove(ee),this.storage.remove(te),this.storage.remove(R);let e=l(this.clock.now());return this.storage.set(Z,e),e}};var Ce="depsmith_session",N=class{constructor(e,t,i,n=k){this.storage=e;this.clock=t;this.timeoutMs=i;this.pending=null;this.scheduled=!1;this.schedule=n}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(Ce);if(!e)return null;let t=JSON.parse(e);return typeof t.id!="string"||typeof t.lastActivityAt!="number"?null:(typeof t.startedAt!="number"&&(t.startedAt=m(t.id)??t.lastActivityAt),t)}catch{return null}}save(e){this.pending=e,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){let e=this.pending;e&&(this.pending=null,this.storage.set(Ce,JSON.stringify(e)))}mint(e){let t={id:l(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let i=this.mint(e);return{sessionId:i.id,startedAt:e,startedSession:{id:i.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let i=this.mint(e);return{sessionId:i.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:i.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let i=m(e);return i===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:t??i}),!0)}rotate(){return this.mint(this.clock.now()).id}};function h(r,e){if(r==null)return{};if(typeof r!="object"||Array.isArray(r))return e.warn("properties must be an object; ignoring",r),{};let t={},i=0;for(let[n,s]of Object.entries(r)){if(i>=200){e.warn("properties exceed 200 keys; excess dropped");break}let o=st(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function re(r){if(r===null)return null;let e=typeof r;if(e==="string"||e==="boolean")return r;if(e==="number")return Number.isFinite(r)?r:void 0;if(r instanceof Date)return isNaN(r.getTime())?void 0:r.toISOString()}function st(r,e){let t=re(r);if(t!==void 0)return t;if(!(r===void 0||typeof r=="function"||typeof r=="symbol")){if(Array.isArray(r)){let i=[];for(let n of r.slice(0,100)){let s=re(n);i.push(s!==void 0?s:Te(n))}return i}if(typeof r=="object"){let i={},n=0;for(let[s,o]of Object.entries(r)){if(n>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let a=re(o);i[String(s)]=a!==void 0?a:Te(o),n++}return i}}}function Te(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}var ot=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],Ie=50,Me=200;function ie(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let s=Object.keys(r).filter(o=>o!=="$clear_all");return s.length>0&&e.warn(`$clear_all is exclusive; ignored ${s.join(", ")}`),{$clear_all:!0}}let t={},i=new Set,n=(s,o)=>i.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(i.add(s),!0);for(let s of ot){let o=r[s];if(!o||typeof o!="object")continue;let a=h(o,e),d={};for(let[u,p]of Object.entries(a))n(u,s)&&(d[u]=p);Object.keys(d).length>0&&(t[s]=d)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[a,d]of Object.entries(r.$add)){if(o>=Ie){e.debug(`$add over ${Ie} keys; excess dropped`);break}if(typeof d!="number"||!Number.isFinite(d)){e.debug(`$add "${a}" is not finite; dropped`);continue}n(a,"$add")&&(s[a]=d,o++)}Object.keys(s).length>0&&(t.$add=s)}if(Array.isArray(r.$unset)){let s=[];for(let o of r.$unset){if(s.length>=Me){e.debug(`$unset over ${Me} keys; excess dropped`);break}typeof o!="string"||o.length===0||n(o,"$unset")&&s.push(o)}s.length>0&&(t.$unset=s)}return Object.keys(t).length>0?t:void 0}function U(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var $e={now:()=>Date.now()};function g(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function Re(r){return r===0||r===408||r===429||r>=500}var at=1e3,dt=32e3;function De(r,e=Math.random){let t=Math.min(at*2**r,dt);return Math.round(e()*t)}async function ut(r){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new TextEncoder().encode(r)).catch(()=>{}),t.close().catch(()=>{});let i=e.readable.getReader(),n=[];for(;;){let{done:d,value:u}=await i.read();if(d)break;n.push(u)}let s=n.reduce((d,u)=>d+u.length,0),o=new Uint8Array(new ArrayBuffer(s)),a=0;for(let d of n)o.set(d,a),a+=d.length;return o}function Ne(r){let e=[];for(let t of r)e.push(t.event_id);return e}var ct=3e4,pt=6e4,lt=10;function ht(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var q=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("collector unreachable; uploads paused");return}let e=this.queue.peek(this.config.batchSize);this.queue.persistNow();let t=await this.uploadWithRetry(e);if(t==="requeue")return;t==="dropped"&&this.deps.logger.warn(`dropped poison batch of ${e.length}`),this.queue.remove(Ne(e))}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1;for(let n=0;n<=this.config.maxRetries;n++){let s=await this.post(e);if(s!==0&&(i=!0),s>=200&&s<300)return t?.ok(),"sent";if(!Re(s))return t?.ok(),this.deps.logger.warn(`non-retryable ${s}; dropping batch`),"dropped";if(this.deps.logger.debug(`upload attempt ${n+1} failed (${s})`),s===0&&!i&&t?.suspect())break;n<this.config.maxRetries&&await this.deps.sleep(De(n))}return i?t?.ok():t?.fail(),"requeue"}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:g(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s=t,o={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream<"u")try{s=await ut(t),o["Content-Encoding"]="gzip"}catch{s=t}let a=ht(s)<=pt;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let d={method:"POST",headers:o,body:s,keepalive:a};return i&&(d.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,d)).status}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:ct}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<lt;){let t=this.queue.peek(this.config.batchSize),i=this.buildPayload(t);if(!navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(i)],{type:"text/plain"})))return;this.queue.remove(Ne(t)),e++}}catch{}}};var ne="depsmith_net_breaker";function Ue(r,e){let t=!1,i=0,n=0,s=3e5,o=(u,p,_)=>typeof u=="number"&&u===u?Math.min(Math.max(u,p),_):p,a=()=>{if(!t){t=!0;try{let u=JSON.parse(r.get(ne)??"0");if(!Array.isArray(u))return;i=o(u[0],0,3),n=o(u[1],0,e.now()+36e5),s=o(u[2],3e5,36e5)}catch{}}},d=()=>{try{i?r.set(ne,JSON.stringify([i,n,s])):r.remove(ne)}catch{}};return{open:()=>(a(),e.now()<n),suspect:()=>(a(),i>0),fail:()=>{a(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),d()},ok:()=>{a(),i&&(i=n=0,s=3e5,d())}}}var K=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var qe=255,x=class{constructor(e,t={}){this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=ce(e),this.logger=new K(this.config.debug),this.clock=t.clock??$e,this.storage=t.storage??this.pickStorage(),this.contextProvider=t.contextProvider;let i=this.config.childSafeMode?new v:this.config.storage==="memory"?this.storage:new $(this.storage,new M(this.config.cookieDomain||void 0));this.identity=new D(i,this.clock),this.session=new N(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new C(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??Ae())),this.queue=new I(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&ge(),this.config.geolocation&&!this.config.childSafeMode&&xe(),this.storage instanceof w&&(this.ready=this.storage.hydrate().then(n=>{try{let s=n.get("depsmith_queue");s&&this.queue.prepend(JSON.parse(s))}catch{this.logger.warn("persisted queue corrupt; discarded")}})),this.uploader=new q(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...n)=>fetch(...n)),clock:this.clock,logger:this.logger,sleep:t.sleep??(n=>new Promise(s=>setTimeout(s,n))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:Ue(this.storage,this.clock)}),t.manualLifecycle||(this.startFlushTimer(),this.attachLifecycle(),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}if(e.startsWith("$")){this.logger.warn(`track: "$"-prefixed names are reserved; dropped "${e}"`);return}this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}tooLong(e,t){return e.length<=qe?!1:(this.logger.warn(`${t} exceeds ${qe} characters (got ${e.length}); dropped`),!0)}page(e,t){this.guard(()=>{let i=e??(typeof document<"u"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...t,name:i})})}screen(e,t){this.page(e,t)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let i=h(t,this.logger);this.capture("$identify","identify",void 0,i,U("$set",i))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.identity.reset(),this.session.rotate(),this.logger.debug("reset: identity and session rotated")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}this.tooLong(e,"group: groupId")||(this.identity.setGroup(e),this.capture("$group","group",void 0,h(t,this.logger)))})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}this.capture("$group","group",void 0,h(e,this.logger))})}setProperty(e,t){this.guard(()=>{this.identity.setUserProp(e,t);let i=h({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,U("$set",i))})}setOnceProperty(e,t){this.guard(()=>{if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.identity.setUserProp(e,t);let i=h({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,U("$set_once",i))})}unsetProperty(e){this.guard(()=>{this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},ie({$unset:[e]},this.logger))})}setUserProperties(e){this.guard(()=>{let t=ie(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.flushUploads()})}optOut(){this.guard(()=>{this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.flushTimer!==null&&clearInterval(this.flushTimer),this.flushTimer=null;for(let e of this.teardownFns.splice(0))e();this.persistNow()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}enqueueEvent(e){this.queue.enqueue(e),this.drained=!1}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides:e,tracking:this.config.trackingOptions}}sessionInSample(e){return this.config.sampleRate>=1?!0:le(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,i,n,s){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let o=this.session.touch();if(o.endedSession&&this.sessionInSample(o.endedSession.id)&&this.enqueueSessionEnd(o.endedSession),o.startedSession&&this.sessionInSample(o.startedSession.id)&&this.enqueueSessionStart(o.startedSession),!this.inSample(o.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let a=this.clock.now(),d=this.contextOptions(),u={event_id:l(a),event:e,event_type:t,timestamp:g(a),session_id:o.sessionId,session_started_at:g(o.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...b(d),traits:n}:b(d),platform:"web",sdk_version:f};s&&(u.user_properties=s);let p={...this.config.defaultProperties,...h(i,this.logger)};Object.keys(p).length>0&&(u.properties=p);let _=this.identity.userId;_&&(u.user_id=_);let oe=this.identity.groupId;oe&&(u.group_id=oe),d.fingerprint&&(u.device_id=O()),this.enqueueEvent(u),this.logger.debug(`captured ${e}`,u),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",t=F(this.config.apiKey),i=this.storage.get(e);i!==null&&i!==t&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear()),this.storage.set(e,t)}pickStorage(){return this.config.storage==="memory"?new v:this.config.storage==="indexeddb"&&typeof indexedDB<"u"?new w:Pe()}enqueueSessionEnd(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:l(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:g(e.lastActivityAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:b(t),platform:"web",sdk_version:f},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=O()),this.enqueueEvent(i)}enqueueSessionStart(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:l(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:g(e.startedAt),session_id:e.id,session_started_at:g(e.startedAt),anonymous_id:this.identity.anonymousId,context:b(t),platform:"web",sdk_version:f},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=O()),t.fingerprint&&(i.properties={...i.properties,...ye()}),this.enqueueEvent(i)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window>"u"||typeof document>"u")return;let e=()=>{this.drained||(this.drained=!0,this.consent.canUpload()&&this.uploader.sendBeaconAll(),this.persistNow())},t=()=>{if(document.visibilityState==="hidden")e();else{this.drained=!1;let s=this.session.touch();s.endedSession&&this.enqueueSessionEnd(s.endedSession),s.startedSession&&this.enqueueSessionStart(s.startedSession)}},i=()=>{this.drained=!1},n=()=>{this.uploader.resetNetworkBreaker(),this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()};window.addEventListener("pagehide",e),window.addEventListener("pageshow",i),document.addEventListener("visibilitychange",t),window.addEventListener("online",n),this.teardownFns.push(()=>{window.removeEventListener("pagehide",e),window.removeEventListener("pageshow",i),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",n)})}startAutocapture(){let e=this.config.autocapture;!e||typeof window>"u"||ae().then(t=>{t&&this.teardownFns.push(t.startAutocapture(e,{emit:i=>this.autocapture(i),page:()=>this.page()}))}).catch(t=>this.logger.debug("autocapture load failed",t))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var c=null,se=null,gr={init(r,e){try{return c&&se===r.apiKey||(c?.shutdown(),c=new x(r,e),se=r.apiKey),c}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>c?.track(r,e),page:(r,e)=>c?.page(r,e),screen:(r,e)=>c?.screen(r,e),identify:(r,e)=>c?.identify(r,e),alias:r=>c?.alias(r),reset:()=>c?.reset(),group:(r,e)=>c?.group(r,e),setGroupTraits:r=>c?.setGroupTraits(r),setProperty:(r,e)=>c?.setProperty(r,e),setOnceProperty:(r,e)=>c?.setOnceProperty(r,e),unsetProperty:r=>c?.unsetProperty(r),setUserProperties:r=>c?.setUserProperties(r),optIn:()=>c?.optIn(),optOut:()=>c?.optOut(),flush:()=>c?.flush()??Promise.resolve(),getAnonymousId:()=>c?.getAnonymousId(),getSessionId:()=>c?.getSessionId(),setSessionId:(r,e)=>c?.setSessionId(r,e),shutdown(){c?.shutdown(),c=null,se=null}};export{Q as AsyncMirrorAdapter,Oe as DEPSMITH_SDK_STORAGE_KEYS,gr as DepsmithSdk,x as DepsmithSdkClient,k as idleScheduler,Ze as syncScheduler};
1
+ var dt=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],G="depsmith_campaign",H="depsmith_referrer";function ut(r){try{return new URL(r).host||void 0}catch{return}}var A=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(G)??{},this.referrer=this.read(H)??{}}read(e){try{let t=this.storage.get(e);if(!t)return null;let i=JSON.parse(t);return i&&typeof i=="object"?i:null}catch{return null}}write(e,t){try{this.storage.set(e,JSON.stringify(t))}catch{}}recordLanding(e,t){let i,n;try{let u=new URL(e);i=u.searchParams,n=u.host}catch{return}let s={};for(let[u,p]of dt){let l=i.get(u);l&&(s[p]=l)}Object.keys(s).length>0&&(this.campaign=s,this.write(G,s));let o=t?ut(t):void 0,d=!!o&&o!==n,a=!1;d&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=d?o:"$direct",d&&(this.referrer.initial_url=t),a=!0),a&&this.write(H,this.referrer)}campaignBlock(){return Object.keys(this.campaign).length>0?{...this.campaign}:void 0}referrerBlock(){return Object.keys(this.referrer).length>0?{...this.referrer}:void 0}clear(){this.campaign={},this.referrer={};try{this.storage.remove(G),this.storage.remove(H)}catch{}}};var W=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=Pe(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=Pe(this.currentUrl,e)?"internal":"external"),this.currentUrl=e,this.counter+=1,!0)}tracking(){let e={};return this.previousUrl!==void 0&&(e.previous_url=this.previousUrl),this.previousType!==void 0&&(e.previous_type=this.previousType),this.counter>0&&(e.counter=this.counter),e}get pageCount(){return this.counter}get current(){return this.currentUrl}resetForNewSession(){this.counter=this.currentUrl===void 0?0:1}},O=class{constructor(e,t={autocapture:!1}){this.sink=e;this.pages=new W;this.enteredAt=0;this.rules=pt(t.pageNames),this.byHref=!!t.autocapture&&t.autocapture.pageviews==="all"}start(e,t){this.pages.recordPage(e,t),this.enteredAt=this.sink.now()}get pageCount(){return this.pages.pageCount}recordExplicit(){this.record(),this.lastViewed=this.pageKey()}manual(e,t,i){this.flushPending(),this.recordExplicit(),this.sink.capture("$page_view","page_view",{...t,...we({source:"manual",name:e,type:i},this.rules),$page_counter:this.pages.pageCount})}autoPageView(e){this.flushPending(),this.record();let t=this.pageKey();if(t!==void 0&&t===this.lastViewed)return;this.lastViewed=t;let i=this.pages.pageCount;if(!e){this.emitView(location,i);return}let n=location.href,s={at:this.sink.now(),counter:i,location:new URL(n),page:{url:n,path:location.pathname,referrer:document.referrer,domain:E(n),url_base:C(n),...this.pages.tracking()},cancel:()=>{}};this.pending=s,s.cancel=e(document.title,()=>this.flushPending())}flushPending(){let e=this.pending;e&&(this.pending=void 0,e.cancel(),this.emitView(e.location,e.counter,e))}discardPending(){this.pending?.cancel(),this.pending=void 0}emitView(e,t,i){let n=document.title;this.sink.capture("$page_view","page_view",{...we({source:"auto",location:e,title:n},this.rules),$page_counter:t},i?.at,i&&{...i.page,title:n})}leave(e){this.flushPending();let t=this.pages.current;if(t===void 0)return;let i={$page_duration_ms:Math.max(0,this.sink.now()-this.enteredAt)};e!==void 0&&(i.$page_max_scroll=e),this.leaving=t;try{this.sink.capture("$page_leave","page_leave",i)}finally{this.leaving=void 0}}restored(e){e&&(this.enteredAt=this.sink.now())}newSession(){this.pages.resetForNewSession()}tracking(){let e=this.pages.tracking();return this.leaving===void 0?e:{...e,url:this.leaving,path:lt(this.leaving),domain:E(this.leaving),url_base:C(this.leaving)}}pageKey(){return this.byHref?ke():globalThis.location?.pathname}record(){let e=ke();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now())}};function we({source:r,name:e,type:t,location:i=globalThis.location,title:n=globalThis.document?.title},s){let o=i&&s?.(i),d=t?.trim()||o?.type;return{$page_name:e?.trim()||o?.name.trim()||n?.trim()||i?.pathname||"Unknown",...d?{$page_type:d}:{},$page_source:r}}function pt(r){if(typeof r=="function")return t=>{try{let i=r(t);return typeof i=="string"?{name:i}:void 0}catch{return}};if(!r||typeof r!="object")return;let e=(Array.isArray(r)?r:Object.entries(r)).map(([t,i])=>[typeof t=="string"&&typeof i=="string"&&ct(t),i]);return t=>{let i=_e(t.pathname);for(let[n,s]of e)if(n&&n.test(i))return{name:s,type:s}}}function ct(r){let e=_e(r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\*|\*\*?/g,t=>t==="*"?"[^/]+":t==="**"?".*":"(?:/.*)?");return new RegExp(`^${e}$`)}function _e(r){return r.replace(/(.)\/$/,"$1")}function ke(){if(!(typeof window>"u"||!window.location))return window.location.href}function Pe(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function lt(r){try{return new URL(r).pathname||void 0}catch{return}}function E(r){try{return new URL(r).host||void 0}catch{return}}function C(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}function xe(){return import("./autocapture.js")}var J=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["idfv","device","idfv"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screenSize","screen_size"],["timezone","timezone"],["userAgent","user_agent"]],gt=Object.fromEntries(J.map(([r])=>[r,!0]));function Ae(r){let e={...gt};if(!r)return e;for(let[t]of J)r[t]===!1&&(e[t]=!1);return e}function Oe(r,e){let t=r;for(let[i,n,s]of J){if(e[i])continue;if(s===void 0){delete t[n];continue}let o={...t[n]};delete o[s],Object.keys(o).length>0?t[n]=o:delete t[n]}return r}var Ee={clicks:"interactive",forms:!0,scrolls:!1,pageviews:"path",ignoredSelectors:[],selectorMaxDepth:5,selectorIgnore:[],attributes:[]};function Ce(r){if(r===!0)return Ee;if(!r||typeof r!="object")return!1;let e={...Ee};for(let[n,s]of Object.entries(r))s!==void 0&&(e[n]=s);let{clicks:t,pageviews:i}=e;return e.clicks=t==="all"?"all":t?"interactive":!1,e.pageviews=i==="all"?"all":i?"path":!1,e}function Te(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=Ce(r.autocapture);return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:Q(r.batchSize??20,1,500),batchIntervalMs:Math.max(r.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(r.maxQueueSize??1e3,1),maxQueueBytes:Math.max(r.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(r.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(r.sampleRate)?Q(r.sampleRate,0,1):1,sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:Q(r.maxRetries??5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,trackingOptions:Ae(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage",pageNames:r.pageNames}}function Q(r,e,t){return Math.min(Math.max(r,e),t)}function Z(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function $e(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e>>>0}function ft(r){return $e(r).toString(36)}function Re(r){return $e(r)/4294967296}function ee(r){return Z(r)+ft(r)}var te={},Ie=!1;function Me(){if(!Ie){Ie=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{te=e}).catch(()=>{})}catch{}}}function re(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=yt(e,t);i&&(r.browser=i);let n=St(e);if(n){let d=mt(n.name,te.platformVersion);r.os=d?{...n,version:d}:n}let s=wt(e,t);s&&(r.deviceType=s);let o=ht(e,n);return o&&(r.device=o),r}function ht(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=te.model?.trim();return i?t.model=i:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function mt(r,e){let t=e?.trim();if(t){if(r==="Windows"){let i=Number.parseInt(t.split(".")[0]??"",10);return!Number.isFinite(i)||i===0?void 0:i>=13?"11":"10"}return Ne(t)}}var vt=[{pattern:/Edg(?:e|A|iOS)?\/([\d.]+)/,name:"Edge",engine:"Blink"},{pattern:/OPR\/([\d.]+)/,name:"Opera",engine:"Blink"},{pattern:/Firefox\/([\d.]+)/,name:"Firefox",engine:"Gecko"},{pattern:/Chrome\/([\d.]+)/,name:"Chrome",engine:"Blink"},{pattern:/Version\/([\d.]+)/,name:"Safari",engine:"WebKit",requires:/Safari/}];function yt(r,e){for(let i of vt){if(i.requires&&!i.requires.test(r))continue;let n=r.match(i.pattern);if(n)return{name:i.name,version:n[1],engine:i.engine}}let t=e?.brands?.find(i=>!/not.?a.?brand/i.test(i.brand));if(t)return{name:t.brand,version:t.version}}var bt=[{pattern:/Windows NT ([\d.]+)/,name:"Windows"},{pattern:/OS ([\d_]+)/,name:"iOS",requires:/iPhone|iPad|iPod/},{pattern:/Android ([\d.]+)/,name:"Android"},{pattern:/Mac OS X ([\d_]+)/,name:"macOS"}];function St(r){for(let e of bt){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Ne((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Ne(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function wt(r,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(r))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(r))return"mobile";if(/Android/.test(r))return"tablet";if(typeof navigator<"u"&&r)return"desktop"}var T=null,$=null;function Ue(){return $!==null||($=kt()),$}function R(){return T!==null||(T=ee(Ue().map(r=>r.value).join("|"))),T}function De(){let r={};for(let e of Ue())r[`$fp_${e.name}`]=e.value;return r}function kt(){let r=[];try{if(typeof screen<"u"&&r.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;r.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),r.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),r.push({name:"plat",value:`plat:${navigator.platform??""}`}),r.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}r.push({name:"canvas",value:`canvas:${Pt()}`})}catch{}return r}function Pt(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),ee(r.toDataURL())):""}catch{return""}}function Le(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};switch(r.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(r.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var I=null,qe=0,Ve=!1,w=!1,Ke=null;function ze(){if(!Ve){Ve=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let r=navigator.permissions;if(typeof r?.query!="function")return;r.query({name:"geolocation"}).then(e=>{Ke=e,e.state==="granted"&&ie(),e.onchange=()=>{e.state==="granted"?ie():I=null}}).catch(()=>{})}catch{}}}function ie(){if(!w){w=!0;try{navigator.geolocation.getCurrentPosition(r=>{w=!1;let{latitude:e,longitude:t,accuracy:i}=r.coords;if(!Number.isFinite(e)||!Number.isFinite(t))return;let n={latitude:e,longitude:t,source:"gps"};Number.isFinite(i)&&(n.accuracy=i),I=n,qe=Date.now()},()=>{w=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{w=!1}}}function Be(){if(I)return Date.now()-qe>3e5&&Ke?.state==="granted"&&ie(),{...I}}var se="@depsmith/depsmith-sdk",b="0.8.0",ne=null;function _t(){if(ne)return ne;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ne=r,r}function k(r={}){let e={library:{name:se,version:b}};m(()=>{if(typeof window<"u"&&window.location){let t=window.location.href;e.page={url:t,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,domain:E(t),url_base:C(t),...r.page??{}}}}),m(()=>{typeof window<"u"&&window.screen&&(e.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),m(()=>{let t=_t();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),m(()=>{let{deviceType:t}=re();t&&(e.device={...e.device,type:t})}),m(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),m(()=>{r.fingerprint&&xt(e)}),m(()=>{if(r.geolocation){let t=Be();t&&(e.location=t)}});try{if(r.overrides){for(let[t,i]of Object.entries(r.overrides))i!==void 0&&(e[t]=i);e.library={name:se,version:b}}}catch{}return r.tracking&&Oe(e,r.tracking),e}function xt(r){let{browser:e,os:t,deviceType:i,device:n}=re();e&&(r.browser=e),t&&(r.os=t);let s={...r.device};i&&(s.type=i),n?.manufacturer&&(s.manufacturer=n.manufacturer),n?.model&&(s.model=n.model),Object.keys(s).length>0&&(r.device=s);let o=Le();o.type&&(r.network={...r.network,type:o.type})}function m(r){try{r()}catch{}}function Fe(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var oe="depsmith_consent",M=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(oe);this.state=n==="granted"||n==="denied"||n==="pending"?n:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(oe,"granted")}optOut(){this.state="denied",this.storage.set(oe,"denied")}};var P=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},At=r=>r();var N="depsmith_queue",Ot=512*1024,ae=2,Et=new Set(["identify","alias","group"]);function Ct(r){return Et.has(r?.event_type)}var U=class{constructor(e,t,i,n={}){this.storage=e;this.maxSize=t;this.logger=i;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=n.maxChars??Ot,this.schedule=n.schedule??P,this.restore()}restore(){try{let e=this.storage.get(N);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let i=t.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string");this.reset(i),i.length!==t.length&&(this.logger.warn("discarded corrupt queued events on restore"),this.markDirty()),this.trimToBudget()&&this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty"),this.reset([]),this.storage.remove(N)}}reset(e){this.events=e,this.sizes=e.map(t=>je(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?ae:this.sizeSum+(this.events.length-1)+ae}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(N,JSON.stringify(this.events)))}prepend(e){let t=new Set(this.events.map(n=>n.event_id)),i=e.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string"&&!t.has(n.event_id));i.length!==0&&(this.reset([...i,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let t=je(e);if(t+ae>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let i=this.events.length-this.maxSize;this.dropOldest(i),this.logger.warn(`queue cap reached; dropped ${i} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!Ct(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e){return this.events.slice(0,e)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let d=this.events[o];if(t.has(d.event_id))continue;let a=this.sizes[o];i.push(d),n.push(a),s+=a}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(N)}};function je(r){return JSON.stringify(r).length}function f(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let i=0;i<16;i++)e[i]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=[];for(let i=0;i<16;i++)t.push(e[i].toString(16).padStart(2,"0"));return`${t[0]}${t[1]}${t[2]}${t[3]}-${t[4]}${t[5]}-${t[6]}${t[7]}-${t[8]}${t[9]}-${t[10]}${t[11]}${t[12]}${t[13]}${t[14]}${t[15]}`}function S(r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r))return null;let e=r.slice(0,8)+r.slice(9,13),t=parseInt(e,16);return Number.isFinite(t)?t:null}var Ye=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer"],v=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},D=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let i of document.cookie.split("; "))if(i.startsWith(t))return decodeURIComponent(i.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",i=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${i}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},Tt=new Set(["depsmith_anonymous_id"]),L=class{constructor(e,t,i=Tt){this.primary=e;this.secondary=t;this.mirrored=i}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let i=this.secondary.get(e);if(t===i)return t;if(t===null&&i!==null)return this.primary.set(e,i),i;if(i===null&&t!==null)return this.secondary.set(e,t),t;let n=$t(t,i)??t;return this.primary.set(e,n),this.secondary.set(e,n),n}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}};function $t(r,e){let t=S(r),i=S(e);return t===null||i===null?null:t<=i?r:e}var de=class{constructor(e,t=Ye){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};var ue=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},_=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let i=indexedDB.open(e,1);i.onupgradeneeded=()=>i.result.createObjectStore("kv"),i.onsuccess=()=>{this.db=i.result;let n=this.db.transaction("kv","readonly").objectStore("kv"),s=n.getAllKeys(),o=n.getAll();o.onsuccess=()=>{let d=s.result;o.result.forEach((a,u)=>{let p=d[u];p!==void 0&&(this.snapshot.set(p,a),this.mirror.has(p)||this.mirror.set(p,a))}),t()},o.onerror=()=>t()},i.onerror=()=>t()}catch{t()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(t,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}};function Xe(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new ue(window.localStorage)}}catch{}return new v}var pe="depsmith_anonymous_id",ce="depsmith_user_id",le="depsmith_group_id",V="depsmith_user_props",q=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(pe);return e||(e=f(this.clock.now()),this.storage.set(pe,e)),e}get userId(){return this.storage.get(ce)}get groupId(){return this.storage.get(le)}identify(e){this.storage.set(ce,e)}setGroup(e){this.storage.set(le,e)}getUserProps(){try{return JSON.parse(this.storage.get(V)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(V,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(V,JSON.stringify(t))}reset(){this.storage.remove(ce),this.storage.remove(le),this.storage.remove(V);let e=f(this.clock.now());return this.storage.set(pe,e),e}};var Ge="depsmith_session",K=class{constructor(e,t,i,n=P){this.storage=e;this.clock=t;this.timeoutMs=i;this.pending=null;this.scheduled=!1;this.schedule=n}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(Ge);if(!e)return null;let t=JSON.parse(e);return typeof t.id!="string"||typeof t.lastActivityAt!="number"?null:(typeof t.startedAt!="number"&&(t.startedAt=S(t.id)??t.lastActivityAt),t)}catch{return null}}save(e){this.pending=e,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){let e=this.pending;e&&(this.pending=null,this.storage.set(Ge,JSON.stringify(e)))}mint(e){let t={id:f(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let i=this.mint(e);return{sessionId:i.id,startedAt:e,startedSession:{id:i.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let i=this.mint(e);return{sessionId:i.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:i.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let i=S(e);return i===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:t??i}),!0)}rotate(){return this.mint(this.clock.now()).id}};function y(r,e){if(r==null)return{};if(typeof r!="object"||Array.isArray(r))return e.warn("properties must be an object; ignoring",r),{};let t={},i=0;for(let[n,s]of Object.entries(r)){if(i>=200){e.warn("properties exceed 200 keys; excess dropped");break}let o=Rt(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function ge(r){if(r===null)return null;let e=typeof r;if(e==="string"||e==="boolean")return r;if(e==="number")return Number.isFinite(r)?r:void 0;if(r instanceof Date)return isNaN(r.getTime())?void 0:r.toISOString()}function Rt(r,e){let t=ge(r);if(t!==void 0)return t;if(!(r===void 0||typeof r=="function"||typeof r=="symbol")){if(Array.isArray(r)){let i=[];for(let n of r.slice(0,100)){let s=ge(n);i.push(s!==void 0?s:He(n))}return i}if(typeof r=="object"){let i={},n=0;for(let[s,o]of Object.entries(r)){if(n>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let d=ge(o);i[String(s)]=d!==void 0?d:He(o),n++}return i}}}function He(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function z(r,e,t){let i={...r},n;for(let s in i)g(s,e,t)&&(n=delete i[s]);return n?i:r}function g(r,e,t){return r?.[0]!=="$"?!1:(t.warn(`${e}: "$"-prefixed keys are reserved; ignored "${r}"`),!0)}function It(r){return r>=500}function We(r){let e={};try{let t=new URL(r,typeof location<"u"?location.href:void 0);e.$net_url=`${t.origin}${t.pathname}`,t.search.length>1&&(e.$net_query=t.search.slice(1)),t.hash.length>1&&(e.$net_fragment=t.hash.slice(1))}catch{e.$net_url=r.slice(0,255)}return e}function Mt(r){try{let e=r?.get("content-length");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}catch{return}}function Je(r,e){if(typeof fetch!="function")return{stop:()=>{}};let t=fetch,i=r.replace(/\/+$/,""),n=async(s,o)=>{let d=Date.now(),a=typeof s=="string"?s:s instanceof URL?s.href:s.url,u=o?.method??(typeof s=="object"&&"method"in s?s.method:"GET");if(a.startsWith(i))return t(s,o);try{let p=await t(s,o);return It(p.status)&&e({...We(a),$net_method:String(u).toUpperCase(),$net_status:p.status,$net_start:d,$net_end:Date.now(),$net_duration_ms:Date.now()-d,...Nt(o,p)}),p}catch(p){throw e({...We(a),$net_method:String(u).toUpperCase(),$net_error_message:p instanceof Error?p.message.slice(0,255):"network error",$net_start:d,$net_end:Date.now(),$net_duration_ms:Date.now()-d}),p}};return globalThis.fetch=n,{stop:()=>{globalThis.fetch===n&&(globalThis.fetch=t)}}}function Nt(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=Mt(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function B(r){return Math.round(r)}function Qe(){let r,e,t,i=0,n=!1,s,o=[],d=(a,u)=>{try{let p=new PerformanceObserver(l=>u(l.getEntries()));p.observe({type:a,buffered:!0}),o.push(p)}catch{}};d("largest-contentful-paint",a=>{let u=a[a.length-1];u&&(r=B(u.startTime))}),d("paint",a=>{for(let u of a)u.name==="first-contentful-paint"&&(e=B(u.startTime))}),d("layout-shift",a=>{for(let u of a)u.hadRecentInput||(i+=u.value??0,n=!0)}),d("event",a=>{for(let u of a){let p=B(u.duration);(t===void 0||p>t)&&(t=p)}});try{let[a]=performance.getEntriesByType("navigation"),u=a;u?.responseStart!==void 0&&u.responseStart>0&&(s=B(u.responseStart))}catch{}return{snapshot(){let a={};return r!==void 0&&(a.$wv_lcp=r),e!==void 0&&(a.$wv_fcp=e),t!==void 0&&(a.$wv_inp=t),n&&(a.$wv_cls=Math.round(i*1e3)/1e3),s!==void 0&&(a.$wv_ttfb=s),a},hasAny(){return r!==void 0||e!==void 0||t!==void 0||n||s!==void 0},stop(){for(let a of o.splice(0))try{a.disconnect()}catch{}}}}var fe="depsmith_super_props";function Ze(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):!g(r,"register",e)}var F=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(fe);if(i){let n=JSON.parse(i);n&&typeof n=="object"&&!Array.isArray(n)&&(this.properties=n)}}catch{}}register(e){let t=!1;for(let[i,n]of Object.entries(e))Ze(i,this.logger)&&(this.properties[i]=n,t=!0);t&&this.persist()}registerOnce(e){let t=!1;for(let[i,n]of Object.entries(e))Ze(i,this.logger)&&(Object.prototype.hasOwnProperty.call(this.properties,i)||(this.properties[i]=n,t=!0));t&&this.persist()}unregister(e){Object.prototype.hasOwnProperty.call(this.properties,e)&&(delete this.properties[e],this.persist())}clear(){if(Object.keys(this.properties).length!==0){this.properties={};try{this.storage.remove(fe)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(fe,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var Ut=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],et=50,tt=200;function he(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let s=Object.keys(r).filter(o=>o!=="$clear_all");return s.length>0&&e.warn(`$clear_all is exclusive; ignored ${s.join(", ")}`),{$clear_all:!0}}let t={},i=new Set,n=(s,o)=>g(s,o,e)?!1:i.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(i.add(s),!0);for(let s of Ut){let o=r[s];if(!o||typeof o!="object")continue;let d=y(o,e),a={};for(let[u,p]of Object.entries(d))n(u,s)&&(a[u]=p);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[d,a]of Object.entries(r.$add)){if(o>=et){e.debug(`$add over ${et} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${d}" is not finite; dropped`);continue}n(d,"$add")&&(s[d]=a,o++)}Object.keys(s).length>0&&(t.$add=s)}if(Array.isArray(r.$unset)){let s=[];for(let o of r.$unset){if(s.length>=tt){e.debug(`$unset over ${tt} keys; excess dropped`);break}typeof o!="string"||o.length===0||n(o,"$unset")&&s.push(o)}s.length>0&&(t.$unset=s)}return Object.keys(t).length>0?t:void 0}function j(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var rt={now:()=>Date.now()};function h(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function it(r){return r===0||r===408||r===429||r>=500}var Dt=1e3,Lt=32e3;function nt(r,e=Math.random){let t=Math.min(Dt*2**r,Lt);return Math.round(e()*t)}async function Vt(r){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new TextEncoder().encode(r)).catch(()=>{}),t.close().catch(()=>{});let i=e.readable.getReader(),n=[];for(;;){let{done:a,value:u}=await i.read();if(a)break;n.push(u)}let s=n.reduce((a,u)=>a+u.length,0),o=new Uint8Array(new ArrayBuffer(s)),d=0;for(let a of n)o.set(a,d),d+=a.length;return o}function st(r){let e=[];for(let t of r)e.push(t.event_id);return e}var qt=3e4,Kt=6e4,zt=10;function Bt(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var Y=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("collector unreachable; uploads paused");return}let e=this.queue.peek(this.config.batchSize);this.queue.persistNow();let t=await this.uploadWithRetry(e);if(t==="requeue")return;t==="dropped"&&this.deps.logger.warn(`dropped poison batch of ${e.length}`),this.queue.remove(st(e))}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1;for(let n=0;n<=this.config.maxRetries;n++){let s=await this.post(e);if(s!==0&&(i=!0),s>=200&&s<300)return t?.ok(),"sent";if(!it(s))return t?.ok(),this.deps.logger.warn(`non-retryable ${s}; dropping batch`),"dropped";if(this.deps.logger.debug(`upload attempt ${n+1} failed (${s})`),s===0&&!i&&t?.suspect())break;n<this.config.maxRetries&&await this.deps.sleep(nt(n))}return i?t?.ok():t?.fail(),"requeue"}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:h(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s=t,o={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream<"u")try{s=await Vt(t),o["Content-Encoding"]="gzip"}catch{s=t}let d=Bt(s)<=Kt;d||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let a={method:"POST",headers:o,body:s,keepalive:d};return i&&(a.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,a)).status}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:qt}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<zt;){let t=this.queue.peek(this.config.batchSize),i=this.buildPayload(t);if(!navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(i)],{type:"text/plain"})))return;this.queue.remove(st(t)),e++}}catch{}}};var me="depsmith_net_breaker";function ot(r,e){let t=!1,i=0,n=0,s=3e5,o=(u,p,l)=>typeof u=="number"&&u===u?Math.min(Math.max(u,p),l):p,d=()=>{if(!t){t=!0;try{let u=JSON.parse(r.get(me)??"0");if(!Array.isArray(u))return;i=o(u[0],0,3),n=o(u[1],0,e.now()+36e5),s=o(u[2],3e5,36e5)}catch{}}},a=()=>{try{i?r.set(me,JSON.stringify([i,n,s])):r.remove(me)}catch{}};return{open:()=>(d(),e.now()<n),suspect:()=>(d(),i>0),fail:()=>{d(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),a()},ok:()=>{d(),i&&(i=n=0,s=3e5,a())}}}var X=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var at=255,x=class{constructor(e,t={}){this.vitalsReported=!1;this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=Te(e),this.logger=new X(this.config.debug),this.clock=t.clock??rt,this.storage=t.storage??this.pickStorage(),this.contextProvider=t.contextProvider,this.pageLife=new O({now:()=>this.clock.now(),capture:(n,s,o,d,a)=>this.capture(n,s,o,void 0,void 0,d,a)},this.config);let i=this.config.childSafeMode?new v:this.config.storage==="memory"?this.storage:new L(this.storage,new D(this.config.cookieDomain||void 0));this.identity=new q(i,this.clock),this.session=new K(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new M(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??Fe())),this.attribution=new A(i),this.superProperties=new F(this.storage,this.logger),!this.contextProvider&&typeof window<"u"&&window.location&&(this.attribution.recordLanding(window.location.href,typeof document<"u"?document.referrer:""),this.pageLife.start(window.location.href,typeof document<"u"?document.referrer:"")),this.queue=new U(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&Me(),this.config.geolocation&&!this.config.childSafeMode&&ze(),this.storage instanceof _&&(this.ready=this.storage.hydrate().then(n=>{try{let s=n.get("depsmith_queue");s&&this.queue.prepend(JSON.parse(s))}catch{this.logger.warn("persisted queue corrupt; discarded")}})),this.uploader=new Y(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...n)=>fetch(...n)),clock:this.clock,logger:this.logger,sleep:t.sleep??(n=>new Promise(s=>setTimeout(s,n))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:ot(this.storage,this.clock)}),t.manualLifecycle||(this.startFlushTimer(),this.attachLifecycle(),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.trackInternal(e,z(t,"track",this.logger))}trackInternal(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}g(e,"track",this.logger)||this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}traits(e,t){return y(z(e,t,this.logger),this.logger)}tooLong(e,t){return e.length<=at?!1:(this.logger.warn(`${t} exceeds ${at} characters (got ${e.length}); dropped`),!0)}page(e,t,i){this.pageInternal(e,z(t,"page",this.logger),i)}pageInternal(e,t,i){this.guard(()=>this.pageLife.manual(e,t,i?.type))}emitWebVitals(){this.vitalsReported||!this.vitals?.hasAny()||(this.vitalsReported=!0,this.capture("$web_vitals","track",this.vitals.snapshot()))}screen(e,t,i){this.page(e,t,i)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let i=this.traits(t,"identify");this.capture("$identify","identify",void 0,i,j("$set",i))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.pageLife.flushPending(),this.identity.reset(),this.session.rotate(),this.attribution.clear(),this.superProperties.clear(),this.logger.debug("reset: identity, session and attribution cleared")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(e,"group: groupId"))return;this.identity.setGroup(e);let i=this.traits(t,"group");this.capture("$group","group",void 0,i)})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}let t=this.traits(e,"setGroupTraits");this.capture("$group","group",void 0,t)})}setProperty(e,t){this.guard(()=>{if(g(e,"setProperty",this.logger))return;this.identity.setUserProp(e,t);let i=y({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,j("$set",i))})}setOnceProperty(e,t){this.guard(()=>{if(g(e,"setOnceProperty",this.logger))return;if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.identity.setUserProp(e,t);let i=y({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,j("$set_once",i))})}unsetProperty(e){this.guard(()=>{g(e,"unsetProperty",this.logger)||(this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},he({$unset:[e]},this.logger)))})}register(e){this.guard(()=>this.superProperties.register(e))}registerOnce(e){this.guard(()=>this.superProperties.registerOnce(e))}unregister(e){this.guard(()=>this.superProperties.unregister(e))}setUserProperties(e){this.guard(()=>{let t=he(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.flushUploads()})}optOut(){this.guard(()=>{this.pageLife.discardPending(),this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.guard(()=>this.pageLife.flushPending()),this.flushTimer!==null&&clearInterval(this.flushTimer),this.flushTimer=null;for(let e of this.teardownFns.splice(0))e();this.persistNow()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}enqueueEvent(e){this.queue.enqueue(e),this.drained=!1}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:Re(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,i,n,s,o,d){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let a=this.session.touch();if(a.startedSession&&this.pageLife.newSession(),a.endedSession&&this.sessionInSample(a.endedSession.id)&&this.enqueueSessionEnd(a.endedSession),a.startedSession&&this.sessionInSample(a.startedSession.id)&&this.enqueueSessionStart(a.startedSession),!this.inSample(a.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let u=o??this.clock.now(),p=this.contextOptions();d&&(p.page=d);let l={event_id:f(u),event:e,event_type:t,timestamp:h(u),session_id:a.sessionId,session_started_at:h(a.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...k(p),traits:n}:k(p),platform:"web",sdk_version:b};s&&(l.user_properties=s);let ye={...this.config.defaultProperties,...this.superProperties.current(),...y(i,this.logger)};Object.keys(ye).length>0&&(l.properties=ye);let be=this.identity.userId;be&&(l.user_id=be);let Se=this.identity.groupId;Se&&(l.group_id=Se),p.fingerprint&&(l.device_id=R()),this.enqueueEvent(l),this.logger.debug(`captured ${e}`,l),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",t=Z(this.config.apiKey),i=this.storage.get(e);i!==null&&i!==t&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear()),this.storage.set(e,t)}pickStorage(){return this.config.storage==="memory"?new v:this.config.storage==="indexeddb"&&typeof indexedDB<"u"?new _:Xe()}enqueueSessionEnd(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:f(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:h(e.lastActivityAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:k(t),platform:"web",sdk_version:b},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=R()),this.enqueueEvent(i)}enqueueSessionStart(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:f(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:h(e.startedAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:k(t),platform:"web",sdk_version:b},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=R()),t.fingerprint&&(i.properties={...i.properties,...De()}),this.enqueueEvent(i)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window>"u"||typeof document>"u")return;let e=()=>{this.drained||(this.guard(()=>this.emitWebVitals()),this.guard(()=>this.leaveOnUnload?.()),this.drained=!0,this.consent.canUpload()&&this.uploader.sendBeaconAll(),this.persistNow())},t=()=>{if(document.visibilityState==="hidden")e();else{this.drained=!1;let s=this.session.touch();s.endedSession&&this.enqueueSessionEnd(s.endedSession),s.startedSession&&(this.pageLife.newSession(),this.enqueueSessionStart(s.startedSession))}},i=s=>{this.drained=!1,this.pageLife.restored(s.persisted)},n=()=>{this.uploader.resetNetworkBreaker(),this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()};window.addEventListener("pagehide",e),window.addEventListener("pageshow",i),document.addEventListener("visibilitychange",t),window.addEventListener("online",n),this.teardownFns.push(()=>{window.removeEventListener("pagehide",e),window.removeEventListener("pageshow",i),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",n)})}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=Qe(),this.teardownFns.push(()=>this.vitals?.stop()));let t=Je(this.config.endpoint,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),xe().then(i=>{i&&(this.teardownFns.push(i.startAutocapture(e,{emit:n=>this.autocapture(n),page:n=>this.guard(()=>this.pageLife.autoPageView(n)),pageLeave:n=>this.guard(()=>this.pageLife.leave(n)),warn:n=>this.logger.warn(n),armUnloadLeave:n=>{this.leaveOnUnload=n}})),this.teardownFns.push(()=>{this.leaveOnUnload=void 0}))}).catch(i=>this.logger.debug("autocapture load failed",i))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var c=null,ve=null,pi={init(r,e){try{return c&&ve===r.apiKey||(c?.shutdown(),c=new x(r,e),ve=r.apiKey),c}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>c?.track(r,e),page:(r,e,t)=>c?.page(r,e,t),screen:(r,e,t)=>c?.screen(r,e,t),identify:(r,e)=>c?.identify(r,e),alias:r=>c?.alias(r),reset:()=>c?.reset(),group:(r,e)=>c?.group(r,e),setGroupTraits:r=>c?.setGroupTraits(r),setProperty:(r,e)=>c?.setProperty(r,e),setOnceProperty:(r,e)=>c?.setOnceProperty(r,e),unsetProperty:r=>c?.unsetProperty(r),setUserProperties:r=>c?.setUserProperties(r),register:r=>c?.register(r),registerOnce:r=>c?.registerOnce(r),unregister:r=>c?.unregister(r),optIn:()=>c?.optIn(),optOut:()=>c?.optOut(),flush:()=>c?.flush()??Promise.resolve(),getAnonymousId:()=>c?.getAnonymousId(),getSessionId:()=>c?.getSessionId(),setSessionId:(r,e)=>c?.setSessionId(r,e),shutdown(){c?.shutdown(),c=null,ve=null}};export{de as AsyncMirrorAdapter,Ye as DEPSMITH_SDK_STORAGE_KEYS,pi as DepsmithSdk,x as DepsmithSdkClient,P as idleScheduler,At as syncScheduler};
2
2
  //# sourceMappingURL=index.js.map