@depsmith/depsmith-sdk 0.9.0 → 0.9.1

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.d.cts CHANGED
@@ -171,7 +171,8 @@ interface DepsmithSdkEvent {
171
171
  * carry a change; applied against `user_id` when set, else `anonymous_id`.
172
172
  */
173
173
  user_properties?: UserPropertyOps;
174
- platform: 'web';
174
+ /** Where the user is. Always `Web` from this SDK (schema 0.9.1; `web` before). */
175
+ platform: 'Web';
175
176
  sdk_version: string;
176
177
  }
177
178
  interface BatchPayload {
@@ -674,14 +675,6 @@ declare class DepsmithSdkClient {
674
675
  private detectConfigDrift;
675
676
  /** The synchronous store. IndexedDB is never returned here — see the constructor. */
676
677
  private pickStorage;
677
- private enqueueSessionEnd;
678
- /**
679
- * Announces a session the SDK just observed beginning.
680
- *
681
- * Not emitted by reset()/rotate() (an explicit user action, not an observed boundary)
682
- * nor by peek()'s mint-if-absent branch (analytics from a getter).
683
- */
684
- private enqueueSessionStart;
685
678
  /**
686
679
  * `$session_start` / `$session_end`, built in one place: the two envelopes differ only in
687
680
  * their name, their timestamp and the fingerprint components the opening one carries.
package/dist/index.d.ts CHANGED
@@ -171,7 +171,8 @@ interface DepsmithSdkEvent {
171
171
  * carry a change; applied against `user_id` when set, else `anonymous_id`.
172
172
  */
173
173
  user_properties?: UserPropertyOps;
174
- platform: 'web';
174
+ /** Where the user is. Always `Web` from this SDK (schema 0.9.1; `web` before). */
175
+ platform: 'Web';
175
176
  sdk_version: string;
176
177
  }
177
178
  interface BatchPayload {
@@ -674,14 +675,6 @@ declare class DepsmithSdkClient {
674
675
  private detectConfigDrift;
675
676
  /** The synchronous store. IndexedDB is never returned here — see the constructor. */
676
677
  private pickStorage;
677
- private enqueueSessionEnd;
678
- /**
679
- * Announces a session the SDK just observed beginning.
680
- *
681
- * Not emitted by reset()/rotate() (an explicit user action, not an observed boundary)
682
- * nor by peek()'s mint-if-absent branch (analytics from a getter).
683
- */
684
- private enqueueSessionStart;
685
678
  /**
686
679
  * `$session_start` / `$session_end`, built in one place: the two envelopes differ only in
687
680
  * their name, their timestamp and the fingerprint components the opening one carries.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ct=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],ne="depsmith_campaign",se="depsmith_referrer";function Tt(r){try{return new URL(r).host||void 0}catch{return}}var N=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(ne)??{},this.referrer=this.read(se)??{}}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 d=new URL(e);i=d.searchParams,n=d.host}catch{return}let s={};for(let[d,p]of Ct){let c=i.get(d);c&&(s[p]=c)}Object.keys(s).length>0&&(this.campaign=s,this.write(ne,s));let o=t?Tt(t):void 0,u=!!o&&o!==n,a=!1;u&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=u?o:"$direct",u&&(this.referrer.initial_url=t),a=!0),a&&this.write(se,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(ne),this.storage.remove(se)}catch{}}};var oe=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=Ne(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=Ne(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}},M=class{constructor(e,t={autocapture:!1}){this.sink=e;this.pages=new oe;this.enteredAt=0;this.left=!1;this.rules=$t(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(),this.autoViewed=void 0}manual(e,t,i){let n=this.pending;if(n&&this.keyOf(n.location)===this.pageKey())this.discardPending();else{this.flushPending();let s=this.autoViewed;if(this.autoViewed=void 0,s&&s.url===Ie()&&this.sink.now()-s.at<=Rt)return}this.recordExplicit(),this.sink.capture("$page_view","page_view",{...t,...$e({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:D(n),url_base:U(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.autoViewed={url:e.href,at:this.sink.now()},this.sink.capture("$page_view","page_view",{...$e({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||this.left)return;this.left=!0;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.left=!1,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:Nt(this.leaving),domain:D(this.leaving),url_base:U(this.leaving)}}pageKey(){let e=globalThis.location;return e&&this.keyOf(e)}keyOf(e){return this.byHref?e.href:e.pathname}record(){let e=Ie();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now(),this.left=!1)}},Rt=2e3;function $e({source:r,name:e,type:t,location:i=globalThis.location,title:n=globalThis.document?.title},s){let o=i&&s?.(i),u=t?.trim()||o?.type;return{$page_name:e?.trim()||o?.name.trim()||n?.trim()||i?.pathname||"Unknown",...u?{$page_type:u}:{},$page_source:r}}function $t(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"&&It(t),i]);return t=>{let i=Me(t.pathname);for(let[n,s]of e)if(n&&n.test(i))return{name:s,type:s}}}function It(r){let e=Me(r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\*|\*\*?/g,t=>t==="*"?"[^/]+":t==="**"?".*":"(?:/.*)?");return new RegExp(`^${e}$`)}function Me(r){return r.replace(/(.)\/$/,"$1")}function Ie(){if(!(typeof window>"u"||!window.location))return window.location.href}function Ne(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function Nt(r){try{return new URL(r).pathname||void 0}catch{return}}function D(r){try{return new URL(r).host||void 0}catch{return}}function U(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}function De(r){if(typeof window>"u"||typeof document>"u")return;let e=setInterval(()=>r.flushIfQueued(),r.intervalMs);e.unref?.();let t=!1,i,n=()=>{let a=i;clearTimeout(a),i=void 0,r.guard(()=>r.vitals()),r.guard(()=>r.leave()),!(t&&!a)&&(t=!0,r.beacon(),r.persistNow())},s=()=>{if(document.visibilityState==="hidden"){if(t)return;r.guard(()=>r.vitals()),t=!0,r.persistNow(),i=setTimeout(()=>{i=void 0,r.flushIfQueued()},0)}else clearTimeout(i),t=!1,r.resume()},o=a=>{t=!1,r.restored(a.persisted)},u=()=>r.online();return window.addEventListener("pagehide",n),window.addEventListener("pageshow",o),document.addEventListener("visibilitychange",s),window.addEventListener("online",u),{rearm:()=>{t=!1},stop:()=>{clearInterval(e),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",o),document.removeEventListener("visibilitychange",s),window.removeEventListener("online",u),clearTimeout(i)}}}function Ue(){return import("./autocapture.js")}var ae=[["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"]],Mt=Object.fromEntries(ae.map(([r])=>[r,!0]));function Le(r){let e={...Mt};if(!r)return e;for(let[t]of ae)r[t]===!1&&(e[t]=!1);return e}function Ve(r,e){let t=r;for(let[i,n,s]of ae){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 Ke={clicks:"interactive",forms:!0,scrolls:!1,pageviews:"path",ignoredSelectors:[],selectorMaxDepth:5,selectorIgnore:[],attributes:[]};function Be(r){if(r===!0)return Ke;if(!r||typeof r!="object")return!1;let e={...Ke};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 qe(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=Be(r.autocapture);return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:P(r.batchSize,20,1,500),batchIntervalMs:P(r.batchIntervalMs,6e4,1e3,2**31-1),maxQueueSize:P(r.maxQueueSize,1e3,1),maxQueueBytes:P(r.maxQueueBytes,512*1024,4096),sessionTimeoutMs:P(r.sessionTimeoutMs,18e5,6e4),sampleRate:ze(r.sampleRate,1,0,1),sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:P(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,scrubUrls:r.scrubUrls??!1,trackingOptions:Le(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage",pageNames:r.pageNames}}function ze(r,e,t,i=1/0){return Math.min(Math.max(Number.isFinite(r)?r:e,t),i)}function P(r,e,t,i){return Math.floor(ze(r,e,t,i))}function ue(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 Fe(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 Dt(r){return Fe(r).toString(36)}function je(r){return Fe(r)/4294967296}function de(r){return ue(r)+Dt(r)}var pe={},Ye=!1;function Xe(){if(!Ye){Ye=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{pe=e}).catch(()=>{})}catch{}}}function ce(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=Kt(e,t);i&&(r.browser=i);let n=qt(e);if(n){let u=Lt(n.name,pe.platformVersion);r.os=u?{...n,version:u}:n}let s=zt(e,t);s&&(r.deviceType=s);let o=Ut(e,n);return o&&(r.device=o),r}function Ut(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=pe.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 Lt(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 We(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 Kt(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 qt(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:We((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function We(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function zt(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 L=null,V=null;function He(){return V!==null||(V=Ft()),V}function le(){return L!==null||(L=de(He().map(r=>r.value).join("|"))),L}function Qe(){let r={};for(let e of He())r[`$fp_${e.name}`]=e.value;return r}function Ft(){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:${jt()}`})}catch{}return r}function jt(){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(),de(r.toDataURL())):""}catch{return""}}function Ge(){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 A=null,Ze=0,Je=!1,E=!1,et=null,K=()=>!0;function tt(r=K){if(K=r,!Je){Je=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let e=navigator.permissions;if(typeof e?.query!="function")return;e.query({name:"geolocation"}).then(t=>{et=t,t.state==="granted"&&fe(),t.onchange=()=>{t.state==="granted"?fe():A=null}}).catch(()=>{})}catch{}}}function fe(){if(!(E||!K())){E=!0;try{navigator.geolocation.getCurrentPosition(r=>{E=!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),A=n,Ze=Date.now()},()=>{E=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{E=!1}}}function rt(){if(K()||(A=null),!!A)return Date.now()-Ze>3e5&&et?.state==="granted"&&fe(),{...A}}var he="@depsmith/depsmith-sdk",O="0.9.0",ge=null;function Yt(){if(ge)return ge;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ge=r,r}function B(r={}){let e={library:{name:he,version:O}};S(()=>{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:D(t),url_base:U(t),...r.page??{}}}}),S(()=>{typeof window<"u"&&window.screen&&(e.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),S(()=>{let t=Yt();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(()=>{let{deviceType:t}=ce();t&&(e.device={...e.device,type:t})}),S(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),S(()=>{r.fingerprint&&Xt(e)}),S(()=>{if(r.geolocation){let t=rt();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:he,version:O}}}catch{}return r.tracking&&Ve(e,r.tracking),e}function Xt(r){let{browser:e,os:t,deviceType:i,device:n}=ce();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=Ge();o.type&&(r.network={...r.network,type:o.type})}function S(r){try{r()}catch{}}function it(){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 me="depsmith_consent",q=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(me);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(me,"granted")}optOut(){this.state="denied",this.storage.set(me,"denied")}};var C=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Wt=r=>r();var v="depsmith_queue",Ht=512*1024,ve=2,Qt=new Set(["identify","alias","group"]);function Gt(r){return Qt.has(r?.event_type)}var z=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??Ht,this.schedule=n.schedule??C,this.restore()}restore(){try{let e=this.storage.get(v);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(v)}}reset(e){this.events=e,this.sizes=e.map(t=>nt(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?ve:this.sizeSum+(this.events.length-1)+ve}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(v,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=nt(e);if(t+ve>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(!Gt(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,t=1/0,i=0){let n=i;for(let s=0;n<this.events.length&&n-i<e&&(s+=this.sizes[n]+1,!(n>i&&s>t));n++);return this.events.slice(i,n)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let u=this.events[o];if(t.has(u.event_id))continue;let a=this.sizes[o];i.push(u),n.push(a),s+=a}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}close(){}clear(){this.reset([]),this.dirty=!1,this.storage.remove(v)}};function nt(r){return JSON.stringify(r).length}var ye=-1,be=0,Jt=67108863;function y(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let n=0;n<16;n++)e[n]=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;let t=(e[6]&7)<<22|e[7]<<14|(e[8]&63)<<8|e[9];r===ye?t=be=be+1&Jt:r>ye&&(ye=r,be=t),e[6]=112|t>>>22,e[7]=t>>>14&255,e[8]=128|t>>>8&63,e[9]=t&255;let i="";for(let n=0;n<16;n++)i+=(e[n]+256).toString(16).slice(1);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function x(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 st=["depsmith_anonymous_id","depsmith_anon_reset_at","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","depsmith_super_props"],w=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)}},F=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{}}},T="depsmith_anon_reset_at",Zt=new Set(["depsmith_anonymous_id",T]),j=class{constructor(e,t,i=Zt){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=this.pick(t,i);return this.primary.set(e,n),this.secondary.set(e,n),n}pick(e,t){let i=x(e),n=x(t);if(i===null||n===null)return e;let s=[this.primary,this.secondary],o=Math.max(...s.map(a=>Number(a.get(T))||0));o&&s.forEach(a=>a.set(T,`${o}`));let u=i>=o;return u!==n>=o?u?e:t:i<=n?e:t}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)}},Se=class{constructor(e,t=st){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 R=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{}}},Y=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 u=s.result;o.result.forEach((a,d)=>{let p=u[d];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 ot(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new R(window.localStorage)}}catch{}return new w}function at(r,e){return r==="indexeddb"&&typeof indexedDB<"u"?new Y:e}function ut(r,e,t,i,n,s){return r instanceof Y?r.hydrate().then(o=>{try{let u="depsmith_consent";if(o.get(u)==="denied"&&!e.get(u)&&t.optOut(),n||!t.canCapture()){i.clear();return}let a=o.get("depsmith_queue");a&&i.prepend(JSON.parse(a))}catch{s.warn("persisted queue corrupt; discarded")}}):Promise.resolve()}function dt(r){try{let e=JSON.parse(r||"[]");return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.event_id=="string"):null}catch{return null}}var X=class extends z{constructor(...t){super(...t);this.known=new Set(this.ids());this.removed=new Set;this.area=null;this.onStorage=t=>{if(t.key!==v||t.storageArea!==this.area)return;let i=dt(t.newValue);if(!i)return;let n=new Set;for(let o of i)n.add(o.event_id);let s=[];if(this.known.forEach(o=>{n.has(o)||s.push(o)}),s.length!==0){for(let o of s)this.known.delete(o),this.removed.add(o);this.remove(s)}};if(this.storage instanceof R){this.area=this.storage.ls;try{typeof window<"u"&&window.addEventListener("storage",this.onStorage)}catch{}}}ids(){let t=[];for(let i of this.events)t.push(i.event_id);return t}persistNow(){if(!this.dirty)return;this.dirty=!1;let t=new Set(this.ids());this.known.forEach(s=>{t.has(s)||this.removed.add(s)});let i=[],n=new Set;for(let s of dt(this.storage.get(v))??[])n.add(s.event_id),!t.has(s.event_id)&&!this.removed.has(s.event_id)&&i.push(s);this.storage.set(v,JSON.stringify(this.bounded(i).concat(this.events))),this.known=t,this.removed.forEach(s=>{n.has(s)||this.removed.delete(s)})}bounded(t){if(t.length===0)return t;let i=this.maxSize-this.events.length,n=this.maxChars-this.serializedLength(),s=[];for(let o=t.length-1;o>=0&&i>0;o--){let u=JSON.stringify(t[o]).length+1;if(u>n)break;n-=u,i--,s.push(t[o])}return s.reverse()}clear(){super.clear(),this.known.clear(),this.removed.clear()}close(){try{typeof window<"u"&&window.removeEventListener("storage",this.onStorage)}catch{}}};var we="depsmith_anonymous_id",ke="depsmith_user_id",_e="depsmith_group_id",W="depsmith_user_props",H=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(we);return e||(e=y(this.clock.now()),this.storage.set(we,e)),e}get userId(){return this.storage.get(ke)}get groupId(){return this.storage.get(_e)}identify(e){this.storage.set(ke,e)}setGroup(e){this.storage.set(_e,e)}getUserProps(){try{return JSON.parse(this.storage.get(W)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(W,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(W,JSON.stringify(t))}reset(){this.storage.remove(ke),this.storage.remove(_e),this.storage.remove(W);let e=this.clock.now();this.storage.set(T,`${e}`);let t=y(e);return this.storage.set(we,t),t}};var pt="depsmith_session",Q=class{constructor(e,t,i,n=C){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(pt);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=x(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(pt,JSON.stringify(e)))}mint(e){let t={id:y(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=x(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 k(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=er(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function Pe(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 er(r,e){let t=Pe(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=Pe(n);i.push(s!==void 0?s:ct(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 u=Pe(o);i[String(s)]=u!==void 0?u:ct(o),n++}return i}}}function ct(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function G(r,e,t){let i={...r},n;for(let s in i)m(s,e,t)&&(n=delete i[s]);return n?i:r}function m(r,e,t){return r?.[0]!=="$"?!1:(t.warn(`${e}: "$"-prefixed keys are reserved; ignored "${r}"`),!0)}function tr(r,e){let t=r?.name;return t==="AbortError"||t!=="TimeoutError"&&!!e?.aborted}function rr(r){let e=r?.message;return typeof e=="string"&&e?e.slice(0,255):"network error"}function ir(r){return r>=500}function lt(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 nr(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 sr(r,e){let t=Object.prototype.toString.call(r)==="[object Request]"?r:void 0;return{raw:String(t?t.url:r),method:String(e?.method??t?.method??"GET").toUpperCase(),signal:e?.signal??t?.signal}}function ft(r,e){if(r.autocapture&&r.autocapture.networkErrors===!1||typeof fetch!="function")return{stop:()=>{}};let i=fetch,n=r.endpoint.replace(/\/+$/,""),s=!1,o=0,u=new Set,a=c=>{let f=Date.now();return f-o>=6e4&&(o=f,u=new Set),u.size>=10||u.has(c)?!1:(u.add(c),!0)},d=(c,f)=>{try{let g=f();a(`${String(g.$net_method)} ${String(g.$net_url)} ${c}`)&&e(g)}catch{}},p=function(...c){let f=Date.now(),g=i.apply(this,c);if(s||typeof g?.then!="function")return g;let b,ie,Re;try{if({raw:b,method:ie,signal:Re}=sr(c[0],c[1]),b.startsWith(n))return g}catch{return g}let Ot=c[1];return g.then(h=>(ir(h.status)&&d(h.status,()=>({...lt(b),$net_method:ie,$net_status:h.status,$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f,...or(Ot,h)})),h),h=>{throw typeof navigator<"u"&&navigator.onLine===!1||tr(h,Re)||d("error",()=>({...lt(b),$net_method:ie,$net_error_message:rr(h),$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f})),h})};return globalThis.fetch=p,{stop:()=>{s=!0,globalThis.fetch===p&&(globalThis.fetch=i)}}}function or(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=nr(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function J(r){return Math.round(r)}function gt(){let r,e,t,i=0,n=!1,s,o=[],u=(a,d)=>{try{let p=new PerformanceObserver(c=>d(c.getEntries()));p.observe({type:a,buffered:!0}),o.push(p)}catch{}};u("largest-contentful-paint",a=>{let d=a[a.length-1];d&&(r=J(d.startTime))}),u("paint",a=>{for(let d of a)d.name==="first-contentful-paint"&&(e=J(d.startTime))}),u("layout-shift",a=>{for(let d of a)d.hadRecentInput||(i+=d.value??0,n=!0)}),u("event",a=>{for(let d of a){let p=J(d.duration);(t===void 0||p>t)&&(t=p)}});try{let[a]=performance.getEntriesByType("navigation"),d=a;d?.responseStart!==void 0&&d.responseStart>0&&(s=J(d.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 xe="depsmith_super_props";function ht(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):!m(r,"register",e)}var Z=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(xe);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))ht(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))ht(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(xe)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(xe,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var ar=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],mt=50,vt=200;function Ee(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)=>m(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 ar){let o=r[s];if(!o||typeof o!="object")continue;let u=k(o,e),a={};for(let[d,p]of Object.entries(u))n(d,s)&&(a[d]=p);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[u,a]of Object.entries(r.$add)){if(o>=mt){e.debug(`$add over ${mt} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${u}" is not finite; dropped`);continue}n(u,"$add")&&(s[u]=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>=vt){e.debug(`$unset over ${vt} 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 Ae(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var yt={now:()=>Date.now()};function _(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function ee(r){return r===0||r===408||r===429||r>=500}var ur=1e3,dr=32e3;function bt(r,e=Math.random){let t=Math.min(ur*2**r,dr);return Math.round(e()*t)}function St(r,e){if(!r)return 0;let t=Number(r),i=t===t?t*1e3:Date.parse(r)-e;return i>0?i:0}async function pr(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:d}=await i.read();if(a)break;n.push(d)}let s=n.reduce((a,d)=>a+d.length,0),o=new Uint8Array(new ArrayBuffer(s)),u=0;for(let a of n)o.set(a,u),u+=a.length;return o}async function wt(r,e){if(e==="none"||typeof CompressionStream>"u")return null;try{return await pr(r)}catch{return null}}function kt(r,e,t,i,n){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let s=t.breaker;if(!t.isOnline()||s?.open()||s?.suspect())return;let o=i;for(let u=0;u<10;u++){let a=r.peek(e.batchSize,48e3,o);if(!a.length)return;let d=n(a);if(navigator.sendBeacon(`${e.endpoint}/e/`,new Blob([JSON.stringify(d)],{type:"text/plain"})))r.remove(a.map(c=>c.event_id));else{if(a.length>1)return;o++}}}catch{}}function cr(r){let e=[];for(let t of r)e.push(t.event_id);return e}var lr=3e4,fr=6e4,gr=256e3;function hr(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var mr=399;function Oe(r){return r>299&&r<400||r===401||r===403}var vr=3e4,yr=60*6e4,te=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null;this.uploading=0;this.limit=0;this.strikes=0;this.wait=0}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.limit=0;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("uploads paused");return}let e=this.config.batchSize,t=this.queue.peek(this.limit||e,gr);this.queue.persistNow(),this.uploading=t.length;let i=await this.uploadWithRetry(t);if(this.uploading=0,Oe(i)||ee(i))return;if(i===400||i===413){if(t.length>1){this.limit=t.length>>1;continue}this.limit=0}if(i>299&&this.deps.logger.notice(`collector answered ${i}; dropped ${t.length} event(s)`),this.queue.remove(cr(t)),i===400)return}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1,n=0;for(let s=0;s<=this.config.maxRetries&&!(s&&(this.deps.canUpload?.()===!1||this.queue.peek(1)[0]?.event_id!==e[0].event_id)||(n=await this.post(e),n&&(i=!0),!ee(n)||this.wait)||(this.deps.logger.debug(`upload attempt ${s+1} failed (${n})`),!i&&t?.suspect()));s++)s<this.config.maxRetries&&await this.deps.sleep(bt(s));return i?(t?.ok(),n>199&&n<300?this.strikes=0:(Oe(n)||ee(n))&&(Oe(n)&&this.deps.logger.notice(`collector refused uploads (${n}); paused`),t?.hold(this.wait||Math.min(vr*2**this.strikes++,yr)))):t?.fail(),n}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:_(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){this.wait=0;let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s={"Content-Type":"application/json"},o=await wt(t,this.config.compression);o&&(s["Content-Encoding"]="gzip");let u=o??t,a=hr(u)<=fr;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let d={method:"POST",headers:s,body:u,keepalive:a};i&&(d.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs()));let p=await this.deps.fetchFn(`${this.config.endpoint}/e/`,d);return p.redirected?mr:(this.wait=St(p.headers?.get("Retry-After"),this.deps.clock.now()),p.status)}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:lr}sendBeaconAll(){kt(this.queue,this.config,this.deps,this.uploading,e=>this.buildPayload(e))}};var $="depsmith_net_breaker";function _t(r,e){let t=!1,i=0,n=0,s=3e5,o=(d,p,c)=>typeof d=="number"&&d===d?Math.min(Math.max(d,p),c):p,u=()=>{if(!t){t=!0;try{let d=JSON.parse(r.get($)??"0");if(!Array.isArray(d))return;i=o(d[0],0,3),n=o(d[1],0,e.now()+36e5),s=o(d[2],3e5,36e5)}catch{}}},a=()=>{try{i||n>e.now()?r.set($,JSON.stringify([i,n,s])):r.remove($)}catch{}};return{open:()=>(u(),e.now()<(n=Math.min(n,e.now()+36e5))),suspect:()=>(u(),i>0),fail:()=>{u(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),a()},ok:()=>{u(),i&&(i=n=0,s=3e5,a())},hold:d=>{u(),n=Math.max(n,e.now()+Math.min(d,36e5)),a()}}}var re=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)}notice(...e){console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var Pt=["url","referrer","previous_url","initial_url"],br=["$ac_href","$ac_form_action","$net_url","$fr_error_file"];function xt(r,e){let t=r.split("#")[0],i=t.indexOf("?");if(i<0)return t;let n=t.slice(i+1).split("&").filter(s=>e.has(Sr(s)));return t.slice(0,i)+(n.length?`?${n.join("&")}`:"")}function Sr(r){let e=r.split("=")[0].replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}function Et(r,e){if(e)try{let t=e.keepParams,i=new Set(Array.isArray(t)?t:[]),n=[[r.context.page,Pt],[r.context.referrer,Pt],[r.properties,br]];for(let[o,u]of n)for(let a of u){let d=o?.[a];typeof d=="string"&&(o[a]=xt(d,i))}let s=r.properties;if(!s)return;if(delete s.$net_fragment,typeof s.$net_query=="string"){let o=xt(`?${s.$net_query}`,i).slice(1);o?s.$net_query=o:delete s.$net_query}}catch{}}var Ce="depsmith_config_fp",At=255,I=class{constructor(e,t={}){this.vitalsReported=!1;this.stopped=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=qe(e),this.logger=new re(this.config.debug),this.clock=t.clock??yt,this.storage=t.storage??this.pickStorage();let i=t.storage?this.storage:at(this.config.storage,this.storage);this.contextProvider=t.contextProvider,this.pageLife=new M({now:()=>this.clock.now(),capture:(a,d,p,c,f)=>this.capture(a,d,p,void 0,void 0,c,f)},this.config);let n=this.config.childSafeMode?new w:this.config.storage==="memory"?this.storage:new j(this.storage,new F(this.config.cookieDomain||void 0));this.identity=new H(n,this.clock),this.session=new Q(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new q(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??it())),this.attribution=new N(n),this.superProperties=new Z(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:""));let s=ue(this.config.apiKey),o={get:a=>i.get(a),set:(a,d)=>{this.storage.get(Ce)===s&&i.set(a,d)},remove:a=>i.remove(a)};this.queue=new X(o,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule});let u=this.detectConfigDrift(s);this.primeDeviceSignals(),this.ready=ut(i,this.storage,this.consent,this.queue,u,this.logger),this.uploader=new te(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??((...a)=>fetch(...a)),clock:this.clock,logger:this.logger,sleep:t.sleep??(a=>new Promise(d=>setTimeout(d,a))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:_t(this.storage,this.clock),canUpload:()=>this.consent.canUpload()}),t.manualLifecycle||(this.lifecycle=De({intervalMs:this.config.batchIntervalMs,guard:a=>this.guard(a),vitals:()=>this.emitWebVitals(),leave:()=>this.leaveOnUnload?.(),restored:a=>this.pageLife.restored(a),resume:()=>this.resumeSession(),flushIfQueued:()=>this.flushIfQueued(),persistNow:()=>this.persistNow(),beacon:()=>{this.consent.canUpload()&&this.uploader.sendBeaconAll()},online:()=>{this.uploader.resetNetworkBreaker(),this.flushIfQueued()}}),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.trackInternal(e,G(t,"track",this.logger))}trackInternal(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}m(e,"track",this.logger)||this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}traits(e,t){return k(G(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,G(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,Ae("$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(()=>{m(e,"setProperty",this.logger)||this.setUserProp(e,t,"$set")})}setUserProp(e,t,i){this.identity.setUserProp(e,t);let n=k({[e]:t},this.logger);this.capture("$identify","identify",void 0,n,Ae(i,n))}setOnceProperty(e,t){this.guard(()=>{if(!m(e,"setOnceProperty",this.logger)){if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.setUserProp(e,t,"$set_once")}})}unsetProperty(e){this.guard(()=>{m(e,"unsetProperty",this.logger)||(this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},Ee({$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=Ee(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.primeDeviceSignals(),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.stopped=!0,this.lifecycle?.stop();for(let e of this.teardownFns.splice(0))e();this.persistNow(),this.queue.close()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}deviceSignals(){return!this.config.childSafeMode&&this.consent.canUpload()}primeDeviceSignals(){this.deviceSignals()&&(this.config.deviceFingerprinting&&Xe(),this.config.geolocation&&tt(()=>this.deviceSignals()))}enqueueEvent(e){Et(e,this.config.scrubUrls),this.queue.enqueue(e),this.lifecycle?.rearm()}flushUploads(){return this.ready.then(()=>this.uploader.flush())}flushIfQueued(){this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}let t=this.deviceSignals();return{fingerprint:this.config.deviceFingerprinting&&t,geolocation:this.config.geolocation&&t,overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:je(`${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,u){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let a=this.touchSession();if(!this.inSample(a.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let d=o??this.clock.now(),p=this.contextOptions();u&&(p.page=u);let c={event_id:y(d),event:e,event_type:t,timestamp:_(d),session_id:a.sessionId,session_started_at:_(a.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...B(p),traits:n}:B(p),platform:"web",sdk_version:O};s&&(c.user_properties=s);let f=k({...this.config.defaultProperties,...this.superProperties.current(),...k(i,this.logger)},this.logger);Object.keys(f).length>0&&(c.properties=f);let g=this.identity.userId;g&&(c.user_id=g);let b=this.identity.groupId;b&&(c.group_id=b),p.fingerprint&&(c.device_id=le()),this.enqueueEvent(c),this.logger.debug(`captured ${e}`,c),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(e){let t=this.storage.get(Ce),i=t!==null&&t!==e;return i&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear(),this.storage.remove($)),this.storage.set(Ce,e),i}pickStorage(){return this.config.storage==="memory"?new w:ot()}enqueueSessionEnd(e){this.enqueueSessionBoundary("end",e.id,e.lastActivityAt,e.startedAt)}enqueueSessionStart(e){this.enqueueSessionBoundary("start",e.id,e.startedAt,e.startedAt)}enqueueSessionBoundary(e,t,i,n){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug(`session_${e} dropped (consent denied)`);return}let s=this.contextOptions(),o={event_id:y(this.clock.now()),event:`$session_${e}`,event_type:`session_${e}`,timestamp:_(i),session_id:t,session_started_at:_(n),anonymous_id:this.identity.anonymousId,context:B(s),platform:"web",sdk_version:O},u=this.identity.userId;u&&(o.user_id=u),s.fingerprint&&(o.device_id=le(),e==="start"&&(o.properties=Qe())),this.enqueueEvent(o)}touchSession(){let e=this.session.touch();return e.startedSession&&this.pageLife.newSession(),e.endedSession&&this.sessionInSample(e.endedSession.id)&&this.enqueueSessionEnd(e.endedSession),e.startedSession&&this.sessionInSample(e.startedSession.id)&&this.enqueueSessionStart(e.startedSession),e}resumeSession(){this.consent.canCapture()&&this.touchSession()}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=gt(),this.teardownFns.push(()=>this.vitals?.stop()));let t=ft(this.config,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),Ue().then(i=>{i&&(this.stopped||(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 l=null,Te=null,en={init(r,e){try{return l&&Te===r.apiKey?l:typeof window>"u"&&r.storage!=="memory"&&!e?.storage?(r.debug&&console.warn("[depsmith-sdk] init skipped: no window"),null):(l?.shutdown(),l=new I(r,e),Te=r.apiKey,l)}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>l?.track(r,e),page:(r,e,t)=>l?.page(r,e,t),screen:(r,e,t)=>l?.screen(r,e,t),identify:(r,e)=>l?.identify(r,e),alias:r=>l?.alias(r),reset:()=>l?.reset(),group:(r,e)=>l?.group(r,e),setGroupTraits:r=>l?.setGroupTraits(r),setProperty:(r,e)=>l?.setProperty(r,e),setOnceProperty:(r,e)=>l?.setOnceProperty(r,e),unsetProperty:r=>l?.unsetProperty(r),setUserProperties:r=>l?.setUserProperties(r),register:r=>l?.register(r),registerOnce:r=>l?.registerOnce(r),unregister:r=>l?.unregister(r),optIn:()=>l?.optIn(),optOut:()=>l?.optOut(),flush:()=>l?.flush()??Promise.resolve(),getAnonymousId:()=>l?.getAnonymousId(),getSessionId:()=>l?.getSessionId(),setSessionId:(r,e)=>l?.setSessionId(r,e),shutdown(){l?.shutdown(),l=null,Te=null}};export{Se as AsyncMirrorAdapter,st as DEPSMITH_SDK_STORAGE_KEYS,en as DepsmithSdk,I as DepsmithSdkClient,C as idleScheduler,Wt as syncScheduler};
1
+ var ne=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=Ne(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=Ne(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}},M=class{constructor(e,t={autocapture:!1}){this.sink=e;this.pages=new ne;this.enteredAt=0;this.left=!1;this.rules=Tt(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(),this.autoViewed=void 0}manual(e,t,i){let n=this.pending;if(n&&this.keyOf(n.location)===this.pageKey())this.discardPending();else{this.flushPending();let s=this.autoViewed;if(this.autoViewed=void 0,s&&s.url===Ie()&&this.sink.now()-s.at<=Ct)return}this.recordExplicit(),this.sink.capture("$page_view","page_view",{...t,...$e({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:P(n),url_base:D(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.autoViewed={url:e.href,at:this.sink.now()},this.sink.capture("$page_view","page_view",{...$e({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||this.left)return;this.left=!0;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.left=!1,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:$t(this.leaving),domain:P(this.leaving),url_base:D(this.leaving)}}pageKey(){let e=globalThis.location;return e&&this.keyOf(e)}keyOf(e){return this.byHref?e.href:e.pathname}record(){let e=Ie();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now(),this.left=!1)}},Ct=2e3;function $e({source:r,name:e,type:t,location:i=globalThis.location,title:n=globalThis.document?.title},s){let o=i&&s?.(i),u=t?.trim()||o?.type;return{$page_name:e?.trim()||o?.name.trim()||n?.trim()||i?.pathname||"Unknown",...u?{$page_type:u}:{},$page_source:r}}function Tt(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"&&Rt(t),i]);return t=>{let i=Me(t.pathname);for(let[n,s]of e)if(n&&n.test(i))return{name:s,type:s}}}function Rt(r){let e=Me(r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\*|\*\*?/g,t=>t==="*"?"[^/]+":t==="**"?".*":"(?:/.*)?");return new RegExp(`^${e}$`)}function Me(r){return r.replace(/(.)\/$/,"$1")}function Ie(){if(!(typeof window>"u"||!window.location))return window.location.href}function Ne(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function $t(r){try{return new URL(r).pathname||void 0}catch{return}}function P(r){try{return new URL(r).host||void 0}catch{return}}function D(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}var It=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],se="depsmith_campaign",oe="depsmith_referrer",U=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(se)??{},this.referrer=this.read(oe)??{}}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 d=new URL(e);i=d.searchParams,n=d.host}catch{return}let s={};for(let[d,p]of It){let c=i.get(d);c&&(s[p]=c)}Object.keys(s).length>0&&(this.campaign=s,this.write(se,s));let o=t?P(t):void 0,u=!!o&&o!==n,a=!1;u&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=u?o:"$direct",u&&(this.referrer.initial_url=t),a=!0),a&&this.write(oe,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(se),this.storage.remove(oe)}catch{}}};function De(r){if(typeof window>"u"||typeof document>"u")return;let e=setInterval(()=>r.flushIfQueued(),r.intervalMs);e.unref?.();let t=!1,i,n=()=>{let a=i;clearTimeout(a),i=void 0,r.guard(()=>r.vitals()),r.guard(()=>r.leave()),!(t&&!a)&&(t=!0,r.beacon(),r.persistNow())},s=()=>{if(document.visibilityState==="hidden"){if(t)return;r.guard(()=>r.vitals()),t=!0,r.persistNow(),i=setTimeout(()=>{i=void 0,r.flushIfQueued()},0)}else clearTimeout(i),t=!1,r.resume()},o=a=>{t=!1,r.restored(a.persisted)},u=()=>r.online();return window.addEventListener("pagehide",n),window.addEventListener("pageshow",o),document.addEventListener("visibilitychange",s),window.addEventListener("online",u),{rearm:()=>{t=!1},stop:()=>{clearInterval(e),window.removeEventListener("pagehide",n),window.removeEventListener("pageshow",o),document.removeEventListener("visibilitychange",s),window.removeEventListener("online",u),clearTimeout(i)}}}function Ue(){return import("./autocapture.js")}var ae=[["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"]],Nt=Object.fromEntries(ae.map(([r])=>[r,!0]));function Le(r){let e={...Nt};if(!r)return e;for(let[t]of ae)r[t]===!1&&(e[t]=!1);return e}function Ve(r,e){let t=r;for(let[i,n,s]of ae){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 Ke={clicks:"interactive",forms:!0,scrolls:!1,pageviews:"path",ignoredSelectors:[],selectorMaxDepth:5,selectorIgnore:[],attributes:[]};function Be(r){if(r===!0)return Ke;if(!r||typeof r!="object")return!1;let e={...Ke};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 qe(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=Be(r.autocapture);return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:x(r.batchSize,20,1,500),batchIntervalMs:x(r.batchIntervalMs,6e4,1e3,2**31-1),maxQueueSize:x(r.maxQueueSize,1e3,1),maxQueueBytes:x(r.maxQueueBytes,512*1024,4096),sessionTimeoutMs:x(r.sessionTimeoutMs,18e5,6e4),sampleRate:ze(r.sampleRate,1,0,1),sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:x(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,scrubUrls:r.scrubUrls??!1,trackingOptions:Le(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage",pageNames:r.pageNames}}function ze(r,e,t,i=1/0){return Math.min(Math.max(Number.isFinite(r)?r:e,t),i)}function x(r,e,t,i){return Math.floor(ze(r,e,t,i))}function ue(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 Fe(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e}function Mt(r){return Fe(r).toString(36)}function je(r){return Fe(r)/4294967296}function de(r){return ue(r)+Mt(r)}var pe={},Ye=!1;function We(){if(!Ye){Ye=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{pe=e}).catch(()=>{})}catch{}}}function ce(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=Vt(e,t);i&&(r.browser=i);let n=Bt(e);if(n){let u=Ut(n.name,pe.platformVersion);r.os=u?{...n,version:u}:n}let s=qt(e,t);s&&(r.deviceType=s);let o=Dt(e,n);return o&&(r.device=o),r}function Dt(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=pe.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 Ut(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 Xe(t)}}var Lt=[{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 Vt(r,e){for(let i of Lt){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 Kt=[{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 Bt(r){for(let e of Kt){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Xe((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Xe(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function qt(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 L=null,V=null;function He(){return V!==null||(V=zt()),V}function le(){return L!==null||(L=de(He().map(r=>r.value).join("|"))),L}function Qe(){let r={};for(let e of He())r[`$fp_${e.name}`]=e.value;return r}function zt(){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:${Ft()}`})}catch{}return r}function Ft(){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(),de(r.toDataURL())):""}catch{return""}}function Ge(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};let e=r.type;if(e==="wifi"||e==="ethernet"||e==="none")return{type:e};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 O=null,Ze=0,Je=!1,A=!1,et=null,K=()=>!0;function tt(r=K){if(K=r,!Je){Je=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let e=navigator.permissions;if(typeof e?.query!="function")return;e.query({name:"geolocation"}).then(t=>{et=t,t.state==="granted"&&fe(),t.onchange=()=>{t.state==="granted"?fe():O=null}}).catch(()=>{})}catch{}}}function fe(){if(!(A||!K())){A=!0;try{navigator.geolocation.getCurrentPosition(r=>{A=!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),O=n,Ze=Date.now()},()=>{A=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{A=!1}}}function rt(){if(K()||(O=null),!!O)return Date.now()-Ze>3e5&&et?.state==="granted"&&fe(),{...O}}var he="@depsmith/depsmith-sdk",C="0.9.1",ge=null;function jt(){if(ge)return ge;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ge=r,r}function B(r={}){let e={library:{name:he,version:C}};S(()=>{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:P(t),url_base:D(t),...r.page??{}}}}),S(()=>{typeof window<"u"&&window.screen&&(e.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),S(()=>{let t=jt();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(()=>{let{deviceType:t}=ce();t&&(e.device={...e.device,type:t})}),S(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),S(()=>{r.fingerprint&&Yt(e)}),S(()=>{if(r.geolocation){let t=rt();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:he,version:C}}}catch{}return r.tracking&&Ve(e,r.tracking),e}function Yt(r){let{browser:e,os:t,deviceType:i,device:n}=ce();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=Ge();o.type&&(r.network={...r.network,type:o.type})}function S(r){try{r()}catch{}}function it(){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 me="depsmith_consent",q=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(me);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(me,"granted")}optOut(){this.state="denied",this.storage.set(me,"denied")}};var T=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},Wt=r=>r();var v="depsmith_queue",Xt=512*1024,ve=2,Ht=new Set(["identify","alias","group"]);function Qt(r){return Ht.has(r?.event_type)}var z=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??Xt,this.schedule=n.schedule??T,this.restore()}restore(){try{let e=this.storage.get(v);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(v)}}reset(e){this.events=e,this.sizes=e.map(t=>nt(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?ve:this.sizeSum+(this.events.length-1)+ve}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(v,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=nt(e);if(t+ve>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(!Qt(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,t=1/0,i=0){let n=i;for(let s=0;n<this.events.length&&n-i<e&&(s+=this.sizes[n]+1,!(n>i&&s>t));n++);return this.events.slice(i,n)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let u=this.events[o];if(t.has(u.event_id))continue;let a=this.sizes[o];i.push(u),n.push(a),s+=a}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}close(){}clear(){this.reset([]),this.dirty=!1,this.storage.remove(v)}};function nt(r){return JSON.stringify(r).length}var ye=-1,be=0,Gt=67108863;function y(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let n=0;n<16;n++)e[n]=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;let t=(e[6]&7)<<22|e[7]<<14|(e[8]&63)<<8|e[9];r===ye?t=be=be+1&Gt:r>ye&&(ye=r,be=t),e[6]=112|t>>>22,e[7]=t>>>14&255,e[8]=128|t>>>8&63,e[9]=t&255;let i="";for(let n=0;n<16;n++)i+=(e[n]+256).toString(16).slice(1);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function E(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 st=["depsmith_anonymous_id","depsmith_anon_reset_at","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","depsmith_super_props"],w=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)}},F=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{}}},R="depsmith_anon_reset_at",Jt=new Set(["depsmith_anonymous_id",R]),j=class{constructor(e,t,i=Jt){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=this.pick(t,i);return this.primary.set(e,n),this.secondary.set(e,n),n}pick(e,t){let i=E(e),n=E(t);if(i===null||n===null)return e;let s=[this.primary,this.secondary],o=Math.max(...s.map(a=>Number(a.get(R))||0));o&&s.forEach(a=>a.set(R,`${o}`));let u=i>=o;return u!==n>=o?u?e:t:i<=n?e:t}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)}},Se=class{constructor(e,t=st){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 $=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{}}},Y=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 u=s.result;o.result.forEach((a,d)=>{let p=u[d];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 ot(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new $(window.localStorage)}}catch{}return new w}function at(r,e){return r==="indexeddb"&&typeof indexedDB<"u"?new Y:e}function ut(r,e,t,i,n,s){return r instanceof Y?r.hydrate().then(o=>{try{let u="depsmith_consent";if(o.get(u)==="denied"&&!e.get(u)&&t.optOut(),n||!t.canCapture()){i.clear();return}let a=o.get("depsmith_queue");a&&i.prepend(JSON.parse(a))}catch{s.warn("persisted queue corrupt; discarded")}}):Promise.resolve()}function dt(r){try{let e=JSON.parse(r||"[]");return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.event_id=="string"):null}catch{return null}}var W=class extends z{constructor(...t){super(...t);this.known=new Set(this.ids());this.removed=new Set;this.area=null;this.onStorage=t=>{if(t.key!==v||t.storageArea!==this.area)return;let i=dt(t.newValue);if(!i)return;let n=new Set;for(let o of i)n.add(o.event_id);let s=[];if(this.known.forEach(o=>{n.has(o)||s.push(o)}),s.length!==0){for(let o of s)this.known.delete(o),this.removed.add(o);this.remove(s)}};if(this.storage instanceof $){this.area=this.storage.ls;try{typeof window<"u"&&window.addEventListener("storage",this.onStorage)}catch{}}}ids(){return this.events.map(t=>t.event_id)}persistNow(){if(!this.dirty)return;this.dirty=!1;let t=new Set(this.ids());this.known.forEach(s=>{t.has(s)||this.removed.add(s)});let i=[],n=new Set;for(let s of dt(this.storage.get(v))??[])n.add(s.event_id),!t.has(s.event_id)&&!this.removed.has(s.event_id)&&i.push(s);this.storage.set(v,JSON.stringify(this.bounded(i).concat(this.events))),this.known=t,this.removed.forEach(s=>{n.has(s)||this.removed.delete(s)})}bounded(t){if(t.length===0)return t;let i=this.maxSize-this.events.length,n=this.maxChars-this.serializedLength(),s=[];for(let o=t.length-1;o>=0&&i>0;o--){let u=JSON.stringify(t[o]).length+1;if(u>n)break;n-=u,i--,s.push(t[o])}return s.reverse()}clear(){super.clear(),this.known.clear(),this.removed.clear()}close(){try{typeof window<"u"&&window.removeEventListener("storage",this.onStorage)}catch{}}};var we="depsmith_anonymous_id",ke="depsmith_user_id",_e="depsmith_group_id",X="depsmith_user_props",H=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(we);return e||(e=y(this.clock.now()),this.storage.set(we,e)),e}get userId(){return this.storage.get(ke)}get groupId(){return this.storage.get(_e)}identify(e){this.storage.set(ke,e)}setGroup(e){this.storage.set(_e,e)}getUserProps(){try{return JSON.parse(this.storage.get(X)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(X,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(X,JSON.stringify(t))}reset(){this.storage.remove(ke),this.storage.remove(_e),this.storage.remove(X);let e=this.clock.now();this.storage.set(R,`${e}`);let t=y(e);return this.storage.set(we,t),t}};var pt="depsmith_session",Q=class{constructor(e,t,i,n=T){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(pt);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=E(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(pt,JSON.stringify(e)))}mint(e){let t={id:y(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=E(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 k(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=Zt(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function Pe(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 Zt(r,e){let t=Pe(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=Pe(n);i.push(s!==void 0?s:ct(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 u=Pe(o);i[String(s)]=u!==void 0?u:ct(o),n++}return i}}}function ct(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function G(r,e,t){let i={...r},n;for(let s in i)m(s,e,t)&&(n=delete i[s]);return n?i:r}function m(r,e,t){return r?.[0]!=="$"?!1:(t.warn(`${e}: "$"-prefixed keys are reserved; ignored "${r}"`),!0)}function er(r,e){let t=r?.name;return t==="AbortError"||t!=="TimeoutError"&&!!e?.aborted}function tr(r){let e=r?.message;return typeof e=="string"&&e?e.slice(0,255):"network error"}function rr(r){return r>=500}function lt(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 ir(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 nr(r,e){let t=Object.prototype.toString.call(r)==="[object Request]"?r:void 0;return{raw:String(t?t.url:r),method:String(e?.method??t?.method??"GET").toUpperCase(),signal:e?.signal??t?.signal}}function ft(r,e){if(r.autocapture&&r.autocapture.networkErrors===!1||typeof fetch!="function")return{stop:()=>{}};let i=fetch,n=r.endpoint.replace(/\/+$/,""),s=!1,o=0,u=new Set,a=c=>{let f=Date.now();return f-o>=6e4&&(o=f,u=new Set),u.size>=10||u.has(c)?!1:(u.add(c),!0)},d=(c,f)=>{try{let g=f();a(`${String(g.$net_method)} ${String(g.$net_url)} ${c}`)&&e(g)}catch{}},p=function(...c){let f=Date.now(),g=i.apply(this,c);if(s||typeof g?.then!="function")return g;let b,ie,Re;try{if({raw:b,method:ie,signal:Re}=nr(c[0],c[1]),b.startsWith(n))return g}catch{return g}let Ot=c[1];return g.then(h=>(rr(h.status)&&d(h.status,()=>({...lt(b),$net_method:ie,$net_status:h.status,$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f,...sr(Ot,h)})),h),h=>{throw typeof navigator<"u"&&navigator.onLine===!1||er(h,Re)||d("error",()=>({...lt(b),$net_method:ie,$net_error_message:tr(h),$net_start:f,$net_end:Date.now(),$net_duration_ms:Date.now()-f})),h})};return globalThis.fetch=p,{stop:()=>{s=!0,globalThis.fetch===p&&(globalThis.fetch=i)}}}function sr(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=ir(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function J(r){return Math.round(r)}function gt(){let r,e,t,i=0,n=!1,s,o=[],u=(a,d)=>{try{let p=new PerformanceObserver(c=>d(c.getEntries()));p.observe({type:a,buffered:!0}),o.push(p)}catch{}};u("largest-contentful-paint",a=>{let d=a[a.length-1];d&&(r=J(d.startTime))}),u("paint",a=>{for(let d of a)d.name==="first-contentful-paint"&&(e=J(d.startTime))}),u("layout-shift",a=>{for(let d of a)d.hadRecentInput||(i+=d.value??0,n=!0)}),u("event",a=>{for(let d of a){let p=J(d.duration);(t===void 0||p>t)&&(t=p)}});try{let[a]=performance.getEntriesByType("navigation"),d=a;d?.responseStart!==void 0&&d.responseStart>0&&(s=J(d.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 xe="depsmith_super_props";function ht(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):!m(r,"register",e)}var Z=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(xe);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))ht(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))ht(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(xe)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(xe,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var or=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],mt=50,vt=200;function Ee(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)=>m(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 or){let o=r[s];if(!o||typeof o!="object")continue;let u=k(o,e),a={};for(let[d,p]of Object.entries(u))n(d,s)&&(a[d]=p);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[u,a]of Object.entries(r.$add)){if(o>=mt){e.debug(`$add over ${mt} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${u}" is not finite; dropped`);continue}n(u,"$add")&&(s[u]=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>=vt){e.debug(`$unset over ${vt} 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 Ae(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var yt={now:()=>Date.now()};function _(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function ee(r){return r===0||r===408||r===429||r>=500}var ar=1e3,ur=32e3;function bt(r,e=Math.random){let t=Math.min(ar*2**r,ur);return Math.round(e()*t)}function St(r,e){if(!r)return 0;let t=Number(r),i=t===t?t*1e3:Date.parse(r)-e;return i>0?i:0}async function dr(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:d}=await i.read();if(a)break;n.push(d)}let s=n.reduce((a,d)=>a+d.length,0),o=new Uint8Array(new ArrayBuffer(s)),u=0;for(let a of n)o.set(a,u),u+=a.length;return o}async function wt(r,e){if(e==="none"||typeof CompressionStream>"u")return null;try{return await dr(r)}catch{return null}}function kt(r,e,t,i,n){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let s=t.breaker;if(!t.isOnline()||s?.open()||s?.suspect())return;let o=i;for(let u=0;u<10;u++){let a=r.peek(e.batchSize,48e3,o);if(!a.length)return;let d=n(a);if(navigator.sendBeacon(`${e.endpoint}/e/`,new Blob([JSON.stringify(d)],{type:"text/plain"})))r.remove(a.map(c=>c.event_id));else{if(a.length>1)return;o++}}}catch{}}function pr(r){return r.map(e=>e.event_id)}var cr=3e4,lr=6e4,fr=256e3;function gr(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var hr=399;function Oe(r){return r>299&&r<400||r===401||r===403}var mr=3e4,vr=60*6e4,te=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null;this.uploading=0;this.limit=0;this.strikes=0;this.wait=0}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.limit=0;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("uploads paused");return}let e=this.config.batchSize,t=this.queue.peek(this.limit||e,fr);this.queue.persistNow(),this.uploading=t.length;let i=await this.uploadWithRetry(t);if(this.uploading=0,Oe(i)||ee(i))return;if(i===400||i===413){if(t.length>1){this.limit=t.length>>1;continue}this.limit=0}if(i>299&&this.deps.logger.notice(`collector answered ${i}; dropped ${t.length} event(s)`),this.queue.remove(pr(t)),i===400)return}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1,n=0;for(let s=0;s<=this.config.maxRetries&&!(s&&(this.deps.canUpload?.()===!1||this.queue.peek(1)[0]?.event_id!==e[0].event_id)||(n=await this.post(e),n&&(i=!0),!ee(n)||this.wait)||(this.deps.logger.debug(`upload attempt ${s+1} failed (${n})`),!i&&t?.suspect()));s++)s<this.config.maxRetries&&await this.deps.sleep(bt(s));return i?(t?.ok(),n>199&&n<300?this.strikes=0:(Oe(n)||ee(n))&&(Oe(n)&&this.deps.logger.notice(`collector refused uploads (${n}); paused`),t?.hold(this.wait||Math.min(mr*2**this.strikes++,vr)))):t?.fail(),n}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:_(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){this.wait=0;let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s={"Content-Type":"application/json"},o=await wt(t,this.config.compression);o&&(s["Content-Encoding"]="gzip");let u=o??t,a=gr(u)<=lr;a||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let d={method:"POST",headers:s,body:u,keepalive:a};i&&(d.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs()));let p=await this.deps.fetchFn(`${this.config.endpoint}/e/`,d);return p.redirected?hr:(this.wait=St(p.headers?.get("Retry-After"),this.deps.clock.now()),p.status)}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:cr}sendBeaconAll(){kt(this.queue,this.config,this.deps,this.uploading,e=>this.buildPayload(e))}};var I="depsmith_net_breaker";function _t(r,e){let t=!1,i=0,n=0,s=3e5,o=(d,p,c)=>typeof d=="number"&&d===d?Math.min(Math.max(d,p),c):p,u=()=>{if(!t){t=!0;try{let d=JSON.parse(r.get(I)??"0");if(!Array.isArray(d))return;i=o(d[0],0,3),n=o(d[1],0,e.now()+36e5),s=o(d[2],3e5,36e5)}catch{}}},a=()=>{try{i||n>e.now()?r.set(I,JSON.stringify([i,n,s])):r.remove(I)}catch{}};return{open:()=>(u(),e.now()<(n=Math.min(n,e.now()+36e5))),suspect:()=>(u(),i>0),fail:()=>{u(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),a()},ok:()=>{u(),i&&(i=n=0,s=3e5,a())},hold:d=>{u(),n=Math.max(n,e.now()+Math.min(d,36e5)),a()}}}var re=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)}notice(...e){console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var Pt=["url","referrer","previous_url","initial_url"],yr=["$ac_href","$ac_form_action","$net_url","$fr_error_file"];function xt(r,e){let t=r.split("#")[0],i=t.indexOf("?");if(i<0)return t;let n=t.slice(i+1).split("&").filter(s=>e.has(br(s)));return t.slice(0,i)+(n.length?`?${n.join("&")}`:"")}function br(r){let e=r.split("=")[0].replace(/\+/g," ");try{return decodeURIComponent(e)}catch{return e}}function Et(r,e){if(e)try{let t=e.keepParams,i=new Set(Array.isArray(t)?t:[]),n=[[r.context.page,Pt],[r.context.referrer,Pt],[r.properties,yr]];for(let[o,u]of n)for(let a of u){let d=o?.[a];typeof d=="string"&&(o[a]=xt(d,i))}let s=r.properties;if(!s)return;if(delete s.$net_fragment,typeof s.$net_query=="string"){let o=xt(`?${s.$net_query}`,i).slice(1);o?s.$net_query=o:delete s.$net_query}}catch{}}var Ce="depsmith_config_fp",At=255,N=class{constructor(e,t={}){this.vitalsReported=!1;this.stopped=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=qe(e),this.logger=new re(this.config.debug),this.clock=t.clock??yt,this.storage=t.storage??this.pickStorage();let i=t.storage?this.storage:at(this.config.storage,this.storage);this.contextProvider=t.contextProvider,this.pageLife=new M({now:()=>this.clock.now(),capture:(a,d,p,c,f)=>this.capture(a,d,p,void 0,void 0,c,f)},this.config);let n=this.config.childSafeMode?new w:this.config.storage==="memory"?this.storage:new j(this.storage,new F(this.config.cookieDomain||void 0));this.identity=new H(n,this.clock),this.session=new Q(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new q(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??it())),this.attribution=new U(n),this.superProperties=new Z(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:""));let s=ue(this.config.apiKey),o={get:a=>i.get(a),set:(a,d)=>{this.storage.get(Ce)===s&&i.set(a,d)},remove:a=>i.remove(a)};this.queue=new W(o,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule});let u=this.detectConfigDrift(s);this.primeDeviceSignals(),this.ready=ut(i,this.storage,this.consent,this.queue,u,this.logger),this.uploader=new te(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??((...a)=>fetch(...a)),clock:this.clock,logger:this.logger,sleep:t.sleep??(a=>new Promise(d=>setTimeout(d,a))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:_t(this.storage,this.clock),canUpload:()=>this.consent.canUpload()}),t.manualLifecycle||(this.lifecycle=De({intervalMs:this.config.batchIntervalMs,guard:a=>this.guard(a),vitals:()=>this.emitWebVitals(),leave:()=>this.leaveOnUnload?.(),restored:a=>this.pageLife.restored(a),resume:()=>this.resumeSession(),flushIfQueued:()=>this.flushIfQueued(),persistNow:()=>this.persistNow(),beacon:()=>{this.consent.canUpload()&&this.uploader.sendBeaconAll()},online:()=>{this.uploader.resetNetworkBreaker(),this.flushIfQueued()}}),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.trackInternal(e,G(t,"track",this.logger))}trackInternal(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}m(e,"track",this.logger)||this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}traits(e,t){return k(G(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,G(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,Ae("$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(()=>{m(e,"setProperty",this.logger)||this.setUserProp(e,t,"$set")})}setUserProp(e,t,i){this.identity.setUserProp(e,t);let n=k({[e]:t},this.logger);this.capture("$identify","identify",void 0,n,Ae(i,n))}setOnceProperty(e,t){this.guard(()=>{if(!m(e,"setOnceProperty",this.logger)){if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.setUserProp(e,t,"$set_once")}})}unsetProperty(e){this.guard(()=>{m(e,"unsetProperty",this.logger)||(this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},Ee({$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=Ee(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.primeDeviceSignals(),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.stopped=!0,this.lifecycle?.stop();for(let e of this.teardownFns.splice(0))e();this.persistNow(),this.queue.close()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}deviceSignals(){return!this.config.childSafeMode&&this.consent.canUpload()}primeDeviceSignals(){this.deviceSignals()&&(this.config.deviceFingerprinting&&We(),this.config.geolocation&&tt(()=>this.deviceSignals()))}enqueueEvent(e){Et(e,this.config.scrubUrls),this.queue.enqueue(e),this.lifecycle?.rearm()}flushUploads(){return this.ready.then(()=>this.uploader.flush())}flushIfQueued(){this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}let t=this.deviceSignals();return{fingerprint:this.config.deviceFingerprinting&&t,geolocation:this.config.geolocation&&t,overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:je(`${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,u){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let a=this.touchSession();if(!this.inSample(a.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let d=o??this.clock.now(),p=this.contextOptions();u&&(p.page=u);let c={event_id:y(d),event:e,event_type:t,timestamp:_(d),session_id:a.sessionId,session_started_at:_(a.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...B(p),traits:n}:B(p),platform:"Web",sdk_version:C};s&&(c.user_properties=s);let f=k({...this.config.defaultProperties,...this.superProperties.current(),...k(i,this.logger)},this.logger);Object.keys(f).length>0&&(c.properties=f);let g=this.identity.userId;g&&(c.user_id=g);let b=this.identity.groupId;b&&(c.group_id=b),p.fingerprint&&(c.device_id=le()),this.enqueueEvent(c),this.logger.debug(`captured ${e}`,c),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(e){let t=this.storage.get(Ce),i=t!==null&&t!==e;return i&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear(),this.storage.remove(I)),this.storage.set(Ce,e),i}pickStorage(){return this.config.storage==="memory"?new w:ot()}enqueueSessionBoundary(e,t,i,n){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug(`session_${e} dropped (consent denied)`);return}let s=this.contextOptions(),o={event_id:y(this.clock.now()),event:`$session_${e}`,event_type:`session_${e}`,timestamp:_(i),session_id:t,session_started_at:_(n),anonymous_id:this.identity.anonymousId,context:B(s),platform:"Web",sdk_version:C},u=this.identity.userId;u&&(o.user_id=u),s.fingerprint&&(o.device_id=le(),e==="start"&&(o.properties=Qe())),this.enqueueEvent(o)}touchSession(){let e=this.session.touch();if(e.startedSession&&this.pageLife.newSession(),e.endedSession&&this.sessionInSample(e.endedSession.id)){let t=e.endedSession;this.enqueueSessionBoundary("end",t.id,t.lastActivityAt,t.startedAt)}if(e.startedSession&&this.sessionInSample(e.startedSession.id)){let t=e.startedSession;this.enqueueSessionBoundary("start",t.id,t.startedAt,t.startedAt)}return e}resumeSession(){this.consent.canCapture()&&this.touchSession()}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=gt(),this.teardownFns.push(()=>this.vitals?.stop()));let t=ft(this.config,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),Ue().then(i=>{i&&(this.stopped||(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 l=null,Te=null,en={init(r,e){try{return l&&Te===r.apiKey?l:typeof window>"u"&&r.storage!=="memory"&&!e?.storage?(r.debug&&console.warn("[depsmith-sdk] init skipped: no window"),null):(l?.shutdown(),l=new N(r,e),Te=r.apiKey,l)}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>l?.track(r,e),page:(r,e,t)=>l?.page(r,e,t),screen:(r,e,t)=>l?.screen(r,e,t),identify:(r,e)=>l?.identify(r,e),alias:r=>l?.alias(r),reset:()=>l?.reset(),group:(r,e)=>l?.group(r,e),setGroupTraits:r=>l?.setGroupTraits(r),setProperty:(r,e)=>l?.setProperty(r,e),setOnceProperty:(r,e)=>l?.setOnceProperty(r,e),unsetProperty:r=>l?.unsetProperty(r),setUserProperties:r=>l?.setUserProperties(r),register:r=>l?.register(r),registerOnce:r=>l?.registerOnce(r),unregister:r=>l?.unregister(r),optIn:()=>l?.optIn(),optOut:()=>l?.optOut(),flush:()=>l?.flush()??Promise.resolve(),getAnonymousId:()=>l?.getAnonymousId(),getSessionId:()=>l?.getSessionId(),setSessionId:(r,e)=>l?.setSessionId(r,e),shutdown(){l?.shutdown(),l=null,Te=null}};export{Se as AsyncMirrorAdapter,st as DEPSMITH_SDK_STORAGE_KEYS,en as DepsmithSdk,N as DepsmithSdkClient,T as idleScheduler,Wt as syncScheduler};
2
2
  //# sourceMappingURL=index.js.map