@prodantix/sdk 0.1.0-beta.351 → 0.2.0-beta.357

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/web.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { P as ProdantixClient } from './client-Ca6xJESF.js';
2
- import { T as Transport, h as TransportRequest, P as ProdantixConfig } from './types-68Sc11g8.js';
3
- import { a as FetchTransportOptions } from './transport-CTPih3Jj.js';
1
+ import { P as ProdantixClient } from './client-BQlU_3Dc.js';
2
+ import { T as Transport, i as TransportRequest, a as StorageAdapter, b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.js';
3
+ import { a as FetchTransportOptions } from './transport-CqAmRbpQ.js';
4
4
  import { F as FetchLike } from './http-BCh716Vs.js';
5
5
 
6
6
  interface AutocaptureOptions {
@@ -81,11 +81,67 @@ interface SessionReplayOptions {
81
81
  * `stop()` it. A missing `sessionId` gets a fresh v4 uuid. */
82
82
  declare function installSessionReplay(options: SessionReplayOptions): SessionRecorder;
83
83
 
84
+ interface CookieJar {
85
+ cookie: string;
86
+ }
87
+ interface CookieStorageOptions {
88
+ domain?: string;
89
+ hostname?: string;
90
+ jar?: CookieJar;
91
+ name: string;
92
+ random?: () => string;
93
+ secure?: boolean;
94
+ }
95
+ declare function resolveCookieDomain(hostname: string, jar: CookieJar, secure: boolean, random?: () => string): string | undefined;
96
+ declare function createCookieStorage(options: CookieStorageOptions): StorageAdapter | null;
97
+
98
+ interface Carry {
99
+ anonymousId: string;
100
+ sessionId: string;
101
+ sessionStartedAt: number;
102
+ }
103
+ interface AnchorLike {
104
+ href: string;
105
+ }
106
+ interface LocationLike {
107
+ hash: string;
108
+ hostname: string;
109
+ pathname: string;
110
+ search: string;
111
+ }
112
+ interface HistoryLike {
113
+ readonly state: unknown;
114
+ replaceState(data: unknown, unused: string, url?: string | null): void;
115
+ }
116
+ interface DocumentLike {
117
+ addEventListener(type: string, listener: (event: unknown) => void, capture?: boolean): void;
118
+ location?: {
119
+ hostname: string;
120
+ } | null;
121
+ removeEventListener(type: string, listener: (event: unknown) => void, capture?: boolean): void;
122
+ }
123
+ interface CarryClient {
124
+ readonly anonymousId: string;
125
+ consent?(): Consent | null;
126
+ readonly sessionId: string | undefined;
127
+ readonly sessionStartedAt: number | undefined;
128
+ }
129
+ declare function decorateLink(anchor: AnchorLike, carry: Carry, linkedDomains: readonly string[], currentHost: string): void;
130
+ declare function readCarry(search: string): Carry | undefined;
131
+ declare function stripCarry(history: HistoryLike, location: LocationLike): void;
132
+ declare function installLinkCarry(doc: DocumentLike, client: CarryClient, linkedDomains: readonly string[]): () => void;
133
+
84
134
  /** Tunables for the built-in session replay, minus the identity fields
85
135
  * `createWebClient` fills in (apiKey, distinctId, replayHost). */
86
136
  type WebSessionReplayOptions = Pick<SessionReplayOptions, 'flushIntervalMs' | 'mask' | 'maxEvents' | 'sessionId'>;
87
137
  interface WebClientOptions extends ProdantixConfig {
88
138
  autocaptureOptions?: AutocaptureOptions;
139
+ cookieDomain?: string;
140
+ /** Registrable domains whose links carry the visitor's anonymous id and
141
+ * session in a `_pdx` query parameter, because a cookie cannot cross a
142
+ * registrable domain. Empty by default. Readonly so a caller hands over the
143
+ * shared platform list as it is, rather than copying it to satisfy a type. */
144
+ linkedDomains?: readonly string[];
89
145
  /** Host of the recorder service (`eu.replay.prodantix.com`). Required to enable
90
146
  * session replay. */
91
147
  replayHost?: string;
@@ -96,4 +152,4 @@ interface WebClientOptions extends ProdantixConfig {
96
152
  }
97
153
  declare function createWebClient(options: WebClientOptions): ProdantixClient;
98
154
 
99
- export { type AutocaptureOptions, type MaskOptions, type SessionReplayOptions, type WebClientOptions, type WebSessionReplayOptions, WebTransport, createWebClient, installAutocapture, installSessionReplay };
155
+ export { type AutocaptureOptions, type Carry, Consent, type CookieJar, type CookieStorageOptions, type MaskOptions, type SessionReplayOptions, type WebClientOptions, type WebSessionReplayOptions, WebTransport, createCookieStorage, createWebClient, decorateLink, installAutocapture, installLinkCarry, installSessionReplay, readCarry, resolveCookieDomain, stripCarry };
package/dist/web.js CHANGED
@@ -1,2 +1,2 @@
1
- import {r,g as g$1,f as f$1,s}from'./chunk-CSIP3PZ7.js';import'./chunk-V77KYPOF.js';import {a as a$1,d as d$1}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';function w(){return globalThis.location}function S(){return globalThis.document}function D(){return globalThis.window??globalThis}function V(e){return typeof e=="object"&&e!==null&&typeof e.tagName=="string"}function O(){let e=w(),t=S(),n={};return e&&(n.$current_url=e.href,n.$pathname=e.pathname,n.$host=e.host),t&&(t.title&&(n.$title=t.title),t.referrer&&(n.$referrer=t.referrer)),n}function H(e){let t={$el_tag:e.tagName.toLowerCase(),$event_type:"click"},n=e.textContent?.trim();n&&(t.$el_text=n.slice(0,255)),e.id&&(t.$el_id=e.id),typeof e.className=="string"&&e.className&&(t.$el_classes=e.className);let i=e.getAttribute("href");return i&&(t.$el_href=i),t}function $(e){let t=globalThis.history,n=D(),i="",r=()=>{let a=w(),l=a?`${a.pathname}${a.search}`:"";l!==i&&(i=l,e.capture("$pageview",{properties:O()}));};if(r(),!t||!n)return ()=>{};let s=t.pushState.bind(t),p=t.replaceState.bind(t);return t.pushState=(...a)=>{s(...a),r();},t.replaceState=(...a)=>{p(...a),r();},n.addEventListener("popstate",r),()=>{t.pushState=s,t.replaceState=p,n.removeEventListener("popstate",r);}}function K(e){let t=S();if(!t)return ()=>{};let n=i=>{let r=i.target;V(r)&&e.capture("$autocapture",{properties:{...O(),...H(r)}});};return t.addEventListener("click",n,true),()=>t.removeEventListener("click",n,true)}function I(e,t={}){let n=[];return (t.pageviews??true)&&n.push($(e)),(t.clicks??true)&&n.push(K(e)),()=>{for(let i of n)i();}}function F(){return globalThis.document?.visibilityState==="hidden"}function B(e){let t=globalThis.navigator,n=globalThis.Blob;if(!t?.sendBeacon||!n)return false;let i=JSON.stringify({...e.body,api_key:e.projectKey});try{let r=new n([i],{type:"application/json"});return t.sendBeacon(e.url,r)}catch{return false}}var c=class{constructor(t={}){a(this,"fetchTransport");this.fetchTransport=new r(t);}async send(t){F()&&B(t)||await this.fetchTransport.send(t);}};var R={maskAllInputs:true,maskAllText:false},W=new Set(["email","password","tel"]);function A(e){return e.replace(/\S/g,"*")}function d(e,t,n){return z(t)||n.maskAllInputs?A(e):e}function f(e,t){return t.maskAllText?A(e):e}function z(e){return W.has((e??"").toLowerCase())}var U=5e3,m=class{constructor(t){this.options=t;a(this,"buffer",[]);a(this,"seq",0);a(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,t.maxEvents),U);}add(t){return this.buffer.push(t),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let t=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:t,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var v=1,k=3,q=9,h=class{constructor(){a(this,"next",1);}allocate(){let t=this.next;return this.next+=1,t}},j=new Set(["NOSCRIPT","SCRIPT"]);function g(e,t,n,i){if(e.nodeType===k){let r=t.allocate();return i?.(e,r),{id:r,textContent:f(e.textValue??"",n),type:"text"}}if(e.nodeType===q){let r=t.allocate();return i?.(e,r),{childNodes:M(e,t,n,i),id:r,type:"document"}}if(e.nodeType===v){let r=e.tagName??"";if(j.has(r))return null;let s=t.allocate();return i?.(e,s),{attributes:X(e,n),childNodes:M(e,t,n,i),id:s,tagName:r,type:"element"}}return null}function M(e,t,n,i){let r=[];for(let s of e.childNodes??[]){let p=g(s,t,n,i);p&&r.push(p);}return r}function X(e,t){let n={};for(let i of e.attributes??[])n[i.name]=i.value;return e.inputValue!==void 0&&(n.value=d(e.inputValue,e.inputType,t)),n}async function P(e,t){let n=`${d$1(t.replayHost)}/v1/replay`;return (await t.fetch(n,{body:JSON.stringify(e),headers:{authorization:`Bearer ${t.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var C=new Set(["INPUT","SELECT","TEXTAREA"]),y=class{constructor(t){this.options=t;a(this,"allocator",new h);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new m({distinctId:t.distinctId,masked:t.mask.maskAllInputs,maxEvents:t.maxEvents,now:t.now,sessionId:t.sessionId}),this.fetchImpl=a$1(t.fetch);}start(){if(this.started)return;let t=Y(),n=t?.documentElement;!t||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(t),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(t){let n=g(this.adapt(t),this.allocator,this.options.mask,(i,r)=>{let s=i.ref;s&&this.mirror.set(s,r);});n&&this.push(2,{node:n});}observeMutations(t){let n=globalThis.MutationObserver;n&&(this.observer=new n(i=>{for(let r of i)this.handleMutation(r);}),this.observer.observe(t,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(t){if(t.type==="characterData"){let n=this.mirror.get(t.target);n!==void 0&&this.push(3,{texts:[{id:n,value:f(t.target.textContent??"",this.options.mask)}]});return}if(t.type==="attributes"&&t.attributeName){let n=this.mirror.get(t.target),i=t.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[t.attributeName]:i.getAttribute(t.attributeName)??""},id:n}]});return}if(t.type==="childList"){let n=this.mirror.get(t.target);if(n===void 0)return;for(let i of Array.from(t.addedNodes)){let r=g(this.adapt(i),this.allocator,this.options.mask,(s,p)=>{let a=s.ref;a&&this.mirror.set(a,p);});r&&this.push(3,{adds:[{node:r,parentId:n}]});}for(let i of Array.from(t.removedNodes)){let r=this.mirror.get(i);r!==void 0&&(this.push(3,{removes:[{id:r,parentId:n}]}),this.mirror.delete(i));}}}observeInteractions(t){t.addEventListener("input",n=>{let i=n.target;if(!i||!C.has(i.tagName))return;let r=this.mirror.get(i);r!==void 0&&this.push(3,{input:{id:r,value:d(i.value??"",i.type,this.options.mask)}});},true),t.addEventListener("scroll",n=>{let i=n.target,r=i?this.mirror.get(i):void 0;this.push(3,{scroll:{id:r??0,x:i?.scrollLeft??0,y:i?.scrollTop??0}});},true);}adapt(t){let n={childNodes:[],nodeType:t.nodeType,ref:t};if(t.nodeType===k)return n.textValue=t.textContent??"",n;if(t.nodeType===v){let i=t;if(n.tagName=i.tagName,n.attributes=Array.from(i.attributes).map(r=>({name:r.name,value:r.value})),C.has(i.tagName)){let r=i;n.inputType=r.type,n.inputValue=r.value??"";}}return n.childNodes=Array.from(t.childNodes).map(i=>this.adapt(i)),n}push(t,n){let i=this.chunker.add({data:n,timestamp:this.options.now(),type:t});i&&this.upload(i);}upload(t){!t||!this.fetchImpl||P(t,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Y(){return globalThis.document}function _(e){let t=new y({apiKey:e.apiKey,distinctId:e.distinctId,flushIntervalMs:e.flushIntervalMs??5e3,mask:{...R,...e.mask},maxEvents:e.maxEvents??200,now:e.now??(()=>Date.now()),onError:e.onError,replayHost:e.replayHost,sessionId:e.sessionId??g$1()});return t.start(),t}function G(){return globalThis.navigator}function J(e){let t=e?.userAgentData?.platform??e?.platform;return t?t.slice(0,50):void 0}function Q(e){let t=()=>{e.flush();};globalThis.document?.addEventListener?.("visibilitychange",t),globalThis.addEventListener?.("pagehide",t);}function It(e){let{autocaptureOptions:t,replayHost:n,sessionReplay:i,sessionReplayOptions:r,...s$1}=e,p=G(),a={...s$1,locale:s$1.locale??(p?.language?p.language.slice(0,20):void 0),os:s$1.os??J(p),storage:s$1.storage??f$1(),transport:s$1.transport??new c({maxRetries:s$1.maxRetries,requestTimeoutMs:s$1.requestTimeoutMs})},l=new s(a);return Q(l),(e.autocapture??true)&&I(l,t),i&&n&&_({apiKey:a.apiKey,distinctId:()=>l.distinctId,onError:a.onError,replayHost:n,...r}),l}export{c as WebTransport,It as createWebClient,I as installAutocapture,_ as installSessionReplay};//# sourceMappingURL=web.js.map
1
+ import {x as x$1,i,h as h$1,f as f$1,g as g$1,l as l$1,y as y$1,u,w as w$1}from'./chunk-5CBVQAZ2.js';import'./chunk-V77KYPOF.js';import {a as a$1,d}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';function B(){return globalThis.location}function q(){return globalThis.document}function me(){return globalThis.window??globalThis}function he(t){return typeof t=="object"&&t!==null&&typeof t.tagName=="string"}function X(){let t=B(),e=q(),n={};return t&&(n.$current_url=t.href,n.$pathname=t.pathname,n.$host=t.host),e&&(e.title&&(n.$title=e.title),e.referrer&&(n.$referrer=e.referrer)),n}function ge(t){let e={$el_tag:t.tagName.toLowerCase(),$event_type:"click"},n=t.textContent?.trim();n&&(e.$el_text=n.slice(0,255)),t.id&&(e.$el_id=t.id),typeof t.className=="string"&&t.className&&(e.$el_classes=t.className);let r=t.getAttribute("href");return r&&(e.$el_href=r),e}function ye(t){let e=globalThis.history,n=me(),r="",i=()=>{let s=B(),c=s?`${s.pathname}${s.search}`:"";c!==r&&(r=c,t.capture("$pageview",{properties:X()}));};if(i(),!e||!n)return ()=>{};let o=e.pushState.bind(e),a=e.replaceState.bind(e);return e.pushState=(...s)=>{o(...s),i();},e.replaceState=(...s)=>{a(...s),i();},n.addEventListener("popstate",i),()=>{e.pushState=o,e.replaceState=a,n.removeEventListener("popstate",i);}}function ke(t){let e=q();if(!e)return ()=>{};let n=r=>{let i=r.target;he(i)&&t.capture("$autocapture",{properties:{...X(),...ge(i)}});};return e.addEventListener("click",n,true),()=>e.removeEventListener("click",n,true)}function G(t,e={}){let n=[];return (e.pageviews??true)&&n.push(ye(t)),(e.clicks??true)&&n.push(ke(t)),()=>{for(let r of n)r();}}function ve(){return globalThis.document?.visibilityState==="hidden"}function be(t){let e=globalThis.navigator,n=globalThis.Blob;if(!e?.sendBeacon||!n)return false;let r=JSON.stringify({...t.body,api_key:t.projectKey});try{let i=new n([r],{type:"application/json"});return e.sendBeacon(t.url,i)}catch{return false}}var f=class{constructor(e={}){a(this,"fetchTransport");this.fetchTransport=new x$1(e);}async send(e){ve()&&be(e)||await this.fetchTransport.send(e);}};var xe=/^\d{1,3}(\.\d{1,3}){3}$/,Le=/^[a-z0-9.-]+$/i;function Y(){return Math.random().toString(36).slice(2,12)}function m(t,e){let n=`${e}=`,r=[];for(let i of t.cookie.split(";")){let o=i.trim();o.startsWith(n)&&r.push(o.slice(n.length));}return r}function l(t,e,n){let r=["Path=/",`Max-Age=${e}`,"SameSite=Lax"];return t&&r.push(`Domain=${t}`),n&&r.push("Secure"),r.join("; ")}function Q(t,e,n,r){try{let i=`pdx_probe_${r()}`,o=r();t.cookie=`${i}=${o}; ${l(e,60,n)}`;let a=m(t,i).includes(o);t.cookie=`${i}=; ${l(e,0,n)}`;let s=m(t,i).includes(o);return a&&!s}catch{return false}}function C(t){let e=t.replace(/^\[|\]$/g,"").toLowerCase();if(e.includes(":")||xe.test(e)||!e.includes("."))return [];let n=e.split("."),r=[];for(let i=n.length-2;i>=0;i-=1)r.push(n.slice(i).join("."));return r}function Z(t,e,n,r=Y){for(let i of C(t))if(Q(e,i,n,r))return i}function Ee(t){let e=new Map,n=JSON.parse(decodeURIComponent(t));if(n===null||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n))typeof i=="string"&&e.set(r,i);return e}var S=class{constructor(e,n,r,i){this.jar=e;this.name=n;this.domain=r;this.secure=i;}getItem(e){return this.read().get(e)??null}setItem(e,n){let r=this.read();r.set(e,n),this.write(r);}removeItem(e){let n=this.read();n.delete(e)&&this.write(n);}read(){try{let e=m(this.jar,this.name);e.length>1&&this.domain&&(this.jar.cookie=`${this.name}=; ${l(void 0,0,this.secure)}`,e=m(this.jar,this.name));let n=e[0];return n?Ee(n):new Map}catch{return new Map}}write(e){try{if(e.size===0){this.jar.cookie=`${this.name}=; ${l(this.domain,0,this.secure)}`;return}let n=encodeURIComponent(JSON.stringify(Object.fromEntries(e)));this.jar.cookie=`${this.name}=${n}; ${l(this.domain,31536e3,this.secure)}`;}catch{return}}};function Se(){return globalThis.document}function Ce(){return globalThis.location?.hostname??""}function we(){return globalThis.location?.protocol==="https:"}function Te(t){if(t===void 0)return;let e=t.startsWith(".")?t.slice(1):t;return Le.test(e)?e.toLowerCase():void 0}function w(t){let e="jar"in t?t.jar:Se();if(!e||globalThis.navigator?.cookieEnabled===false)return null;let r=t.random??Y,i=t.secure??we(),o=t.hostname??Ce();try{let a=Te(t.domain)??Z(o,e,i,r);return Q(e,a,i,r)?new S(e,t.name,a,i):null}catch{return null}}var ne="_pdx",re="~",Ae=200,Ne=/^\d+$/;function ie(t,e,n,r){let i=Oe(t.href);if(i===void 0||A(i.search).some(N))return;let o=ee(i.hostname,n);o===void 0||o===ee(r,n)||(i.search=`${i.search}${i.search?"&":"?"}${ne}=${Ie(e)}`,t.href=i.href);}function Ie(t){return [t.anonymousId,t.sessionId,String(t.sessionStartedAt)].map(Pe).join(re)}function oe(t){let e=A(t).find(N);if(e===void 0)return;let n=Re(e).split(re);if(n.length!==3)return;let r=h(n[0]),i=h(n[1]),o=h(n[2]);if(!(!te(r)||!te(i)||!Me(o)))return {anonymousId:r,sessionId:i,sessionStartedAt:Number(o)}}function se(t,e){let n=A(e.search),r=n.filter(o=>!N(o));if(r.length===n.length)return;let i=r.length>0?`?${r.join("&")}`:"";t.replaceState(t.state,"",`${e.pathname}${i}${e.hash}`);}function ae(t){if(t.location===void 0||typeof t.location.search!="string")return;let e=oe(t.location.search);if(e===void 0)return;let n=u(t.storage,t.shared,t.namespace,e.anonymousId);return w$1(t.shared,t.namespace,{id:e.sessionId,startedAt:e.sessionStartedAt},t.now),t.history!==void 0&&se(t.history,t.location),n}function T(t,e,n){if(n.length===0)return ()=>{};let r=i=>{let o=De(i.target);if(o===void 0)return;let a=_e(e);a!==void 0&&ie(o,a,n,t.location?.hostname??"");};return t.addEventListener("click",r,true),t.addEventListener("auxclick",r,true),()=>{t.removeEventListener("click",r,true),t.removeEventListener("auxclick",r,true);}}function Oe(t){try{let e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"?e:void 0}catch{return}}function ee(t,e){let n=e.map(r=>r.replace(/^\./,"").toLowerCase());return C(t).find(r=>n.includes(r))}function A(t){return t.replace(/^\?/,"").split("&").filter(e=>e!=="")}function N(t){let e=t.indexOf("=");return h(e===-1?t:t.slice(0,e))===ne}function Re(t){let e=t.indexOf("=");return e===-1?"":t.slice(e+1)}function Pe(t){return encodeURIComponent(t).replace(/~/g,"%7E")}function h(t){try{return decodeURIComponent(t)}catch{return}}function te(t){if(t===void 0)return false;let e=i(t);return e>=1&&e<=Ae}function Me(t){return t!==void 0&&Ne.test(t)&&Number.isSafeInteger(Number(t))}function _e(t){if(t.consent?.()?.identityLink===false)return;let e=t.sessionId,n=t.sessionStartedAt;if(!(e===void 0||n===void 0))return {anonymousId:t.anonymousId,sessionId:e,sessionStartedAt:n}}function $e(t){return typeof t.tagName=="string"&&t.tagName.toUpperCase()==="A"&&typeof t.href=="string"}function De(t){let e=typeof t=="object"?t:null;for(;e;){if($e(e))return e;e=e.parentElement??null;}}var ue={maskAllInputs:true,maskAllText:false},He=new Set(["email","password","tel"]);function de(t){return t.replace(/\S/g,"*")}function g(t,e,n){return je(e)||n.maskAllInputs?de(t):t}function y(t,e){return e.maskAllText?de(t):t}function je(t){return He.has((t??"").toLowerCase())}var Ve=5e3,k=class{constructor(e){this.options=e;a(this,"buffer",[]);a(this,"seq",0);a(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,e.maxEvents),Ve);}add(e){return this.buffer.push(e),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let e=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:e,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var I=1,O=3,Ke=9,v=class{constructor(){a(this,"next",1);}allocate(){let e=this.next;return this.next+=1,e}},Fe=new Set(["NOSCRIPT","SCRIPT"]);function b(t,e,n,r){if(t.nodeType===O){let i=e.allocate();return r?.(t,i),{id:i,textContent:y(t.textValue??"",n),type:"text"}}if(t.nodeType===Ke){let i=e.allocate();return r?.(t,i),{childNodes:ce(t,e,n,r),id:i,type:"document"}}if(t.nodeType===I){let i=t.tagName??"";if(Fe.has(i))return null;let o=e.allocate();return r?.(t,o),{attributes:Ue(t,n),childNodes:ce(t,e,n,r),id:o,tagName:i,type:"element"}}return null}function ce(t,e,n,r){let i=[];for(let o of t.childNodes??[]){let a=b(o,e,n,r);a&&i.push(a);}return i}function Ue(t,e){let n={};for(let r of t.attributes??[])n[r.name]=r.value;return t.inputValue!==void 0&&(n.value=g(t.inputValue,t.inputType,e)),n}async function le(t,e){let n=`${d(e.replayHost)}/v1/replay`;return (await e.fetch(n,{body:JSON.stringify(t),headers:{authorization:`Bearer ${e.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var pe=new Set(["INPUT","SELECT","TEXTAREA"]),x=class{constructor(e){this.options=e;a(this,"allocator",new v);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new k({distinctId:e.distinctId,masked:e.mask.maskAllInputs,maxEvents:e.maxEvents,now:e.now,sessionId:e.sessionId}),this.fetchImpl=a$1(e.fetch);}start(){if(this.started)return;let e=Je(),n=e?.documentElement;!e||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(e),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(e){let n=b(this.adapt(e),this.allocator,this.options.mask,(r,i)=>{let o=r.ref;o&&this.mirror.set(o,i);});n&&this.push(2,{node:n});}observeMutations(e){let n=globalThis.MutationObserver;n&&(this.observer=new n(r=>{for(let i of r)this.handleMutation(i);}),this.observer.observe(e,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(e){if(e.type==="characterData"){let n=this.mirror.get(e.target);n!==void 0&&this.push(3,{texts:[{id:n,value:y(e.target.textContent??"",this.options.mask)}]});return}if(e.type==="attributes"&&e.attributeName){let n=this.mirror.get(e.target),r=e.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[e.attributeName]:r.getAttribute(e.attributeName)??""},id:n}]});return}if(e.type==="childList"){let n=this.mirror.get(e.target);if(n===void 0)return;for(let r of Array.from(e.addedNodes)){let i=b(this.adapt(r),this.allocator,this.options.mask,(o,a)=>{let s=o.ref;s&&this.mirror.set(s,a);});i&&this.push(3,{adds:[{node:i,parentId:n}]});}for(let r of Array.from(e.removedNodes)){let i=this.mirror.get(r);i!==void 0&&(this.push(3,{removes:[{id:i,parentId:n}]}),this.mirror.delete(r));}}}observeInteractions(e){e.addEventListener("input",n=>{let r=n.target;if(!r||!pe.has(r.tagName))return;let i=this.mirror.get(r);i!==void 0&&this.push(3,{input:{id:i,value:g(r.value??"",r.type,this.options.mask)}});},true),e.addEventListener("scroll",n=>{let r=n.target,i=r?this.mirror.get(r):void 0;this.push(3,{scroll:{id:i??0,x:r?.scrollLeft??0,y:r?.scrollTop??0}});},true);}adapt(e){let n={childNodes:[],nodeType:e.nodeType,ref:e};if(e.nodeType===O)return n.textValue=e.textContent??"",n;if(e.nodeType===I){let r=e;if(n.tagName=r.tagName,n.attributes=Array.from(r.attributes).map(i=>({name:i.name,value:i.value})),pe.has(r.tagName)){let i=r;n.inputType=i.type,n.inputValue=i.value??"";}}return n.childNodes=Array.from(e.childNodes).map(r=>this.adapt(r)),n}push(e,n){let r=this.chunker.add({data:n,timestamp:this.options.now(),type:e});r&&this.upload(r);}upload(e){!e||!this.fetchImpl||le(e,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Je(){return globalThis.document}function fe(t){let e=new x({apiKey:t.apiKey,distinctId:t.distinctId,flushIntervalMs:t.flushIntervalMs??5e3,mask:{...ue,...t.mask},maxEvents:t.maxEvents??200,now:t.now??(()=>Date.now()),onError:t.onError,replayHost:t.replayHost,sessionId:t.sessionId??h$1()});return e.start(),e}function We(){return globalThis.navigator}function ze(){return globalThis.document}function Be(){return globalThis.history}function qe(){return globalThis.location}function Xe(t){let e=t?.userAgentData?.platform??t?.platform;return e?e.slice(0,50):void 0}function Ge(t){let e=()=>{t.flush();};globalThis.document?.addEventListener?.("visibilitychange",e),globalThis.addEventListener?.("pagehide",e);}function Ye(t,e,n){try{return w({domain:e,name:`pdx_${l$1(t)}`})??n}catch{return n}}function Ht(t){let{autocaptureOptions:e,cookieDomain:n,linkedDomains:r,replayHost:i,sessionReplay:o,sessionReplayOptions:a,...s}=t,c=We(),R=f$1(),P=s.storage??R,M=s.sharedStorage??Ye(s.apiKey,n,R),_=ae({history:Be(),location:qe(),namespace:l$1(s.apiKey),now:(s.clock??g$1).now().getTime(),shared:M,storage:P}),L={...s,locale:s.locale??(c?.language?c.language.slice(0,20):void 0),os:s.os??Xe(c),sessionTracking:s.sessionTracking??true,sharedStorage:M,storage:P,transport:s.transport??new f({maxRetries:s.maxRetries,requestTimeoutMs:s.requestTimeoutMs})},d=new y$1(L);_!==void 0&&d.alias(_),Ge(d),(t.autocapture??true)&&G(d,e);let $=ze();return $&&r&&T($,d,r),o&&i&&fe({apiKey:L.apiKey,distinctId:()=>d.distinctId,onError:L.onError,replayHost:i,...a,sessionId:a?.sessionId??d.sessionId}),d}export{f as WebTransport,w as createCookieStorage,Ht as createWebClient,ie as decorateLink,G as installAutocapture,T as installLinkCarry,fe as installSessionReplay,oe as readCarry,Z as resolveCookieDomain,se as stripCarry};//# sourceMappingURL=web.js.map
2
2
  //# sourceMappingURL=web.js.map
package/package.json CHANGED
@@ -63,5 +63,5 @@
63
63
  "sideEffects": false,
64
64
  "type": "module",
65
65
  "types": "./dist/index.d.ts",
66
- "version": "0.1.0-beta.351"
66
+ "version": "0.2.0-beta.357"
67
67
  }
@@ -1,2 +0,0 @@
1
- import {c as c$1,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {a as a$1,d,b as b$1,c}from'./chunk-VG77TYVX.js';import {a}from'./chunk-5XGN7UAV.js';var h=class extends Error{constructor(t,r,n){super(r,n);a(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends h{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends h{constructor(t,r){super("validation",r);a(this,"field");this.field=t,this.name="ValidationError";}},l=class extends h{constructor(t,r,n){super("transport",t,n);a(this,"status");this.status=r,this.name="TransportError";}};var y=class{constructor(){a(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};function be(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new y}return new y}var K="prodantix-js",D="0.0.1";var f=Symbol("absent");function ne(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,s)?r[s]:f}function p(s){return s===f?"undefined":String(s)}function O(s){return s===f?Number.NaN:Number(s)}function N(s){return s!==f&&s!==null&&s!==""}function L(s,e){if(!Array.isArray(e))return false;let t=p(s);return e.map(r=>String(r)).includes(t)}function V(s,e){let t=ne(s.attribute,e),r=s.value;switch(s.op){case "is_set":return N(t);case "is_not_set":return !N(t);case "eq":return p(t)===p(r===void 0?f:r);case "neq":return p(t)!==p(r===void 0?f:r);case "contains":return p(t).includes(p(r===void 0?f:r));case "in":return L(t,r);case "not_in":return Array.isArray(r)?!L(t,r):false;case "gt":return k(t,r,(n,i)=>n>i);case "gte":return k(t,r,(n,i)=>n>=i);case "lt":return k(t,r,(n,i)=>n<i);case "lte":return k(t,r,(n,i)=>n<=i);case "in_cohort":return typeof r=="string"&&r!==""&&(e.cohorts??[]).includes(r);case "not_in_cohort":return typeof r=="string"&&r!==""&&!(e.cohorts??[]).includes(r);default:return false}}function k(s,e,t){let r=O(s),n=e===void 0?Number.NaN:O(e);return Number.isNaN(r)||Number.isNaN(n)?false:t(r,n)}function j(s,e){let t=`${s}:${e}`,r=2166136261;for(let n=0;n<t.length;n++)r^=t.charCodeAt(n),r=Math.imul(r,16777619);return (r>>>0)%100}function _(s,e){return s.targeting.length===0||s.targeting.every(t=>V(t,e))}function U(s,e){let t=j(s.key,e.distinctId),r=s.variations??[];if(r.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let n=0;for(let i=r.length-1;i>=0;i--)if(n+=r[i].weight,t<n)return r[i].key;return r[0].key}function P(s,e,t,r){for(let n of s.prerequisites??[]){if(r.includes(n.flagKey))return false;let i=e.find(c=>c.key===n.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=P(i,e,t,r)&&_(i,t)&&U(i,t)===n.variationKey;if(r.pop(),!a)return false}return true}function b(s,e,t){return s.enabled?P(s,e,t,[s.key])?_(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:j(s.key,t.distinctId)<s.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function Ee(s,e){return b(s,[],e)}function z(s,e){let t={};for(let r of s)t[r.key]=b(r,s,e).enabled;return t}function x(s,e,t){let r=s.variations??[],n=r[0];if(!n)return null;if(!s.enabled||!P(s,e,t,[s.key])||!_(s,t))return n;let i=U(s,t);return r.find(a=>a.key===i)??n}function Se(s,e){return x(s,[],e)}function Te(s,e,t){let r=s.find(n=>n.key===e);return r?x(r,s,t)?.value??null:null}function H(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var F=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,r=b$1(),n=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{n!==void 0&&clearTimeout(n);}}async memberships(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var w=class{constructor(e){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=a$1(e.fetch),this.host=d(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(t,r,{headers:this.authHeaders(),method:"GET"});if(!n.ok)throw new l(`inbox request failed with status ${n.status}`,n.status);return JSON.parse(await n.text()).messages??[]}async markRead(e,t){let r=this.requireFetch(),n=`${this.host}/v1/messages/read`,i=await this.request(r,n,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,r){let n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...r,signal:n?.signal})}finally{i!==void 0&&clearTimeout(i);}}};function J(s){return s>=400&&s<500&&s!==429}var I=class{constructor(e={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=a$1(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??c,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),n;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,r);if(a.ok)return;if(J(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);n=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&J(a.status))throw a;n=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:n})}async attempt(e,t,r){let n=b$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:r,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:n?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Q={now:()=>new Date};function E(s){return s.toISOString()}function ie(){return globalThis.crypto}function oe(s){s[6]=s[6]&15|64,s[8]=s[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(s[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ae(){let s=ie();if(s?.randomUUID)return s.randomUUID();let e=new Uint8Array(16);if(s?.getRandomValues)s.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return oe(e)}var B={uuid:ae};var le=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ce=/^(?:\$|[a-z])[a-z0-9_.]*$/;function G(s){let e=0;for(let t of s)e+=1;return e}function W(s){return le.test(s)}function ue(s){return ce.test(s)}function X(s){let e=G(s);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function Y(s){let e=G(s);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!ue(s))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var de=s=>{};function Z(s){if(!s.apiKey||!W(s.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new v("host is required (the ingest base URL)");let e=d(s.host),t=s.defaultProperties;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??Q,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:s.flagsHost?d(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??B,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:s.apiKey.slice(0,16),onError:s.onError??de,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??K,sdkVersion:s.sdkVersion??D,socketFactory:s.socketFactory,storage:s.storage??new y,streamFlags:s.streamFlags??false,transport:s.transport}}function ee(s,e,t){Y(s.eventName),X(s.distinctId);let r={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:E(s.timestamp??e.now())};return s.context&&(r.context=s.context),s.sessionId&&(r.session_id=s.sessionId),r}var he="/socket.io/?EIO=4&transport=websocket",pe=250,S=class{constructor(e){this.options=e;a(this,"socket",null);a(this,"heartbeat",null);a(this,"pending",null);a(this,"lastKey","");a(this,"ready",false);a(this,"closed",false);a(this,"heartbeatWindow",45e3);a(this,"factory");a(this,"setTimer");a(this,"clearTimer");this.factory=e.socketFactory??fe,this.setTimer=e.setTimer??((t,r)=>setTimeout(t,r)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${he}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=c$1(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(a$2({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(b$2());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let r=t.payload?.key;this.lastKey=typeof r=="string"?r:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},pe));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function fe(s){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(s)}var T=class{constructor(e,t,r){this.storage=e;this.ids=t;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=t.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var C=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;a(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var ge="queue",me=1e3,te=3e4,se=s=>{let e={};return s.avatar!==void 0&&(e.$avatar=s.avatar),s.email!==void 0&&(e.$email=s.email),s.name!==void 0&&(e.$name=s.name),s.phone!==void 0&&(e.$phone=s.phone),e},R=class{constructor(e){a(this,"config");a(this,"identity");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");a(this,"membershipCache");a(this,"stream");a(this,"shutDown",false);a(this,"exposures",new Set);this.config=Z(e),this.identity=new T(this.config.storage,this.config.ids,this.config.namespace),this.queue=new C(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new h("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new I({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new w({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,t={}){try{let r={...this.config.defaultProperties(),...t.properties??{}},n=ee({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:t.sessionId,timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(r){this.config.onError(r);}}identify(e,t={}){let r=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),i=this.identity.identify(e),a={};n&&i.changed&&(a.$anon_distinct_id=r);let c={...se(t.traits??{}),...t.set??{}};Object.keys(c).length>0&&(a.$set=c),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,r){let n={$group_key:t,$group_type:e};r&&(n.$set=r),this.capture("$group",{properties:n});}setPersonProperties(e,t){let r={};e&&(r.$set=e),t&&(r.$set_once=t),this.capture("$set",{properties:r});}setPersonTraits(e){let t=se(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let r=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(r)),r}async getVariant(e){let t=await this.getAllFlags(),r=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,r?.key??String(t[e]??false)),r}async getVariantLocal(e,t={}){let r=await this.flagSnapshot(),n=r.flags.find(re=>re.key===e),i=await this.localContext(t,r.flags),a=n?x(n,r.flags,i):null,c=n?b(n,r.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(c)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let r=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(r)||(this.exposures.add(r),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return z(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let r=await this.flagSnapshot(),n=r.flags.find(c=>c.key===e),i=await this.localContext(t,r.flags),a=n?b(n,r.flags,i).enabled:false;return this.recordExposure(e,(n?x(n,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let r=this.identity.getDistinctId(),n=e.cohorts;if(n===void 0&&H(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<te?n=this.membershipCache.cohorts:(n=await this.flagsClient.memberships(r),this.membershipCache={cohorts:n,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:n,distinctId:r,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<te)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new S({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(r=>this.config.onError(r));},onClosed:r=>{this.stream=void 0,r&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(me);try{await this.transport.send({body:{events:e,sent_at:E(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${ge}`}};function xt(s){return new R(s)}export{h as a,v as b,m as c,l as d,y as e,be as f,ae as g,K as h,D as i,V as j,j as k,Ee as l,z as m,Se as n,Te as o,F as p,w as q,I as r,R as s,xt as t};//# sourceMappingURL=chunk-CSIP3PZ7.js.map
2
- //# sourceMappingURL=chunk-CSIP3PZ7.js.map