@prodantix/sdk 0.7.0-beta.438 → 0.7.0-beta.440

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.
Files changed (43) hide show
  1. package/dist/chat.cjs +5 -107
  2. package/dist/chat.d.cts +93 -8
  3. package/dist/chat.d.ts +93 -8
  4. package/dist/chat.js +5 -107
  5. package/dist/chunk-L4P6GMBC.js +2 -0
  6. package/dist/client-Cz7M6XJC.d.ts +477 -0
  7. package/dist/client-vogZuHfD.d.cts +477 -0
  8. package/dist/{config-C9Njc6-j.d.ts → config-Dmk59mPh.d.ts} +40 -2
  9. package/dist/{config-CpfUyEw8.d.cts → config-Dxf1vAMu.d.cts} +40 -2
  10. package/dist/consent.iife.js +20 -0
  11. package/dist/ctas.iife.js +37 -0
  12. package/dist/forms.iife.js +16 -0
  13. package/dist/guides.iife.js +3 -0
  14. package/dist/index.cjs +1 -1
  15. package/dist/index.d.cts +5 -4
  16. package/dist/index.d.ts +5 -4
  17. package/dist/index.js +1 -1
  18. package/dist/messenger-help.iife.js +1 -1
  19. package/dist/messenger-tickets.iife.js +3 -0
  20. package/dist/messenger.cjs +1 -1
  21. package/dist/messenger.d.cts +1 -1
  22. package/dist/messenger.d.ts +1 -1
  23. package/dist/messenger.iife.js +5 -107
  24. package/dist/messenger.js +1 -1
  25. package/dist/node.cjs +1 -1
  26. package/dist/node.d.cts +3 -2
  27. package/dist/node.d.ts +3 -2
  28. package/dist/node.js +1 -1
  29. package/dist/pages.iife.js +2 -0
  30. package/dist/prodantix-push-sw.js +3 -0
  31. package/dist/surveys.iife.js +2 -0
  32. package/dist/{transport-DKFvkfX4.d.ts → transport-C4mkCaix.d.ts} +1 -1
  33. package/dist/{transport-DN9pXyrX.d.cts → transport-C9C4hqlF.d.cts} +1 -1
  34. package/dist/{types-Q2VNlJbG.d.cts → types-BUXFV_aE.d.cts} +11 -0
  35. package/dist/{types-Q2VNlJbG.d.ts → types-BUXFV_aE.d.ts} +11 -0
  36. package/dist/web.cjs +36 -1
  37. package/dist/web.d.cts +185 -4
  38. package/dist/web.d.ts +185 -4
  39. package/dist/web.js +36 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-D6PMLUYA.js +0 -2
  42. package/dist/client-CL6Xvhay.d.cts +0 -135
  43. package/dist/client-QyKW0LFW.d.ts +0 -135
