@prodantix/sdk 0.8.0-beta.651 → 0.8.0-beta.654

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,8 +40,8 @@ if (await prodantix.isFeatureEnabled('new-checkout')) {
40
40
  registrable domain, so `xyz.com`, `app.xyz.com` and `console.xyz.com` see one person; the
41
41
  identified id stays per origin in `localStorage` and never enters the cookie. Pass `cookieDomain`
42
42
  to name the domain (a site whose subdomains belong to different tenants must), or `sharedStorage`
43
- to write no cookie. The queue persists in `localStorage`, delivery is by `navigator.sendBeacon`
44
- on page hide, and pageviews and clicks are autocaptured. Pass `autocapture: false` to disable
43
+ to write no cookie. The queue persists in `localStorage`, a batch sent while the page is
44
+ hidden goes by a `keepalive` fetch so it outlives the page, and pageviews and clicks are autocaptured. Pass `autocapture: false` to disable
45
45
  capture, or `autocaptureOptions: { pageviews, clicks }` to tune it.
46
46
 
47
47
  Autocapture collects no customer content by default. A click records the element's tag, id and
package/dist/chat.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { A as ArticleRef, a as ArticleReaction, b as ArticleHit, c as ArticleCollection, H as HelpWords, M as MessengerAttachments, d as AppearanceSettings, U as UploadRefusalCode, C as ChatUploadRefusal, T as TicketWords, e as ChatThread, P as PageContext, f as ChatTurn, g as ChatUpload, h as ChatIdentity, i as MessengerConfig, j as ChatClientOptions } from './config-C8WD1Pge.cjs';
2
- export { B as BubbleFill, k as BubbleShape, l as ChatAttachment, m as ChatClient, n as ChatStorage, o as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, p as FileResponseLike, L as LauncherContent, q as LauncherFill, r as LauncherShape, s as LauncherSize, t as MessengerSkin, N as NamePlacement, S as StampContent, u as StampPlacement, v as resolveAppearance } from './config-C8WD1Pge.cjs';
1
+ import { A as ArticleRef, a as ArticleReaction, b as ArticleHit, c as ArticleCollection, H as HelpWords, M as MessengerAttachments, d as AppearanceSettings, U as UploadRefusalCode, C as ChatUploadRefusal, T as TicketWords, e as ChatThread, P as PageContext, f as ChatTurn, g as ChatUpload, h as ChatIdentity, i as MessengerConfig, j as ChatClientOptions } from './config-BgUX3vOB.cjs';
2
+ export { B as BubbleFill, k as BubbleShape, l as ChatAttachment, m as ChatClient, n as ChatStorage, o as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, p as FileResponseLike, L as LauncherContent, q as LauncherFill, r as LauncherShape, s as LauncherSize, t as MessengerSkin, N as NamePlacement, S as StampContent, u as StampPlacement, v as resolveAppearance } from './config-BgUX3vOB.cjs';
3
3
  import { S as SocketFactory } from './types-BUXFV_aE.cjs';
4
- import './http-BCh716Vs.cjs';
4
+ import './http-CAOViYSh.cjs';
5
5
 
6
6
  declare const SEARCH_PAUSE_MS = 300;
7
7
  declare const TYPED_MINIMUM = 3;
package/dist/chat.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { A as ArticleRef, a as ArticleReaction, b as ArticleHit, c as ArticleCollection, H as HelpWords, M as MessengerAttachments, d as AppearanceSettings, U as UploadRefusalCode, C as ChatUploadRefusal, T as TicketWords, e as ChatThread, P as PageContext, f as ChatTurn, g as ChatUpload, h as ChatIdentity, i as MessengerConfig, j as ChatClientOptions } from './config-Bhwwo-uC.js';
2
- export { B as BubbleFill, k as BubbleShape, l as ChatAttachment, m as ChatClient, n as ChatStorage, o as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, p as FileResponseLike, L as LauncherContent, q as LauncherFill, r as LauncherShape, s as LauncherSize, t as MessengerSkin, N as NamePlacement, S as StampContent, u as StampPlacement, v as resolveAppearance } from './config-Bhwwo-uC.js';
1
+ import { A as ArticleRef, a as ArticleReaction, b as ArticleHit, c as ArticleCollection, H as HelpWords, M as MessengerAttachments, d as AppearanceSettings, U as UploadRefusalCode, C as ChatUploadRefusal, T as TicketWords, e as ChatThread, P as PageContext, f as ChatTurn, g as ChatUpload, h as ChatIdentity, i as MessengerConfig, j as ChatClientOptions } from './config-B4yq8a9P.js';
2
+ export { B as BubbleFill, k as BubbleShape, l as ChatAttachment, m as ChatClient, n as ChatStorage, o as ComposerShape, D as DEFAULT_APPEARANCE_SETTINGS, F as FileFetchLike, p as FileResponseLike, L as LauncherContent, q as LauncherFill, r as LauncherShape, s as LauncherSize, t as MessengerSkin, N as NamePlacement, S as StampContent, u as StampPlacement, v as resolveAppearance } from './config-B4yq8a9P.js';
3
3
  import { S as SocketFactory } from './types-BUXFV_aE.js';
4
- import './http-BCh716Vs.js';
4
+ import './http-CAOViYSh.js';
5
5
 
6
6
  declare const SEARCH_PAUSE_MS = 300;
7
7
  declare const TYPED_MINIMUM = 3;
package/dist/chat.js CHANGED
@@ -1,4 +1,4 @@
1
- import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chunk-ODN4ZELX.js';import {a}from'./chunk-5XGN7UAV.js';var z="X-Prodantix-Conversation-Token",_="prodantix.chat.handle";function W(){let i=globalThis.localStorage;if(i)return {get:e=>i.getItem(e),remove:e=>i.removeItem(e),set:(e,t)=>i.setItem(e,t)}}var L=class{constructor(e$1){this.options=e$1;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);a(this,"fromArticle",null);this.fetchImpl=e(e$1.fetchImpl),this.fileFetchImpl=e$1.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=h(e$1.host),this.storage=e$1.storage??W(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,fromArticle:this.fromArticle,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.fromArticle=null,this.storage?.set(_,JSON.stringify(this.handle)),true)}cameFrom(e){this.fromArticle={language:e.language,pageId:e.pageId};}async send(e,t,n){if(!await this.ensureThread())return null;let r=this.handle;return r?(await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:r.token}))?.turn??null:null}async upload(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,n.token,async r=>JSON.parse(await r.text()),e,t):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async helpCentre(e,t,n){let r=new URLSearchParams({...t,...this.options.locale&&{lang:this.options.locale},...this.identity&&{user_hash:this.identity.userHash,user_id:this.identity.userId}}).toString();return this.request(n?"POST":"GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`,n?{body:{...n,distinctId:this.options.distinctId}}:{})}get visitor(){return this.identity&&{...this.identity,distinctId:this.options.distinctId}}edge(e,t,n){return this.request(t?"POST":"GET",e,{body:t,token:n})}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(_);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(_),null}async fileRequest(e,t,n,r,a,s){let l={authorization:`Bearer ${this.options.apiKey}`,[z]:n};a&&(l["content-type"]=a.type||"application/octet-stream");try{let h=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:l,method:e});if(h.ok)return await r(h);let u=s?.(await h.text());if(u)return u;this.options.onError?.(new d(`prodantix chat ${t}: ${h.status}`,h.status));}catch(h){this.options.onError?.(h);}return null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new d("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(a[z]=n.token);try{let s=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:a,method:e}),l=await s.text();return s.ok?l?JSON.parse(l):{}:(this.options.onError?.(new d(`prodantix chat ${t}: ${s.status}`,s.status)),null)}catch(s){return this.options.onError?.(s),null}}};var J={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function P(i,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:i.timezone,weekday:"short"}).formatToParts(e),n=J[t.find(l=>l.type==="weekday")?.value??""];if(!n)return false;let r=t.find(l=>l.type==="hour")?.value??"",a=t.find(l=>l.type==="minute")?.value??"",s=`${r}:${a}`;return i.windows.some(l=>l.days.includes(n)&&l.open<=s&&s<l.close)}var f={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},X=["quiet","standard"],V=["round","square"],Z=["rounded","tailed"],Q=["filled","outlined"],ee=["circle","pill","squircle"],te=["filled","outlined"],ne=["avatar","glyph","team_faces"],ie=["large","medium","small"],re=["above","hidden","inline"],ae=["beside_name","none","under_turn"],se=["time","time_and_latency"],y=(i,e,t)=>typeof i=="string"&&e.includes(i)?i:t,B=(i,e)=>typeof i=="boolean"?i:e,oe={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},le={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ce={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},de={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},pe={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function E(i){let e=typeof i=="object"&&i!==null?i:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:oe[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=r===void 0?void 0:le[r],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,l=s===void 0?void 0:ce[s],h=typeof e.skin=="string"?e.skin:void 0,u=h===void 0?void 0:de[h],d=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=d===void 0?void 0:pe[d],p={bubbleFill:y(e.bubbleFill,Q,c?.[1]??f.bubbleFill),bubbleShape:y(e.bubbleShape,Z,c?.[0]??f.bubbleShape),composerShape:y(e.composerShape,V,u?.[1]??f.composerShape),dayDividers:B(e.dayDividers,l?.[0]??f.dayDividers),launcherContent:y(e.launcherContent,ne,n?.[2]??f.launcherContent),launcherFill:y(e.launcherFill,te,n?.[1]??f.launcherFill),launcherShape:y(e.launcherShape,ee,n?.[0]??f.launcherShape),launcherSize:y(e.launcherSize,ie,n?.[3]??f.launcherSize),nameAvatar:B(e.nameAvatar,a?.[1]??f.nameAvatar),namePlacement:y(e.namePlacement,re,a?.[0]??f.namePlacement),skin:y(e.skin,X,u?.[0]??f.skin),stampContent:y(e.stampContent,se,l?.[2]??f.stampContent),stampPlacement:y(e.stampPlacement,ae,l?.[1]??f.stampPlacement)};return p.stampPlacement==="beside_name"&&p.namePlacement==="hidden"&&(p.stampPlacement="under_turn"),p}function O(i){let e=i.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var he="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",ue={large:66,medium:56,small:46},me={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},ge={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},fe={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},be=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",ye={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},xe={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},ve={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Se={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function D(i,e,t,n){return `.launcher{--fab-size:${ue[n]}px;${me[i]}${ge[e]}}${fe[t]}${be}${ye[i]}${xe[e]}${ve[i]}${Se[i]}`}function q(i,e,t,n=r=>r){let r=document.createDocumentFragment();if(i==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${he}"/></svg>`,r.append(...a.childNodes,R()),r}return i==="avatar"?(r.append(j(t[0],e,n),R()),r):(r.append(H(t,e,n),R()),r)}function H(i,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let r of i.slice(0,2))n.append(j(r,e,t));return n}function j(i,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),i&&(n.style.background=i.tone),i?.avatarUrl){let r=document.createElement("img");return r.alt="",r.src=t(i.avatarUrl),n.append(r),n}return n.textContent=i?i.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function R(){let i=document.createElement("span");return i.className="live",i.setAttribute("aria-hidden","true"),i}var ke={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(i,e)=>`That file is ${i}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:i=>{let e=new Date(i);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:i=>`${i} unread`},w={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...f};function Ce(i,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let n=document.createElement("img");return n.src=e,n.alt="",n.width=12,n.height=12,t.append(n,i),t}var Te={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},we={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Le={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Ee={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ae={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Pe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Fe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',_e={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Re=".lat{font-size:11px;opacity:.7;margin-left:6px}",G=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
1
+ import {c,a as a$1,b as b$1}from'./chunk-V77KYPOF.js';import {e,h,d,b}from'./chunk-5WTMO52O.js';import {a}from'./chunk-5XGN7UAV.js';var z="X-Prodantix-Conversation-Token",_="prodantix.chat.handle";function W(){let i=globalThis.localStorage;if(i)return {get:e=>i.getItem(e),remove:e=>i.removeItem(e),set:(e,t)=>i.setItem(e,t)}}var L=class{constructor(e$1){this.options=e$1;a(this,"fetchImpl");a(this,"fileFetchImpl");a(this,"host");a(this,"storage");a(this,"handle");a(this,"identity",null);a(this,"fromArticle",null);this.fetchImpl=e(e$1.fetchImpl),this.fileFetchImpl=e$1.fileFetchImpl??((t,n)=>fetch(t,n)),this.host=h(e$1.host),this.storage=e$1.storage??W(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}avatarUrl(e){return e.startsWith("/")?`${this.host}${e}?api_key=${encodeURIComponent(this.options.apiKey)}`:e}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,fromArticle:this.fromArticle,subject:e,userHash:this.identity?.userHash,userId:this.identity?.userId}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.fromArticle=null,this.storage?.set(_,JSON.stringify(this.handle)),true)}cameFrom(e){this.fromArticle={language:e.language,pageId:e.pageId};}async send(e,t,n){if(!await this.ensureThread())return null;let r=this.handle;return r?(await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{attachmentIds:n,body:e,pageContext:t},token:r.token}))?.turn??null:null}async upload(e,t){if(!await this.ensureThread())return null;let n=this.handle;return n?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(n.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,n.token,async r=>JSON.parse(await r.text()),e,t):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,n=>n.blob()):null}async helpCentre(e,t,n){let r=new URLSearchParams({...t,...this.options.locale&&{lang:this.options.locale},...this.identity&&{user_hash:this.identity.userHash,user_id:this.identity.userId}}).toString();return this.request(n?"POST":"GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`,n?{body:{...n,distinctId:this.options.distinctId}}:{})}get visitor(){return this.identity&&{...this.identity,distinctId:this.options.distinctId}}edge(e,t,n){return this.request(t?"POST":"GET",e,{body:t,token:n})}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(_);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch(t){this.options.onError?.(t);}return this.storage?.remove(_),null}async fileRequest(e,t,n,r,a,s){let l={authorization:`Bearer ${this.options.apiKey}`,[z]:n};a&&(l["content-type"]=a.type||"application/octet-stream");try{let h=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:l,method:e});if(h.ok)return await r(h);let u=s?.(await h.text());if(u)return u;this.options.onError?.(new d(`prodantix chat ${t}: ${h.status}`,h.status));}catch(h){this.options.onError?.(h);}return null}async request(e,t,n={}){let r=this.fetchImpl;if(!r)return this.options.onError?.(new d("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};n.token&&(a[z]=n.token);try{let s=await r(`${this.host}${t}`,{body:n.body===void 0?void 0:JSON.stringify(n.body),headers:a,method:e}),l=await s.text();return s.ok?l?JSON.parse(l):{}:(this.options.onError?.(new d(`prodantix chat ${t}: ${s.status}`,s.status)),null)}catch(s){return this.options.onError?.(s),null}}};var J={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function P(i,e){let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:i.timezone,weekday:"short"}).formatToParts(e),n=J[t.find(l=>l.type==="weekday")?.value??""];if(!n)return false;let r=t.find(l=>l.type==="hour")?.value??"",a=t.find(l=>l.type==="minute")?.value??"",s=`${r}:${a}`;return i.windows.some(l=>l.days.includes(n)&&l.open<=s&&s<l.close)}var f={bubbleFill:"filled",bubbleShape:"tailed",composerShape:"round",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"standard",stampContent:"time",stampPlacement:"none"},X=["quiet","standard"],V=["round","square"],Z=["rounded","tailed"],Q=["filled","outlined"],ee=["circle","pill","squircle"],te=["filled","outlined"],ne=["avatar","glyph","team_faces"],ie=["large","medium","small"],re=["above","hidden","inline"],ae=["beside_name","none","under_turn"],se=["time","time_and_latency"],y=(i,e,t)=>typeof i=="string"&&e.includes(i)?i:t,B=(i,e)=>typeof i=="boolean"?i:e,oe={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},le={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ce={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},de={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},pe={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function E(i){let e=typeof i=="object"&&i!==null?i:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,n=t===void 0?void 0:oe[t],r=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=r===void 0?void 0:le[r],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,l=s===void 0?void 0:ce[s],h=typeof e.skin=="string"?e.skin:void 0,u=h===void 0?void 0:de[h],d=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=d===void 0?void 0:pe[d],p={bubbleFill:y(e.bubbleFill,Q,c?.[1]??f.bubbleFill),bubbleShape:y(e.bubbleShape,Z,c?.[0]??f.bubbleShape),composerShape:y(e.composerShape,V,u?.[1]??f.composerShape),dayDividers:B(e.dayDividers,l?.[0]??f.dayDividers),launcherContent:y(e.launcherContent,ne,n?.[2]??f.launcherContent),launcherFill:y(e.launcherFill,te,n?.[1]??f.launcherFill),launcherShape:y(e.launcherShape,ee,n?.[0]??f.launcherShape),launcherSize:y(e.launcherSize,ie,n?.[3]??f.launcherSize),nameAvatar:B(e.nameAvatar,a?.[1]??f.nameAvatar),namePlacement:y(e.namePlacement,re,a?.[0]??f.namePlacement),skin:y(e.skin,X,u?.[0]??f.skin),stampContent:y(e.stampContent,se,l?.[2]??f.stampContent),stampPlacement:y(e.stampPlacement,ae,l?.[1]??f.stampPlacement)};return p.stampPlacement==="beside_name"&&p.namePlacement==="hidden"&&(p.stampPlacement="under_turn"),p}function O(i){let e=i.split(/\s+/).filter(n=>n.length>0);return (e.length>1?`${e[0]?.slice(0,1)}${e[1]?.slice(0,1)}`:e[0]?.slice(0,2)??"").toUpperCase()}var he="M20 11.6a7.4 7.4 0 0 1-7.4 7.4H8.2L4 21.8l1-4.1A7.4 7.4 0 1 1 20 11.6Z",ue={large:66,medium:56,small:46},me={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},ge={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},fe={avatar:"",glyph:".launcher svg{width:calc(var(--fab-size) * 0.375);height:calc(var(--fab-size) * 0.375);}",team_faces:".launcher .faces{display:flex;}.launcher .faces .av{box-shadow:0 0 0 2px var(--paper);}.launcher .faces .av+.av{margin-left:-10px;}"},be=".launcher .live{width:10px;height:10px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}.launcher.closed .live{display:none}",ye={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},xe={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},ve={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Se={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function D(i,e,t,n){return `.launcher{--fab-size:${ue[n]}px;${me[i]}${ge[e]}}${fe[t]}${be}${ye[i]}${xe[e]}${ve[i]}${Se[i]}`}function q(i,e,t,n=r=>r){let r=document.createDocumentFragment();if(i==="glyph"||t.length===0){let a=document.createElement("span");return a.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${he}"/></svg>`,r.append(...a.childNodes,R()),r}return i==="avatar"?(r.append(j(t[0],e,n),R()),r):(r.append(H(t,e,n),R()),r)}function H(i,e,t=n=>n){let n=document.createElement("span");n.className="faces";for(let r of i.slice(0,2))n.append(j(r,e,t));return n}function j(i,e,t){let n=document.createElement("span");if(n.className="av",n.setAttribute("aria-hidden","true"),i&&(n.style.background=i.tone),i?.avatarUrl){let r=document.createElement("img");return r.alt="",r.src=t(i.avatarUrl),n.append(r),n}return n.textContent=i?i.initials:e.agentLabel.slice(0,2).toUpperCase(),n}function R(){let i=document.createElement("span");return i.className="live",i.setAttribute("aria-hidden","true"),i}var ke={agentLabel:"Agent",aiLabel:"AI",attachLabel:"Attach a file",awayBody:"We are away right now, but we will reply as soon as we are back.",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",fileRefusal:(i,e)=>`That file is ${i}. Send a PNG, JPEG, WebP, GIF or PDF up to ${e}.`,inputPlaceholder:"Type a message",launcherLabel:"Chat with us",removeFileLabel:"Remove file",replyTime:"Usually replying in a few minutes",retryLabel:"Not delivered. Retry",sendLabel:"Send",timeLabel:i=>{let e=new Date(i);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:i=>`${i} unread`},w={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...f};function Ce(i,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let n=document.createElement("img");return n.src=e,n.alt="",n.width=12,n.height=12,t.append(n,i),t}var Te={quiet:".composer{position:relative;padding:8px 10px 10px}.composer input{padding-right:36px}.composer button{position:absolute;top:50%;right:14px;width:28px;min-width:28px;height:28px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:16px;height:16px}.composer button .sendtext{display:none}.panel{border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,.12)}.header{background:var(--paper);color:var(--ink);height:44px;padding:0 8px 0 16px;border-bottom:1px solid var(--hairline)}.header h2{font-size:11px;letter-spacing:.11em;text-transform:uppercase;color:var(--ink-3)}.header .faces,.header .status{display:none}.header .close{top:6px}.close{color:var(--ink-2)}",standard:".panel{border-radius:16px;box-shadow:0 16px 40px rgba(0,0,0,.2)}.header{background:var(--a);color:#fff;flex-direction:column;align-items:flex-start;gap:14px;padding:18px 14px 20px 20px}.header h2{font-size:19px;font-weight:640}"},we={round:".composer{padding:10px 10px 12px;gap:6px}.composer input{height:36px;border-radius:18px;padding:0 14px}.composer button{width:36px;min-width:36px;height:36px;padding:0;border-radius:18px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:36px;border-radius:8px;padding:0 12px}"},Le={rounded:".turn{border-radius:18px;padding:10px 15px}",tailed:".turn.agent,.turn.ai{border-radius:12px 12px 12px 4px}.turn.end_user{border-radius:12px 12px 4px 12px}"},Ee={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ae={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".body .author.below{display:block;margin:4px 0 0;font-size:11.5px;font-weight:500;color:var(--ink-2);text-transform:none;letter-spacing:0;opacity:1}"},Pe=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn.agent .body,.turn.ai .body{background:var(--fill);padding:9px 13px;border-radius:inherit}.author{text-transform:none;letter-spacing:0;font-size:12.5px;font-weight:600;opacity:1}",Fe='.divider{display:flex;align-items:center;gap:10px;margin:0;font-size:11px;opacity:.6}.divider:before,.divider:after{content:"";flex:1;height:1px;background:var(--hairline)}',_e={beside_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}",none:"",under_turn:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}"},Re=".lat{font-size:11px;opacity:.7;margin-left:6px}",G=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
2
2
  --fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
3
3
  --online: oklch(72% 0.13 163.23);`;function He(i){return i==="light"?"":i==="dark"?`:host { ${G} }`:`@media (prefers-color-scheme: dark) {
4
4
  :host {
@@ -1,2 +1,2 @@
1
- import {a as a$1}from'./chunk-5XGN7UAV.js';var n=class extends Error{constructor(r,o,i){super(o,i);a$1(this,"code");this.code=r,this.name="ProdantixError";}},a=class extends n{constructor(t){super("config",t),this.name="ConfigError";}},l=class extends n{constructor(r,o){super("validation",o);a$1(this,"field");this.field=r,this.name="ValidationError";}},c=class extends n{constructor(r,o,i){super("transport",r,i);a$1(this,"status");this.status=o,this.name="TransportError";}};function p(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function h(){let e=globalThis.AbortController;return e?new e:void 0}var g=e=>new Promise(t=>{setTimeout(t,e);});function f(e){return e.replace(/\/+$/,"")}export{n as a,a as b,l as c,c as d,p as e,h as f,g,f as h};//# sourceMappingURL=chunk-ODN4ZELX.js.map
2
- //# sourceMappingURL=chunk-ODN4ZELX.js.map
1
+ import {a as a$1}from'./chunk-5XGN7UAV.js';var n=class extends Error{constructor(r,o,i){super(o,i);a$1(this,"code");this.code=r,this.name="ProdantixError";}},a=class extends n{constructor(t){super("config",t),this.name="ConfigError";}},l=class extends n{constructor(r,o){super("validation",o);a$1(this,"field");this.field=r,this.name="ValidationError";}},c=class extends n{constructor(r,o,i){super("transport",r,i);a$1(this,"status");this.status=o,this.name="TransportError";}};function p(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function h(){let e=globalThis.AbortController;return e?new e:void 0}var g=e=>new Promise(t=>{setTimeout(t,e);});function f(e){return e.replace(/\/+$/,"")}export{n as a,a as b,l as c,c as d,p as e,h as f,g,f as h};//# sourceMappingURL=chunk-5WTMO52O.js.map
2
+ //# sourceMappingURL=chunk-5WTMO52O.js.map
@@ -0,0 +1,2 @@
1
+ import {c,a as a$2,b as b$2}from'./chunk-V77KYPOF.js';import {e,h,d,f as f$1,g as g$1,a as a$1,b as b$1,c as c$1}from'./chunk-5WTMO52O.js';import {a}from'./chunk-5XGN7UAV.js';var g=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);}},v=class{constructor(e,t=()=>false){this.real=e;this.passes=t;a(this,"held",new g);a(this,"opened",false);}get isOpen(){return this.opened}open(){this.opened=true;}close(){this.opened=false;}target(e){return this.opened||this.passes(e)?this.real:this.held}getItem(e){return this.target(e).getItem(e)}removeItem(e){this.target(e).removeItem(e);}setItem(e,t){this.target(e).setItem(e,t);}};function Ze(){try{let s=globalThis.localStorage;if(s){let e="__pdx_probe__";return s.setItem(e,"1"),s.removeItem(e),s}}catch{return new g}return new g}var Z={now:()=>new Date};function w(s){return s.toISOString()}function ee(){if(typeof window>"u"||typeof Intl>"u")return null;let s=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof s=="string"&&s!==""?s:null}var Te=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var $e=/^(?:\$|[a-z])[a-z0-9_.]*$/;function te(s){let e=0;for(let t of s)e+=1;return e}function se(s){return Te.test(s)}function Ae(s){return $e.test(s)}function ne(s){let e=te(s);if(e<1||e>200)throw new c$1("distinct_id","distinct_id must be between 1 and 200 characters")}function ie(s){let e=te(s);if(e<1||e>200)throw new c$1("event_name","event_name must be between 1 and 200 characters");if(!Ae(s))throw new c$1("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var re="prodantix-js",oe="0.8.0";function Pe(){return globalThis.crypto}function Re(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 Me(){let s=Pe();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 Re(e)}var ae={uuid:Me};var qe=s=>{};function le(s){if(!s.apiKey||!se(s.apiKey))throw new b$1("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!s.host)throw new b$1("host is required (the ingest base URL)");let e=h(s.host),t=s.defaultProperties,n=s.storage??new g;return {apiKey:s.apiKey,autocapture:s.autocapture??false,clock:s.clock??Z,consent:s.consent,consentMode:s.consentMode,defaultProperties:typeof t=="function"?t:()=>t??{},describeElement:s.describeElement,flagsHost:s.flagsHost?h(s.flagsHost):e,flushAt:s.flushAt??20,flushIntervalMs:s.flushIntervalMs??1e4,host:e,ids:s.ids??ae,locale:s.locale,maxQueueSize:s.maxQueueSize??1e3,maxRetries:s.maxRetries??3,namespace:Ke(s.apiKey),onError:s.onError??qe,os:s.os,requestTimeoutMs:s.requestTimeoutMs??1e4,sdkName:s.sdkName??re,sdkVersion:s.sdkVersion??oe,sessionTracking:s.sessionTracking??false,sharedStorage:s.sharedStorage??n,socketFactory:s.socketFactory,storage:n,streamFlags:s.streamFlags??false,transport:s.transport}}function Ke(s){return s.slice(0,16)}var y=Symbol("absent");function Oe(s,e){if(s==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,s))return t[s];let n=e.attributes??{};return Object.prototype.hasOwnProperty.call(n,s)?n[s]:y}function f(s){return s===y?"undefined":String(s)}function ce(s){return s===y?Number.NaN:Number(s)}function ue(s){return s!==y&&s!==null&&s!==""}function de(s,e){if(!Array.isArray(e))return false;let t=f(s);return e.map(n=>String(n)).includes(t)}function pe(s,e){let t=Oe(s.attribute,e),n=s.value;switch(s.op){case "is_set":return ue(t);case "is_not_set":return !ue(t);case "eq":return f(t)===f(n===void 0?y:n);case "neq":return f(t)!==f(n===void 0?y:n);case "contains":return f(t).includes(f(n===void 0?y:n));case "in":return de(t,n);case "not_in":return Array.isArray(n)?!de(t,n):false;case "gt":return _(t,n,(i,r)=>i>r);case "gte":return _(t,n,(i,r)=>i>=r);case "lt":return _(t,n,(i,r)=>i<r);case "lte":return _(t,n,(i,r)=>i<=r);case "in_cohort":return typeof n=="string"&&n!==""&&(e.cohorts??[]).includes(n);case "not_in_cohort":return typeof n=="string"&&n!==""&&!(e.cohorts??[]).includes(n);default:return false}}function _(s,e,t){let n=ce(s),i=e===void 0?Number.NaN:ce(e);return Number.isNaN(n)||Number.isNaN(i)?false:t(n,i)}function he(s,e){let t=`${s}:${e}`,n=2166136261;for(let i=0;i<t.length;i++)n^=t.charCodeAt(i),n=Math.imul(n,16777619);return (n>>>0)%100}function N(s,e){return s.targeting.length===0||s.targeting.every(t=>pe(t,e))}function me(s,e){let t=he(s.key,e.distinctId),n=s.variations??[];if(n.length===0)return s.rolloutPercentage>=100||t<s.rolloutPercentage?"true":"false";let i=0;for(let r=n.length-1;r>=0;r--)if(i+=n[r].weight,t<i)return n[r].key;return n[0].key}function j(s,e,t,n){for(let i of s.prerequisites??[]){if(n.includes(i.flagKey))return false;let r=e.find(c=>c.key===i.flagKey);if(!r||!r.enabled)return false;n.push(r.key);let a=j(r,e,t,n)&&N(r,t)&&me(r,t)===i.variationKey;if(n.pop(),!a)return false}return true}function b(s,e,t){return s.enabled?j(s,e,t,[s.key])?N(s,t)?s.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:he(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 yt(s,e){return b(s,[],e)}function ge(s,e){let t={};for(let n of s)t[n.key]=b(n,s,e).enabled;return t}function S(s,e,t){let n=s.variations??[],i=n[0];if(!i)return null;if(!s.enabled||!j(s,e,t,[s.key])||!N(s,t))return i;let r=me(s,t);return n.find(a=>a.key===r)??i}function vt(s,e){return S(s,[],e)}function bt(s,e,t){let n=s.find(i=>i.key===e);return n?S(n,s,t)?.value??null:null}function fe(s){return s.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}var F=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{r!==void 0&&clearTimeout(r);}}async snapshot(){let e=this.fetch;if(!e)throw new d("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,n=f$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let r=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!r.ok)throw new d(`flag snapshot request failed with status ${r.status}`,r.status);let a=JSON.parse(await r.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{i!==void 0&&clearTimeout(i);}}async memberships(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{r!==void 0&&clearTimeout(r);}}};var ye="$survey_shown",ve="$survey_dismissed",be="$survey_sent",C=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async surveys(e,t){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await n(`${this.host}/v1/surveys?distinct_id=${encodeURIComponent(e)}${t?`&lang=${encodeURIComponent(t)}`:""}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`surveys request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).surveys??[]}finally{r!==void 0&&clearTimeout(r);}}},De=864e5,Le=s=>`${s.id}:${s.iteration}`;function V(s,e){return s.length===0?true:s.some(t=>{switch(t.matches){case "exact":return e===t.value;case "starts_with":return e.startsWith(t.value);default:return e.includes(t.value)}})}function It(s,e,t,n,i){return s.kind!=="popover"||e.settled.includes(Le(s))||s.showOnce&&e.settled.some(r=>r.startsWith(`${s.id}:`))||s.waitDays>0&&e.lastShownAt!==void 0&&n-e.lastShownAt<s.waitDays*De||s.event&&s.event!==i?false:V(s.urls,t)}function Ne(s,e,t){return s>=(e.minScore??0)&&s<=(e.maxScore??t)}function Et(s,e,t){let n=e.kind==="nps"?10:e.scale??5,i=e.branches.find(a=>a.choice!=null?t===a.choice:typeof t=="number"&&Ne(t,a,n));if(i)return i.next??null;let r=s.questions.findIndex(a=>a.id===e.id);return s.questions[r+1]?.id??null}function I(s,e){let t={$survey_id:s.id,$survey_iteration:s.iteration,$survey_name:s.name};for(let[n,i]of Object.entries(e))t[`$survey_response_${n}`]=i;return t}var Mt="$guide_shown",qt="$guide_step_viewed",Kt="$guide_step_missed",Ot="$guide_completed",Dt="$guide_dismissed",Lt="$checklist_task_done",E=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async guides(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=f$1(),i=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let r=await t(`${this.host}/v1/guides?distinct_id=${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!r.ok)throw new d(`guides request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).guides??[]}finally{i!==void 0&&clearTimeout(i);}}},je=864e5,Se=s=>`${s.id}:${s.iteration}`,Ve=(s,e)=>`${Se(s)}:${e}`;function Nt(s,e,t,n,i){return e.settled.includes(Se(s))||s.showOnce&&e.settled.some(r=>r.startsWith(`${s.id}:`))||s.kind!=="checklist"&&s.waitDays>0&&e.lastShownAt!==void 0&&n-e.lastShownAt<s.waitDays*je||s.event&&s.event!==i?false:V(s.urls,t)}var jt=(s,e)=>s.steps.filter(t=>e.done.includes(Ve(s,t.id))).map(t=>t.id),Vt=(s,e)=>s.kind==="checklist"?s.steps.find(t=>t.event===e):void 0;function ke(s,e){let t={$guide_id:s.id,$guide_iteration:s.iteration,$guide_name:s.name};return e!==void 0&&(t.$guide_step_id=e),t}function k(s){if(typeof s!="string")return;let e=Array.from(s).length;return e>=1&&e<=200?s:void 0}function $(s,e){return `pdx.${s}.${e}`}var U="consent",Ge=["identityLink","analytics","marketing","functional"];function G(s){if(typeof s!="string")return null;try{let e=JSON.parse(s);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,n={};for(let i of Ge){let r=t[i];typeof r=="boolean"&&(n[i]=r);}return typeof t.version=="number"&&Number.isInteger(t.version)&&(n.version=t.version),Array.isArray(t.categories)&&t.categories.every(i=>typeof i=="string")&&(n.categories=t.categories),Object.keys(n).length===0?null:n}catch{return null}}var xe=s=>s.endsWith(`.${U}`);function A(s,e){return G(s.getItem($(e,U)))}function Ue(s,e,t){let n=$(e,U),i=G(JSON.stringify(t)),r=i===null?null:G(JSON.stringify({...A(s,e)??{},...i}));if(r===null){s.removeItem(n);return}s.setItem(n,JSON.stringify(r));}function Bt(s,e,t,n){let i=$(t,"anonymous_id"),r=k(e.getItem(i))??k(s.getItem(i));return e.setItem(i,n),s.setItem(i,n),r!==void 0&&r!==n?r:void 0}var T=class{constructor(e,t,n,i){this.storage=e;this.shared=t;this.ids=n;this.namespace=i;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");this.refresh();}refresh(){let e=k(this.shared.getItem(this.key("anonymous_id"))),t=k(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let n=k(this.storage.getItem(this.key("distinct_id")));n?(this.distinctId=n,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}}consent(){return A(this.shared,this.namespace)}setConsent(e){Ue(this.shared,this.namespace,e);}assumeAnonymousId(e){this.anonymousId=e,this.shared.setItem(this.key("anonymous_id"),e),this.storage.setItem(this.key("anonymous_id"),e),this.identified||(this.distinctId=e);}identify(e){let t=!this.identified||this.distinctId!==e,n=this.storage.getItem(this.key("linked_anonymous_id")),i=t||n!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!i||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return $(this.namespace,e)}};var P=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,i=await this.request(t,n,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new d(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,t){let n=this.requireFetch(),i=`${this.host}/v1/messages/read`,r=await this.request(n,i,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!r.ok)throw new d(`mark-read request failed with status ${r.status}`,r.status)}requireFetch(){if(!this.fetch)throw new d("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,n){let i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...n,signal:i?.signal})}finally{r!==void 0&&clearTimeout(r);}}};var u={autocapture:"$autocapture",createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",pageleave:"$pageleave",pageview:"$pageview",screen:"$screen",set:"$set",webVitals:"$web_vitals"},Be=[{emittedBy:"web_and_flutter",meaning:"A click anywhere on the page, with the element that was clicked. The web SDK sends it by default; autocapture: false or autocaptureOptions.clicks: false turns it off. A Flutter app sends each tap as this event too, under TelemetryTapCapture.",name:u.autocapture,properties:["$event_type","$el_description","$el_description_source","$el_action","$el_tag","$el_text","$el_id","$el_classes","$el_href","$current_url","$pathname","$host","$title","$referrer","$screen_name"]},{emittedBy:"web",meaning:"A page shown, including every client-side navigation the History API makes: one per distinct path and query.",name:u.pageview,properties:["$current_url","$pathname","$host","$title","$referrer"]},{emittedBy:"web",meaning:"A landing page left the visitor's sight, by a tab switch, a closed tab or a navigation away, with the seconds it was in front of them so far. A page returned to and left again sends it again with the larger total.",name:u.pageleave,properties:["$engaged_seconds","$page_id","$page_view_id","$page_variant"]},{emittedBy:"web",meaning:"A page's Core Web Vitals, sent once per page load the first time the page leaves the visitor's sight: largest contentful paint, first contentful paint, cumulative layout shift, interaction to next paint and time to first byte, each only when the browser measured it. autocaptureOptions.webVitals: false turns it off.",name:u.webVitals,properties:["$lcp_ms","$fcp_ms","$cls","$inp_ms","$ttfb_ms","$pathname"]},{emittedBy:"flutter",meaning:"A named route pushed or replaced in a Flutter app, the mobile counterpart of $pageview.",name:u.screen,properties:["screen"]},{emittedBy:"every",meaning:"A person becomes known by a distinct id. The anonymous trail before it is joined to them, and any traits ride along under $set.",name:u.identify,properties:["$anon_distinct_id","$set"]},{emittedBy:"every",meaning:"A second id for the same person, so events sent under either resolve to one profile.",name:u.createAlias,properties:["alias"]},{emittedBy:"every",meaning:"The person is placed in a group such as a company or a team; group properties ride along under $set.",name:u.group,properties:["$group_type","$group_key","$set"]},{emittedBy:"every",meaning:"Person properties written without an identify: $set overwrites, $set_once fills only what is still empty.",name:u.set,properties:["$set","$set_once"]},{emittedBy:"every",meaning:"A flag was evaluated for this person, sent once per distinct answer. Experiments attribute exposure from it.",name:u.featureFlagCalled,properties:["$feature_flag","$feature_flag_response"]}],Xt=s=>s.startsWith("$"),Zt=s=>Be.find(e=>e.name===s);var we=6e4;function He(s){return s.length*3<=we||new TextEncoder().encode(s).length<=we}function _e(s){return s>=400&&s<500&&s!==429}var R=class{constructor(e$1={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=e(e$1.fetch),this.maxRetries=e$1.maxRetries??3,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4,this.baseDelayMs=e$1.baseDelayMs??500,this.maxDelayMs=e$1.maxDelayMs??3e4,this.sleep=e$1.sleep??g$1,this.random=e$1.random??Math.random;}async send(e,t={}){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let i=JSON.stringify(e.body),r=t.keepalive===true&&He(i),a;for(let c=0;c<=this.maxRetries;c+=1){try{let h=await this.attempt(n,e,i,r);if(h.ok)return;if(_e(h.status))throw new d(`ingest rejected batch with status ${h.status}`,h.status);a=new d(`ingest transient status ${h.status}`,h.status);}catch(h){if(h instanceof d&&h.status!==void 0&&_e(h.status))throw h;a=h;}c<this.maxRetries&&await this.sleep(this.backoff(c));}throw new d("ingest delivery failed after retries",void 0,{cause:a})}async attempt(e,t,n,i){let r=f$1(),a=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:n,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},...i?{keepalive:!0}:{},method:"POST",signal:r?.signal})}finally{a!==void 0&&clearTimeout(a);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var as="$cta_viewed",ls="$cta_clicked",cs="$cta_dismissed",Fe=(s,e)=>{let t={$cta_id:s.id,$cta_kind:s.kind,$cta_variant:s.variant.key,$cta_version:s.version},n=e===void 0?void 0:s.variant.content.buttons[e];return n&&e!==void 0&&(t.$cta_button=e,t.$cta_button_label=n.label,n.action.kind==="form"&&(t.$cta_form_id=n.action.value)),t},M=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async ctas(e){let t=this.fetch;if(!t)throw new d("no fetch implementation available in this runtime");let n=new URLSearchParams({anonymous:String(e.anonymous),device:e.device,distinct_id:e.distinctId,language:e.language,url:e.url}),i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await t(`${this.host}/v1/ctas?${n.toString()}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(a.status<200||a.status>=300)throw new d(`ctas request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).ctas}finally{r!==void 0&&clearTimeout(r);}}};function Ce(s,e,t){ie(s.eventName),ne(s.distinctId);let n={distinct_id:s.distinctId,event_id:s.eventId??t.uuid(),event_name:s.eventName,properties:s.properties??{},schema_version:1,timestamp:w(s.timestamp??e.now())};return s.context&&(n.context=s.context),s.sessionId&&(n.session_id=s.sessionId),n}var Je="/socket.io/?EIO=4&transport=websocket",ze=250,q=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??Qe,this.setTimer=e.setTimer??((t,n)=>setTimeout(t,n)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Je}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=n=>this.receive(String(n.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(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 n=t.payload?.key;this.lastKey=typeof n=="string"?n:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},ze));}}}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 Qe(s){let e=globalThis.WebSocket;if(!e)throw new d("no WebSocket");return new e(s)}var ks="$form_viewed",xs="$form_started",B=class extends Error{constructor(t,n,i){super(i);a(this,"fields");a(this,"status");this.name="FormRefusedError",this.status=t,this.fields=n;}},K=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=e(e$1.fetch),this.host=h(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async request(e,t){let n=this.fetch;if(!n)throw new d("no fetch implementation available in this runtime");let i=f$1(),r=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a={authorization:`Bearer ${this.projectKey}`};t.body!==void 0&&(a["content-type"]="application/json");let c=await n(`${this.host}${e}`,{body:t.body,headers:a,method:t.method,signal:i?.signal});return {status:c.status,text:await c.text()}}finally{r!==void 0&&clearTimeout(r);}}async form(e,t){let{status:n,text:i}=await this.request(`/v1/forms/${encodeURIComponent(e)}?distinct_id=${encodeURIComponent(t)}`,{method:"GET"});if(n<200||n>=300)throw new d(`form request failed with status ${n}`,n);return JSON.parse(i)}async submit(e,t){let{status:n,text:i}=await this.request(`/v1/forms/${encodeURIComponent(e)}/submissions`,{body:JSON.stringify(t),method:"POST"});if(n>=200&&n<300)return JSON.parse(i).afterSubmit;let r=[],a=`form submission failed with status ${n}`;try{let c=JSON.parse(i);r=c.error?.fields??[],a=c.error?.message??a;}catch{r=[];}throw new B(n,r,a)}};var O=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 We={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Ie(s){return `pdx.${s}.session`}function Is(s,e,t,n){let i={id:t.id,lastActivityAt:n,startedAt:t.startedAt};s.setItem(Ie(e),JSON.stringify(i));}var D=class{constructor(e,t,n,i,r=We){this.storage=e;this.ids=t;this.clock=n;this.namespace=i;this.options=r;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let n=this.live(this.read(),e),i=n!==void 0&&n.id!==t.id?n:t;return this.write({...i,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return Ie(this.namespace)}};var Ye="queue",Xe=1e3,Ee=3e4,H=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},J=class{constructor(e){a(this,"config");a(this,"identity");a(this,"session");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"surveysClient");a(this,"guidesClient");a(this,"captureListeners",new Set);a(this,"formsClient");a(this,"ctasClient");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);a(this,"gates");a(this,"cookielessId");a(this,"storageListeners",new Set);let t=le(e),n=A(t.sharedStorage,t.namespace)??t.consent??null;if(this.gates=[new v(t.storage),new v(t.sharedStorage,xe)],t.consentMode!=="banner"||n?.analytics===true)for(let a of this.gates)a.open();let[i,r]=this.gates;this.config={...t,sharedStorage:r,storage:i},this.identity=new T(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new D(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new O(this.config.maxQueueSize,({dropped:a})=>{this.config.onError(new a$1("queue_overflow",`event queue overflow: dropped ${a.length} oldest event(s)`));}),this.transport=this.config.transport??new R({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 P({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.surveysClient=new C({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.guidesClient=new E({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.formsClient=new K({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.ctasClient=new M({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()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let n={...this.config.defaultProperties(),...t.element===void 0?{}:this.config.describeElement?.(t.element)??{},...t.properties??{}},i=Ce({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:n,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(i);}catch(n){this.config.onError(n);}for(let n of this.captureListeners)try{n(e);}catch(i){this.config.onError(i);}}onCapture(e){return this.captureListeners.add(e),()=>{this.captureListeners.delete(e);}}identify(e,t={}){if(this.isCookieless())return;this.identity.refresh();let n=this.identity.identify(e),i={};n.anonymousToLink!==void 0&&(i.$anon_distinct_id=n.anonymousToLink);let r=ee(),a={...r===null?{}:{$timezone:r},...H(t.traits??{}),...t.set??{}};Object.keys(a).length>0&&(i.$set=a),this.capture(u.identify,{properties:i});}link(e,t,n){if(this.isCookieless())return;let i={$anon_distinct_id:t},r=H(n??{});Object.keys(r).length>0&&(i.$set=r),this.capture(u.identify,{distinctId:e,properties:i});}setConsent(e){this.identity.setConsent(e),e.analytics===true&&this.allowStorage(),e.analytics===false&&this.config.consentMode==="banner"&&this.forbidStorage();}isCookieless(){return !this.gates[0].isOpen}takeCookielessId(e){this.cookielessId=e,this.isCookieless()&&this.identity.assumeAnonymousId(e);}allowStorage(){if(this.isCookieless()){for(let e of this.gates)e.open();this.identity.refresh();for(let e of [...this.storageListeners])e();}}onStorageAllowed(e){return this.storageListeners.add(e),()=>{this.storageListeners.delete(e);}}forbidStorage(){if(!this.isCookieless()){for(let e of ["anonymous_id","distinct_id","linked_anonymous_id","session"])this.config.storage.removeItem(`pdx.${this.config.namespace}.${e}`),this.config.sharedStorage.removeItem(`pdx.${this.config.namespace}.${e}`);for(let e of this.gates)e.close();this.identity.refresh(),this.cookielessId!==void 0&&this.identity.assumeAnonymousId(this.cookielessId);}}consent(){return this.identity.consent()}alias(e){this.capture(u.createAlias,{properties:{alias:e}});}group(e,t,n){let i={$group_key:t,$group_type:e};n&&(i.$set=n),this.capture(u.group,{properties:i});}setPersonProperties(e,t){if(this.isCookieless())return;let n={};e&&(n.$set=e),t&&(n.$set_once=t),this.capture(u.set,{properties:n});}setPersonTraits(e){if(this.isCookieless())return;let t=H(e);Object.keys(t).length!==0&&this.capture(u.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 n=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(n)),n}async getVariant(e){let t=await this.getAllFlags(),n=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,n?.key??String(t[e]??false)),n}async getVariantLocal(e,t={}){let n=await this.flagSnapshot(),i=n.flags.find(h=>h.key===e),r=await this.localContext(t,n.flags),a=i?S(i,n.flags,r):null,c=i?b(i,n.flags,r).enabled:false;return this.recordExposure(e,a?.key??String(c)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let n=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(n)||(this.exposures.add(n),this.capture(u.featureFlagCalled,{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 ge(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let n=await this.flagSnapshot(),i=n.flags.find(c=>c.key===e),r=await this.localContext(t,n.flags),a=i?b(i,n.flags,r).enabled:false;return this.recordExposure(e,(i?S(i,n.flags,r)?.key:void 0)??String(a)),a}async localContext(e,t){let n=this.identity.getDistinctId(),i=e.cohorts;if(i===void 0&&fe(t)){let r=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&r-this.membershipCache.fetchedAt<Ee?i=this.membershipCache.cohorts:(i=await this.flagsClient.memberships(n),this.membershipCache={cohorts:i,distinctId:n,fetchedAt:r});}return {attributes:e.attributes,cohorts:i,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<Ee)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 q({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(n=>this.config.onError(n));},onClosed:n=>{this.stream=void 0,n&&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 getSurveys(e){return this.surveysClient.surveys(this.identity.getDistinctId(),e??this.config.locale)}captureSurveyShown(e){this.capture(ye,{properties:I(e,{})});}captureSurveyDismissed(e){this.capture(ve,{properties:I(e,{})});}captureSurveySent(e,t){this.capture(be,{properties:I(e,t)});}async getGuides(){return this.guidesClient.guides(this.identity.getDistinctId())}captureGuide(e,t,n){this.capture(e,{properties:ke(t,n)});}async getForm(e){return this.formsClient.form(e,this.identity.getDistinctId())}async submitForm(e,t,n,i){let{$page_id:r,$page_variant:a}=this.config.defaultProperties();return this.formsClient.submit(e,{answers:t,challenge:n,distinctId:this.identity.getDistinctId(),isAnonymous:!this.identity.isIdentified(),pageUrl:typeof window>"u"?"":window.location.href,solution:i,...typeof r=="string"&&typeof a=="string"?{pageId:r,pageVariant:a}:{}})}async getCtas(e){return this.ctasClient.ctas({...e,anonymous:!this.identity.isIdentified(),distinctId:this.identity.getDistinctId()})}captureCta(e,t,n){this.capture(e,{properties:Fe(t,n)});}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Xe);try{await this.transport.send({body:{events:e,sent_at:w(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.session?.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}.${Ye}`}};function Js(s){return new J(s)}export{Js as $,V as A,It as B,Et as C,I as D,Mt as E,qt as F,Kt as G,Ot as H,Dt as I,Lt as J,E as K,Se as L,Ve as M,Nt as N,jt as O,Vt as P,ke as Q,G as R,Bt as S,P as T,Is as U,u as V,Be as W,Xt as X,Zt as Y,R as Z,J as _,g as a,Ze as b,Z as c,Me as d,te as e,re as f,oe as g,Ke as h,as as i,ls as j,cs as k,pe as l,he as m,yt as n,ge as o,vt as p,bt as q,F as r,ks as s,xs as t,B as u,ye as v,ve as w,be as x,C as y,Le as z};//# sourceMappingURL=chunk-ZQWZ4CKH.js.map
2
+ //# sourceMappingURL=chunk-ZQWZ4CKH.js.map
@@ -1,4 +1,4 @@
1
- import { F as FetchLike } from './http-BCh716Vs.cjs';
1
+ import { F as FetchLike } from './http-CAOViYSh.cjs';
2
2
  import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-BUXFV_aE.cjs';
3
3
 
4
4
  type CtaKind = 'banner' | 'embedded' | 'popup' | 'slide_in';
@@ -1,4 +1,4 @@
1
- import { F as FetchLike } from './http-BCh716Vs.js';
1
+ import { F as FetchLike } from './http-CAOViYSh.js';
2
2
  import { e as EventProperties, P as ProdantixConfig, b as Consent, f as FlagVariant, I as InboxMessage } from './types-BUXFV_aE.js';
3
3
 
4
4
  type CtaKind = 'banner' | 'embedded' | 'popup' | 'slide_in';
@@ -1,4 +1,4 @@
1
- import { F as FetchLike } from './http-BCh716Vs.js';
1
+ import { F as FetchLike } from './http-CAOViYSh.js';
2
2
 
3
3
  interface ChatTurn {
4
4
  id: string;
@@ -1,4 +1,4 @@
1
- import { F as FetchLike } from './http-BCh716Vs.cjs';
1
+ import { F as FetchLike } from './http-CAOViYSh.cjs';
2
2
 
3
3
  interface ChatTurn {
4
4
  id: string;