@depsmith/depsmith-sdk 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -44,6 +44,11 @@ interface UserPropertyOps {
44
44
  type Scalar = string | number | boolean | null;
45
45
  type PropertyValue = Scalar | Scalar[] | Record<string, Scalar>;
46
46
  type Properties = Record<string, PropertyValue>;
47
+ /** The third argument of `page()` / `screen()`. */
48
+ interface PageOptions {
49
+ /** The kind of page (`product`, `collection`, `cart`, …), sent as `$page_type`. */
50
+ type?: string;
51
+ }
47
52
  type EventType = 'track' | 'page_view' | 'page_leave' | 'screen' | 'identify' | 'alias' | 'group' | 'autocapture' | 'session_start' | 'session_end';
48
53
  type NetworkType = '2g' | '3g' | '4g' | '5g' | 'wifi' | 'ethernet' | 'none' | 'unknown';
49
54
  interface EventContext {
@@ -93,7 +98,7 @@ interface EventContext {
93
98
  initial_url?: string;
94
99
  initial_domain?: string;
95
100
  };
96
- screen?: {
101
+ screen_size?: {
97
102
  width?: number;
98
103
  height?: number;
99
104
  density?: number;
@@ -204,9 +209,10 @@ interface TrackingOptions {
204
209
  network?: boolean;
205
210
  osName?: boolean;
206
211
  osVersion?: boolean;
207
- /** context.page. Not the `name` property on $page_view — that is a property, not context. */
212
+ /** context.page. Not `$page_name` on $page_view — that is a property, not context. */
208
213
  page?: boolean;
209
- screen?: boolean;
214
+ /** context.screen_size: display width, height and density. */
215
+ screenSize?: boolean;
210
216
  timezone?: boolean;
211
217
  /** context.user_agent. */
212
218
  userAgent?: boolean;
@@ -257,7 +263,22 @@ interface DepsmithSdkConfig {
257
263
  cookieDomain?: string;
258
264
  /** Queue persistence backend. */
259
265
  storage?: 'localstorage' | 'indexeddb' | 'memory';
266
+ /**
267
+ * Readable `$page_name`s for automatic page views, and for `page()` calls made without a name.
268
+ * A name passed to `page()` always wins; with no match the name falls back to the title.
269
+ *
270
+ * - **Patterns:** `{ '/products/*': 'Product', '/': 'Home' }`. `*` is one path segment, `**` the
271
+ * rest of the path. The first match wins, in insertion order, so put specific patterns
272
+ * before broad ones (or use the `[pattern, name]` array form). A pattern match also sets
273
+ * `$page_type` to its name.
274
+ * - **Function:** `(location) => string | undefined`, called per view. Sets the name only.
275
+ * Web-only; config.schema.json can describe the object form alone.
276
+ */
277
+ pageNames?: PageNames;
260
278
  }
279
+ /** What a `pageNames` function is handed: `window.location`, or a URL with the same fields. */
280
+ type PageLocation = Pick<Location, 'href' | 'pathname' | 'search' | 'hash' | 'host'>;
281
+ type PageNames = Record<string, string> | ReadonlyArray<readonly [pattern: string, name: string]> | ((location: PageLocation) => string | undefined);
261
282
  /**
262
283
  * Which clicks produce a `$autocapture` event.
263
284
  * 'interactive' — only clicks resolving to a link/button/[role=button]/submit control
@@ -266,13 +287,28 @@ interface DepsmithSdkConfig {
266
287
  * true — alias of 'interactive'; false disables click capture.
267
288
  */
268
289
  type ClickCapture = boolean | 'interactive' | 'all';
290
+ /**
291
+ * When an automatic `$page_view` (and its `$page_leave`) is sent.
292
+ * 'path' — when `location.pathname` changes. The default: a query-string or `#` change is
293
+ * filters, sort order, pagination or an in-page anchor, not a new page.
294
+ * 'all' — when anything in the URL changes, query and `#` included (the pre-0.8 behaviour).
295
+ * true — alias of 'path'; false sends none automatically.
296
+ */
297
+ type PageViewCapture = boolean | 'path' | 'all';
269
298
  interface AutocaptureConfig {
270
299
  clicks?: ClickCapture;
271
300
  forms?: boolean;
272
301
  scrolls?: boolean;
273
- pageviews?: boolean;
302
+ pageviews?: PageViewCapture;
274
303
  ignoredSelectors?: string[];
275
304
  selectorMaxDepth?: number;
305
+ /**
306
+ * Extra patterns for ids, classes and test-attribute values that `$ac_selector` should skip as
307
+ * generated, on top of the built-in rules (CSS-in-JS and CSS-module hashes, utility classes,
308
+ * long digit runs). Regex sources, e.g. `['^theme-', '^js-']`; an invalid one is skipped with
309
+ * a debug warning.
310
+ */
311
+ selectorIgnore?: string[];
276
312
  /**
277
313
  * `data-*` attribute names to attach to click and change events as `$ac_attr_<name>`.
278
314
  *
@@ -427,6 +463,13 @@ declare class DepsmithSdkClient {
427
463
  private ready;
428
464
  constructor(config: DepsmithSdkConfig, overrides?: InternalOverrides);
429
465
  track(name: string, properties?: Properties): void;
466
+ /**
467
+ * `track()` without the `$`-key check on properties, for the SDK's own integrations. Not part
468
+ * of the public API: the Shopify pixel needs it because it stamps `$shopify_client_id` on every
469
+ * event it maps, which a public `track()` would now drop as reserved. Event names are checked
470
+ * exactly as in `track()`.
471
+ */
472
+ trackInternal(name: string, properties?: Properties): void;
430
473
  /**
431
474
  * Rejects an envelope id the collector's schema would refuse, at the point it enters the SDK.
432
475
  *
@@ -441,8 +484,22 @@ declare class DepsmithSdkClient {
441
484
  * prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is
442
485
  * the rule throughout: such an event would 400 and take the whole batch with it.
443
486
  */
487
+ /** Client traits as sent: `$` keys dropped, then sanitised like event properties. */
488
+ private traits;
444
489
  private tooLong;
445
- page(name?: string, properties?: Properties): void;
490
+ /** `options.type` is sent as `$page_type` (API_SPEC §2). */
491
+ page(name?: string, properties?: Properties, options?: PageOptions): void;
492
+ /**
493
+ * `page()` without the `$`-key check, for the SDK's own integrations. Not part of the public
494
+ * API: the Shopify pixel sends checkout page views with `$checkout_step` and
495
+ * `$shopify_client_id`, which a public `page()` would now drop as reserved. Still a manual
496
+ * view — it is a call, not autocapture.
497
+ *
498
+ * Advances navigation state even for an explicit call, so an app that drives pageviews by hand
499
+ * (no autocapture) still gets previous_url and counter — and claims the URL so autocapture
500
+ * cannot emit a second view for the same page.
501
+ */
502
+ pageInternal(name?: string, properties?: Properties, options?: PageOptions): void;
446
503
  /**
447
504
  * `$web_vitals`, once per page, on the first time the tab is hidden.
448
505
  *
@@ -456,7 +513,7 @@ declare class DepsmithSdkClient {
456
513
  */
457
514
  private emitWebVitals;
458
515
  /** Alias of page() — unified mobile naming. */
459
- screen(name?: string, properties?: Properties): void;
516
+ screen(name?: string, properties?: Properties, options?: PageOptions): void;
460
517
  identify(userId: string, traits?: Properties): void;
461
518
  alias(aliasId: string): void;
462
519
  reset(): void;
@@ -625,8 +682,8 @@ declare class DepsmithSdkClient {
625
682
  declare const DepsmithSdk: {
626
683
  init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null;
627
684
  track: (name: string, properties?: Properties) => void;
628
- page: (name?: string, properties?: Properties) => void;
629
- screen: (name?: string, properties?: Properties) => void;
685
+ page: (name?: string, properties?: Properties, options?: PageOptions) => void;
686
+ screen: (name?: string, properties?: Properties, options?: PageOptions) => void;
630
687
  identify: (userId: string, traits?: Properties) => void;
631
688
  alias: (aliasId: string) => void;
632
689
  reset: () => void;
@@ -652,4 +709,4 @@ declare const DepsmithSdk: {
652
709
  shutdown(): void;
653
710
  };
654
711
 
655
- export { type AsyncKV, AsyncMirrorAdapter, type AutocaptureConfig, type BatchPayload, type ConsentState, DEPSMITH_SDK_STORAGE_KEYS, DepsmithSdk, DepsmithSdkClient, type DepsmithSdkConfig, type DepsmithSdkEvent, type EventContext, type EventType, type InternalOverrides, type KVStorage, type Properties, type PropertyValue, type Scheduler, type TrackingOptions, type UserPropertyOps, idleScheduler, syncScheduler };
712
+ export { type AsyncKV, AsyncMirrorAdapter, type AutocaptureConfig, type BatchPayload, type ConsentState, DEPSMITH_SDK_STORAGE_KEYS, DepsmithSdk, DepsmithSdkClient, type DepsmithSdkConfig, type DepsmithSdkEvent, type EventContext, type EventType, type InternalOverrides, type KVStorage, type PageLocation, type PageNames, type PageOptions, type Properties, type PropertyValue, type Scheduler, type TrackingOptions, type UserPropertyOps, idleScheduler, syncScheduler };
package/dist/index.d.ts CHANGED
@@ -44,6 +44,11 @@ interface UserPropertyOps {
44
44
  type Scalar = string | number | boolean | null;
45
45
  type PropertyValue = Scalar | Scalar[] | Record<string, Scalar>;
46
46
  type Properties = Record<string, PropertyValue>;
47
+ /** The third argument of `page()` / `screen()`. */
48
+ interface PageOptions {
49
+ /** The kind of page (`product`, `collection`, `cart`, …), sent as `$page_type`. */
50
+ type?: string;
51
+ }
47
52
  type EventType = 'track' | 'page_view' | 'page_leave' | 'screen' | 'identify' | 'alias' | 'group' | 'autocapture' | 'session_start' | 'session_end';
48
53
  type NetworkType = '2g' | '3g' | '4g' | '5g' | 'wifi' | 'ethernet' | 'none' | 'unknown';
49
54
  interface EventContext {
@@ -93,7 +98,7 @@ interface EventContext {
93
98
  initial_url?: string;
94
99
  initial_domain?: string;
95
100
  };
96
- screen?: {
101
+ screen_size?: {
97
102
  width?: number;
98
103
  height?: number;
99
104
  density?: number;
@@ -204,9 +209,10 @@ interface TrackingOptions {
204
209
  network?: boolean;
205
210
  osName?: boolean;
206
211
  osVersion?: boolean;
207
- /** context.page. Not the `name` property on $page_view — that is a property, not context. */
212
+ /** context.page. Not `$page_name` on $page_view — that is a property, not context. */
208
213
  page?: boolean;
209
- screen?: boolean;
214
+ /** context.screen_size: display width, height and density. */
215
+ screenSize?: boolean;
210
216
  timezone?: boolean;
211
217
  /** context.user_agent. */
212
218
  userAgent?: boolean;
@@ -257,7 +263,22 @@ interface DepsmithSdkConfig {
257
263
  cookieDomain?: string;
258
264
  /** Queue persistence backend. */
259
265
  storage?: 'localstorage' | 'indexeddb' | 'memory';
266
+ /**
267
+ * Readable `$page_name`s for automatic page views, and for `page()` calls made without a name.
268
+ * A name passed to `page()` always wins; with no match the name falls back to the title.
269
+ *
270
+ * - **Patterns:** `{ '/products/*': 'Product', '/': 'Home' }`. `*` is one path segment, `**` the
271
+ * rest of the path. The first match wins, in insertion order, so put specific patterns
272
+ * before broad ones (or use the `[pattern, name]` array form). A pattern match also sets
273
+ * `$page_type` to its name.
274
+ * - **Function:** `(location) => string | undefined`, called per view. Sets the name only.
275
+ * Web-only; config.schema.json can describe the object form alone.
276
+ */
277
+ pageNames?: PageNames;
260
278
  }
279
+ /** What a `pageNames` function is handed: `window.location`, or a URL with the same fields. */
280
+ type PageLocation = Pick<Location, 'href' | 'pathname' | 'search' | 'hash' | 'host'>;
281
+ type PageNames = Record<string, string> | ReadonlyArray<readonly [pattern: string, name: string]> | ((location: PageLocation) => string | undefined);
261
282
  /**
262
283
  * Which clicks produce a `$autocapture` event.
263
284
  * 'interactive' — only clicks resolving to a link/button/[role=button]/submit control
@@ -266,13 +287,28 @@ interface DepsmithSdkConfig {
266
287
  * true — alias of 'interactive'; false disables click capture.
267
288
  */
268
289
  type ClickCapture = boolean | 'interactive' | 'all';
290
+ /**
291
+ * When an automatic `$page_view` (and its `$page_leave`) is sent.
292
+ * 'path' — when `location.pathname` changes. The default: a query-string or `#` change is
293
+ * filters, sort order, pagination or an in-page anchor, not a new page.
294
+ * 'all' — when anything in the URL changes, query and `#` included (the pre-0.8 behaviour).
295
+ * true — alias of 'path'; false sends none automatically.
296
+ */
297
+ type PageViewCapture = boolean | 'path' | 'all';
269
298
  interface AutocaptureConfig {
270
299
  clicks?: ClickCapture;
271
300
  forms?: boolean;
272
301
  scrolls?: boolean;
273
- pageviews?: boolean;
302
+ pageviews?: PageViewCapture;
274
303
  ignoredSelectors?: string[];
275
304
  selectorMaxDepth?: number;
305
+ /**
306
+ * Extra patterns for ids, classes and test-attribute values that `$ac_selector` should skip as
307
+ * generated, on top of the built-in rules (CSS-in-JS and CSS-module hashes, utility classes,
308
+ * long digit runs). Regex sources, e.g. `['^theme-', '^js-']`; an invalid one is skipped with
309
+ * a debug warning.
310
+ */
311
+ selectorIgnore?: string[];
276
312
  /**
277
313
  * `data-*` attribute names to attach to click and change events as `$ac_attr_<name>`.
278
314
  *
@@ -427,6 +463,13 @@ declare class DepsmithSdkClient {
427
463
  private ready;
428
464
  constructor(config: DepsmithSdkConfig, overrides?: InternalOverrides);
429
465
  track(name: string, properties?: Properties): void;
466
+ /**
467
+ * `track()` without the `$`-key check on properties, for the SDK's own integrations. Not part
468
+ * of the public API: the Shopify pixel needs it because it stamps `$shopify_client_id` on every
469
+ * event it maps, which a public `track()` would now drop as reserved. Event names are checked
470
+ * exactly as in `track()`.
471
+ */
472
+ trackInternal(name: string, properties?: Properties): void;
430
473
  /**
431
474
  * Rejects an envelope id the collector's schema would refuse, at the point it enters the SDK.
432
475
  *
@@ -441,8 +484,22 @@ declare class DepsmithSdkClient {
441
484
  * prefix, inventing data rather than losing it. Rejecting a schema-invalid value at capture is
442
485
  * the rule throughout: such an event would 400 and take the whole batch with it.
443
486
  */
487
+ /** Client traits as sent: `$` keys dropped, then sanitised like event properties. */
488
+ private traits;
444
489
  private tooLong;
445
- page(name?: string, properties?: Properties): void;
490
+ /** `options.type` is sent as `$page_type` (API_SPEC §2). */
491
+ page(name?: string, properties?: Properties, options?: PageOptions): void;
492
+ /**
493
+ * `page()` without the `$`-key check, for the SDK's own integrations. Not part of the public
494
+ * API: the Shopify pixel sends checkout page views with `$checkout_step` and
495
+ * `$shopify_client_id`, which a public `page()` would now drop as reserved. Still a manual
496
+ * view — it is a call, not autocapture.
497
+ *
498
+ * Advances navigation state even for an explicit call, so an app that drives pageviews by hand
499
+ * (no autocapture) still gets previous_url and counter — and claims the URL so autocapture
500
+ * cannot emit a second view for the same page.
501
+ */
502
+ pageInternal(name?: string, properties?: Properties, options?: PageOptions): void;
446
503
  /**
447
504
  * `$web_vitals`, once per page, on the first time the tab is hidden.
448
505
  *
@@ -456,7 +513,7 @@ declare class DepsmithSdkClient {
456
513
  */
457
514
  private emitWebVitals;
458
515
  /** Alias of page() — unified mobile naming. */
459
- screen(name?: string, properties?: Properties): void;
516
+ screen(name?: string, properties?: Properties, options?: PageOptions): void;
460
517
  identify(userId: string, traits?: Properties): void;
461
518
  alias(aliasId: string): void;
462
519
  reset(): void;
@@ -625,8 +682,8 @@ declare class DepsmithSdkClient {
625
682
  declare const DepsmithSdk: {
626
683
  init(config: DepsmithSdkConfig, overrides?: InternalOverrides): DepsmithSdkClient | null;
627
684
  track: (name: string, properties?: Properties) => void;
628
- page: (name?: string, properties?: Properties) => void;
629
- screen: (name?: string, properties?: Properties) => void;
685
+ page: (name?: string, properties?: Properties, options?: PageOptions) => void;
686
+ screen: (name?: string, properties?: Properties, options?: PageOptions) => void;
630
687
  identify: (userId: string, traits?: Properties) => void;
631
688
  alias: (aliasId: string) => void;
632
689
  reset: () => void;
@@ -652,4 +709,4 @@ declare const DepsmithSdk: {
652
709
  shutdown(): void;
653
710
  };
654
711
 
655
- export { type AsyncKV, AsyncMirrorAdapter, type AutocaptureConfig, type BatchPayload, type ConsentState, DEPSMITH_SDK_STORAGE_KEYS, DepsmithSdk, DepsmithSdkClient, type DepsmithSdkConfig, type DepsmithSdkEvent, type EventContext, type EventType, type InternalOverrides, type KVStorage, type Properties, type PropertyValue, type Scheduler, type TrackingOptions, type UserPropertyOps, idleScheduler, syncScheduler };
712
+ export { type AsyncKV, AsyncMirrorAdapter, type AutocaptureConfig, type BatchPayload, type ConsentState, DEPSMITH_SDK_STORAGE_KEYS, DepsmithSdk, DepsmithSdkClient, type DepsmithSdkConfig, type DepsmithSdkEvent, type EventContext, type EventType, type InternalOverrides, type KVStorage, type PageLocation, type PageNames, type PageOptions, type Properties, type PropertyValue, type Scheduler, type TrackingOptions, type UserPropertyOps, idleScheduler, syncScheduler };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var tt=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],F="depsmith_campaign",j="depsmith_referrer";function rt(r){try{return new URL(r).host||void 0}catch{return}}var P=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(F)??{},this.referrer=this.read(j)??{}}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,c]of tt){let l=i.get(d);l&&(s[c]=l)}Object.keys(s).length>0&&(this.campaign=s,this.write(F,s));let o=t?rt(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(j,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(F),this.storage.remove(j)}catch{}}};var X=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=be(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=be(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}},A=class{constructor(e){this.sink=e;this.pages=new X;this.enteredAt=0}start(e,t){this.pages.recordPage(e,t),this.enteredAt=this.sink.now()}get pageCount(){return this.pages.pageCount}recordExplicit(){this.record(),this.lastViewed=Y()}autoPageView(){this.record();let e=Y();if(e!==void 0&&e===this.lastViewed)return;this.lastViewed=e;let t=typeof document<"u"?document.title:"";this.sink.capture("$page_view","page_view",{name:t||"Unknown",$page_counter:this.pages.pageCount})}leave(e){let t=this.pages.current;if(t===void 0)return;let i={$page_duration_ms:Math.max(0,this.sink.now()-this.enteredAt)};e!==void 0&&(i.$page_max_scroll=e),this.leaving=t;try{this.sink.capture("$page_leave","page_leave",i)}finally{this.leaving=void 0}}restored(e){e&&(this.enteredAt=this.sink.now())}newSession(){this.pages.resetForNewSession()}tracking(){let e=this.pages.tracking();return this.leaving===void 0?e:{...e,url:this.leaving,path:it(this.leaving),domain:G(this.leaving),url_base:W(this.leaving)}}record(){let e=Y();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now())}};function Y(){if(!(typeof window>"u"||!window.location))return window.location.href}function be(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function it(r){try{return new URL(r).pathname||void 0}catch{return}}function G(r){try{return new URL(r).host||void 0}catch{return}}function W(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}function Se(){return import("./autocapture.js")}var H=[["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"],["screen","screen"],["timezone","timezone"],["userAgent","user_agent"]],nt=Object.fromEntries(H.map(([r])=>[r,!0]));function we(r){let e={...nt};if(!r)return e;for(let[t]of H)r[t]===!1&&(e[t]=!1);return e}function ke(r,e){let t=r;for(let[i,n,s]of H){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 Q={clicks:"interactive",forms:!0,scrolls:!0,pageviews:!0,ignoredSelectors:[],selectorMaxDepth:5,attributes:[]};function st(r){return r===void 0?Q.clicks:r===!0?"interactive":r}function _e(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=r.autocapture===!0?Q:r.autocapture&&typeof r.autocapture=="object"?{...Q,...r.autocapture,clicks:st(r.autocapture.clicks)}:!1;return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:J(r.batchSize??20,1,500),batchIntervalMs:Math.max(r.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(r.maxQueueSize??1e3,1),maxQueueBytes:Math.max(r.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(r.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(r.sampleRate)?J(r.sampleRate,0,1):1,sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:J(r.maxRetries??5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,trackingOptions:we(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage"}}function J(r,e,t){return Math.min(Math.max(r,e),t)}function Z(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function xe(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 ot(r){return xe(r).toString(36)}function Pe(r){return xe(r)/4294967296}function ee(r){return Z(r)+ot(r)}var te={},Ae=!1;function Ee(){if(!Ae){Ae=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{te=e}).catch(()=>{})}catch{}}}function re(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=ct(e,t);i&&(r.browser=i);let n=lt(e);if(n){let u=dt(n.name,te.platformVersion);r.os=u?{...n,version:u}:n}let s=ft(e,t);s&&(r.deviceType=s);let o=at(e,n);return o&&(r.device=o),r}function at(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=te.model?.trim();return i?t.model=i:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function dt(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 Oe(t)}}var ut=[{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 ct(r,e){for(let i of ut){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 pt=[{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 lt(r){for(let e of pt){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Oe((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Oe(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function ft(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 E=null,O=null;function Ce(){return O!==null||(O=gt()),O}function C(){return E!==null||(E=ee(Ce().map(r=>r.value).join("|"))),E}function Te(){let r={};for(let e of Ce())r[`$fp_${e.name}`]=e.value;return r}function gt(){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:${ht()}`})}catch{}return r}function ht(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),ee(r.toDataURL())):""}catch{return""}}function $e(){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 T=null,Re=0,Ie=!1,S=!1,Me=null;function Ue(){if(!Ie){Ie=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let r=navigator.permissions;if(typeof r?.query!="function")return;r.query({name:"geolocation"}).then(e=>{Me=e,e.state==="granted"&&ie(),e.onchange=()=>{e.state==="granted"?ie():T=null}}).catch(()=>{})}catch{}}}function ie(){if(!S){S=!0;try{navigator.geolocation.getCurrentPosition(r=>{S=!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),T=n,Re=Date.now()},()=>{S=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{S=!1}}}function De(){if(T)return Date.now()-Re>3e5&&Me?.state==="granted"&&ie(),{...T}}var se="@depsmith/depsmith-sdk",y="0.7.0",ne=null;function mt(){if(ne)return ne;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ne=r,r}function w(r={}){let e={library:{name:se,version:y}};m(()=>{if(typeof window<"u"&&window.location){let t=window.location.href;e.page={url:t,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,domain:G(t),url_base:W(t),...r.page??{}}}}),m(()=>{typeof window<"u"&&window.screen&&(e.screen={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),m(()=>{let t=mt();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),m(()=>{let{deviceType:t}=re();t&&(e.device={...e.device,type:t})}),m(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),m(()=>{r.fingerprint&&vt(e)}),m(()=>{if(r.geolocation){let t=De();t&&(e.location=t)}});try{if(r.overrides){for(let[t,i]of Object.entries(r.overrides))i!==void 0&&(e[t]=i);e.library={name:se,version:y}}}catch{}return r.tracking&&ke(e,r.tracking),e}function vt(r){let{browser:e,os:t,deviceType:i,device:n}=re();e&&(r.browser=e),t&&(r.os=t);let s={...r.device};i&&(s.type=i),n?.manufacturer&&(s.manufacturer=n.manufacturer),n?.model&&(s.model=n.model),Object.keys(s).length>0&&(r.device=s);let o=$e();o.type&&(r.network={...r.network,type:o.type})}function m(r){try{r()}catch{}}function Ne(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var oe="depsmith_consent",$=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(oe);this.state=n==="granted"||n==="denied"||n==="pending"?n:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(oe,"granted")}optOut(){this.state="denied",this.storage.set(oe,"denied")}};var k=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},yt=r=>r();var I="depsmith_queue",bt=512*1024,ae=2,St=new Set(["identify","alias","group"]);function wt(r){return St.has(r?.event_type)}var R=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??bt,this.schedule=n.schedule??k,this.restore()}restore(){try{let e=this.storage.get(I);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(I)}}reset(e){this.events=e,this.sizes=e.map(t=>Le(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?ae:this.sizeSum+(this.events.length-1)+ae}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(I,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=Le(e);if(t+ae>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let i=this.events.length-this.maxSize;this.dropOldest(i),this.logger.warn(`queue cap reached; dropped ${i} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!wt(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e){return this.events.slice(0,e)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let 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()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(I)}};function Le(r){return JSON.stringify(r).length}function f(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let i=0;i<16;i++)e[i]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=[];for(let i=0;i<16;i++)t.push(e[i].toString(16).padStart(2,"0"));return`${t[0]}${t[1]}${t[2]}${t[3]}-${t[4]}${t[5]}-${t[6]}${t[7]}-${t[8]}${t[9]}-${t[10]}${t[11]}${t[12]}${t[13]}${t[14]}${t[15]}`}function b(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 qe=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer"],v=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},M=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let i of document.cookie.split("; "))if(i.startsWith(t))return decodeURIComponent(i.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",i=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${i}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},kt=new Set(["depsmith_anonymous_id"]),U=class{constructor(e,t,i=kt){this.primary=e;this.secondary=t;this.mirrored=i}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let i=this.secondary.get(e);if(t===i)return t;if(t===null&&i!==null)return this.primary.set(e,i),i;if(i===null&&t!==null)return this.secondary.set(e,t),t;let n=_t(t,i)??t;return this.primary.set(e,n),this.secondary.set(e,n),n}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}};function _t(r,e){let t=b(r),i=b(e);return t===null||i===null?null:t<=i?r:e}var de=class{constructor(e,t=qe){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};var ue=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},_=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let i=indexedDB.open(e,1);i.onupgradeneeded=()=>i.result.createObjectStore("kv"),i.onsuccess=()=>{this.db=i.result;let n=this.db.transaction("kv","readonly").objectStore("kv"),s=n.getAllKeys(),o=n.getAll();o.onsuccess=()=>{let u=s.result;o.result.forEach((a,d)=>{let c=u[d];c!==void 0&&(this.snapshot.set(c,a),this.mirror.has(c)||this.mirror.set(c,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 Ke(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new ue(window.localStorage)}}catch{}return new v}var ce="depsmith_anonymous_id",pe="depsmith_user_id",le="depsmith_group_id",D="depsmith_user_props",N=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(ce);return e||(e=f(this.clock.now()),this.storage.set(ce,e)),e}get userId(){return this.storage.get(pe)}get groupId(){return this.storage.get(le)}identify(e){this.storage.set(pe,e)}setGroup(e){this.storage.set(le,e)}getUserProps(){try{return JSON.parse(this.storage.get(D)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(D,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(D,JSON.stringify(t))}reset(){this.storage.remove(pe),this.storage.remove(le),this.storage.remove(D);let e=f(this.clock.now());return this.storage.set(ce,e),e}};var Ve="depsmith_session",L=class{constructor(e,t,i,n=k){this.storage=e;this.clock=t;this.timeoutMs=i;this.pending=null;this.scheduled=!1;this.schedule=n}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(Ve);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=b(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(Ve,JSON.stringify(e)))}mint(e){let t={id:f(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let i=this.mint(e);return{sessionId:i.id,startedAt:e,startedSession:{id:i.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let i=this.mint(e);return{sessionId:i.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:i.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let i=b(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 g(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=xt(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function fe(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 xt(r,e){let t=fe(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=fe(n);i.push(s!==void 0?s:Be(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=fe(o);i[String(s)]=u!==void 0?u:Be(o),n++}return i}}}function Be(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function Pt(r){return r>=500}function ze(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 At(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 Fe(r,e){if(typeof fetch!="function")return{stop:()=>{}};let t=fetch,i=r.replace(/\/+$/,""),n=async(s,o)=>{let u=Date.now(),a=typeof s=="string"?s:s instanceof URL?s.href:s.url,d=o?.method??(typeof s=="object"&&"method"in s?s.method:"GET");if(a.startsWith(i))return t(s,o);try{let c=await t(s,o);return Pt(c.status)&&e({...ze(a),$net_method:String(d).toUpperCase(),$net_status:c.status,$net_start:u,$net_end:Date.now(),$net_duration_ms:Date.now()-u,...Et(o,c)}),c}catch(c){throw e({...ze(a),$net_method:String(d).toUpperCase(),$net_error_message:c instanceof Error?c.message.slice(0,255):"network error",$net_start:u,$net_end:Date.now(),$net_duration_ms:Date.now()-u}),c}};return globalThis.fetch=n,{stop:()=>{globalThis.fetch===n&&(globalThis.fetch=t)}}}function Et(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=At(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function q(r){return Math.round(r)}function je(){let r,e,t,i=0,n=!1,s,o=[],u=(a,d)=>{try{let c=new PerformanceObserver(l=>d(l.getEntries()));c.observe({type:a,buffered:!0}),o.push(c)}catch{}};u("largest-contentful-paint",a=>{let d=a[a.length-1];d&&(r=q(d.startTime))}),u("paint",a=>{for(let d of a)d.name==="first-contentful-paint"&&(e=q(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 c=q(d.duration);(t===void 0||c>t)&&(t=c)}});try{let[a]=performance.getEntriesByType("navigation"),d=a;d?.responseStart!==void 0&&d.responseStart>0&&(s=q(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 ge="depsmith_super_props";function Ye(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):r.startsWith("$")?(e.warn(`register: "$"-prefixed keys are reserved; ignored "${r}"`),!1):!0}var K=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(ge);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))Ye(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))Ye(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(ge)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(ge,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var Ot=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],Xe=50,Ge=200;function he(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let s=Object.keys(r).filter(o=>o!=="$clear_all");return s.length>0&&e.warn(`$clear_all is exclusive; ignored ${s.join(", ")}`),{$clear_all:!0}}let t={},i=new Set,n=(s,o)=>i.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(i.add(s),!0);for(let s of Ot){let o=r[s];if(!o||typeof o!="object")continue;let u=g(o,e),a={};for(let[d,c]of Object.entries(u))n(d,s)&&(a[d]=c);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>=Xe){e.debug(`$add over ${Xe} 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>=Ge){e.debug(`$unset over ${Ge} 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 V(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var We={now:()=>Date.now()};function h(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function He(r){return r===0||r===408||r===429||r>=500}var Ct=1e3,Tt=32e3;function Je(r,e=Math.random){let t=Math.min(Ct*2**r,Tt);return Math.round(e()*t)}async function $t(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}function Qe(r){let e=[];for(let t of r)e.push(t.event_id);return e}var It=3e4,Rt=6e4,Mt=10;function Ut(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var B=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("collector unreachable; uploads paused");return}let e=this.queue.peek(this.config.batchSize);this.queue.persistNow();let t=await this.uploadWithRetry(e);if(t==="requeue")return;t==="dropped"&&this.deps.logger.warn(`dropped poison batch of ${e.length}`),this.queue.remove(Qe(e))}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1;for(let n=0;n<=this.config.maxRetries;n++){let s=await this.post(e);if(s!==0&&(i=!0),s>=200&&s<300)return t?.ok(),"sent";if(!He(s))return t?.ok(),this.deps.logger.warn(`non-retryable ${s}; dropping batch`),"dropped";if(this.deps.logger.debug(`upload attempt ${n+1} failed (${s})`),s===0&&!i&&t?.suspect())break;n<this.config.maxRetries&&await this.deps.sleep(Je(n))}return i?t?.ok():t?.fail(),"requeue"}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:h(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s=t,o={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream<"u")try{s=await $t(t),o["Content-Encoding"]="gzip"}catch{s=t}let u=Ut(s)<=Rt;u||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let a={method:"POST",headers:o,body:s,keepalive:u};return i&&(a.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,a)).status}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:It}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<Mt;){let t=this.queue.peek(this.config.batchSize),i=this.buildPayload(t);if(!navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(i)],{type:"text/plain"})))return;this.queue.remove(Qe(t)),e++}}catch{}}};var me="depsmith_net_breaker";function Ze(r,e){let t=!1,i=0,n=0,s=3e5,o=(d,c,l)=>typeof d=="number"&&d===d?Math.min(Math.max(d,c),l):c,u=()=>{if(!t){t=!0;try{let d=JSON.parse(r.get(me)??"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?r.set(me,JSON.stringify([i,n,s])):r.remove(me)}catch{}};return{open:()=>(u(),e.now()<n),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())}}}var z=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var et=255,x=class{constructor(e,t={}){this.pageLife=new A({now:()=>this.clock.now(),capture:(e,t,i)=>this.capture(e,t,i)});this.vitalsReported=!1;this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=_e(e),this.logger=new z(this.config.debug),this.clock=t.clock??We,this.storage=t.storage??this.pickStorage(),this.contextProvider=t.contextProvider;let i=this.config.childSafeMode?new v:this.config.storage==="memory"?this.storage:new U(this.storage,new M(this.config.cookieDomain||void 0));this.identity=new N(i,this.clock),this.session=new L(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new $(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??Ne())),this.attribution=new P(i),this.superProperties=new K(this.storage,this.logger),!this.contextProvider&&typeof window<"u"&&window.location&&(this.attribution.recordLanding(window.location.href,typeof document<"u"?document.referrer:""),this.pageLife.start(window.location.href,typeof document<"u"?document.referrer:"")),this.queue=new R(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&Ee(),this.config.geolocation&&!this.config.childSafeMode&&Ue(),this.storage instanceof _&&(this.ready=this.storage.hydrate().then(n=>{try{let s=n.get("depsmith_queue");s&&this.queue.prepend(JSON.parse(s))}catch{this.logger.warn("persisted queue corrupt; discarded")}})),this.uploader=new B(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...n)=>fetch(...n)),clock:this.clock,logger:this.logger,sleep:t.sleep??(n=>new Promise(s=>setTimeout(s,n))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:Ze(this.storage,this.clock)}),t.manualLifecycle||(this.startFlushTimer(),this.attachLifecycle(),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}if(e.startsWith("$")){this.logger.warn(`track: "$"-prefixed names are reserved; dropped "${e}"`);return}this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}tooLong(e,t){return e.length<=et?!1:(this.logger.warn(`${t} exceeds ${et} characters (got ${e.length}); dropped`),!0)}page(e,t){this.guard(()=>{this.pageLife.recordExplicit();let i=e??(typeof document<"u"?document.title:void 0)??"Unknown";this.capture("$page_view","page_view",{...t,name:i,$page_counter:this.pageLife.pageCount})})}emitWebVitals(){this.vitalsReported||!this.vitals?.hasAny()||(this.vitalsReported=!0,this.capture("$web_vitals","track",this.vitals.snapshot()))}screen(e,t){this.page(e,t)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let i=g(t,this.logger);this.capture("$identify","identify",void 0,i,V("$set",i))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.identity.reset(),this.session.rotate(),this.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}this.tooLong(e,"group: groupId")||(this.identity.setGroup(e),this.capture("$group","group",void 0,g(t,this.logger)))})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}this.capture("$group","group",void 0,g(e,this.logger))})}setProperty(e,t){this.guard(()=>{this.identity.setUserProp(e,t);let i=g({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,V("$set",i))})}setOnceProperty(e,t){this.guard(()=>{if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.identity.setUserProp(e,t);let i=g({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,V("$set_once",i))})}unsetProperty(e){this.guard(()=>{this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},he({$unset:[e]},this.logger))})}register(e){this.guard(()=>this.superProperties.register(e))}registerOnce(e){this.guard(()=>this.superProperties.registerOnce(e))}unregister(e){this.guard(()=>this.superProperties.unregister(e))}setUserProperties(e){this.guard(()=>{let t=he(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.flushUploads()})}optOut(){this.guard(()=>{this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.flushTimer!==null&&clearInterval(this.flushTimer),this.flushTimer=null;for(let e of this.teardownFns.splice(0))e();this.persistNow()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}enqueueEvent(e){this.queue.enqueue(e),this.drained=!1}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:Pe(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,i,n,s){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let o=this.session.touch();if(o.startedSession&&this.pageLife.newSession(),o.endedSession&&this.sessionInSample(o.endedSession.id)&&this.enqueueSessionEnd(o.endedSession),o.startedSession&&this.sessionInSample(o.startedSession.id)&&this.enqueueSessionStart(o.startedSession),!this.inSample(o.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let u=this.clock.now(),a=this.contextOptions(),d={event_id:f(u),event:e,event_type:t,timestamp:h(u),session_id:o.sessionId,session_started_at:h(o.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...w(a),traits:n}:w(a),platform:"web",sdk_version:y};s&&(d.user_properties=s);let c={...this.config.defaultProperties,...this.superProperties.current(),...g(i,this.logger)};Object.keys(c).length>0&&(d.properties=c);let l=this.identity.userId;l&&(d.user_id=l);let ye=this.identity.groupId;ye&&(d.group_id=ye),a.fingerprint&&(d.device_id=C()),this.enqueueEvent(d),this.logger.debug(`captured ${e}`,d),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",t=Z(this.config.apiKey),i=this.storage.get(e);i!==null&&i!==t&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear()),this.storage.set(e,t)}pickStorage(){return this.config.storage==="memory"?new v:this.config.storage==="indexeddb"&&typeof indexedDB<"u"?new _:Ke()}enqueueSessionEnd(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:f(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:h(e.lastActivityAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:w(t),platform:"web",sdk_version:y},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=C()),this.enqueueEvent(i)}enqueueSessionStart(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:f(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:h(e.startedAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:w(t),platform:"web",sdk_version:y},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=C()),t.fingerprint&&(i.properties={...i.properties,...Te()}),this.enqueueEvent(i)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window>"u"||typeof document>"u")return;let e=()=>{this.drained||(this.guard(()=>this.emitWebVitals()),this.guard(()=>this.leaveOnUnload?.()),this.drained=!0,this.consent.canUpload()&&this.uploader.sendBeaconAll(),this.persistNow())},t=()=>{if(document.visibilityState==="hidden")e();else{this.drained=!1;let s=this.session.touch();s.endedSession&&this.enqueueSessionEnd(s.endedSession),s.startedSession&&(this.pageLife.newSession(),this.enqueueSessionStart(s.startedSession))}},i=s=>{this.drained=!1,this.pageLife.restored(s.persisted)},n=()=>{this.uploader.resetNetworkBreaker(),this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()};window.addEventListener("pagehide",e),window.addEventListener("pageshow",i),document.addEventListener("visibilitychange",t),window.addEventListener("online",n),this.teardownFns.push(()=>{window.removeEventListener("pagehide",e),window.removeEventListener("pageshow",i),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",n)})}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=je(),this.teardownFns.push(()=>this.vitals?.stop()));let t=Fe(this.config.endpoint,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),Se().then(i=>{i&&(this.teardownFns.push(i.startAutocapture(e,{emit:n=>this.autocapture(n),page:()=>this.guard(()=>this.pageLife.autoPageView()),pageLeave:n=>this.guard(()=>this.pageLife.leave(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 p=null,ve=null,Hr={init(r,e){try{return p&&ve===r.apiKey||(p?.shutdown(),p=new x(r,e),ve=r.apiKey),p}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>p?.track(r,e),page:(r,e)=>p?.page(r,e),screen:(r,e)=>p?.screen(r,e),identify:(r,e)=>p?.identify(r,e),alias:r=>p?.alias(r),reset:()=>p?.reset(),group:(r,e)=>p?.group(r,e),setGroupTraits:r=>p?.setGroupTraits(r),setProperty:(r,e)=>p?.setProperty(r,e),setOnceProperty:(r,e)=>p?.setOnceProperty(r,e),unsetProperty:r=>p?.unsetProperty(r),setUserProperties:r=>p?.setUserProperties(r),register:r=>p?.register(r),registerOnce:r=>p?.registerOnce(r),unregister:r=>p?.unregister(r),optIn:()=>p?.optIn(),optOut:()=>p?.optOut(),flush:()=>p?.flush()??Promise.resolve(),getAnonymousId:()=>p?.getAnonymousId(),getSessionId:()=>p?.getSessionId(),setSessionId:(r,e)=>p?.setSessionId(r,e),shutdown(){p?.shutdown(),p=null,ve=null}};export{de as AsyncMirrorAdapter,qe as DEPSMITH_SDK_STORAGE_KEYS,Hr as DepsmithSdk,x as DepsmithSdkClient,k as idleScheduler,yt as syncScheduler};
1
+ var dt=[["utm_source","source"],["utm_medium","medium"],["utm_campaign","name"],["utm_term","term"],["utm_content","content"]],G="depsmith_campaign",H="depsmith_referrer";function ut(r){try{return new URL(r).host||void 0}catch{return}}var A=class{constructor(e){this.storage=e;this.campaign={};this.referrer={};this.campaign=this.read(G)??{},this.referrer=this.read(H)??{}}read(e){try{let t=this.storage.get(e);if(!t)return null;let i=JSON.parse(t);return i&&typeof i=="object"?i:null}catch{return null}}write(e,t){try{this.storage.set(e,JSON.stringify(t))}catch{}}recordLanding(e,t){let i,n;try{let u=new URL(e);i=u.searchParams,n=u.host}catch{return}let s={};for(let[u,p]of dt){let l=i.get(u);l&&(s[p]=l)}Object.keys(s).length>0&&(this.campaign=s,this.write(G,s));let o=t?ut(t):void 0,d=!!o&&o!==n,a=!1;d&&(this.referrer.url=t,this.referrer.domain=o,a=!0),this.referrer.initial_domain===void 0&&(this.referrer.initial_domain=d?o:"$direct",d&&(this.referrer.initial_url=t),a=!0),a&&this.write(H,this.referrer)}campaignBlock(){return Object.keys(this.campaign).length>0?{...this.campaign}:void 0}referrerBlock(){return Object.keys(this.referrer).length>0?{...this.referrer}:void 0}clear(){this.campaign={},this.referrer={};try{this.storage.remove(G),this.storage.remove(H)}catch{}}};var W=class{constructor(){this.counter=0}recordPage(e,t){return e===this.currentUrl?!1:(this.currentUrl===void 0?t?(this.previousUrl=t,this.previousType=Pe(t,e)?"internal":"external"):this.previousType="direct":(this.previousUrl=this.currentUrl,this.previousType=Pe(this.currentUrl,e)?"internal":"external"),this.currentUrl=e,this.counter+=1,!0)}tracking(){let e={};return this.previousUrl!==void 0&&(e.previous_url=this.previousUrl),this.previousType!==void 0&&(e.previous_type=this.previousType),this.counter>0&&(e.counter=this.counter),e}get pageCount(){return this.counter}get current(){return this.currentUrl}resetForNewSession(){this.counter=this.currentUrl===void 0?0:1}},O=class{constructor(e,t={autocapture:!1}){this.sink=e;this.pages=new W;this.enteredAt=0;this.rules=pt(t.pageNames),this.byHref=!!t.autocapture&&t.autocapture.pageviews==="all"}start(e,t){this.pages.recordPage(e,t),this.enteredAt=this.sink.now()}get pageCount(){return this.pages.pageCount}recordExplicit(){this.record(),this.lastViewed=this.pageKey()}manual(e,t,i){this.flushPending(),this.recordExplicit(),this.sink.capture("$page_view","page_view",{...t,...we({source:"manual",name:e,type:i},this.rules),$page_counter:this.pages.pageCount})}autoPageView(e){this.flushPending(),this.record();let t=this.pageKey();if(t!==void 0&&t===this.lastViewed)return;this.lastViewed=t;let i=this.pages.pageCount;if(!e){this.emitView(location,i);return}let n=location.href,s={at:this.sink.now(),counter:i,location:new URL(n),page:{url:n,path:location.pathname,referrer:document.referrer,domain:E(n),url_base:C(n),...this.pages.tracking()},cancel:()=>{}};this.pending=s,s.cancel=e(document.title,()=>this.flushPending())}flushPending(){let e=this.pending;e&&(this.pending=void 0,e.cancel(),this.emitView(e.location,e.counter,e))}discardPending(){this.pending?.cancel(),this.pending=void 0}emitView(e,t,i){let n=document.title;this.sink.capture("$page_view","page_view",{...we({source:"auto",location:e,title:n},this.rules),$page_counter:t},i?.at,i&&{...i.page,title:n})}leave(e){this.flushPending();let t=this.pages.current;if(t===void 0)return;let i={$page_duration_ms:Math.max(0,this.sink.now()-this.enteredAt)};e!==void 0&&(i.$page_max_scroll=e),this.leaving=t;try{this.sink.capture("$page_leave","page_leave",i)}finally{this.leaving=void 0}}restored(e){e&&(this.enteredAt=this.sink.now())}newSession(){this.pages.resetForNewSession()}tracking(){let e=this.pages.tracking();return this.leaving===void 0?e:{...e,url:this.leaving,path:lt(this.leaving),domain:E(this.leaving),url_base:C(this.leaving)}}pageKey(){return this.byHref?ke():globalThis.location?.pathname}record(){let e=ke();if(e===void 0)return;this.pages.recordPage(e,typeof document<"u"?document.referrer:"")&&(this.enteredAt=this.sink.now())}};function we({source:r,name:e,type:t,location:i=globalThis.location,title:n=globalThis.document?.title},s){let o=i&&s?.(i),d=t?.trim()||o?.type;return{$page_name:e?.trim()||o?.name.trim()||n?.trim()||i?.pathname||"Unknown",...d?{$page_type:d}:{},$page_source:r}}function pt(r){if(typeof r=="function")return t=>{try{let i=r(t);return typeof i=="string"?{name:i}:void 0}catch{return}};if(!r||typeof r!="object")return;let e=(Array.isArray(r)?r:Object.entries(r)).map(([t,i])=>[typeof t=="string"&&typeof i=="string"&&ct(t),i]);return t=>{let i=_e(t.pathname);for(let[n,s]of e)if(n&&n.test(i))return{name:s,type:s}}}function ct(r){let e=_e(r).replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\*|\*\*?/g,t=>t==="*"?"[^/]+":t==="**"?".*":"(?:/.*)?");return new RegExp(`^${e}$`)}function _e(r){return r.replace(/(.)\/$/,"$1")}function ke(){if(!(typeof window>"u"||!window.location))return window.location.href}function Pe(r,e){try{return new URL(r).host===new URL(e).host}catch{return!1}}function lt(r){try{return new URL(r).pathname||void 0}catch{return}}function E(r){try{return new URL(r).host||void 0}catch{return}}function C(r){try{let e=new URL(r);return`${e.origin}${e.pathname}`}catch{return}}function xe(){return import("./autocapture.js")}var J=[["appVersion","app"],["browser","browser"],["carrier","network","carrier"],["deviceManufacturer","device","manufacturer"],["deviceModel","device","model"],["deviceType","device","type"],["idfv","device","idfv"],["language","locale"],["network","network"],["osName","os","name"],["osVersion","os","version"],["page","page"],["screenSize","screen_size"],["timezone","timezone"],["userAgent","user_agent"]],gt=Object.fromEntries(J.map(([r])=>[r,!0]));function Ae(r){let e={...gt};if(!r)return e;for(let[t]of J)r[t]===!1&&(e[t]=!1);return e}function Oe(r,e){let t=r;for(let[i,n,s]of J){if(e[i])continue;if(s===void 0){delete t[n];continue}let o={...t[n]};delete o[s],Object.keys(o).length>0?t[n]=o:delete t[n]}return r}var Ee={clicks:"interactive",forms:!0,scrolls:!1,pageviews:"path",ignoredSelectors:[],selectorMaxDepth:5,selectorIgnore:[],attributes:[]};function Ce(r){if(r===!0)return Ee;if(!r||typeof r!="object")return!1;let e={...Ee};for(let[n,s]of Object.entries(r))s!==void 0&&(e[n]=s);let{clicks:t,pageviews:i}=e;return e.clicks=t==="all"?"all":t?"interactive":!1,e.pageviews=i==="all"?"all":i?"path":!1,e}function Te(r){if(!r||typeof r.apiKey!="string"||r.apiKey.length===0)throw new Error("depsmith-sdk: apiKey is required");if(typeof r.endpoint!="string"||!/^https?:\/\//.test(r.endpoint))throw new Error("depsmith-sdk: endpoint must be an http(s) URL");let e=Ce(r.autocapture);return{apiKey:r.apiKey,endpoint:r.endpoint.replace(/\/+$/,""),batchSize:Q(r.batchSize??20,1,500),batchIntervalMs:Math.max(r.batchIntervalMs??6e4,1e3),maxQueueSize:Math.max(r.maxQueueSize??1e3,1),maxQueueBytes:Math.max(r.maxQueueBytes??512*1024,4096),sessionTimeoutMs:Math.max(r.sessionTimeoutMs??18e5,6e4),sampleRate:Number.isFinite(r.sampleRate)?Q(r.sampleRate,0,1):1,sessionEvents:r.sessionEvents==="derive"?"derive":"emit",consentMode:r.consentMode??"granted",respectDnt:r.respectDnt??!0,maxRetries:Q(r.maxRetries??5,0,10),debug:r.debug??!1,defaultProperties:r.defaultProperties??{},autocapture:e,compression:r.compression??"gzip",childSafeMode:r.childSafeMode??!1,anonymizeIp:(r.anonymizeIp??!1)||(r.childSafeMode??!1),deviceFingerprinting:r.deviceFingerprinting??!0,geolocation:r.geolocation??!1,trackingOptions:Ae(r.trackingOptions),cookieDomain:r.cookieDomain??"",storage:r.storage??"localstorage",pageNames:r.pageNames}}function Q(r,e,t){return Math.min(Math.max(r,e),t)}function Z(r){let e=5381;for(let t=0;t<r.length;t++)e=(e<<5)+e+r.charCodeAt(t)>>>0;return e.toString(36)}function $e(r){let e=2166136261;for(let t=0;t<r.length;t++)e^=r.charCodeAt(t),e=Math.imul(e,16777619)>>>0;return e>>>0}function ft(r){return $e(r).toString(36)}function Re(r){return $e(r)/4294967296}function ee(r){return Z(r)+ft(r)}var te={},Ie=!1;function Me(){if(!Ie){Ie=!0;try{let r=navigator?.userAgentData;if(typeof r?.getHighEntropyValues!="function")return;r.getHighEntropyValues(["model","platformVersion"]).then(e=>{te=e}).catch(()=>{})}catch{}}}function re(){let r={};if(typeof navigator>"u")return r;let e=navigator.userAgent||"",t=navigator.userAgentData,i=yt(e,t);i&&(r.browser=i);let n=St(e);if(n){let d=mt(n.name,te.platformVersion);r.os=d?{...n,version:d}:n}let s=wt(e,t);s&&(r.deviceType=s);let o=ht(e,n);return o&&(r.device=o),r}function ht(r,e){let t={};(e?.name==="iOS"||e?.name==="macOS")&&(t.manufacturer="Apple");let i=te.model?.trim();return i?t.model=i:/iPhone/.test(r)?t.model="iPhone":/iPad/.test(r)&&(t.model="iPad"),t.manufacturer||t.model?t:void 0}function mt(r,e){let t=e?.trim();if(t){if(r==="Windows"){let i=Number.parseInt(t.split(".")[0]??"",10);return!Number.isFinite(i)||i===0?void 0:i>=13?"11":"10"}return Ne(t)}}var vt=[{pattern:/Edg(?:e|A|iOS)?\/([\d.]+)/,name:"Edge",engine:"Blink"},{pattern:/OPR\/([\d.]+)/,name:"Opera",engine:"Blink"},{pattern:/Firefox\/([\d.]+)/,name:"Firefox",engine:"Gecko"},{pattern:/Chrome\/([\d.]+)/,name:"Chrome",engine:"Blink"},{pattern:/Version\/([\d.]+)/,name:"Safari",engine:"WebKit",requires:/Safari/}];function yt(r,e){for(let i of vt){if(i.requires&&!i.requires.test(r))continue;let n=r.match(i.pattern);if(n)return{name:i.name,version:n[1],engine:i.engine}}let t=e?.brands?.find(i=>!/not.?a.?brand/i.test(i.brand));if(t)return{name:t.brand,version:t.version}}var bt=[{pattern:/Windows NT ([\d.]+)/,name:"Windows"},{pattern:/OS ([\d_]+)/,name:"iOS",requires:/iPhone|iPad|iPod/},{pattern:/Android ([\d.]+)/,name:"Android"},{pattern:/Mac OS X ([\d_]+)/,name:"macOS"}];function St(r){for(let e of bt){if(e.requires&&!e.requires.test(r))continue;let t=r.match(e.pattern);if(t)return{name:e.name,version:Ne((t[1]??"").replace(/_/g,"."))}}if(/Linux/.test(r))return{name:"Linux"}}function Ne(r){let e=r.replace(/(\.0)+$/,"");return e.length>0?e:r}function wt(r,e){if(/iPad|Tablet|Nexus 7|Kindle|Silk/.test(r))return"tablet";if(e?.mobile===!0||/Mobi|iPhone|Android.*Mobile|Windows Phone/.test(r))return"mobile";if(/Android/.test(r))return"tablet";if(typeof navigator<"u"&&r)return"desktop"}var T=null,$=null;function Ue(){return $!==null||($=kt()),$}function R(){return T!==null||(T=ee(Ue().map(r=>r.value).join("|"))),T}function De(){let r={};for(let e of Ue())r[`$fp_${e.name}`]=e.value;return r}function kt(){let r=[];try{if(typeof screen<"u"&&r.push({name:"screen",value:`${screen.width}x${screen.height}x${screen.colorDepth}`}),typeof navigator<"u"){let e=navigator;r.push({name:"hc",value:`hc:${navigator.hardwareConcurrency??""}`}),r.push({name:"dm",value:`dm:${e.deviceMemory??""}`}),r.push({name:"plat",value:`plat:${navigator.platform??""}`}),r.push({name:"touch",value:`touch:${(navigator.maxTouchPoints??0)>0}`})}r.push({name:"canvas",value:`canvas:${Pt()}`})}catch{}return r}function Pt(){try{if(typeof document>"u")return"";let r=document.createElement("canvas");r.width=240,r.height=60;let e=r.getContext("2d");return e?(e.textBaseline="top",e.font="14px 'Arial'",e.fillStyle="#f60",e.fillRect(10,10,100,30),e.fillStyle="#069",e.fillText(`DepsmithSdk fingerprint ${String.fromCodePoint(127760)}`,12,15),e.strokeStyle="rgba(0,120,200,0.5)",e.arc(50,30,20,0,Math.PI*2),e.stroke(),ee(r.toDataURL())):""}catch{return""}}function Le(){try{if(typeof navigator>"u")return{};let r=navigator.connection;if(!r)return{};switch(r.type){case"wifi":return{type:"wifi"};case"ethernet":return{type:"ethernet"};case"none":return{type:"none"}}switch(r.effectiveType){case"slow-2g":case"2g":return{type:"2g"};case"3g":return{type:"3g"};case"4g":return{type:"4g"}}return{}}catch{return{}}}var I=null,qe=0,Ve=!1,w=!1,Ke=null;function ze(){if(!Ve){Ve=!0;try{if(typeof navigator>"u"||!navigator.geolocation)return;let r=navigator.permissions;if(typeof r?.query!="function")return;r.query({name:"geolocation"}).then(e=>{Ke=e,e.state==="granted"&&ie(),e.onchange=()=>{e.state==="granted"?ie():I=null}}).catch(()=>{})}catch{}}}function ie(){if(!w){w=!0;try{navigator.geolocation.getCurrentPosition(r=>{w=!1;let{latitude:e,longitude:t,accuracy:i}=r.coords;if(!Number.isFinite(e)||!Number.isFinite(t))return;let n={latitude:e,longitude:t,source:"gps"};Number.isFinite(i)&&(n.accuracy=i),I=n,qe=Date.now()},()=>{w=!1},{enableHighAccuracy:!1,maximumAge:3e5,timeout:1e4})}catch{w=!1}}}function Be(){if(I)return Date.now()-qe>3e5&&Ke?.state==="granted"&&ie(),{...I}}var se="@depsmith/depsmith-sdk",b="0.8.0",ne=null;function _t(){if(ne)return ne;let r={};try{r.timezone=Intl.DateTimeFormat().resolvedOptions().timeZone}catch{}return typeof navigator<"u"&&(r.locale=navigator.language,r.userAgent=navigator.userAgent),ne=r,r}function k(r={}){let e={library:{name:se,version:b}};m(()=>{if(typeof window<"u"&&window.location){let t=window.location.href;e.page={url:t,path:window.location.pathname,referrer:typeof document<"u"?document.referrer:void 0,title:typeof document<"u"?document.title:void 0,domain:E(t),url_base:C(t),...r.page??{}}}}),m(()=>{typeof window<"u"&&window.screen&&(e.screen_size={width:window.screen.width,height:window.screen.height,density:window.devicePixelRatio})}),m(()=>{let t=_t();t.locale!==void 0&&(e.locale=t.locale),t.userAgent!==void 0&&(e.user_agent=t.userAgent),t.timezone!==void 0&&(e.timezone=t.timezone)}),m(()=>{let{deviceType:t}=re();t&&(e.device={...e.device,type:t})}),m(()=>{if(r.attribution){let t=r.attribution.campaignBlock();t&&(e.campaign=t);let i=r.attribution.referrerBlock();i&&(e.referrer=i)}}),m(()=>{r.fingerprint&&xt(e)}),m(()=>{if(r.geolocation){let t=Be();t&&(e.location=t)}});try{if(r.overrides){for(let[t,i]of Object.entries(r.overrides))i!==void 0&&(e[t]=i);e.library={name:se,version:b}}}catch{}return r.tracking&&Oe(e,r.tracking),e}function xt(r){let{browser:e,os:t,deviceType:i,device:n}=re();e&&(r.browser=e),t&&(r.os=t);let s={...r.device};i&&(s.type=i),n?.manufacturer&&(s.manufacturer=n.manufacturer),n?.model&&(s.model=n.model),Object.keys(s).length>0&&(r.device=s);let o=Le();o.type&&(r.network={...r.network,type:o.type})}function m(r){try{r()}catch{}}function Fe(){try{if(typeof navigator>"u")return!1;let r=navigator,e=typeof window<"u"?window:{},t=navigator.doNotTrack??e.doNotTrack??r.msDoNotTrack;return t==="1"||t==="yes"}catch{return!1}}var oe="depsmith_consent",M=class{constructor(e,t,i){this.storage=e;this.dntActive=i;let n=e.get(oe);this.state=n==="granted"||n==="denied"||n==="pending"?n:t}effective(){return this.dntActive?"denied":this.state}canCapture(){return this.effective()!=="denied"}canUpload(){return this.effective()==="granted"}get current(){return this.effective()}optIn(){this.state="granted",this.storage.set(oe,"granted")}optOut(){this.state="denied",this.storage.set(oe,"denied")}};var P=r=>{let e=globalThis.requestIdleCallback;if(typeof e=="function"){e(r,{timeout:250});return}setTimeout(r,0)},At=r=>r();var N="depsmith_queue",Ot=512*1024,ae=2,Et=new Set(["identify","alias","group"]);function Ct(r){return Et.has(r?.event_type)}var U=class{constructor(e,t,i,n={}){this.storage=e;this.maxSize=t;this.logger=i;this.events=[];this.sizes=[];this.sizeSum=0;this.dirty=!1;this.scheduled=!1;this.maxChars=n.maxChars??Ot,this.schedule=n.schedule??P,this.restore()}restore(){try{let e=this.storage.get(N);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;let i=t.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string");this.reset(i),i.length!==t.length&&(this.logger.warn("discarded corrupt queued events on restore"),this.markDirty()),this.trimToBudget()&&this.markDirty()}catch{this.logger.warn("queue storage corrupt; starting empty"),this.reset([]),this.storage.remove(N)}}reset(e){this.events=e,this.sizes=e.map(t=>je(t)),this.sizeSum=this.sizes.reduce((t,i)=>t+i,0)}serializedLength(){return this.events.length===0?ae:this.sizeSum+(this.events.length-1)+ae}trimToBudget(){let e=0;for(;this.events.length>0&&this.serializedLength()>this.maxChars;)this.evictAt(this.victimIndex()),e++;return e>0&&this.logger.warn(`queue byte cap reached; dropped ${e} event(s)`),e>0}markDirty(){this.dirty=!0,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){this.dirty&&(this.dirty=!1,this.storage.set(N,JSON.stringify(this.events)))}prepend(e){let t=new Set(this.events.map(n=>n.event_id)),i=e.filter(n=>!!n&&typeof n=="object"&&typeof n.event_id=="string"&&!t.has(n.event_id));i.length!==0&&(this.reset([...i,...this.events]),this.events.length>this.maxSize&&this.dropOldest(this.events.length-this.maxSize),this.trimToBudget(),this.markDirty())}enqueue(e){let t=je(e);if(t+ae>this.maxChars){this.logger.warn(`event ${e.event_id} exceeds the queue byte cap; dropped`);return}if(this.events.push(e),this.sizes.push(t),this.sizeSum+=t,this.events.length>this.maxSize){let i=this.events.length-this.maxSize;this.dropOldest(i),this.logger.warn(`queue cap reached; dropped ${i} event(s)`)}this.trimToBudget(),this.markDirty()}victimIndex(){for(let e=0;e<this.events.length;e++)if(!Ct(this.events[e]))return e;return 0}evictAt(e){this.events.splice(e,1),this.sizeSum-=this.sizes.splice(e,1)[0]??0}dropOldest(e){for(let t=0;t<e&&this.events.length>0;t++)this.evictAt(this.victimIndex())}get size(){return this.events.length}peek(e){return this.events.slice(0,e)}remove(e){let t=new Set(e),i=[],n=[],s=0;for(let o=0;o<this.events.length;o++){let d=this.events[o];if(t.has(d.event_id))continue;let a=this.sizes[o];i.push(d),n.push(a),s+=a}this.events=i,this.sizes=n,this.sizeSum=s,this.markDirty()}clear(){this.reset([]),this.dirty=!1,this.storage.remove(N)}};function je(r){return JSON.stringify(r).length}function f(r){let e=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(e);else for(let i=0;i<16;i++)e[i]=Math.floor(Math.random()*256);e[0]=r/2**40&255,e[1]=r/2**32&255,e[2]=r/2**24&255,e[3]=r/2**16&255,e[4]=r/2**8&255,e[5]=r&255,e[6]=e[6]&15|112,e[8]=e[8]&63|128;let t=[];for(let i=0;i<16;i++)t.push(e[i].toString(16).padStart(2,"0"));return`${t[0]}${t[1]}${t[2]}${t[3]}-${t[4]}${t[5]}-${t[6]}${t[7]}-${t[8]}${t[9]}-${t[10]}${t[11]}${t[12]}${t[13]}${t[14]}${t[15]}`}function S(r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r))return null;let e=r.slice(0,8)+r.slice(9,13),t=parseInt(e,16);return Number.isFinite(t)?t:null}var Ye=["depsmith_anonymous_id","depsmith_user_id","depsmith_group_id","depsmith_user_props","depsmith_session","depsmith_consent","depsmith_queue","depsmith_config_fp","depsmith_net_breaker","depsmith_campaign","depsmith_referrer"],v=class{constructor(){this.data=new Map}get(e){return this.data.get(e)??null}set(e,t){this.data.set(e,t)}remove(e){this.data.delete(e)}},D=class{constructor(e){this.domain=e}get(e){try{let t=`${encodeURIComponent(e)}=`;for(let i of document.cookie.split("; "))if(i.startsWith(t))return decodeURIComponent(i.slice(t.length))}catch{}return null}attributes(e){let t=this.domain?`; domain=${this.domain}`:"",i=typeof location<"u"&&location.protocol==="https:"?"; Secure":"";return`${t}; path=/; max-age=${e}; SameSite=Lax${i}`}set(e,t){try{document.cookie=`${encodeURIComponent(e)}=${encodeURIComponent(t)}${this.attributes(3456e4)}`}catch{}}remove(e){try{document.cookie=`${encodeURIComponent(e)}=${this.attributes(0)}`}catch{}}},Tt=new Set(["depsmith_anonymous_id"]),L=class{constructor(e,t,i=Tt){this.primary=e;this.secondary=t;this.mirrored=i}get(e){let t=this.primary.get(e);if(!this.mirrored.has(e))return t;let i=this.secondary.get(e);if(t===i)return t;if(t===null&&i!==null)return this.primary.set(e,i),i;if(i===null&&t!==null)return this.secondary.set(e,t),t;let n=$t(t,i)??t;return this.primary.set(e,n),this.secondary.set(e,n),n}set(e,t){this.primary.set(e,t),this.mirrored.has(e)&&this.secondary.set(e,t)}remove(e){this.primary.remove(e),this.secondary.remove(e)}};function $t(r,e){let t=S(r),i=S(e);return t===null||i===null?null:t<=i?r:e}var de=class{constructor(e,t=Ye){this.backend=e;this.keys=t;this.mirror=new Map;this.hydrated=null}hydrate(){return this.hydrated??(this.hydrated=Promise.all(this.keys.map(async e=>{try{let t=await this.backend.getItem(e);typeof t=="string"&&!this.mirror.has(e)&&this.mirror.set(e,t)}catch{}})).then(()=>{})),this.hydrated}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),Promise.resolve(this.backend.setItem(e,t)).catch(()=>{})}remove(e){this.mirror.delete(e),Promise.resolve(this.backend.removeItem(e)).catch(()=>{})}};var ue=class{constructor(e){this.ls=e}get(e){try{return this.ls.getItem(e)}catch{return null}}set(e,t){try{this.ls.setItem(e,t)}catch{}}remove(e){try{this.ls.removeItem(e)}catch{}}},_=class{constructor(e="depsmith-sdk"){this.mirror=new Map;this.snapshot=new Map;this.db=null;this.ready=this.open(e)}open(e){return new Promise(t=>{try{let i=indexedDB.open(e,1);i.onupgradeneeded=()=>i.result.createObjectStore("kv"),i.onsuccess=()=>{this.db=i.result;let n=this.db.transaction("kv","readonly").objectStore("kv"),s=n.getAllKeys(),o=n.getAll();o.onsuccess=()=>{let d=s.result;o.result.forEach((a,u)=>{let p=d[u];p!==void 0&&(this.snapshot.set(p,a),this.mirror.has(p)||this.mirror.set(p,a))}),t()},o.onerror=()=>t()},i.onerror=()=>t()}catch{t()}})}hydrate(){return this.ready.then(()=>this.snapshot)}get(e){return this.mirror.get(e)??null}set(e,t){this.mirror.set(e,t),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").put(t,e)}catch{}})}remove(e){this.mirror.delete(e),this.ready.then(()=>{try{this.db?.transaction("kv","readwrite").objectStore("kv").delete(e)}catch{}})}};function Xe(){try{if(typeof window<"u"&&window.localStorage){let r="__depsmith_probe__";return window.localStorage.setItem(r,"1"),window.localStorage.removeItem(r),new ue(window.localStorage)}}catch{}return new v}var pe="depsmith_anonymous_id",ce="depsmith_user_id",le="depsmith_group_id",V="depsmith_user_props",q=class{constructor(e,t){this.storage=e;this.clock=t}get anonymousId(){let e=this.storage.get(pe);return e||(e=f(this.clock.now()),this.storage.set(pe,e)),e}get userId(){return this.storage.get(ce)}get groupId(){return this.storage.get(le)}identify(e){this.storage.set(ce,e)}setGroup(e){this.storage.set(le,e)}getUserProps(){try{return JSON.parse(this.storage.get(V)??"{}")}catch{return{}}}setUserProp(e,t){let i=this.getUserProps();i[e]=t,this.storage.set(V,JSON.stringify(i))}hasUserProp(e){return e in this.getUserProps()}unsetUserProp(e){let t=this.getUserProps();delete t[e],this.storage.set(V,JSON.stringify(t))}reset(){this.storage.remove(ce),this.storage.remove(le),this.storage.remove(V);let e=f(this.clock.now());return this.storage.set(pe,e),e}};var Ge="depsmith_session",K=class{constructor(e,t,i,n=P){this.storage=e;this.clock=t;this.timeoutMs=i;this.pending=null;this.scheduled=!1;this.schedule=n}load(){let e=this.readStored(),t=this.pending;return t?!e||t.lastActivityAt>=e.lastActivityAt?t:(this.pending=null,e):e}readStored(){try{let e=this.storage.get(Ge);if(!e)return null;let t=JSON.parse(e);return typeof t.id!="string"||typeof t.lastActivityAt!="number"?null:(typeof t.startedAt!="number"&&(t.startedAt=S(t.id)??t.lastActivityAt),t)}catch{return null}}save(e){this.pending=e,!this.scheduled&&(this.scheduled=!0,this.schedule(()=>{this.scheduled=!1,this.persistNow()}))}persistNow(){let e=this.pending;e&&(this.pending=null,this.storage.set(Ge,JSON.stringify(e)))}mint(e){let t={id:f(e),lastActivityAt:e,startedAt:e};return this.save(t),t}touch(){let e=this.clock.now(),t=this.load();if(!t){let i=this.mint(e);return{sessionId:i.id,startedAt:e,startedSession:{id:i.id,startedAt:e}}}if(e-t.lastActivityAt>this.timeoutMs){let i=this.mint(e);return{sessionId:i.id,startedAt:e,endedSession:{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt},startedSession:{id:i.id,startedAt:e}}}return this.save({id:t.id,lastActivityAt:e,startedAt:t.startedAt}),{sessionId:t.id,startedAt:t.startedAt}}peek(){let e=this.load();return e?e.id:this.mint(this.clock.now()).id}adopt(e,t){let i=S(e);return i===null?!1:(this.save({id:e,lastActivityAt:this.clock.now(),startedAt:t??i}),!0)}rotate(){return this.mint(this.clock.now()).id}};function y(r,e){if(r==null)return{};if(typeof r!="object"||Array.isArray(r))return e.warn("properties must be an object; ignoring",r),{};let t={},i=0;for(let[n,s]of Object.entries(r)){if(i>=200){e.warn("properties exceed 200 keys; excess dropped");break}let o=Rt(s,e);if(o===void 0){e.debug(`property "${n}" dropped (unsupported value)`);continue}t[String(n)]=o,i++}return t}function ge(r){if(r===null)return null;let e=typeof r;if(e==="string"||e==="boolean")return r;if(e==="number")return Number.isFinite(r)?r:void 0;if(r instanceof Date)return isNaN(r.getTime())?void 0:r.toISOString()}function Rt(r,e){let t=ge(r);if(t!==void 0)return t;if(!(r===void 0||typeof r=="function"||typeof r=="symbol")){if(Array.isArray(r)){let i=[];for(let n of r.slice(0,100)){let s=ge(n);i.push(s!==void 0?s:He(n))}return i}if(typeof r=="object"){let i={},n=0;for(let[s,o]of Object.entries(r)){if(n>=50){e.debug("nested object exceeds 50 keys; excess dropped");break}let d=ge(o);i[String(s)]=d!==void 0?d:He(o),n++}return i}}}function He(r){try{return JSON.stringify(r)??"null"}catch{return String(r)}}function z(r,e,t){let i={...r},n;for(let s in i)g(s,e,t)&&(n=delete i[s]);return n?i:r}function g(r,e,t){return r?.[0]!=="$"?!1:(t.warn(`${e}: "$"-prefixed keys are reserved; ignored "${r}"`),!0)}function It(r){return r>=500}function We(r){let e={};try{let t=new URL(r,typeof location<"u"?location.href:void 0);e.$net_url=`${t.origin}${t.pathname}`,t.search.length>1&&(e.$net_query=t.search.slice(1)),t.hash.length>1&&(e.$net_fragment=t.hash.slice(1))}catch{e.$net_url=r.slice(0,255)}return e}function Mt(r){try{let e=r?.get("content-length");if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}catch{return}}function Je(r,e){if(typeof fetch!="function")return{stop:()=>{}};let t=fetch,i=r.replace(/\/+$/,""),n=async(s,o)=>{let d=Date.now(),a=typeof s=="string"?s:s instanceof URL?s.href:s.url,u=o?.method??(typeof s=="object"&&"method"in s?s.method:"GET");if(a.startsWith(i))return t(s,o);try{let p=await t(s,o);return It(p.status)&&e({...We(a),$net_method:String(u).toUpperCase(),$net_status:p.status,$net_start:d,$net_end:Date.now(),$net_duration_ms:Date.now()-d,...Nt(o,p)}),p}catch(p){throw e({...We(a),$net_method:String(u).toUpperCase(),$net_error_message:p instanceof Error?p.message.slice(0,255):"network error",$net_start:d,$net_end:Date.now(),$net_duration_ms:Date.now()-d}),p}};return globalThis.fetch=n,{stop:()=>{globalThis.fetch===n&&(globalThis.fetch=t)}}}function Nt(r,e){let t={},i=typeof r?.body=="string"?r.body.length:void 0;i!==void 0&&(t.$net_req_bytes=i);let n=Mt(e.headers);return n!==void 0&&(t.$net_res_bytes=n),t}function B(r){return Math.round(r)}function Qe(){let r,e,t,i=0,n=!1,s,o=[],d=(a,u)=>{try{let p=new PerformanceObserver(l=>u(l.getEntries()));p.observe({type:a,buffered:!0}),o.push(p)}catch{}};d("largest-contentful-paint",a=>{let u=a[a.length-1];u&&(r=B(u.startTime))}),d("paint",a=>{for(let u of a)u.name==="first-contentful-paint"&&(e=B(u.startTime))}),d("layout-shift",a=>{for(let u of a)u.hadRecentInput||(i+=u.value??0,n=!0)}),d("event",a=>{for(let u of a){let p=B(u.duration);(t===void 0||p>t)&&(t=p)}});try{let[a]=performance.getEntriesByType("navigation"),u=a;u?.responseStart!==void 0&&u.responseStart>0&&(s=B(u.responseStart))}catch{}return{snapshot(){let a={};return r!==void 0&&(a.$wv_lcp=r),e!==void 0&&(a.$wv_fcp=e),t!==void 0&&(a.$wv_inp=t),n&&(a.$wv_cls=Math.round(i*1e3)/1e3),s!==void 0&&(a.$wv_ttfb=s),a},hasAny(){return r!==void 0||e!==void 0||t!==void 0||n||s!==void 0},stop(){for(let a of o.splice(0))try{a.disconnect()}catch{}}}}var fe="depsmith_super_props";function Ze(r,e){return r.length===0?(e.warn("register: empty property key ignored"),!1):!g(r,"register",e)}var F=class{constructor(e,t){this.storage=e;this.logger=t;this.properties={};try{let i=this.storage.get(fe);if(i){let n=JSON.parse(i);n&&typeof n=="object"&&!Array.isArray(n)&&(this.properties=n)}}catch{}}register(e){let t=!1;for(let[i,n]of Object.entries(e))Ze(i,this.logger)&&(this.properties[i]=n,t=!0);t&&this.persist()}registerOnce(e){let t=!1;for(let[i,n]of Object.entries(e))Ze(i,this.logger)&&(Object.prototype.hasOwnProperty.call(this.properties,i)||(this.properties[i]=n,t=!0));t&&this.persist()}unregister(e){Object.prototype.hasOwnProperty.call(this.properties,e)&&(delete this.properties[e],this.persist())}clear(){if(Object.keys(this.properties).length!==0){this.properties={};try{this.storage.remove(fe)}catch{}}}current(){return{...this.properties}}persist(){try{this.storage.set(fe,JSON.stringify(this.properties))}catch{this.logger.debug("register: could not persist super properties")}}};var Ut=["$set","$set_once","$append","$prepend","$pre_insert","$post_insert","$remove"],et=50,tt=200;function he(r,e){if(!r||typeof r!="object")return;if(r.$clear_all===!0){let s=Object.keys(r).filter(o=>o!=="$clear_all");return s.length>0&&e.warn(`$clear_all is exclusive; ignored ${s.join(", ")}`),{$clear_all:!0}}let t={},i=new Set,n=(s,o)=>g(s,o,e)?!1:i.has(s)?(e.debug(`"${s}" has an operator already; ${o} dropped`),!1):(i.add(s),!0);for(let s of Ut){let o=r[s];if(!o||typeof o!="object")continue;let d=y(o,e),a={};for(let[u,p]of Object.entries(d))n(u,s)&&(a[u]=p);Object.keys(a).length>0&&(t[s]=a)}if(r.$add&&typeof r.$add=="object"){let s={},o=0;for(let[d,a]of Object.entries(r.$add)){if(o>=et){e.debug(`$add over ${et} keys; excess dropped`);break}if(typeof a!="number"||!Number.isFinite(a)){e.debug(`$add "${d}" is not finite; dropped`);continue}n(d,"$add")&&(s[d]=a,o++)}Object.keys(s).length>0&&(t.$add=s)}if(Array.isArray(r.$unset)){let s=[];for(let o of r.$unset){if(s.length>=tt){e.debug(`$unset over ${tt} keys; excess dropped`);break}typeof o!="string"||o.length===0||n(o,"$unset")&&s.push(o)}s.length>0&&(t.$unset=s)}return Object.keys(t).length>0?t:void 0}function j(r,e){return Object.keys(e).length>0?{[r]:e}:void 0}var rt={now:()=>Date.now()};function h(r){return new Date(r).toISOString().replace(/(\.\d{3})\d*Z$/,"$1Z")}function it(r){return r===0||r===408||r===429||r>=500}var Dt=1e3,Lt=32e3;function nt(r,e=Math.random){let t=Math.min(Dt*2**r,Lt);return Math.round(e()*t)}async function Vt(r){let e=new CompressionStream("gzip"),t=e.writable.getWriter();t.write(new TextEncoder().encode(r)).catch(()=>{}),t.close().catch(()=>{});let i=e.readable.getReader(),n=[];for(;;){let{done:a,value:u}=await i.read();if(a)break;n.push(u)}let s=n.reduce((a,u)=>a+u.length,0),o=new Uint8Array(new ArrayBuffer(s)),d=0;for(let a of n)o.set(a,d),d+=a.length;return o}function st(r){let e=[];for(let t of r)e.push(t.event_id);return e}var qt=3e4,Kt=6e4,zt=10;function Bt(r){return typeof r=="string"?new TextEncoder().encode(r).byteLength:r instanceof Uint8Array?r.byteLength:0}var Y=class{constructor(e,t,i){this.queue=e;this.config=t;this.deps=i;this.inFlight=null}pending(){return this.inFlight??Promise.resolve()}resetNetworkBreaker(){this.deps.breaker?.ok()}flush(){return this.inFlight?this.inFlight:(this.inFlight=this.drain().catch(e=>this.deps.logger.error("flush failed",e)).finally(()=>{this.inFlight=null}),this.inFlight)}async drain(){for(;this.queue.size>0;){if(!this.deps.isOnline()){this.deps.logger.debug("offline; deferring upload");return}if(this.deps.breaker?.open()){this.deps.logger.debug("collector unreachable; uploads paused");return}let e=this.queue.peek(this.config.batchSize);this.queue.persistNow();let t=await this.uploadWithRetry(e);if(t==="requeue")return;t==="dropped"&&this.deps.logger.warn(`dropped poison batch of ${e.length}`),this.queue.remove(st(e))}}async uploadWithRetry(e){let t=this.deps.breaker,i=!1;for(let n=0;n<=this.config.maxRetries;n++){let s=await this.post(e);if(s!==0&&(i=!0),s>=200&&s<300)return t?.ok(),"sent";if(!it(s))return t?.ok(),this.deps.logger.warn(`non-retryable ${s}; dropping batch`),"dropped";if(this.deps.logger.debug(`upload attempt ${n+1} failed (${s})`),s===0&&!i&&t?.suspect())break;n<this.config.maxRetries&&await this.deps.sleep(nt(n))}return i?t?.ok():t?.fail(),"requeue"}buildPayload(e){let t={batch:e,api_key:this.config.apiKey,source:"sdk",sent_at:h(this.deps.clock.now())};return this.config.anonymizeIp&&(t.anonymize_ip=!0),t}async post(e){let t=JSON.stringify(this.buildPayload(e)),i=typeof AbortController<"u"?new AbortController:null,n=null;try{let s=t,o={"Content-Type":"application/json"};if(this.config.compression!=="none"&&typeof CompressionStream<"u")try{s=await Vt(t),o["Content-Encoding"]="gzip"}catch{s=t}let d=Bt(s)<=Kt;d||this.deps.logger.debug("payload over keepalive cap; sending without keepalive");let a={method:"POST",headers:o,body:s,keepalive:d};return i&&(a.signal=i.signal,n=setTimeout(()=>i.abort(),this.timeoutMs())),(await this.deps.fetchFn(`${this.config.endpoint}/e/`,a)).status}catch{return 0}finally{n!==null&&clearTimeout(n)}}timeoutMs(){let e=this.config.requestTimeoutMs;return typeof e=="number"&&e>0?e:qt}sendBeaconAll(){try{if(typeof navigator>"u"||!navigator.sendBeacon)return;let e=0;for(;this.queue.size>0&&e<zt;){let t=this.queue.peek(this.config.batchSize),i=this.buildPayload(t);if(!navigator.sendBeacon(`${this.config.endpoint}/e/`,new Blob([JSON.stringify(i)],{type:"text/plain"})))return;this.queue.remove(st(t)),e++}}catch{}}};var me="depsmith_net_breaker";function ot(r,e){let t=!1,i=0,n=0,s=3e5,o=(u,p,l)=>typeof u=="number"&&u===u?Math.min(Math.max(u,p),l):p,d=()=>{if(!t){t=!0;try{let u=JSON.parse(r.get(me)??"0");if(!Array.isArray(u))return;i=o(u[0],0,3),n=o(u[1],0,e.now()+36e5),s=o(u[2],3e5,36e5)}catch{}}},a=()=>{try{i?r.set(me,JSON.stringify([i,n,s])):r.remove(me)}catch{}};return{open:()=>(d(),e.now()<n),suspect:()=>(d(),i>0),fail:()=>{d(),++i>=3&&(n=e.now()+s,s=Math.min(s*2,36e5),i=3),a()},ok:()=>{d(),i&&(i=n=0,s=3e5,a())}}}var X=class{constructor(e){this.enabled=e}setEnabled(e){this.enabled=e}debug(...e){this.enabled&&console.debug("[depsmith-sdk]",...e)}warn(...e){this.enabled&&console.warn("[depsmith-sdk]",...e)}error(...e){this.enabled&&console.error("[depsmith-sdk]",...e)}};var at=255,x=class{constructor(e,t={}){this.vitalsReported=!1;this.flushTimer=null;this.drained=!1;this.teardownFns=[];this.ready=Promise.resolve();this.config=Te(e),this.logger=new X(this.config.debug),this.clock=t.clock??rt,this.storage=t.storage??this.pickStorage(),this.contextProvider=t.contextProvider,this.pageLife=new O({now:()=>this.clock.now(),capture:(n,s,o,d,a)=>this.capture(n,s,o,void 0,void 0,d,a)},this.config);let i=this.config.childSafeMode?new v:this.config.storage==="memory"?this.storage:new L(this.storage,new D(this.config.cookieDomain||void 0));this.identity=new q(i,this.clock),this.session=new K(this.storage,this.clock,this.config.sessionTimeoutMs,t.schedule),this.consent=new M(this.storage,this.config.consentMode,this.config.respectDnt&&(t.dnt??Fe())),this.attribution=new A(i),this.superProperties=new F(this.storage,this.logger),!this.contextProvider&&typeof window<"u"&&window.location&&(this.attribution.recordLanding(window.location.href,typeof document<"u"?document.referrer:""),this.pageLife.start(window.location.href,typeof document<"u"?document.referrer:"")),this.queue=new U(this.storage,this.config.maxQueueSize,this.logger,{maxChars:this.config.maxQueueBytes,schedule:t.schedule}),this.detectConfigDrift(),this.config.deviceFingerprinting&&!this.config.childSafeMode&&Me(),this.config.geolocation&&!this.config.childSafeMode&&ze(),this.storage instanceof _&&(this.ready=this.storage.hydrate().then(n=>{try{let s=n.get("depsmith_queue");s&&this.queue.prepend(JSON.parse(s))}catch{this.logger.warn("persisted queue corrupt; discarded")}})),this.uploader=new Y(this.queue,{endpoint:this.config.endpoint,apiKey:this.config.apiKey,batchSize:this.config.batchSize,maxRetries:this.config.maxRetries,compression:this.config.compression,anonymizeIp:this.config.anonymizeIp,requestTimeoutMs:t.requestTimeoutMs},{fetchFn:t.fetchFn??((...n)=>fetch(...n)),clock:this.clock,logger:this.logger,sleep:t.sleep??(n=>new Promise(s=>setTimeout(s,n))),isOnline:t.isOnline??(()=>typeof navigator>"u"?!0:navigator.onLine!==!1),breaker:ot(this.storage,this.clock)}),t.manualLifecycle||(this.startFlushTimer(),this.attachLifecycle(),this.startAutocapture()),this.logger.debug("initialized",{endpoint:this.config.endpoint})}track(e,t){this.trackInternal(e,z(t,"track",this.logger))}trackInternal(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("track: event name required");return}g(e,"track",this.logger)||this.tooLong(e,"track: event name")||this.capture(e,"track",t)})}traits(e,t){return y(z(e,t,this.logger),this.logger)}tooLong(e,t){return e.length<=at?!1:(this.logger.warn(`${t} exceeds ${at} characters (got ${e.length}); dropped`),!0)}page(e,t,i){this.pageInternal(e,z(t,"page",this.logger),i)}pageInternal(e,t,i){this.guard(()=>this.pageLife.manual(e,t,i?.type))}emitWebVitals(){this.vitalsReported||!this.vitals?.hasAny()||(this.vitalsReported=!0,this.capture("$web_vitals","track",this.vitals.snapshot()))}screen(e,t,i){this.page(e,t,i)}identify(e,t){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("identify: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("identify: userId required");return}if(this.tooLong(e,"identify: userId"))return;this.identity.identify(e);let i=this.traits(t,"identify");this.capture("$identify","identify",void 0,i,j("$set",i))})}alias(e){this.guard(()=>{if(this.config.childSafeMode){this.logger.warn("alias: disabled in childSafeMode (COPPA)");return}if(typeof e!="string"||e.length===0){this.logger.warn("alias: aliasId required");return}this.capture("$alias","alias",{alias:e})})}reset(){this.guard(()=>{this.pageLife.flushPending(),this.identity.reset(),this.session.rotate(),this.attribution.clear(),this.superProperties.clear(),this.logger.debug("reset: identity, session and attribution cleared")})}group(e,t){this.guard(()=>{if(typeof e!="string"||e.length===0){this.logger.warn("group: groupId required");return}if(this.tooLong(e,"group: groupId"))return;this.identity.setGroup(e);let i=this.traits(t,"group");this.capture("$group","group",void 0,i)})}setGroupTraits(e){this.guard(()=>{if(!this.identity.groupId){this.logger.warn("setGroupTraits: no group set");return}let t=this.traits(e,"setGroupTraits");this.capture("$group","group",void 0,t)})}setProperty(e,t){this.guard(()=>{if(g(e,"setProperty",this.logger))return;this.identity.setUserProp(e,t);let i=y({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,j("$set",i))})}setOnceProperty(e,t){this.guard(()=>{if(g(e,"setOnceProperty",this.logger))return;if(this.identity.hasUserProp(e)){this.logger.debug(`setOnceProperty: "${e}" already set`);return}this.identity.setUserProp(e,t);let i=y({[e]:t},this.logger);this.capture("$identify","identify",void 0,i,j("$set_once",i))})}unsetProperty(e){this.guard(()=>{g(e,"unsetProperty",this.logger)||(this.identity.unsetUserProp(e),this.capture("$identify","identify",void 0,{[e]:null},he({$unset:[e]},this.logger)))})}register(e){this.guard(()=>this.superProperties.register(e))}registerOnce(e){this.guard(()=>this.superProperties.registerOnce(e))}unregister(e){this.guard(()=>this.superProperties.unregister(e))}setUserProperties(e){this.guard(()=>{let t=he(e,this.logger);t&&this.capture("$identify","identify",void 0,void 0,t)})}optIn(){this.guard(()=>{this.consent.optIn(),this.logger.debug("consent granted"),this.flushUploads()})}optOut(){this.guard(()=>{this.pageLife.discardPending(),this.consent.optOut(),this.queue.clear(),this.logger.debug("consent denied; queue cleared")})}async flush(){try{if(!this.consent.canUpload()){this.logger.debug("flush skipped: consent not granted");return}await this.flushUploads()}catch(e){this.logger.error("flush error",e)}}autocapture(e){this.guard(()=>this.capture("$autocapture","autocapture",e))}drainInFlight(){return this.uploader.pending()}getAnonymousId(){return this.identity.anonymousId}getSessionId(){return this.session.peek()}setSessionId(e,t){this.guard(()=>{(typeof e!="string"||!this.session.adopt(e,t))&&this.logger.warn(`setSessionId: expected a UUIDv7; ignored "${String(e)}"`)})}shutdown(){this.guard(()=>this.pageLife.flushPending()),this.flushTimer!==null&&clearInterval(this.flushTimer),this.flushTimer=null;for(let e of this.teardownFns.splice(0))e();this.persistNow()}persistNow(){try{this.queue.persistNow(),this.session.persistNow()}catch{}}enqueueEvent(e){this.queue.enqueue(e),this.drained=!1}flushUploads(){return this.ready.then(()=>this.uploader.flush())}contextOptions(){let e;try{e=this.contextProvider?.()}catch{}return{fingerprint:this.config.deviceFingerprinting&&!this.config.childSafeMode&&this.consent.current==="granted",geolocation:this.config.geolocation&&!this.config.childSafeMode&&this.consent.current==="granted",overrides:e,tracking:this.config.trackingOptions,attribution:this.attribution,page:this.pageLife.tracking()}}sessionInSample(e){return this.config.sampleRate>=1?!0:Re(`${this.config.apiKey}:${e}`)<this.config.sampleRate}inSample(e,t){return t==="identify"||t==="alias"||t==="group"?!0:this.sessionInSample(e)}capture(e,t,i,n,s,o,d){if(!this.consent.canCapture()){this.logger.debug(`capture dropped (consent denied): ${e}`);return}let a=this.session.touch();if(a.startedSession&&this.pageLife.newSession(),a.endedSession&&this.sessionInSample(a.endedSession.id)&&this.enqueueSessionEnd(a.endedSession),a.startedSession&&this.sessionInSample(a.startedSession.id)&&this.enqueueSessionStart(a.startedSession),!this.inSample(a.sessionId,t)){this.logger.debug(`capture dropped (out of sample): ${e}`);return}let u=o??this.clock.now(),p=this.contextOptions();d&&(p.page=d);let l={event_id:f(u),event:e,event_type:t,timestamp:h(u),session_id:a.sessionId,session_started_at:h(a.startedAt),anonymous_id:this.identity.anonymousId,context:n?{...k(p),traits:n}:k(p),platform:"web",sdk_version:b};s&&(l.user_properties=s);let ye={...this.config.defaultProperties,...this.superProperties.current(),...y(i,this.logger)};Object.keys(ye).length>0&&(l.properties=ye);let be=this.identity.userId;be&&(l.user_id=be);let Se=this.identity.groupId;Se&&(l.group_id=Se),p.fingerprint&&(l.device_id=R()),this.enqueueEvent(l),this.logger.debug(`captured ${e}`,l),this.queue.size>=this.config.batchSize&&this.consent.canUpload()&&this.flushUploads()}detectConfigDrift(){let e="depsmith_config_fp",t=Z(this.config.apiKey),i=this.storage.get(e);i!==null&&i!==t&&(this.logger.warn("apiKey changed since last run; dropping queued events for the old project"),this.queue.clear()),this.storage.set(e,t)}pickStorage(){return this.config.storage==="memory"?new v:this.config.storage==="indexeddb"&&typeof indexedDB<"u"?new _:Xe()}enqueueSessionEnd(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_end dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:f(this.clock.now()),event:"$session_end",event_type:"session_end",timestamp:h(e.lastActivityAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:k(t),platform:"web",sdk_version:b},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=R()),this.enqueueEvent(i)}enqueueSessionStart(e){if(this.config.sessionEvents==="derive")return;if(!this.consent.canCapture()){this.logger.debug("session_start dropped (consent denied)");return}let t=this.contextOptions(),i={event_id:f(this.clock.now()),event:"$session_start",event_type:"session_start",timestamp:h(e.startedAt),session_id:e.id,session_started_at:h(e.startedAt),anonymous_id:this.identity.anonymousId,context:k(t),platform:"web",sdk_version:b},n=this.identity.userId;n&&(i.user_id=n),t.fingerprint&&(i.device_id=R()),t.fingerprint&&(i.properties={...i.properties,...De()}),this.enqueueEvent(i)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()},this.config.batchIntervalMs)}attachLifecycle(){if(typeof window>"u"||typeof document>"u")return;let e=()=>{this.drained||(this.guard(()=>this.emitWebVitals()),this.guard(()=>this.leaveOnUnload?.()),this.drained=!0,this.consent.canUpload()&&this.uploader.sendBeaconAll(),this.persistNow())},t=()=>{if(document.visibilityState==="hidden")e();else{this.drained=!1;let s=this.session.touch();s.endedSession&&this.enqueueSessionEnd(s.endedSession),s.startedSession&&(this.pageLife.newSession(),this.enqueueSessionStart(s.startedSession))}},i=s=>{this.drained=!1,this.pageLife.restored(s.persisted)},n=()=>{this.uploader.resetNetworkBreaker(),this.queue.size>0&&this.consent.canUpload()&&this.flushUploads()};window.addEventListener("pagehide",e),window.addEventListener("pageshow",i),document.addEventListener("visibilitychange",t),window.addEventListener("online",n),this.teardownFns.push(()=>{window.removeEventListener("pagehide",e),window.removeEventListener("pageshow",i),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",n)})}startAutocapture(){let e=this.config.autocapture;if(!e||typeof window>"u")return;typeof PerformanceObserver<"u"&&(this.vitals=Qe(),this.teardownFns.push(()=>this.vitals?.stop()));let t=Je(this.config.endpoint,i=>this.guard(()=>this.capture("$network_request","track",i)));this.teardownFns.push(()=>t.stop()),xe().then(i=>{i&&(this.teardownFns.push(i.startAutocapture(e,{emit:n=>this.autocapture(n),page:n=>this.guard(()=>this.pageLife.autoPageView(n)),pageLeave:n=>this.guard(()=>this.pageLife.leave(n)),warn:n=>this.logger.warn(n),armUnloadLeave:n=>{this.leaveOnUnload=n}})),this.teardownFns.push(()=>{this.leaveOnUnload=void 0}))}).catch(i=>this.logger.debug("autocapture load failed",i))}guard(e){try{e()}catch(t){this.logger.error("internal error",t)}}};var c=null,ve=null,pi={init(r,e){try{return c&&ve===r.apiKey||(c?.shutdown(),c=new x(r,e),ve=r.apiKey),c}catch(t){return r?.debug&&console.error("[depsmith-sdk] init failed:",t),null}},track:(r,e)=>c?.track(r,e),page:(r,e,t)=>c?.page(r,e,t),screen:(r,e,t)=>c?.screen(r,e,t),identify:(r,e)=>c?.identify(r,e),alias:r=>c?.alias(r),reset:()=>c?.reset(),group:(r,e)=>c?.group(r,e),setGroupTraits:r=>c?.setGroupTraits(r),setProperty:(r,e)=>c?.setProperty(r,e),setOnceProperty:(r,e)=>c?.setOnceProperty(r,e),unsetProperty:r=>c?.unsetProperty(r),setUserProperties:r=>c?.setUserProperties(r),register:r=>c?.register(r),registerOnce:r=>c?.registerOnce(r),unregister:r=>c?.unregister(r),optIn:()=>c?.optIn(),optOut:()=>c?.optOut(),flush:()=>c?.flush()??Promise.resolve(),getAnonymousId:()=>c?.getAnonymousId(),getSessionId:()=>c?.getSessionId(),setSessionId:(r,e)=>c?.setSessionId(r,e),shutdown(){c?.shutdown(),c=null,ve=null}};export{de as AsyncMirrorAdapter,Ye as DEPSMITH_SDK_STORAGE_KEYS,pi as DepsmithSdk,x as DepsmithSdkClient,P as idleScheduler,At as syncScheduler};
2
2
  //# sourceMappingURL=index.js.map