@@ -1,111 +1,9 @@
1
- (function(){'use strict';var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var h=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var P=class extends Error{constructor(t,r,i){super(r,i);h(this,"code");this.code=t,this.name="ProdantixError";}},N=class extends P{constructor(e){super("config",e),this.name="ConfigError";}};var E=class extends P{constructor(t,r,i){super("transport",t,i);h(this,"status");this.status=r,this.name="TransportError";}};function _(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function F(n){return n.replace(/\/+$/,"")}var q="X-Prodantix-Conversation-Token",O="prodantix.chat.handle";function pe(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var H=class{constructor(e){this.options=e;h(this,"fetchImpl");h(this,"fileFetchImpl");h(this,"host");h(this,"storage");h(this,"handle");h(this,"identity",null);var t,r;this.fetchImpl=_(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,a)=>fetch(i,a)),this.host=F(e.host),this.storage=(r=e.storage)!=null?r:pe(),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){var r,i,a;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(a=this.storage)==null||a.set(O,JSON.stringify(this.handle)),true)}async send(e,t,r){var o;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (o=a==null?void 0:a.turn)!=null?o:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async helpCentre(e,t){let r=Object.entries({...t,...this.options.locale?{lang:this.options.locale}:{}}).map(([i,a])=>`${i}=${encodeURIComponent(a)}`).join("&");return this.request("GET",`/v1/messenger/articles${e}${r?`?${r}`:""}`)}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r,i,a;let e=(t=this.storage)==null?void 0:t.get(O);if(!e)return null;try{let o=JSON.parse(e);if(typeof o.conversationId=="string"&&typeof o.token=="string")return {conversationId:o.conversationId,token:o.token}}catch(o){(i=(r=this.options).onError)==null||i.call(r,o);}return (a=this.storage)==null||a.remove(O),null}async fileRequest(e,t,r,i,a){var s,p,d,l;let o={authorization:`Bearer ${this.options.apiKey}`,[q]:r};a&&(o["content-type"]=a.type||"application/octet-stream");try{let c=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:o,method:e});if(c.ok)return await i(c);(p=(s=this.options).onError)==null||p.call(s,new E(`prodantix chat ${t}: ${c.status}`,c.status));}catch(c){(l=(d=this.options).onError)==null||l.call(d,c);}return null}async request(e,t,r={}){var o,s,p,d,l,c;let i=this.fetchImpl;if(!i)return (s=(o=this.options).onError)==null||s.call(o,new E("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[q]=r.token);try{let m=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),g=await m.text();return m.ok?g?JSON.parse(g):{}:((d=(p=this.options).onError)==null||d.call(p,new E(`prodantix chat ${t}: ${m.status}`,m.status)),null)}catch(m){return (c=(l=this.options).onError)==null||c.call(l,m),null}}};var ue={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function I(n,e){var s,p,d,l,c,m;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=ue[(p=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?p:""];if(!r)return false;let i=(l=(d=t.find(g=>g.type==="hour"))==null?void 0:d.value)!=null?l:"",a=(m=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?m:"",o=`${i}:${a}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var C={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"},he=["quiet","standard"],me=["round","square"],ge=["rounded","tailed"],fe=["filled","outlined"],be=["circle","pill","squircle"],xe=["filled","outlined"],ye=["avatar","glyph","team_faces"],ve=["large","medium","small"],Se=["above","hidden","inline"],ke=["beside_name","none","under_turn"],Ce=["time","time_and_latency"],w=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,j=(n,e)=>typeof n=="boolean"?n:e,Ee={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"]},we={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Te={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"]},Ae={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Le={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function M(n){var g,k,S,f,x,u,v,b,y,T,B,D,G;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:Ee[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:we[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:Te[o],p=typeof e.skin=="string"?e.skin:void 0,d=p===void 0?void 0:Ae[p],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=l===void 0?void 0:Le[l],m={bubbleFill:w(e.bubbleFill,fe,(g=c==null?void 0:c[1])!=null?g:C.bubbleFill),bubbleShape:w(e.bubbleShape,ge,(k=c==null?void 0:c[0])!=null?k:C.bubbleShape),composerShape:w(e.composerShape,me,(S=d==null?void 0:d[1])!=null?S:C.composerShape),dayDividers:j(e.dayDividers,(f=s==null?void 0:s[0])!=null?f:C.dayDividers),launcherContent:w(e.launcherContent,ye,(x=r==null?void 0:r[2])!=null?x:C.launcherContent),launcherFill:w(e.launcherFill,xe,(u=r==null?void 0:r[1])!=null?u:C.launcherFill),launcherShape:w(e.launcherShape,be,(v=r==null?void 0:r[0])!=null?v:C.launcherShape),launcherSize:w(e.launcherSize,ve,(b=r==null?void 0:r[3])!=null?b:C.launcherSize),nameAvatar:j(e.nameAvatar,(y=a==null?void 0:a[1])!=null?y:C.nameAvatar),namePlacement:w(e.namePlacement,Se,(T=a==null?void 0:a[0])!=null?T:C.namePlacement),skin:w(e.skin,he,(B=d==null?void 0:d[0])!=null?B:C.skin),stampContent:w(e.stampContent,Ce,(D=s==null?void 0:s[2])!=null?D:C.stampContent),stampPlacement:w(e.stampPlacement,ke,(G=s==null?void 0:s[1])!=null?G:C.stampPlacement)};return m.stampPlacement==="beside_name"&&m.namePlacement==="hidden"&&(m.stampPlacement="under_turn"),m}function W(n){var r,i,a,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(o=(a=e[0])==null?void 0:a.slice(0,2))!=null?o:"").toUpperCase()}var Pe="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",Ne={large:66,medium:56,small:46},_e={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;"},Fe={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);"},He={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;}"},Ie=".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}",Me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Re={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},$e={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Oe={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function Y(n,e,t,r){return `.launcher{--fab-size:${Ne[r]}px;${_e[n]}${Fe[e]}}${He[t]}${Ie}${Me[n]}${Re[e]}${$e[n]}${Oe[n]}`}function J(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="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="${Pe}"/></svg>`,i.append(...a.childNodes,K()),i}return n==="avatar"?(i.append(X(t[0],e,r),K()),i):(i.append(U(t,e,r),K()),i)}function U(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(X(i,e,t));return r}function X(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function K(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}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:(n,e)=>`That file is ${n}. 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:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},L={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...C};function Ue(n,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let r=document.createElement("img");return r.src=e,r.alt="",r.width=12,r.height=12,t.append(r,n),t}var ze={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}"},Be={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}"},De={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}"},Ge={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},qe={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}"},je=".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}",We='.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)}',Ye={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}"},Je=".lat{font-size:11px;opacity:.7;margin-left:6px}",V=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
1
+ (function(){'use strict';var ce=Object.defineProperty;var de=(n,e,t)=>e in n?ce(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var p=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var _=class extends Error{constructor(t,r,i){super(r,i);p(this,"code");this.code=t,this.name="ProdantixError";}},F=class extends _{constructor(e){super("config",e),this.name="ConfigError";}};var w=class extends _{constructor(t,r,i){super("transport",t,i);p(this,"status");this.status=r,this.name="TransportError";}};function I(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function H(n){return n.replace(/\/+$/,"")}var j="X-Prodantix-Conversation-Token",U="prodantix.chat.handle";function pe(){let n=globalThis.localStorage;if(n)return {get:e=>n.getItem(e),remove:e=>n.removeItem(e),set:(e,t)=>n.setItem(e,t)}}var M=class{constructor(e){this.options=e;p(this,"fetchImpl");p(this,"fileFetchImpl");p(this,"host");p(this,"storage");p(this,"handle");p(this,"identity",null);p(this,"fromArticle",null);var t,r;this.fetchImpl=I(e.fetchImpl),this.fileFetchImpl=(t=e.fileFetchImpl)!=null?t:((i,a)=>fetch(i,a)),this.host=H(e.host),this.storage=(r=e.storage)!=null?r:pe(),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){var r,i,a;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,fromArticle:this.fromArticle,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.fromArticle=null,(a=this.storage)==null||a.set(U,JSON.stringify(this.handle)),true)}cameFrom(e){this.fromArticle={language:e.language,pageId:e.pageId};}async send(e,t,r){var s;if(!await this.ensureThread())return null;let i=this.handle;if(!i)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(i.conversationId)}/turns`,{body:{attachmentIds:r,body:e,pageContext:t},token:i.token});return (s=a==null?void 0:a.turn)!=null?s:null}async upload(e){if(!await this.ensureThread())return null;let t=this.handle;return t?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,t.token,async r=>JSON.parse(await r.text()),e):null}async file(e){let t=this.handle;return t?this.fileRequest("GET",e,t.token,r=>r.blob()):null}async helpCentre(e,t,r){let i=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(r?"POST":"GET",`/v1/messenger/articles${e}${i?`?${i}`:""}`,r?{body:{...r,distinctId:this.options.distinctId}}:{})}get visitor(){return this.identity&&{...this.identity,distinctId:this.options.distinctId}}edge(e,t,r){return this.request(t?"POST":"GET",e,{body:t,token:r})}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r,i,a;let e=(t=this.storage)==null?void 0:t.get(U);if(!e)return null;try{let s=JSON.parse(e);if(typeof s.conversationId=="string"&&typeof s.token=="string")return {conversationId:s.conversationId,token:s.token}}catch(s){(i=(r=this.options).onError)==null||i.call(r,s);}return (a=this.storage)==null||a.remove(U),null}async fileRequest(e,t,r,i,a){var o,u,d,l;let s={authorization:`Bearer ${this.options.apiKey}`,[j]:r};a&&(s["content-type"]=a.type||"application/octet-stream");try{let c=await this.fileFetchImpl(`${this.host}${t}`,{body:a,headers:s,method:e});if(c.ok)return await i(c);(u=(o=this.options).onError)==null||u.call(o,new w(`prodantix chat ${t}: ${c.status}`,c.status));}catch(c){(l=(d=this.options).onError)==null||l.call(d,c);}return null}async request(e,t,r={}){var s,o,u,d,l,c;let i=this.fetchImpl;if(!i)return (o=(s=this.options).onError)==null||o.call(s,new w("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[j]=r.token);try{let h=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),g=await h.text();return h.ok?g?JSON.parse(g):{}:((d=(u=this.options).onError)==null||d.call(u,new w(`prodantix chat ${t}: ${h.status}`,h.status)),null)}catch(h){return (c=(l=this.options).onError)==null||c.call(l,h),null}}};var ue={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function R(n,e){var o,u,d,l,c,h;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=ue[(u=(o=t.find(g=>g.type==="weekday"))==null?void 0:o.value)!=null?u:""];if(!r)return false;let i=(l=(d=t.find(g=>g.type==="hour"))==null?void 0:d.value)!=null?l:"",a=(h=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?h:"",s=`${i}:${a}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=s&&s<g.close)}var C={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"},he=["quiet","standard"],ge=["round","square"],me=["rounded","tailed"],fe=["filled","outlined"],be=["circle","pill","squircle"],ye=["filled","outlined"],xe=["avatar","glyph","team_faces"],ve=["large","medium","small"],ke=["above","hidden","inline"],Se=["beside_name","none","under_turn"],Ce=["time","time_and_latency"],A=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,W=(n,e)=>typeof n=="boolean"?n:e,Ee={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"]},Te={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},we={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"]},Ae={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Le={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function $(n){var g,S,k,f,y,m,b,v,x,T,E,P,q;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:Ee[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:Te[i],s=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,o=s===void 0?void 0:we[s],u=typeof e.skin=="string"?e.skin:void 0,d=u===void 0?void 0:Ae[u],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=l===void 0?void 0:Le[l],h={bubbleFill:A(e.bubbleFill,fe,(g=c==null?void 0:c[1])!=null?g:C.bubbleFill),bubbleShape:A(e.bubbleShape,me,(S=c==null?void 0:c[0])!=null?S:C.bubbleShape),composerShape:A(e.composerShape,ge,(k=d==null?void 0:d[1])!=null?k:C.composerShape),dayDividers:W(e.dayDividers,(f=o==null?void 0:o[0])!=null?f:C.dayDividers),launcherContent:A(e.launcherContent,xe,(y=r==null?void 0:r[2])!=null?y:C.launcherContent),launcherFill:A(e.launcherFill,ye,(m=r==null?void 0:r[1])!=null?m:C.launcherFill),launcherShape:A(e.launcherShape,be,(b=r==null?void 0:r[0])!=null?b:C.launcherShape),launcherSize:A(e.launcherSize,ve,(v=r==null?void 0:r[3])!=null?v:C.launcherSize),nameAvatar:W(e.nameAvatar,(x=a==null?void 0:a[1])!=null?x:C.nameAvatar),namePlacement:A(e.namePlacement,ke,(T=a==null?void 0:a[0])!=null?T:C.namePlacement),skin:A(e.skin,he,(E=d==null?void 0:d[0])!=null?E:C.skin),stampContent:A(e.stampContent,Ce,(P=o==null?void 0:o[2])!=null?P:C.stampContent),stampPlacement:A(e.stampPlacement,Se,(q=o==null?void 0:o[1])!=null?q:C.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function Y(n){var r,i,a,s;let e=n.split(/\s+/).filter(o=>o.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(i=e[1])==null?void 0:i.slice(0,1)}`:(s=(a=e[0])==null?void 0:a.slice(0,2))!=null?s:"").toUpperCase()}var Pe="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",Ne={large:66,medium:56,small:46},_e={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;"},Fe={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);"},Ie={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;}"},He=".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}",Me={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Re={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},$e={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Oe={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function J(n,e,t,r){return `.launcher{--fab-size:${Ne[r]}px;${_e[n]}${Fe[e]}}${Ie[t]}${He}${Me[n]}${Re[e]}${$e[n]}${Oe[n]}`}function X(n,e,t,r=i=>i){let i=document.createDocumentFragment();if(n==="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="${Pe}"/></svg>`,i.append(...a.childNodes,z()),i}return n==="avatar"?(i.append(V(t[0],e,r),z()),i):(i.append(B(t,e,r),z()),i)}function B(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let i of n.slice(0,2))r.append(V(i,e,t));return r}function V(n,e,t){let r=document.createElement("span");if(r.className="av",r.setAttribute("aria-hidden","true"),n&&(r.style.background=n.tone),n!=null&&n.avatarUrl){let i=document.createElement("img");return i.alt="",i.src=t(n.avatarUrl),r.append(i),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function z(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}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:(n,e)=>`That file is ${n}. 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:n=>{let e=new Date(n);return Number.isNaN(e.getTime())?"":`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`},title:"Support",unreadLabel:n=>`${n} unread`},N={accentColor:"#5958fc",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...C};function Ue(n,e){let t=document.createElement("a");t.className="powered",t.href="https://prodantix.com",t.target="_blank",t.rel="noopener";let r=document.createElement("img");return r.src=e,r.alt="",r.width=12,r.height=12,t.append(r,n),t}var ze={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}"},Be={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}"},De={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}"},Ge={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},qe={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}"},je=".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}",We='.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)}',Ye={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}"},Je=".lat{font-size:11px;opacity:.7;margin-left:6px}",Q=`--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
- --online: oklch(72% 0.13 163.23);`;function Xe(n){return n==="light"?"":n==="dark"?`:host { ${V} }`:`@media (prefers-color-scheme: dark) {
3
+ --online: oklch(72% 0.13 163.23);`;function Xe(n){return n==="light"?"":n==="dark"?`:host { ${Q} }`:`@media (prefers-color-scheme: dark) {
4
4
  :host {
5
- ${V}
5
+ ${Q}
6
6
  }
7
- }`}var Ve=/https?:\/\/[^\s<>"]+/g,Qe=/[.,;:!?)]$/,Ze=n=>{let e=n;for(;Qe.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function et(n,e){var r;let t=0;for(let i of e.matchAll(Ve)){let a=(r=i.index)!=null?r:0,o=Ze(i[0]);a>t&&n.append(e.slice(t,a));let s=document.createElement("a");s.href=o,s.target="_blank",s.rel="noopener noreferrer",s.textContent=o,n.append(s),t=a+o.length;}t<e.length&&n.append(e.slice(t));}var tt=["P","BR","STRONG","EM","A","UL","OL","LI"],nt=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",rt=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),it=n=>[...n.querySelectorAll("*")].every(e=>tt.includes(e.tagName)&&[...e.attributes].every(t=>rt(e.tagName,t)));function at(n,e="system"){let t=M(n),r=n.launcherPosition==="bottom_left"?"left":"right",i=n.accentColor;return `${`
8
- :host {
9
- all: initial; z-index: 2147483000; --a: ${i};
10
- --paper: #fff; --ink: #0f172a; --ink-3: rgba(0,0,0,.55);
11
- --fill: #f1f5f9; --hairline: #e2e8f0; --ink-2: rgba(0,0,0,.72);
12
- --online: oklch(53.8% 0.1274 163.23);
13
- color-scheme: ${e==="system"?"light dark":e};
14
- }
15
- ${Xe(e)}
16
- * { box-sizing: border-box; font-family: system-ui, sans-serif; }
17
- .launcher {
18
- z-index: 2147483000; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
19
- border-radius: 28px; border: none; cursor: pointer;
20
- display: inline-flex; align-items: center; justify-content: center;
21
- background: ${i}; color: #fff; font-size: 24px;
22
- box-shadow: 0 4px 12px rgba(0,0,0,.2);
23
- }
24
- .launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
25
- .launcher { transition: background-color 120ms ease; }
26
- .launcher:hover { background: color-mix(in srgb, #000 12%, ${i}); }
27
- .launcher:active { background: color-mix(in srgb, #000 20%, ${i}); }
28
- @media (prefers-reduced-motion: reduce) {
29
- .launcher { transition: none; }
30
- }
31
- .badge {
32
- position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
33
- border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
34
- display: flex; align-items: center; justify-content: center; padding: 0 4px;
35
- }
36
- .badge[hidden] { display: none; }
37
- .panel {
38
- z-index: 2147483001; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
39
- height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
40
- border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
41
- display: flex; flex-direction: column; overflow: hidden;
42
- }
43
- .header { position: relative; padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
44
- .header h2 { margin: 0; font-size: 15px; }
45
- .header .faces { display: flex; }
46
- .header .av { width: 36px; height: 36px; box-shadow: 0 0 0 2px var(--a); }
47
- .header .av + .av { margin-left: -12px; }
48
- .headmain { display: flex; flex-direction: column; }
49
- .header .status { display: flex; align-items: center; gap: 6px; margin: 5px 0 0; font-size: 12.5px; color: rgb(255 255 255 / 80%); }
50
- .header .status .live { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--online); box-shadow: 0 0 0 2px var(--paper); }
51
- .panel.closed .status { display: none; }
52
- .header .close { position: absolute; top: 8px; right: 8px; }
53
- .close {
54
- display: inline-flex; align-items: center; justify-content: center;
55
- width: 32px; height: 32px; padding: 0;
56
- background: none; border: none; border-radius: 8px;
57
- color: inherit; cursor: pointer;
58
- transition: background-color 120ms ease;
59
- }
60
- .close svg { display: block; width: 22px; height: 22px; }
61
- .close:hover { background: color-mix(in srgb, currentColor 14%, transparent); }
62
- .close:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
63
- .log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
64
- .turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
65
- .turn.end_user { align-self: flex-end; background: ${i}; color: #fff; }
66
- .turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
67
- .turn.ai a { color: ${i}; text-decoration: underline; overflow-wrap: anywhere; }
68
- .author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
69
- .turn[data-pending] { opacity: .6; }
70
- .turn[data-failed] { opacity: 1; box-shadow: inset 0 0 0 1px #dc2626; }
71
- .retry { display: block; margin: 5px 0 0; padding: 0; background: none; border: 0; color: inherit; font: inherit; font-size: 11.5px; text-decoration: underline; cursor: pointer; opacity: .85; }
72
- .away { display: flex; gap: 10px; align-items: flex-start; margin: 12px 12px 0; padding: 10px 14px; font-size: 13px; line-height: 1.43; color: ${i}; background: color-mix(in srgb, ${i} 12%, transparent); border-radius: 4px; }
73
- .awayglyph { flex: none; width: 16px; height: 16px; margin-top: 1px; border: 1.5px solid currentColor; border-radius: 50%; }
74
- .empty { display: flex; flex-direction: column; gap: 8px; padding: 20px 16px; }
75
- .empty h3 { margin: 0; font-size: 18px; font-weight: 640; letter-spacing: -.015em; }
76
- .empty > p { margin: 0 0 8px; font-size: 13.5px; color: var(--ink-2); }
77
- .prompt {
78
- position: relative; display: flex; align-items: center; min-height: 44px; padding: 10px 14px; text-align: left;
79
- font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--ink);
80
- background: none; border: 1px solid var(--hairline); border-radius: 8px; cursor: pointer;
81
- }
82
- .promptwords { min-width: 0; overflow-wrap: anywhere; }
83
- .promptwords > :last-child { margin-bottom: 0; }
84
- .prompt p { margin: 0 0 16px; line-height: 1.6; }
85
- .prompt ul, .prompt ol { margin: 0 0 16px; padding-left: 32px; }
86
- .prompt li { margin: 8px 0; line-height: 1.6; }
87
- .prompt a { position: relative; z-index: 1; color: ${i}; text-decoration: underline; overflow-wrap: anywhere; }
88
- .promptpress { position: absolute; inset: 0; padding: 0; background: none; border: 0; border-radius: inherit; cursor: pointer; }
89
- .promptpress:focus-visible { outline: 2px solid ${i}; outline-offset: 2px; }
90
- .av { width: 30px; height: 30px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 650; color: #fff; background: oklch(52% 0.17 22); }
91
- .av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
92
- .av img { width: 100%; height: 100%; display: block; object-fit: cover; border-radius: inherit; }
93
- .composer { display: flex; gap: 6px; padding: 10px; border-top: 1px solid var(--hairline); }
94
- .composer input { flex: 1; min-width: 0; height: 36px; padding: 0 12px; border: 0; border-radius: 8px; font-size: 14px; background: var(--fill); color: var(--ink); }
95
- .composer input:focus-visible { outline: 2px solid ${i}; }
96
- .composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 56px; height: 36px; padding: 0 14px; background: ${i}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 13.5px; font-weight: 550; }
97
- .composer button:hover { background: color-mix(in srgb, #000 12%, ${i}); }
98
- .composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
99
- .composer button .sendglyph { display: none; width: 17px; height: 17px; }
100
- .composer button:focus-visible { outline: 2px solid #0b0e14; }
101
- .powered { display: flex; align-items: center; justify-content: center; gap: 4px; height: 24px; font-size: 11px; font-weight: 500; color: var(--ink-3); text-decoration: none; }
102
- .powered:hover { color: var(--ink-2); }
103
- .powered:focus-visible { outline: 2px solid var(--ink); outline-offset: -2px; }
104
- .powered img { width: 12px; height: 12px; }
105
- @media (prefers-reduced-motion: no-preference) {
106
- .panel { animation: rise 180ms ease-out; }
107
- @keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
108
- }
109
- .scrim,.grip{display:none}@media (max-width:770px){.panel{inset:auto 0 0;width:100%;max-width:none;height:86dvh;max-height:86dvh}:host .panel{border-bottom-left-radius:0;border-bottom-right-radius:0}.scrim{display:block;position:fixed;inset:0;z-index:2147483000;background:rgb(15 23 42/.24)}.grip{display:block;position:absolute;top:7px;left:calc(50% - 17px);width:34px;height:4px;border-radius:2px;background:currentColor;opacity:.45}.panel:not([data-dragging]){transition:translate .2s}.composer{padding-bottom:max(12px,env(safe-area-inset-bottom))}}
110
- `}${Be[t.composerShape]}${ze[t.skin]}${Y(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${De[t.bubbleShape]}${Ge[t.bubbleFill]}${qe[t.namePlacement]}${t.nameAvatar?je:""}${t.dayDividers?We:""}${Ye[t.stampPlacement]}${t.stampContent==="time_and_latency"?Je:""}`}var ot=["end_user","agent","ai"];function st(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var lt='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',R=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;h(this,"root");h(this,"strings");h(this,"settings");h(this,"appearance");h(this,"launcher");h(this,"badge");h(this,"panel",null);h(this,"scrim",null);h(this,"lastFocused",null);h(this,"unread",0);h(this,"pendingTurns",0);h(this,"openNow");h(this,"styles");h(this,"scheme");h(this,"picked",null);h(this,"objectUrls",[]);h(this,"helpLoader");h(this,"kit",null);h(this,"kitLoad",null);h(this,"filesLoader");h(this,"filesKit",null);h(this,"filesLoad",null);var o;this.strings={...Ke,...r},this.appearance={...L,...i},this.settings=M({...L,...i}),this.root=e.attachShadow({mode:(o=a.shadowMode)!=null?o:"closed"}),this.openNow=I(this.appearance.availability,new Date),this.scheme=a.scheme,this.helpLoader=a.help,this.filesLoader=a.files,this.styles=pt(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(J(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...L,...e},this.settings=M(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){var e;this.styles(`${at(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(((e=this.appearance.attachments)==null?void 0:e.enabled)===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):((this.kitLoad)!=null||(this.kitLoad=this.helpLoader().then(t=>(this.kit=t,this.paint(),t))),this.kitLoad)}loadFiles(){return this.filesLoader?((this.filesLoad)!=null||(this.filesLoad=this.filesLoader().then(t=>(this.filesKit=t,this.paint(),t))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("span");r.className="grip",r.setAttribute("aria-hidden","true"),t.append(r);let i=(v=this.appearance.team)!=null?v:[];i.length>0&&t.append(U(i,this.strings,b=>this.client.avatarUrl(b)));let a=document.createElement("div");a.className="headmain";let o=document.createElement("h2");o.textContent=this.strings.title;let s=document.createElement("p");s.className="status";let p=document.createElement("span");p.className="live",p.setAttribute("aria-hidden","true"),s.append(p,this.strings.replyTime),a.append(o,s);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=lt,d.addEventListener("click",()=>this.close()),t.append(a,d);let l=document.createElement("div");l.className="log",l.setAttribute("role","log"),l.setAttribute("aria-live","polite"),l.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let m=document.createElement("input");m.type="text",m.setAttribute("aria-label",this.strings.inputPlaceholder),m.placeholder=this.strings.inputPlaceholder;let g=document.createElement("button");g.type="submit",g.setAttribute("aria-label",this.strings.sendLabel),g.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let k=document.createElement("span");k.className="sendtext",k.textContent=this.strings.sendLabel,g.append(k),c.append(m,g),c.addEventListener("submit",b=>{b.preventDefault(),this.submit(m,l);}),e.append(t,l,c),this.appearance.poweredBy&&e.append(Ue(this.appearance.poweredBy,this.client.avatarUrl("/messenger-mark.png"))),e.addEventListener("keydown",b=>this.onKeydown(b,e,d));let S=document.createElement("div");S.className="scrim",S.addEventListener("click",()=>this.close()),this.root.append(S,e),this.panel=e,this.scrim=S,dt(e,()=>this.close()),m.focus();let f=this.appearance.attachments,[x]=await Promise.all([this.client.load(),this.loadKit(),f!=null&&f.enabled&&this.client.upload?this.loadFiles():null]);if(x!=null&&x.turns.some(b=>{var y;return (y=b.attachments)==null?void 0:y.length})&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&(f!=null&&f.enabled)&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:b=>{this.picked=b;},objectUrl:b=>this.objectUrl(b),removeFileLabel:this.strings.removeFileLabel,root:this.root},c,m,l,f);let u=this.helpHost();(u==null?void 0:u.placement)==="tab"&&u.host.source.collections&&u.host.source.collectionArticles&&u.kit.helpTab(u.host),(u==null?void 0:u.placement)==="while_typing"&&u.kit.whileTyping(u.host,m,c),x&&x.turns.length>0?this.renderThread(l,x):this.renderFirstRun(l,m),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,r.append(i);let a=this.helpHost();if((a==null?void 0:a.placement)==="first_view")a.kit.firstView(a.host,r);else {let s=document.createElement("p");s.textContent=this.strings.emptyBody,r.append(s);}this.appearance.starterPrompts.filter(nt).forEach((s,p)=>{let d=document.createElement("div");d.className="prompt";let l=document.createElement("div");l.className="promptwords",l.id=`prompt-${p}`;let c=document.createElement("template");c.innerHTML=s.html,it(c.content)?l.append(c.content):l.textContent=s.text;for(let g of l.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let m=document.createElement("button");m.className="promptpress",m.type="button",m.setAttribute("aria-labelledby",l.id),m.addEventListener("click",()=>{t.value=s.text,this.submit(t,e);}),d.append(l,m),r.append(d);}),e.replaceChildren(r);}helpHost(){let e=this.appearance.help,{kit:t,panel:r}=this,i=e&&t&&r?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:r,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){var e;if(this.panel){this.panel.remove(),(e=this.scrim)==null||e.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let t of this.objectUrls)URL.revokeObjectURL(t);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){var t;if(this.panel&&((t=e.attachments)!=null&&t.length)&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var s,p,d;(s=e.querySelector(".empty"))==null||s.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await((d=(p=this.client).upload)==null?void 0:d.call(p,r)):void 0,o=a===null?null:await this.client.send(t,st(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),o){i.dataset.turnId=o.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var o;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((o=t.querySelector(".body"))!=null?o:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var c,m,g,k,S,f,x;(c=e.querySelector(".empty"))==null||c.remove();let i=ot.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,o=document.createElement("div");if(o.className=`turn ${i}`,o.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let u=document.createElement("span");if(u.className=i==="ai"?"av bot":"av",u.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let v=document.createElement("img");v.alt="",v.src=this.client.avatarUrl(t.authorAvatarUrl),u.append(v);}else {u.textContent=i==="ai"?this.strings.aiLabel:W(this.agentName(t));let v=i==="agent"?(g=(m=this.appearance.team)==null?void 0:m.find(b=>b.name===t.authorName))==null?void 0:g.tone:void 0;v&&(u.style.background=v);}o.append(u);}let p=document.createElement("div");if(p.className="body",i==="end_user"){let u=this.filesKit,v=b=>this.objectUrl(b);r&&(u==null||u.drawFile(p,r.name,r.type,r.size,Promise.resolve(r),v));for(let b of (k=t.attachments)!=null?k:[])u==null||u.drawFile(p,b.name,b.contentType,b.bytes,(x=(f=(S=this.client).file)==null?void 0:f.call(S,b.url))!=null?x:Promise.resolve(null),v);}let d=i!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(i==="ai"?et(l,t.body):l.textContent=t.body,d||i==="ai"&&a.namePlacement==="hidden"){let u=document.createElement("div");u.className=i==="ai"?"author ai":"author",u.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&u.append(this.stamp(t)),a.namePlacement==="inline"?(u.classList.add("below"),p.append(l,u)):p.append(u,l);}else t.body&&p.append(l);return a.stampPlacement==="under_turn"&&p.append(this.stamp(t)),o.append(p),e.append(o),e.scrollTop=e.scrollHeight,o}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(p=>!p.closest("[hidden]")&&!p.hidden);if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},ct="(max-width: 770px)";function dt(n,e){let t=null;n.addEventListener("pointerdown",i=>{var o,s;if(t||i.button!==0||!((o=globalThis.matchMedia)!=null&&o.call(globalThis,ct).matches))return;let a=i.target;if(!(a!=null&&a.closest("a, button, input, textarea, iframe"))){for(;a&&a!==n;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},(s=n.setPointerCapture)==null||s.call(n,i.pointerId),n.dataset.dragging="";}}),n.addEventListener("pointermove",i=>{if((t==null?void 0:t.id)!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),n.style.translate=`0 ${t.offset}px`;});let r=i=>{let a=t;if((a==null?void 0:a.id)!==i.pointerId)return;t=null,delete n.dataset.dragging;let o=a.offset>Math.min(72,n.getBoundingClientRect().height*.4),s=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;o||s?e():n.style.translate="";};n.addEventListener("pointerup",r),n.addEventListener("pointercancel",r);}var pt=n=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in n&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return n.adoptedStyleSheets=[t],r=>t.replaceSync(r)}let e=document.createElement("style");return n.append(e),t=>{e.textContent=t;}};function Q(n){return `40${JSON.stringify(n)}`}function Z(){return "3"}function ee(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=z(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=z(i);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=z(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function z(n){try{return JSON.parse(n)}catch(e){return null}}var ut="/socket.io/?EIO=4&transport=websocket",$=class{constructor(e){this.options=e;h(this,"socket",null);h(this,"heartbeat",null);h(this,"ready",false);h(this,"closed",false);h(this,"heartbeatWindow",45e3);h(this,"factory");h(this,"setTimer");h(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ht,this.setTimer=(r=e.setTimer)!=null?r:((a,o)=>setTimeout(a,o)),this.clearTimer=(i=e.clearTimer)!=null?i:(a=>clearTimeout(a));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${ut}`,t;try{t=this.factory(e);}catch(r){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();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,a,o;let t=ee(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(Q(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(Z());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(a=this.socket)==null||a.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}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(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ht(n){let e=globalThis.WebSocket;if(!e)throw new E("no WebSocket");return new e(n)}var mt=6e4;function te(n){var x,u,v,b;let e=globalThis.document;if(!e)throw new N("prodantix chat requires a document; mount it in the browser");let t=(x=n.mountPoint)!=null?x:e.createElement("div");n.mountPoint||e.body.append(t);let r=new H(n),i=new R(t,r,n.strings,n.appearance,{files:n.files,help:n.help}),a=(v=(u=n.appearance)==null?void 0:u.availability)!=null?v:L.availability,o,s=()=>{i.setOpenNow(I(a,new Date)),o=setTimeout(s,mt);};s();let p=new Set,d,l=null,c=(b=n.pollIntervalMs)!=null?b:15e3,m=y=>{p.has(y.id)||y.authorKind==="end_user"||(p.add(y.id),i.onIncomingTurn(y));},g=async()=>{if(!r.hasThread)return;let y=await r.load();if(y){for(let T of y.turns)m(T);p=new Set(y.turns.map(T=>T.id));}},k=()=>{d||c<=0||(d=setInterval(()=>void g(),c));},S=()=>{d&&clearInterval(d),d=void 0;},f=()=>{if(l||!n.socketHost)return;let y=r.socketAuth;y&&(l=new $({auth:y,host:n.socketHost,onClosed:T=>{l=null,k(),T&&f();},onReady:S,onTurn:m,socketFactory:n.socketFactory}),l.open());};return k(),f(),{close:()=>i.close(),destroy:()=>{S(),clearTimeout(o),l==null||l.close(),l=null,i.close(),t.remove();},identify:y=>r.identify(y),open:()=>{i.open().then(f);}}}var gt="prodantix.messenger.config",ne=n=>{var t,r,i,a;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((a=(i=n.document)==null?void 0:i.documentElement)==null?void 0:a.lang)||void 0},re=(n,e)=>`${gt}:${n}:${e!=null?e:""}`;function ie(n,e,t){let r=n==null?void 0:n.get(re(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function ae(n){var a,o,s,p,d;let e=_(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new E("no fetch available for the prodantix messenger")),null;let t=F(n.host),r=re(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (o=n.onError)==null||o.call(n,new E(`prodantix messenger config: ${l.status}`,l.status)),null;let c=JSON.parse(await l.text());return c.enabled?((p=n.storage)==null||p.set(r,JSON.stringify({apiKey:n.apiKey,config:c})),c):((s=n.storage)==null||s.remove(r),c)}catch(l){return (d=n.onError)==null||d.call(n,l),null}}var ft=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function bt(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!ft.includes(r)||e(r,...i);}}function xt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}function se(n,e,t,r,i){return new Promise(a=>{let o=n.document.createElement("script");o.src=e,o.onload=()=>{var p;let s=(p=r())!=null?p:null;s||i(`${A} the ${t} script registered nothing.`),a(s);},o.onerror=()=>{i(`${A} the ${t} script could not load from ${new URL(e).origin}.`),a(null);},n.document.head.append(o);})}var yt=(n,e,t)=>se(n,`${e}/messenger-help.js`,"help centre",()=>n.prodantixMessengerHelp,t),vt=(n,e,t)=>se(n,`${e}/messenger-files.js`,"files",()=>n.prodantixMessengerFiles,t);async function le(n,e={}){var g,k,S;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${A} no project key on the install snippet; nothing will load.`),null;let a=xt((k=e.scriptSrc)!=null?k:St(n));if(!a)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=kt(n),s=ne(n),p=ie(o,i,s),d=await ae({apiKey:i,host:a,locale:s,onError:f=>t(`${A} settings could not be read: ${String(f)}`),storage:o}),l=d!=null?d:p;if(!l)return t(`${A} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let c=te({apiKey:i,appearance:l,distinctId:Et(n,o),files:()=>vt(n,a,t),help:l.help?()=>yt(n,a,t):void 0,host:a,locale:s,socketHost:l.socketUrl||void 0}),m=(f,...x)=>{if((f==="open"||f==="toggle")&&c.open(),f==="close"&&c.close(),f==="shutdown"&&c.destroy(),f==="identify"){let u=Ct(x[0]);if(!u){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}c.identify(u);}};return bt((S=r==null?void 0:r.q)!=null?S:[],m),n.prodantix=Object.assign((f,...x)=>m(f,...x),{k:i,q:[]}),c}function St(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function kt(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function Ct(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var oe="prodantix.messenger.anon";function Et(n,e){var i,a,o;let t=e==null?void 0:e.get(oe);if(t)return t;let r=`anon_${(o=(a=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:a.call(i))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(oe,r),r}le(window);})();//# sourceMappingURL=messenger.iife.js.map
7
+ }`}var Ve=/https?:\/\/[^\s<>"]+/g,Qe=/[.,;:!?)]$/,Ze=n=>{let e=n;for(;Qe.test(e);){let t=e.split("(").length-1,r=e.split(")").length-1;if(e.endsWith(")")&&t>=r)break;e=e.slice(0,-1);}return e};function et(n,e){var r;let t=0;for(let i of e.matchAll(Ve)){let a=(r=i.index)!=null?r:0,s=Ze(i[0]);a>t&&n.append(e.slice(t,a));let o=document.createElement("a");o.href=s,o.target="_blank",o.rel="noopener noreferrer",o.textContent=s,n.append(o),t=a+s.length;}t<e.length&&n.append(e.slice(t));}var tt=["P","BR","STRONG","EM","A","UL","OL","LI"],nt=n=>typeof n=="object"&&n!==null&&"html"in n&&typeof n.html=="string"&&"text"in n&&typeof n.text=="string",rt=(n,e)=>e.name==="class"||e.name==="data-block-type"?true:n!=="A"?false:e.name==="target"||e.name==="rel"?true:e.name==="href"&&/^https?:\/\//i.test(e.value.trim()),it=n=>[...n.querySelectorAll("*")].every(e=>tt.includes(e.tagName)&&[...e.attributes].every(t=>rt(e.tagName,t)));function at(n,e="system"){let t=$(n),r=n.launcherPosition==="bottom_left"?"left":"right",i=n.accentColor;return `${`:host{all:initial;z-index:2147483000;--a:${i};--paper:#fff;--ink:#0f172a;--ink-3:rgba(0,0,0,.55);--fill:#f1f5f9;--hairline:#e2e8f0;--ink-2:rgba(0,0,0,.72);--online:oklch(53.8% 0.1274 163.23);color-scheme:${e==="system"?"light dark":e}}${Xe(e)}*{box-sizing:border-box;font-family:system-ui,sans-serif}.launcher{z-index:2147483000;position:fixed;${r}:${n.launcherOffsetX}px;bottom:${n.launcherOffsetY}px;width:56px;height:56px;border-radius:28px;border:none;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;background:${i};color:#fff;font-size:24px;box-shadow:0 4px 12px rgba(0,0,0,.2)}.launcher:focus-visible{outline:3px solid #0b0e14;outline-offset:2px}.launcher{transition:background-color 120ms ease}.launcher:hover{background:color-mix(in srgb,#000 12%,${i})}.launcher:active{background:color-mix(in srgb,#000 20%,${i})}@media (prefers-reduced-motion:reduce){.launcher{transition:none}}.badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;border-radius:10px;background:#dc2626;color:#fff;font-size:12px;display:flex;align-items:center;justify-content:center;padding:0 4px}.badge[hidden]{display:none}.panel{z-index:2147483001;position:fixed;${r}:${n.launcherOffsetX}px;bottom:${n.launcherOffsetY+68}px;width:360px;max-width:calc(100vw - 40px);height:520px;max-height:calc(100vh - 120px);background:var(--paper);color:var(--ink);border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.24);display:flex;flex-direction:column;overflow:hidden}.header{position:relative;padding:14px 16px;background:#0b0e14;color:#fff;display:flex;align-items:center;justify-content:space-between}.header h2{margin:0;font-size:15px}.header .faces{display:flex}.header .av{width:36px;height:36px;box-shadow:0 0 0 2px var(--a)}.header .av + .av{margin-left:-12px}.headmain{display:flex;flex-direction:column}.header .status{display:flex;align-items:center;gap:6px;margin:5px 0 0;font-size:12.5px;color:rgb(255 255 255 / 80%)}.header .status .live{flex:none;width:10px;height:10px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper)}.panel.closed .status{display:none}.header .close{position:absolute;top:8px;right:8px}.close{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;background:none;border:none;border-radius:8px;color:inherit;cursor:pointer;transition:background-color 120ms ease}.close svg{display:block;width:22px;height:22px}.close:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.close:focus-visible{outline:2px solid currentColor;outline-offset:1px}.log{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:8px}.turn{max-width:80%;padding:8px 12px;border-radius:12px;font-size:14px}.turn.end_user{align-self:flex-end;background:${i};color:#fff}.turn.agent,.turn.ai{align-self:flex-start;background:var(--fill);color:var(--ink)}.turn.ai a{color:${i};text-decoration:underline;overflow-wrap:anywhere}.author{font-size:11px;opacity:.7;margin-bottom:2px}.turn[data-pending]{opacity:.6}.turn[data-failed]{opacity:1;box-shadow:inset 0 0 0 1px #dc2626}.retry{display:block;margin:5px 0 0;padding:0;background:none;border:0;color:inherit;font:inherit;font-size:11.5px;text-decoration:underline;cursor:pointer;opacity:.85}.away{display:flex;gap:10px;align-items:flex-start;margin:12px 12px 0;padding:10px 14px;font-size:13px;line-height:1.43;color:${i};background:color-mix(in srgb,${i}12%,transparent);border-radius:4px}.awayglyph{flex:none;width:16px;height:16px;margin-top:1px;border:1.5px solid currentColor;border-radius:50%}.empty{display:flex;flex-direction:column;gap:8px;padding:20px 16px}.empty h3{margin:0;font-size:18px;font-weight:640;letter-spacing:-.015em}.empty > p{margin:0 0 8px;font-size:13.5px;color:var(--ink-2)}.prompt{position:relative;display:flex;align-items:center;min-height:44px;padding:10px 14px;text-align:left;font-family:inherit;font-size:13.5px;font-weight:500;color:var(--ink);background:none;border:1px solid var(--hairline);border-radius:8px;cursor:pointer}.promptwords{min-width:0;overflow-wrap:anywhere}.promptwords > :last-child{margin-bottom:0}.prompt p{margin:0 0 16px;line-height:1.6}.prompt ul,.prompt ol{margin:0 0 16px;padding-left:32px}.prompt li{margin:8px 0;line-height:1.6}.prompt a{position:relative;z-index:1;color:${i};text-decoration:underline;overflow-wrap:anywhere}.promptpress{position:absolute;inset:0;padding:0;background:none;border:0;border-radius:inherit;cursor:pointer}.promptpress:focus-visible{outline:2px solid ${i};outline-offset:2px}.av{width:30px;height:30px;border-radius:50%;flex:none;display:inline-flex;align-items:center;justify-content:center;font-size:11.5px;font-weight:650;color:#fff;background:oklch(52% 0.17 22)}.av.bot{border-radius:9px;background:var(--fill);color:var(--ink)}.av img{width:100%;height:100%;display:block;object-fit:cover;border-radius:inherit}.composer{display:flex;gap:6px;padding:10px;border-top:1px solid var(--hairline)}.composer input{flex:1;min-width:0;height:36px;padding:0 12px;border:0;border-radius:8px;font-size:14px;background:var(--fill);color:var(--ink)}.composer input:focus-visible{outline:2px solid ${i}}.composer button{display:inline-flex;align-items:center;justify-content:center;gap:0;min-width:56px;height:36px;padding:0 14px;background:${i};color:#fff;border:none;border-radius:8px;cursor:pointer;font-family:inherit;font-size:13.5px;font-weight:550}.composer button:hover{background:color-mix(in srgb,#000 12%,${i})}.composer button:focus-visible{outline:2px solid var(--ink);outline-offset:2px}.composer button .sendglyph{display:none;width:17px;height:17px}.composer button:focus-visible{outline:2px solid #0b0e14}.powered{display:flex;align-items:center;justify-content:center;gap:4px;height:24px;font-size:11px;font-weight:500;color:var(--ink-3);text-decoration:none}.powered:hover{color:var(--ink-2)}.powered:focus-visible{outline:2px solid var(--ink);outline-offset:-2px}.powered img{width:12px;height:12px}@media (prefers-reduced-motion:no-preference){.panel{animation:rise 180ms ease-out}@keyframes rise{from{transform:translateY(8px);opacity:0}to{transform:none;opacity:1}}}.scrim,.grip{display:none}@media (max-width:770px){.panel{inset:auto 0 0;width:100%;max-width:none;height:86dvh;max-height:86dvh}:host .panel{border-bottom-left-radius:0;border-bottom-right-radius:0}.scrim{display:block;position:fixed;inset:0;z-index:2147483000;background:rgb(15 23 42/.24)}.grip{display:block;position:absolute;top:7px;left:calc(50% - 17px);width:34px;height:4px;border-radius:2px;background:currentColor;opacity:.45}.panel:not([data-dragging]){transition:translate .2s}.composer{padding-bottom:max(12px,env(safe-area-inset-bottom))}}`}${Be[t.composerShape]}${ze[t.skin]}${J(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${De[t.bubbleShape]}${Ge[t.bubbleFill]}${qe[t.namePlacement]}${t.nameAvatar?je:""}${t.dayDividers?We:""}${Ye[t.stampPlacement]}${t.stampContent==="time_and_latency"?Je:""}`}var st=["end_user","agent","ai"];function ot(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var lt='<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M15.88 9.29 12 13.17 8.12 9.29a.996.996 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41l4.59 4.59c.39.39 1.02.39 1.41 0l4.59-4.59c.39-.39.39-1.02 0-1.41-.39-.38-1.03-.39-1.42 0"/></svg>',O=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;p(this,"root");p(this,"strings");p(this,"settings");p(this,"appearance");p(this,"launcher");p(this,"badge");p(this,"panel",null);p(this,"scrim",null);p(this,"lastFocused",null);p(this,"unread",0);p(this,"pendingTurns",0);p(this,"openNow");p(this,"styles");p(this,"scheme");p(this,"picked",null);p(this,"objectUrls",[]);p(this,"helpLoader");p(this,"kit",null);p(this,"kitLoad",null);p(this,"filesLoader");p(this,"filesKit",null);p(this,"filesLoad",null);p(this,"ticketsLoader");p(this,"ticketsLoad");var s;this.strings={...Ke,...r},this.appearance={...N,...i},this.settings=$({...N,...i}),this.root=e.attachShadow({mode:(s=a.shadowMode)!=null?s:"closed"}),this.openNow=R(this.appearance.availability,new Date),this.scheme=a.scheme,this.helpLoader=a.help,this.filesLoader=a.files,this.ticketsLoader=a.tickets,this.styles=pt(this.root),this.paint(),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.drawLauncher(),this.root.append(this.launcher);}drawLauncher(){if(this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.replaceChildren(),this.launcher.append(X(this.settings.launcherContent,this.strings,this.appearance.team,e=>this.client.avatarUrl(e))),this.settings.launcherShape==="pill"){let e=document.createElement("span");e.className="label",e.textContent=this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...N,...e},this.settings=$(this.appearance),t!==void 0&&(this.scheme=t),this.paint(),this.drawLauncher(),this.panel&&(this.close(),this.open());}paint(){var e;this.styles(`${at(this.appearance,this.scheme)}${this.kit&&this.appearance.help?this.kit.HELP_CSS:""}${this.filesKit?this.filesKit.filesCss(((e=this.appearance.attachments)==null?void 0:e.enabled)===true,this.settings.composerShape):""}`);}loadKit(){return !this.appearance.help||!this.helpLoader?Promise.resolve(null):((this.kitLoad)!=null||(this.kitLoad=this.helpLoader().then(t=>(this.kit=t,this.paint(),t))),this.kitLoad)}loadFiles(){return this.filesLoader?((this.filesLoad)!=null||(this.filesLoad=this.filesLoader().then(t=>(this.filesKit=t,this.paint(),t))),this.filesLoad):Promise.resolve(null)}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v,x,T;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=document.createElement("span");r.className="grip",r.setAttribute("aria-hidden","true"),t.append(r);let i=(v=this.appearance.team)!=null?v:[];i.length>0&&t.append(B(i,this.strings,E=>this.client.avatarUrl(E)));let a=document.createElement("div");a.className="headmain";let s=document.createElement("h2");s.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let u=document.createElement("span");u.className="live",u.setAttribute("aria-hidden","true"),o.append(u,this.strings.replyTime),a.append(s,o);let d=document.createElement("button");d.className="close",d.type="button",d.setAttribute("aria-label",this.strings.closeLabel),d.innerHTML=lt,d.addEventListener("click",()=>this.close()),t.append(a,d);let l=document.createElement("div");l.className="log",l.setAttribute("role","log"),l.setAttribute("aria-live","polite"),l.setAttribute("aria-label",this.strings.title);let c=document.createElement("form");c.className="composer";let h=document.createElement("input");h.type="text",h.setAttribute("aria-label",this.strings.inputPlaceholder),h.placeholder=this.strings.inputPlaceholder;let g=document.createElement("button");g.type="submit",g.setAttribute("aria-label",this.strings.sendLabel),g.innerHTML='<svg class="sendglyph" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 12 20 4.5 15 20l-3.6-5.4L4.5 12Z"/></svg>';let S=document.createElement("span");S.className="sendtext",S.textContent=this.strings.sendLabel,g.append(S),c.append(h,g),c.addEventListener("submit",E=>{E.preventDefault(),this.submit(h,l);}),e.append(t,l,c),this.appearance.poweredBy&&e.append(Ue(this.appearance.poweredBy,this.client.avatarUrl("/messenger-mark.png"))),e.addEventListener("keydown",E=>this.onKeydown(E,e,d));let k=document.createElement("div");k.className="scrim",k.addEventListener("click",()=>this.close()),this.root.append(k,e),this.panel=e,this.scrim=k,dt(e,()=>this.close()),h.focus();let f=this.appearance.attachments,[y,,,m]=await Promise.all([this.client.load(),this.loadKit(),f!=null&&f.enabled&&this.client.upload?this.loadFiles():null,(T=this.ticketsLoad)!=null?T:this.ticketsLoad=(x=this.ticketsLoader)==null?void 0:x.call(this)]);if(y!=null&&y.turns.some(E=>{var P;return (P=E.attachments)==null?void 0:P.length})&&await this.loadFiles(),this.panel!==e)return;this.filesKit&&(f!=null&&f.enabled)&&this.client.upload&&this.filesKit.attachField({attachLabel:this.strings.attachLabel,fileRefusal:this.strings.fileRefusal,hold:E=>{this.picked=E;},objectUrl:E=>this.objectUrl(E),removeFileLabel:this.strings.removeFileLabel,root:this.root},c,h,l,f);let b=this.helpHost();(b==null?void 0:b.placement)==="tab"&&b.host.source.collections&&b.host.source.collectionArticles&&b.kit.helpTab(b.host),(b==null?void 0:b.placement)==="while_typing"&&b.kit.whileTyping(b.host,h,c),m&&this.appearance.tickets&&m.ticketsTab(e,this.client,this.appearance.tickets.words),y&&y.turns.length>0?this.renderThread(l,y):this.renderFirstRun(l,h),this.openNow||this.renderAway(t);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let i=document.createElement("h3");i.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle,r.append(i);let a=this.helpHost();if((a==null?void 0:a.placement)==="first_view")a.kit.firstView(a.host,r);else {let o=document.createElement("p");o.textContent=this.strings.emptyBody,r.append(o);}this.appearance.starterPrompts.filter(nt).forEach((o,u)=>{let d=document.createElement("div");d.className="prompt";let l=document.createElement("div");l.className="promptwords",l.id=`prompt-${u}`;let c=document.createElement("template");c.innerHTML=o.html,it(c.content)?l.append(c.content):l.textContent=o.text;for(let g of l.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let h=document.createElement("button");h.className="promptpress",h.type="button",h.setAttribute("aria-labelledby",l.id),h.addEventListener("click",()=>{t.value=o.text,this.submit(t,e);}),d.append(l,h),r.append(d);}),e.replaceChildren(r);}helpHost(){let e=this.appearance.help,{kit:t,panel:r}=this,i=e&&t&&r?t.hostOf(this.client,{close:()=>this.close(),closeLabel:this.strings.closeLabel,panel:r,scheme:this.scheme,words:e.words}):null;return i&&t&&e?{host:i,kit:t,placement:e.placement}:null}renderAway(e){let t=document.createElement("div");t.className="away";let r=document.createElement("span");r.className="awayglyph",r.setAttribute("aria-hidden","true");let i=document.createElement("span");i.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,t.append(r,i),e.after(t);}objectUrl(e){let t=URL.createObjectURL(e);return this.objectUrls.push(t),t}close(){var e;if(this.panel){this.panel.remove(),(e=this.scrim)==null||e.remove(),this.panel=null,this.scrim=null,this.picked=null;for(let t of this.objectUrls)URL.revokeObjectURL(t);this.objectUrls=[],this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus();}}onIncomingTurn(e){var t;if(this.panel&&((t=e.attachments)!=null&&t.length)&&!this.filesKit&&this.filesLoader){this.loadFiles().then(()=>this.takeTurn(e));return}this.takeTurn(e);}takeTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&!this.hasTurn(t,e.id)&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){let r=e.value.trim(),i=this.picked;if(!(!r&&!i)){e.value="",this.picked=null;for(let a of this.root.querySelectorAll(".file,.ferr,.hsugg"))a.remove();await this.sendBody(t,r,i);}}async sendBody(e,t,r=null){var o,u,d;(o=e.querySelector(".empty"))==null||o.remove(),this.pendingTurns+=1;let i=this.appendTurn(e,{authorId:null,authorKind:"end_user",body:t,createdAt:new Date().toISOString(),id:`pending-${this.pendingTurns}`},r);i.setAttribute("data-pending","");let a=r?await((d=(u=this.client).upload)==null?void 0:d.call(u,r)):void 0,s=a===null?null:await this.client.send(t,ot(),a?[a.id]:void 0);if(i.removeAttribute("data-pending"),s){i.dataset.turnId=s.id;return}this.markFailed(e,i,t,r);}markFailed(e,t,r,i){var s;t.setAttribute("data-failed","");let a=document.createElement("button");a.type="button",a.className="retry",a.textContent=this.strings.retryLabel,a.addEventListener("click",()=>{t.remove(),this.sendBody(e,r,i);}),((s=t.querySelector(".body"))!=null?s:t).append(a);}hasTurn(e,t){for(let r of e.children)if(r instanceof HTMLElement&&r.dataset.turnId===t)return true;return false}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t,r=null){var c,h,g,S,k,f,y;(c=e.querySelector(".empty"))==null||c.remove();let i=st.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,s=document.createElement("div");if(s.className=`turn ${i}`,s.dataset.turnId=t.id,i!=="end_user"&&a.nameAvatar){let m=document.createElement("span");if(m.className=i==="ai"?"av bot":"av",m.setAttribute("aria-hidden","true"),i==="agent"&&t.authorAvatarUrl){let b=document.createElement("img");b.alt="",b.src=this.client.avatarUrl(t.authorAvatarUrl),m.append(b);}else {m.textContent=i==="ai"?this.strings.aiLabel:Y(this.agentName(t));let b=i==="agent"?(g=(h=this.appearance.team)==null?void 0:h.find(v=>v.name===t.authorName))==null?void 0:g.tone:void 0;b&&(m.style.background=b);}s.append(m);}let u=document.createElement("div");if(u.className="body",i==="end_user"){let m=this.filesKit,b=v=>this.objectUrl(v);r&&(m==null||m.drawFile(u,r.name,r.type,r.size,Promise.resolve(r),b));for(let v of (S=t.attachments)!=null?S:[])m==null||m.drawFile(u,v.name,v.contentType,v.bytes,(y=(f=(k=this.client).file)==null?void 0:f.call(k,v.url))!=null?y:Promise.resolve(null),b);}let d=i!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(i==="ai"?et(l,t.body):l.textContent=t.body,d||i==="ai"&&a.namePlacement==="hidden"){let m=document.createElement("div");m.className=i==="ai"?"author ai":"author",m.textContent=i==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&m.append(this.stamp(t)),a.namePlacement==="inline"?(m.classList.add("below"),u.append(l,m)):u.append(m,l);}else t.body&&u.append(l);return a.stampPlacement==="under_turn"&&u.append(this.stamp(t)),s.append(u),e.append(s),e.scrollTop=e.scrollHeight,s}agentName(e){return e.authorName||this.strings.agentLabel}stamp(e){let t=document.createElement("span");return t.className="stamp",t.textContent=this.strings.timeLabel(e.createdAt),t}onKeydown(e,t,r){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let i=[...t.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')].filter(u=>!u.closest("[hidden]")&&!u.hidden);if(i.length===0)return;let a=i[0],s=i[i.length-1],o=this.root.activeElement;e.shiftKey&&o===a?(e.preventDefault(),s.focus()):!e.shiftKey&&o===s?(e.preventDefault(),a.focus()):o===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}},ct="(max-width: 770px)";function dt(n,e){let t=null;n.addEventListener("pointerdown",i=>{var s,o;if(t||i.button!==0||!((s=globalThis.matchMedia)!=null&&s.call(globalThis,ct).matches))return;let a=i.target;if(!(a!=null&&a.closest("a, button, input, textarea, iframe"))){for(;a&&a!==n;a=a.parentElement)if(a.scrollTop>0)return;t={at:i.timeStamp,id:i.pointerId,offset:0,startY:i.clientY},(o=n.setPointerCapture)==null||o.call(n,i.pointerId),n.dataset.dragging="";}}),n.addEventListener("pointermove",i=>{if((t==null?void 0:t.id)!==i.pointerId)return;let a=i.clientY-t.startY;t.offset=a>=0?a:-16*(1-Math.exp(a/48)),n.style.translate=`0 ${t.offset}px`;});let r=i=>{let a=t;if((a==null?void 0:a.id)!==i.pointerId)return;t=null,delete n.dataset.dragging;let s=a.offset>Math.min(72,n.getBoundingClientRect().height*.4),o=a.offset/Math.max(1,i.timeStamp-a.at)>.5&&a.offset>16;s||o?e():n.style.translate="";};n.addEventListener("pointerup",r),n.addEventListener("pointercancel",r);}var pt=n=>{if(typeof CSSStyleSheet=="function"&&"adoptedStyleSheets"in n&&"replaceSync"in CSSStyleSheet.prototype){let t=new CSSStyleSheet;return n.adoptedStyleSheets=[t],r=>t.replaceSync(r)}let e=document.createElement("style");return n.append(e),t=>{e.textContent=t;}};function Z(n){return `40${JSON.stringify(n)}`}function ee(){return "3"}function te(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let s=D(t);return {kind:"open",pingInterval:typeof(s==null?void 0:s.pingInterval)=="number"?s.pingInterval:25e3,pingTimeout:typeof(s==null?void 0:s.pingTimeout)=="number"?s.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let s=D(i);return {kind:"connectError",message:typeof(s==null?void 0:s.message)=="string"?s.message:"refused"}}if(r!=="2")return {kind:"other"};let a=D(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function D(n){try{return JSON.parse(n)}catch(e){return null}}var ut="/socket.io/?EIO=4&transport=websocket",K=class{constructor(e){this.options=e;p(this,"socket",null);p(this,"heartbeat",null);p(this,"ready",false);p(this,"closed",false);p(this,"heartbeatWindow",45e3);p(this,"factory");p(this,"setTimer");p(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ht,this.setTimer=(r=e.setTimer)!=null?r:((a,s)=>setTimeout(a,s)),this.clearTimer=(i=e.clearTimer)!=null?i:(a=>clearTimeout(a));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${ut}`,t;try{t=this.factory(e);}catch(r){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();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,a,s;let t=te(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(Z(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(ee());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(a=this.socket)==null||a.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let o=(s=t.payload)==null?void 0:s.turn;o&&this.options.onTurn(o);}}}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(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function ht(n){let e=globalThis.WebSocket;if(!e)throw new w("no WebSocket");return new e(n)}var gt=6e4;function ne(n){var y,m,b,v;let e=globalThis.document;if(!e)throw new F("prodantix chat requires a document; mount it in the browser");let t=(y=n.mountPoint)!=null?y:e.createElement("div");n.mountPoint||e.body.append(t);let r=new M(n),i=new O(t,r,n.strings,n.appearance,{files:n.files,help:n.help,tickets:n.tickets}),a=(b=(m=n.appearance)==null?void 0:m.availability)!=null?b:N.availability,s,o=()=>{i.setOpenNow(R(a,new Date)),s=setTimeout(o,gt);};o();let u=new Set,d,l=null,c=(v=n.pollIntervalMs)!=null?v:15e3,h=x=>{u.has(x.id)||x.authorKind==="end_user"||(u.add(x.id),i.onIncomingTurn(x));},g=async()=>{if(!r.hasThread)return;let x=await r.load();if(x){for(let T of x.turns)h(T);u=new Set(x.turns.map(T=>T.id));}},S=()=>{d||c<=0||(d=setInterval(()=>void g(),c));},k=()=>{d&&clearInterval(d),d=void 0;},f=()=>{if(l||!n.socketHost)return;let x=r.socketAuth;x&&(l=new K({auth:x,host:n.socketHost,onClosed:T=>{l=null,S(),T&&f();},onReady:k,onTurn:h,socketFactory:n.socketFactory}),l.open());};return S(),f(),{close:()=>i.close(),destroy:()=>{k(),clearTimeout(s),l==null||l.close(),l=null,i.close(),t.remove();},identify:x=>r.identify(x),open:()=>{i.open().then(f);}}}var mt="prodantix.messenger.config",re=n=>{var t,r,i,a;let e=(t=n.navigator)==null?void 0:t.languages;return Array.isArray(e)&&e.length>0?e.join(","):((r=n.navigator)==null?void 0:r.language)||((a=(i=n.document)==null?void 0:i.documentElement)==null?void 0:a.lang)||void 0},ie=(n,e)=>`${mt}:${n}:${e!=null?e:""}`;function ae(n,e,t){let r=n==null?void 0:n.get(ie(e,t));if(!r)return null;try{let i=JSON.parse(r);return (i==null?void 0:i.apiKey)===e?i.config:null}catch(i){return null}}async function se(n){var a,s,o,u,d;let e=I(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new w("no fetch available for the prodantix messenger")),null;let t=H(n.host),r=ie(n.apiKey,n.locale),i=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${i}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (s=n.onError)==null||s.call(n,new w(`prodantix messenger config: ${l.status}`,l.status)),null;let c=JSON.parse(await l.text());return c.enabled?((u=n.storage)==null||u.set(r,JSON.stringify({apiKey:n.apiKey,config:c})),c):((o=n.storage)==null||o.remove(r),c)}catch(l){return (d=n.onError)==null||d.call(n,l),null}}var ft=["close","identify","open","shutdown","toggle"],L="[prodantix/messenger]";function bt(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!ft.includes(r)||e(r,...i);}}function yt(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}function G(n,e,t,r,i){return new Promise(a=>{let s=n.document.createElement("script");s.src=e,s.onload=()=>{var u;let o=(u=r())!=null?u:null;o||i(`${L} the ${t} script registered nothing.`),a(o);},s.onerror=()=>{i(`${L} the ${t} script could not load from ${new URL(e).origin}.`),a(null);},n.document.head.append(s);})}var xt=(n,e,t)=>G(n,`${e}/messenger-help.js`,"help centre",()=>n.prodantixMessengerHelp,t),vt=(n,e,t)=>G(n,`${e}/messenger-files.js`,"files",()=>n.prodantixMessengerFiles,t),kt=(n,e,t)=>G(n,`${e}/messenger-tickets.js`,"tickets",()=>n.prodantixMessengerTickets,t);async function le(n,e={}){var g,S,k;let t=(g=e.warn)!=null?g:(f=>console.warn(f)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${L} no project key on the install snippet; nothing will load.`),null;let a=yt((S=e.scriptSrc)!=null?S:St(n));if(!a)return t(`${L} could not tell which host served this script; nothing will load.`),null;let s=Ct(n),o=re(n),u=ae(s,i,o),d=await se({apiKey:i,host:a,locale:o,onError:f=>t(`${L} settings could not be read: ${String(f)}`),storage:s}),l=d!=null?d:u;if(!l)return t(`${L} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let c=ne({apiKey:i,appearance:l,distinctId:Tt(n,s),files:()=>vt(n,a,t),help:l.help?()=>xt(n,a,t):void 0,host:a,locale:o,socketHost:l.socketUrl||void 0,tickets:l.tickets?()=>kt(n,a,t):void 0}),h=(f,...y)=>{if((f==="open"||f==="toggle")&&c.open(),f==="close"&&c.close(),f==="shutdown"&&c.destroy(),f==="identify"){let m=Et(y[0]);if(!m){console.error(`${L} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}c.identify(m);}};return bt((k=r==null?void 0:r.q)!=null?k:[],h),n.prodantix=Object.assign((f,...y)=>h(f,...y),{k:i,q:[]}),c}function St(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function Ct(n){let e=n.localStorage;if(e)return {get:t=>e.getItem(t),remove:t=>e.removeItem(t),set:(t,r)=>e.setItem(t,r)}}function Et(n){if(typeof n!="object"||n===null)return null;let{userHash:e,userId:t}=n;return typeof t!="string"||typeof e!="string"||t.trim()===""||e.trim()===""?null:{userHash:e,userId:t}}var oe="prodantix.messenger.anon";function Tt(n,e){var i,a,s;let t=e==null?void 0:e.get(oe);if(t)return t;let r=`anon_${(s=(a=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:a.call(i))!=null?s:Math.random().toString(36).slice(2)}`;return e==null||e.set(oe,r),r}le(window);
8
+ })();//# sourceMappingURL=messenger.iife.js.map
111
9
  //# sourceMappingURL=messenger.iife.js.map
package/dist/messenger.js CHANGED
@@ -1,2 +1,2 @@
1
- import {e,d as d$1,h}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var f="prodantix.messenger.config",m=e=>{let r=e.navigator?.languages;return Array.isArray(r)&&r.length>0?r.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},l=(e,r)=>`${f}:${e}:${r??""}`;function u(e,r,i){let n=e?.get(l(r,i));if(!n)return null;try{let a=JSON.parse(n);return a?.apiKey===r?a.config:null}catch{return null}}async function d(e$1){let r=e(e$1.fetchImpl);if(!r)return e$1.onError?.(new d$1("no fetch available for the prodantix messenger")),null;let i=h(e$1.host),n=l(e$1.apiKey,e$1.locale),a=e$1.locale?`?locale=${encodeURIComponent(e$1.locale)}`:"";try{let t=await r(`${i}/v1/messenger/config${a}`,{headers:{authorization:`Bearer ${e$1.apiKey}`},method:"GET"});if(!t.ok)return e$1.onError?.(new d$1(`prodantix messenger config: ${t.status}`,t.status)),null;let s=JSON.parse(await t.text());return s.enabled?(e$1.storage?.set(n,JSON.stringify({apiKey:e$1.apiKey,config:s})),s):(e$1.storage?.remove(n),s)}catch(t){return e$1.onError?.(t),null}}export{f as MESSENGER_CACHE_KEY,l as cacheKeyFor,u as cachedMessengerConfig,d as fetchMessengerConfig,m as localeCandidates};//# sourceMappingURL=messenger.js.map
1
+ import {e,d as d$1,h}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var p="prodantix.messenger.config",d=e=>{let t=e.navigator?.languages;return Array.isArray(t)&&t.length>0?t.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},l=(e,t)=>`${p}:${e}:${t??""}`;function m(e,t,a){let n=e?.get(l(t,a));if(!n)return null;try{let s=JSON.parse(n);return s?.apiKey===t?s.config:null}catch{return null}}async function u(e$1){let t=e(e$1.fetchImpl);if(!t)return e$1.onError?.(new d$1("no fetch available for the prodantix messenger")),null;let a=h(e$1.host),n=l(e$1.apiKey,e$1.locale),s=e$1.locale?`?locale=${encodeURIComponent(e$1.locale)}`:"";try{let r=await t(`${a}/v1/messenger/config${s}`,{headers:{authorization:`Bearer ${e$1.apiKey}`},method:"GET"});if(!r.ok)return e$1.onError?.(new d$1(`prodantix messenger config: ${r.status}`,r.status)),null;let i=JSON.parse(await r.text());return i.enabled?(e$1.storage?.set(n,JSON.stringify({apiKey:e$1.apiKey,config:i})),i):(e$1.storage?.remove(n),i)}catch(r){return e$1.onError?.(r),null}}export{p as MESSENGER_CACHE_KEY,l as cacheKeyFor,m as cachedMessengerConfig,u as fetchMessengerConfig,d as localeCandidates};//# sourceMappingURL=messenger.js.map
2
2
  //# sourceMappingURL=messenger.js.map
package/dist/node.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var fe=Object.defineProperty;var ge=(n,e,t)=>e in n?fe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ge(n,typeof e!="symbol"?e+"":e,t);var p=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends p{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends p{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function y(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var V=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var k=class{constructor(){o(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);}};var j={now:()=>new Date};function b(n){return n.toISOString()}function me(){return globalThis.crypto}function ye(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[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 ve(){let n=me();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return ye(e)}var G={uuid:ve};var ke=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function x(n){let e=0;for(let t of n)e+=1;return e}function J(n){return ke.test(n)}function xe(n){return be.test(n)}function H(n){let e=x(n);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=x(n);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!xe(n))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var B="prodantix-js",z="0.7.0";var Ee=n=>{};function Q(n){if(!n.apiKey||!J(n.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new v("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties,s=n.storage??new k;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??j,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},describeElement:n.describeElement,flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??G,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:$(n.apiKey),onError:n.onError??Ee,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??B,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function $(n){return n.slice(0,16)}function W(n,e,t){U(n.eventName),H(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:b(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function Se(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:g}function f(n){return n===g?"undefined":String(n)}function Y(n){return n===g?Number.NaN:Number(n)}function X(n){return n!==g&&n!==null&&n!==""}function Z(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(s=>String(s)).includes(t)}function ee(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(t);case "eq":return f(t)===f(s===void 0?g:s);case "neq":return f(t)!==f(s===void 0?g:s);case "contains":return f(t).includes(f(s===void 0?g:s));case "in":return Z(t,s);case "not_in":return Array.isArray(s)?!Z(t,s):false;case "gt":return E(t,s,(r,i)=>r>i);case "gte":return E(t,s,(r,i)=>r>=i);case "lt":return E(t,s,(r,i)=>r<i);case "lte":return E(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function E(n,e,t){let s=Y(n),r=e===void 0?Number.NaN:Y(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function te(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function N(n,e){return n.targeting.length===0||n.targeting.every(t=>ee(t,e))}function ne(n,e){let t=te(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function R(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=R(i,e,t,s)&&N(i,t)&&ne(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?R(n,e,t,[n.key])?N(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:te(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function se(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function O(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!R(n,e,t,[n.key])||!N(n,t))return r;let i=ne(n,t);return s.find(a=>a.key===i)??r}function re(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ie(n){return `40${JSON.stringify(n)}`}function oe(){return "3"}function ae(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=M(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=M(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=M(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function M(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,I=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Ce,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.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=ae(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ie({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(oe());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 s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},we));}}}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 Ce(n){let e=globalThis.WebSocket;if(!e)throw new c("no WebSocket");return new e(n)}var w=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(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 c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=u(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function q(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function L(n,e){return `pdx.${n}.${e}`}var ce="consent";function K(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function Fe(n,e){return K(n.getItem(L(e,ce)))}function Te(n,e,t){let s=L(e,ce);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=q(this.shared.getItem(this.key("anonymous_id"))),t=q(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 s=q(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,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 Fe(this.shared,this.namespace)}setConsent(e){Te(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||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 L(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var T=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(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 _e={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Ae(n){return `pdx.${n}.session`}var _=class{constructor(e,t,s,r,i=_e){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}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 s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,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 Ae(this.namespace)}};var l={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function le(n){return n>=400&&n<500&&n!==429}var A=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=y(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??V,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(le(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&le(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Pe="queue",$e=1e3,de=3e4,D=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},P=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new C(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 _(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new T(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new p("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new A({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new w({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({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 s={...this.config.defaultProperties(),...t.element===void 0?{}:this.config.describeElement?.(t.element)??{},...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...D(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(l.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=D(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(l.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(l.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(l.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(l.set,{properties:s});}setPersonTraits(e){let t=D(e);Object.keys(t).length!==0&&this.capture(l.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 s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?O(r,s.flags,i):null,d=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture(l.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 se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?O(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&re(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<de?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<de)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 I({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&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($e);try{await this.transport.send({body:{events:e,sent_at:b(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}.${Pe}`}};var Ne=200;function ue(){return globalThis.process}function Re(n){ue()?.on("beforeExit",()=>{n.flush();});}function Xt(n){let e=ue(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new P(t);return Re(s),s}function Zt(n,e){let t=$(e),s=Oe(n,`pdx_${t}`);if(s===void 0)return null;let r=Me(s);if(r===void 0)return null;let i=pe(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:K(r[`pdx.${t}.consent`]),sessionId:qe(r[`pdx.${t}.session`])}}function Oe(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Me(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function pe(n){if(typeof n!="string")return;let e=x(n);return e>=1&&e<=Ne?n:void 0}function qe(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:pe(e.id)??null}catch{return null}}exports.createNodeClient=Xt;exports.readSharedIdentity=Zt;//# sourceMappingURL=node.cjs.map
1
+ 'use strict';var Te=Object.defineProperty;var $e=(n,e,t)=>e in n?Te(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>$e(n,typeof e!="symbol"?e+"":e,t);var g=class extends Error{constructor(t,r,s){super(r,s);o(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends g{constructor(e){super("config",e),this.name="ConfigError";}},y=class extends g{constructor(t,r){super("validation",r);o(this,"field");this.field=t,this.name="ValidationError";}},l=class extends g{constructor(t,r,s){super("transport",t,s);o(this,"status");this.status=r,this.name="TransportError";}};function h(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var W=n=>new Promise(e=>{setTimeout(e,n);});function p(n){return n.replace(/\/+$/,"")}var b=class{constructor(){o(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);}},S=class{constructor(e,t=()=>false){this.real=e;this.passes=t;o(this,"held",new b);o(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);}};var Y={now:()=>new Date};function x(n){return n.toISOString()}function X(){if(typeof window>"u"||typeof Intl>"u")return null;let n=Intl.DateTimeFormat().resolvedOptions().timeZone;return typeof n=="string"&&n!==""?n:null}function Ae(){return globalThis.crypto}function Pe(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[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 Re(){let n=Ae();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return Pe(e)}var Z={uuid:Re};var Me=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Ne=/^(?:\$|[a-z])[a-z0-9_.]*$/;function C(n){let e=0;for(let t of n)e+=1;return e}function ee(n){return Me.test(n)}function Oe(n){return Ne.test(n)}function te(n){let e=C(n);if(e<1||e>200)throw new y("distinct_id","distinct_id must be between 1 and 200 characters")}function ne(n){let e=C(n);if(e<1||e>200)throw new y("event_name","event_name must be between 1 and 200 characters");if(!Oe(n))throw new y("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var re="prodantix-js",se="0.7.0";var qe=n=>{};function ie(n){if(!n.apiKey||!ee(n.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new v("host is required (the ingest base URL)");let e=p(n.host),t=n.defaultProperties,r=n.storage??new b;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??Y,consent:n.consent,consentMode:n.consentMode,defaultProperties:typeof t=="function"?t:()=>t??{},describeElement:n.describeElement,flagsHost:n.flagsHost?p(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??Z,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:L(n.apiKey),onError:n.onError??qe,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??re,sdkVersion:n.sdkVersion??se,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??r,socketFactory:n.socketFactory,storage:r,streamFlags:n.streamFlags??false,transport:n.transport}}function L(n){return n.slice(0,16)}var oe=(n,e)=>{let t={$cta_id:n.id,$cta_kind:n.kind,$cta_variant:n.variant.key,$cta_version:n.version},r=e===void 0?void 0:n.variant.content.buttons[e];return r&&e!==void 0&&(t.$cta_button=e,t.$cta_button_label=r.label,r.action.kind==="form"&&(t.$cta_form_id=r.action.value)),t},w=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async ctas(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=new URLSearchParams({anonymous:String(e.anonymous),device:e.device,distinct_id:e.distinctId,language:e.language,url:e.url}),s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(`${this.host}/v1/ctas?${r.toString()}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(a.status<200||a.status>=300)throw new l(`ctas request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).ctas}finally{i!==void 0&&clearTimeout(i);}}};function ae(n,e,t){ne(n.eventName),te(n.distinctId);let r={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:x(n.timestamp??e.now())};return n.context&&(r.context=n.context),n.sessionId&&(r.session_id=n.sessionId),r}var m=Symbol("absent");function Ke(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,n)?r[n]:m}function f(n){return n===m?"undefined":String(n)}function le(n){return n===m?Number.NaN:Number(n)}function ce(n){return n!==m&&n!==null&&n!==""}function de(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(r=>String(r)).includes(t)}function ue(n,e){let t=Ke(n.attribute,e),r=n.value;switch(n.op){case "is_set":return ce(t);case "is_not_set":return !ce(t);case "eq":return f(t)===f(r===void 0?m:r);case "neq":return f(t)!==f(r===void 0?m:r);case "contains":return f(t).includes(f(r===void 0?m:r));case "in":return de(t,r);case "not_in":return Array.isArray(r)?!de(t,r):false;case "gt":return E(t,r,(s,i)=>s>i);case "gte":return E(t,r,(s,i)=>s>=i);case "lt":return E(t,r,(s,i)=>s<i);case "lte":return E(t,r,(s,i)=>s<=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 E(n,e,t){let r=le(n),s=e===void 0?Number.NaN:le(e);return Number.isNaN(r)||Number.isNaN(s)?false:t(r,s)}function pe(n,e){let t=`${n}:${e}`,r=2166136261;for(let s=0;s<t.length;s++)r^=t.charCodeAt(s),r=Math.imul(r,16777619);return (r>>>0)%100}function G(n,e){return n.targeting.length===0||n.targeting.every(t=>ue(t,e))}function he(n,e){let t=pe(n.key,e.distinctId),r=n.variations??[];if(r.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let s=0;for(let i=r.length-1;i>=0;i--)if(s+=r[i].weight,t<s)return r[i].key;return r[0].key}function j(n,e,t,r){for(let s of n.prerequisites??[]){if(r.includes(s.flagKey))return false;let i=e.find(c=>c.key===s.flagKey);if(!i||!i.enabled)return false;r.push(i.key);let a=j(i,e,t,r)&&G(i,t)&&he(i,t)===s.variationKey;if(r.pop(),!a)return false}return true}function _(n,e,t){return n.enabled?j(n,e,t,[n.key])?G(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:pe(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function ge(n,e){let t={};for(let r of n)t[r.key]=_(r,n,e).enabled;return t}function V(n,e,t){let r=n.variations??[],s=r[0];if(!s)return null;if(!n.enabled||!j(n,e,t,[n.key])||!G(n,t))return s;let i=he(n,t);return r.find(a=>a.key===i)??s}function fe(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function me(n){return `40${JSON.stringify(n)}`}function ye(){return "3"}function ve(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=U(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),s=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let a=U(s);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let i=U(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function U(n){try{return JSON.parse(n)}catch{return null}}var De="/socket.io/?EIO=4&transport=websocket",Le=250,I=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Ge,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(/\/+$/,"")}${De}`,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=ve(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(me({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(ye());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);},Le));}}}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 Ge(n){let e=globalThis.WebSocket;if(!e)throw new l("no WebSocket");return new e(n)}var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=p(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)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.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=u(),s=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{s!==void 0&&clearTimeout(s);}}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)}`,s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await t(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.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 B=class extends Error{constructor(t,r,s){super(s);o(this,"fields");o(this,"status");this.name="FormRefusedError",this.status=t,this.fields=r;}},T=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async request(e,t){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a={authorization:`Bearer ${this.projectKey}`};t.body!==void 0&&(a["content-type"]="application/json");let c=await r(`${this.host}${e}`,{body:t.body,headers:a,method:t.method,signal:s?.signal});return {status:c.status,text:await c.text()}}finally{i!==void 0&&clearTimeout(i);}}async form(e,t){let{status:r,text:s}=await this.request(`/v1/forms/${encodeURIComponent(e)}?distinct_id=${encodeURIComponent(t)}`,{method:"GET"});if(r<200||r>=300)throw new l(`form request failed with status ${r}`,r);return JSON.parse(s)}async submit(e,t){let{status:r,text:s}=await this.request(`/v1/forms/${encodeURIComponent(e)}/submissions`,{body:JSON.stringify(t),method:"POST"});if(r>=200&&r<300)return JSON.parse(s).afterSubmit;let i=[],a=`form submission failed with status ${r}`;try{let c=JSON.parse(s);i=c.error?.fields??[],a=c.error?.message??a;}catch{i=[];}throw new B(r,i,a)}};var be="$survey_shown",Se="$survey_dismissed",ke="$survey_sent",$=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async surveys(e,t){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await r(`${this.host}/v1/surveys?distinct_id=${encodeURIComponent(e)}${t?`&lang=${encodeURIComponent(t)}`:""}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new l(`surveys request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).surveys??[]}finally{i!==void 0&&clearTimeout(i);}}};function A(n,e){let t={$survey_id:n.id,$survey_iteration:n.iteration,$survey_name:n.name};for(let[r,s]of Object.entries(e))t[`$survey_response_${r}`]=s;return t}var P=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async guides(e){let t=this.fetch;if(!t)throw new l("no fetch implementation available in this runtime");let r=u(),s=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let i=await t(`${this.host}/v1/guides?distinct_id=${encodeURIComponent(e)}`,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!i.ok)throw new l(`guides request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).guides??[]}finally{s!==void 0&&clearTimeout(s);}}};function xe(n,e){let t={$guide_id:n.id,$guide_iteration:n.iteration,$guide_name:n.name};return e!==void 0&&(t.$guide_step_id=e),t}function H(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function J(n,e){return `pdx.${n}.${e}`}var z="consent",je=["identityLink","analytics","marketing","functional"];function k(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let s of je){let i=t[s];typeof i=="boolean"&&(r[s]=i);}return typeof t.version=="number"&&Number.isInteger(t.version)&&(r.version=t.version),Array.isArray(t.categories)&&t.categories.every(s=>typeof s=="string")&&(r.categories=t.categories),Object.keys(r).length===0?null:r}catch{return null}}var Ce=n=>n.endsWith(`.${z}`);function M(n,e){return k(n.getItem(J(e,z)))}function Ve(n,e,t){let r=J(e,z),s=k(JSON.stringify(t)),i=s===null?null:k(JSON.stringify({...M(n,e)??{},...s}));if(i===null){n.removeItem(r);return}n.setItem(r,JSON.stringify(i));}var R=class{constructor(e,t,r,s){this.storage=e;this.shared=t;this.ids=r;this.namespace=s;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=H(this.shared.getItem(this.key("anonymous_id"))),t=H(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 r=H(this.storage.getItem(this.key("distinct_id")));r?(this.distinctId=r,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 M(this.shared,this.namespace)}setConsent(e){Ve(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,r=this.storage.getItem(this.key("linked_anonymous_id")),s=t||r!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!s||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 J(this.namespace,e)}};var N=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=h(e.fetch),this.host=p(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)}`,s=await this.request(t,r,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new l(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,t){let r=this.requireFetch(),s=`${this.host}/v1/messages/read`,i=await this.request(r,s,{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 s=u(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...r,signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var O=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(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 Ue={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Be(n){return `pdx.${n}.session`}var q=class{constructor(e,t,r,s,i=Ue){this.storage=e;this.ids=t;this.clock=r;this.namespace=s;this.options=i;}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 r=this.live(this.read(),e),s=r!==void 0&&r.id!==t.id?r:t;return this.write({...s,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 Be(this.namespace)}};var d={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function we(n){return n>=400&&n<500&&n!==429}var K=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=h(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??W,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),s;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,r);if(a.ok)return;if(we(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);s=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&we(a.status))throw a;s=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,t,r){let s=u(),i=s?setTimeout(()=>s.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:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var He="queue",Je=1e3,Ee=3e4,Q=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},D=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"surveysClient");o(this,"guidesClient");o(this,"captureListeners",new Set);o(this,"formsClient");o(this,"ctasClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);o(this,"gates");o(this,"cookielessId");o(this,"storageListeners",new Set);let t=ie(e),r=M(t.sharedStorage,t.namespace)??t.consent??null;if(this.gates=[new S(t.storage),new S(t.sharedStorage,Ce)],t.consentMode!=="banner"||r?.analytics===true)for(let a of this.gates)a.open();let[s,i]=this.gates;this.config={...t,sharedStorage:i,storage:s},this.identity=new R(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 q(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 g("queue_overflow",`event queue overflow: dropped ${a.length} oldest event(s)`));}),this.transport=this.config.transport??new K({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 N({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.surveysClient=new $({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.guidesClient=new P({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.formsClient=new T({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.ctasClient=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()}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 r={...this.config.defaultProperties(),...t.element===void 0?{}:this.config.describeElement?.(t.element)??{},...t.properties??{}},s=ae({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:r,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(r){this.config.onError(r);}for(let r of this.captureListeners)try{r(e);}catch(s){this.config.onError(s);}}onCapture(e){return this.captureListeners.add(e),()=>{this.captureListeners.delete(e);}}identify(e,t={}){if(this.isCookieless())return;this.identity.refresh();let r=this.identity.identify(e),s={};r.anonymousToLink!==void 0&&(s.$anon_distinct_id=r.anonymousToLink);let i=X(),a={...i===null?{}:{$timezone:i},...Q(t.traits??{}),...t.set??{}};Object.keys(a).length>0&&(s.$set=a),this.capture(d.identify,{properties:s});}link(e,t,r){if(this.isCookieless())return;let s={$anon_distinct_id:t},i=Q(r??{});Object.keys(i).length>0&&(s.$set=i),this.capture(d.identify,{distinctId:e,properties:s});}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(d.createAlias,{properties:{alias:e}});}group(e,t,r){let s={$group_key:t,$group_type:e};r&&(s.$set=r),this.capture(d.group,{properties:s});}setPersonProperties(e,t){if(this.isCookieless())return;let r={};e&&(r.$set=e),t&&(r.$set_once=t),this.capture(d.set,{properties:r});}setPersonTraits(e){if(this.isCookieless())return;let t=Q(e);Object.keys(t).length!==0&&this.capture(d.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(),s=r.flags.find(Fe=>Fe.key===e),i=await this.localContext(t,r.flags),a=s?V(s,r.flags,i):null,c=s?_(s,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(d.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 r=await this.flagSnapshot(),s=r.flags.find(c=>c.key===e),i=await this.localContext(t,r.flags),a=s?_(s,r.flags,i).enabled:false;return this.recordExposure(e,(s?V(s,r.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let r=this.identity.getDistinctId(),s=e.cohorts;if(s===void 0&&fe(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===r&&i-this.membershipCache.fetchedAt<Ee?s=this.membershipCache.cohorts:(s=await this.flagsClient.memberships(r),this.membershipCache={cohorts:s,distinctId:r,fetchedAt:i});}return {attributes:e.attributes,cohorts:s,distinctId:r,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 I({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 getSurveys(e){return this.surveysClient.surveys(this.identity.getDistinctId(),e??this.config.locale)}captureSurveyShown(e){this.capture(be,{properties:A(e,{})});}captureSurveyDismissed(e){this.capture(Se,{properties:A(e,{})});}captureSurveySent(e,t){this.capture(ke,{properties:A(e,t)});}async getGuides(){return this.guidesClient.guides(this.identity.getDistinctId())}captureGuide(e,t,r){this.capture(e,{properties:xe(t,r)});}async getForm(e){return this.formsClient.form(e,this.identity.getDistinctId())}async submitForm(e,t,r,s){let{$page_id:i,$page_variant:a}=this.config.defaultProperties();return this.formsClient.submit(e,{answers:t,challenge:r,distinctId:this.identity.getDistinctId(),isAnonymous:!this.identity.isIdentified(),pageUrl:typeof window>"u"?"":window.location.href,solution:s,...typeof i=="string"&&typeof a=="string"?{pageId:i,pageVariant:a}:{}})}async getCtas(e){return this.ctasClient.ctas({...e,anonymous:!this.identity.isIdentified(),distinctId:this.identity.getDistinctId()})}captureCta(e,t,r){this.capture(e,{properties:oe(t,r)});}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Je);try{await this.transport.send({body:{events:e,sent_at:x(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}.${He}`}};var ze=200;function _e(){return globalThis.process}function Qe(n){_e()?.on("beforeExit",()=>{n.flush();});}function Nn(n){let e=_e(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},r=new D(t);return Qe(r),r}function On(n,e){let t=L(e),r=We(n,`pdx_${t}`);if(r===void 0)return null;let s=Ye(r);if(s===void 0)return null;let i=Ie(s[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:k(s[`pdx.${t}.consent`]),sessionId:Xe(s[`pdx.${t}.session`])}}function We(n,e){let t=`${e}=`;for(let r of n.split(";")){let s=r.trim();if(s.startsWith(t))return s.slice(t.length)}}function Ye(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function Ie(n){if(typeof n!="string")return;let e=C(n);return e>=1&&e<=ze?n:void 0}function Xe(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:Ie(e.id)??null}catch{return null}}exports.createNodeClient=Nn;exports.readSharedIdentity=On;//# sourceMappingURL=node.cjs.map
2
2
  //# sourceMappingURL=node.cjs.map
package/dist/node.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { P as ProdantixClient } from './client-CL6Xvhay.cjs';
2
- import { b as Consent, P as ProdantixConfig } from './types-Q2VNlJbG.cjs';
1
+ import { P as ProdantixClient } from './client-vogZuHfD.cjs';
2
+ import { b as Consent, P as ProdantixConfig } from './types-BUXFV_aE.cjs';
3
+ import './http-BCh716Vs.cjs';
3
4
 
4
5
  /** What the web SDK's cookie says about the visitor on this request: the
5
6
  * anonymous id every subdomain of the site shares, the session it is in, and
package/dist/node.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { P as ProdantixClient } from './client-QyKW0LFW.js';
2
- import { b as Consent, P as ProdantixConfig } from './types-Q2VNlJbG.js';
1
+ import { P as ProdantixClient } from './client-Cz7M6XJC.js';
2
+ import { b as Consent, P as ProdantixConfig } from './types-BUXFV_aE.js';
3
+ import './http-BCh716Vs.js';
3
4
 
4
5
  /** What the web SDK's cookie says about the visitor on this request: the
5
6
  * anonymous id every subdomain of the site shares, the session it is in, and
package/dist/node.js CHANGED
@@ -1,2 +1,2 @@
1
- import {y as y$1,h as h$1,p as p$1,e}from'./chunk-D6PMLUYA.js';import'./chunk-V77KYPOF.js';import'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var a=200;function f(){return globalThis.process}function p(t){f()?.on("beforeExit",()=>{t.flush();});}function h(t){let n=f(),e={...t,os:t.os??(n?.platform?n.platform.slice(0,50):void 0),streamFlags:t.streamFlags??true},r=new y$1(e);return p(r),r}function w(t,n){let e=h$1(n),r=m(t,`pdx_${e}`);if(r===void 0)return null;let o=g(r);if(o===void 0)return null;let i=l(o[`pdx.${e}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:p$1(o[`pdx.${e}.consent`]),sessionId:y(o[`pdx.${e}.session`])}}function m(t,n){let e=`${n}=`;for(let r of t.split(";")){let o=r.trim();if(o.startsWith(e))return o.slice(e.length)}}function g(t){try{let n=JSON.parse(decodeURIComponent(t));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function l(t){if(typeof t!="string")return;let n=e(t);return n>=1&&n<=a?t:void 0}function y(t){if(typeof t!="string")return null;try{let n=JSON.parse(t);return n===null||typeof n!="object"||typeof n.startedAt!="number"||typeof n.lastActivityAt!="number"?null:l(n.id)??null}catch{return null}}export{h as createNodeClient,w as readSharedIdentity};//# sourceMappingURL=node.js.map
1
+ import {_,h as h$1,R,e}from'./chunk-L4P6GMBC.js';import'./chunk-V77KYPOF.js';import'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var a=200;function f(){return globalThis.process}function p(t){f()?.on("beforeExit",()=>{t.flush();});}function h(t){let n=f(),e={...t,os:t.os??(n?.platform?n.platform.slice(0,50):void 0),streamFlags:t.streamFlags??true},r=new _(e);return p(r),r}function w(t,n){let e=h$1(n),r=m(t,`pdx_${e}`);if(r===void 0)return null;let o=g(r);if(o===void 0)return null;let i=l(o[`pdx.${e}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:R(o[`pdx.${e}.consent`]),sessionId:y(o[`pdx.${e}.session`])}}function m(t,n){let e=`${n}=`;for(let r of t.split(";")){let o=r.trim();if(o.startsWith(e))return o.slice(e.length)}}function g(t){try{let n=JSON.parse(decodeURIComponent(t));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function l(t){if(typeof t!="string")return;let n=e(t);return n>=1&&n<=a?t:void 0}function y(t){if(typeof t!="string")return null;try{let n=JSON.parse(t);return n===null||typeof n!="object"||typeof n.startedAt!="number"||typeof n.lastActivityAt!="number"?null:l(n.id)??null}catch{return null}}export{h as createNodeClient,w as readSharedIdentity};//# sourceMappingURL=node.js.map
2
2
  //# sourceMappingURL=node.js.map