@prodantix/sdk 0.7.0 → 0.8.0-beta.651
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/dist/chat.cjs +3 -3
- package/dist/chat.d.cts +8 -4
- package/dist/chat.d.ts +8 -4
- package/dist/chat.js +4 -4
- package/dist/chunk-YHIIKYUP.js +2 -0
- package/dist/{config-C6Yz_Tdf.d.ts → config-Bhwwo-uC.d.ts} +12 -2
- package/dist/{config-Cs3L7V_P.d.cts → config-C8WD1Pge.d.cts} +12 -2
- package/dist/consent.iife.js +45 -14
- package/dist/ctas.iife.js +3 -3
- package/dist/forms.iife.js +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1 -1
- package/dist/messenger-files.iife.js +1 -1
- package/dist/messenger.cjs +1 -1
- package/dist/messenger.d.cts +1 -1
- package/dist/messenger.d.ts +1 -1
- package/dist/messenger.iife.js +2 -2
- package/dist/messenger.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/pages.iife.js +1 -1
- package/dist/web.cjs +4 -4
- package/dist/web.d.cts +2 -0
- package/dist/web.d.ts +2 -0
- package/dist/web.js +24 -24
- package/package.json +4 -4
- package/dist/chunk-L4P6GMBC.js +0 -2
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{J as CHECKLIST_TASK_DONE,Z as FetchTransport,r as FlagsClient,H as GUIDE_COMPLETED,I as GUIDE_DISMISSED,E as GUIDE_SHOWN,G as GUIDE_STEP_MISSED,F as GUIDE_STEP_VIEWED,K as GuidesClient,a as MemoryStorage,T as MessagesClient,_ as ProdantixClient,f as SDK_NAME,g as SDK_VERSION,w as SURVEY_DISMISSED,x as SURVEY_SENT,v as SURVEY_SHOWN,V as SYSTEM_EVENT,W as SYSTEM_EVENTS,y as SurveysClient,p as assignVariant,m as bucket,$ as createClient,o as evaluateAll,n as evaluateFlag,q as getVariant,L as guideKey,Q as guideProperties,B as isDue,N as isGuideDue,X as isSystemEventName,l as matches,C as nextQuestion,D as responseProperties,z as settledKey,Y as systemEvent,P as taskFor,M as taskKey,O as tasksDone,A as urlMatches}from'./chunk-
|
|
1
|
+
export{J as CHECKLIST_TASK_DONE,Z as FetchTransport,r as FlagsClient,H as GUIDE_COMPLETED,I as GUIDE_DISMISSED,E as GUIDE_SHOWN,G as GUIDE_STEP_MISSED,F as GUIDE_STEP_VIEWED,K as GuidesClient,a as MemoryStorage,T as MessagesClient,_ as ProdantixClient,f as SDK_NAME,g as SDK_VERSION,w as SURVEY_DISMISSED,x as SURVEY_SENT,v as SURVEY_SHOWN,V as SYSTEM_EVENT,W as SYSTEM_EVENTS,y as SurveysClient,p as assignVariant,m as bucket,$ as createClient,o as evaluateAll,n as evaluateFlag,q as getVariant,L as guideKey,Q as guideProperties,B as isDue,N as isGuideDue,X as isSystemEventName,l as matches,C as nextQuestion,D as responseProperties,z as settledKey,Y as systemEvent,P as taskFor,M as taskKey,O as tasksDone,A as urlMatches}from'./chunk-YHIIKYUP.js';import'./chunk-V77KYPOF.js';export{b as ConfigError,a as ProdantixError,d as TransportError,c as ValidationError}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){'use strict';var f=Object.defineProperty;var
|
|
1
|
+
(function(){'use strict';var f=Object.defineProperty;var x=(t,r)=>{for(var o in r)f(t,o,{get:r[o],enumerable:true});};var u={};x(u,{attachField:()=>k,drawFile:()=>T,filesCss:()=>b,markRefused:()=>C,sizeOf:()=>m,uploadRefusalOf:()=>y});var g=".att{display:block;width:180px;margin-bottom:6px;border-radius:8px;overflow:hidden}.att img{display:block;width:100%}.pdfc{display:inline-flex;gap:8px;align-items:center;margin-bottom:6px;padding:6px 8px;border-radius:8px;background:color-mix(in srgb,currentColor 16%,transparent);color:inherit;font-size:12.5px;text-decoration:none;overflow-wrap:anywhere}.pdfc b,.file b{flex:none;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border-radius:4px;font-size:9px;letter-spacing:.04em;background:color-mix(in srgb,currentColor 22%,transparent)}.att:last-child,.pdfc:last-child{margin-bottom:0}.refused{display:block;margin:5px 0 0;font-size:11.5px}";function h(t){let r=t==="round"?14:12;return `.field{position:relative;flex:1;min-width:0;display:flex}.composer .field input{padding-left:${r+26}px}.composer button.clip{position:absolute;top:50%;left:${r-5}px;right:auto;width:28px;min-width:28px;height:28px;padding:0;border-radius:7px;background:none;color:var(--ink-2);transform:translateY(-50%)}.composer button.clip:hover{background:color-mix(in srgb,currentColor 14%,transparent)}.clip svg{display:block;width:18px;height:18px}.file{display:inline-flex;gap:8px;align-items:center;align-self:flex-start;max-width:calc(100% - 20px);margin:0 10px 8px;padding:6px 10px 6px 6px;font-size:12.5px;color:var(--ink);border:1px solid var(--hairline);border-radius:8px}.file .th{flex:none;width:28px;height:28px;border-radius:4px;object-fit:cover}.file .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.file .sz,.file .x{flex:none;color:var(--ink-3)}.file .x{margin-left:4px;padding:0;border:0;background:none;font:inherit;font-size:16px;line-height:1;cursor:pointer}.ferr{margin:0 10px 6px;font-size:12px;color:oklch(60% 0.2 27)}`}var b=(t,r)=>`${g}${t?h(r):""}`;function m(t){return t<999500?`${Math.max(1,Math.round(t/1e3))} KB`:`${(t/1e6).toFixed(1)} MB`}var E='<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="m16.5 6.5-7.8 7.8a2.1 2.1 0 0 0 3 3l8.1-8.1a4.2 4.2 0 0 0-6-6L5.7 11.3a6.3 6.3 0 0 0 8.9 8.9l6.6-6.6"/></svg>';function k(t,r,o,c,i){let l=document.createElement("span");l.className="field";let e=document.createElement("input");e.type="file",e.accept=i.accept.join(","),e.hidden=true,e.addEventListener("change",()=>{var d;let a=(d=e.files)==null?void 0:d[0];e.value="",a&&v(t,c,r,i,a);});let n=document.createElement("button");n.type="button",n.className="clip",n.setAttribute("aria-label",t.attachLabel),n.innerHTML=E,n.addEventListener("click",()=>e.click()),o.replaceWith(l),l.append(n,o,e);}function v(t,r,o,c,i){let l=i.size>c.maxBytes||!c.accept.includes(i.type);for(let s of t.root.querySelectorAll(l?".ferr":".file,.ferr"))s.remove();if(l){let s=document.createElement("p");s.className="ferr",s.setAttribute("role","alert"),s.textContent=t.fileRefusal(m(i.size),`${c.maxBytes/1e6} MB`),o.before(s),r.scrollTop=r.scrollHeight;return}t.hold(i);let e=document.createElement("span");e.className="file";let n;if(i.type==="application/pdf")n=document.createElement("b"),n.textContent="PDF";else {let s=document.createElement("img");s.className="th",s.alt="",s.src=t.objectUrl(i),n=s;}let a=document.createElement("span");a.className="name",a.textContent=i.name;let d=document.createElement("span");d.className="sz",d.textContent=`\xB7 ${m(i.size)}`;let p=document.createElement("button");p.type="button",p.className="x",p.setAttribute("aria-label",t.removeFileLabel),p.textContent="\xD7",p.addEventListener("click",()=>{t.hold(null),e.remove();}),e.append(n,a,d,p),o.before(e),r.scrollTop=r.scrollHeight;}function T(t,r,o,c,i,l){let e=document.createElement("a");if(o==="application/pdf"){e.className="pdfc",e.download=r;let n=document.createElement("b");n.textContent="PDF",e.append(n,`${r} \xB7 ${m(c)}`);}else {e.className="att",e.target="_blank",e.rel="noopener noreferrer";let n=document.createElement("img");n.alt=r,n.addEventListener("load",()=>{let a=e.closest(".log");a&&(a.scrollTop=a.scrollHeight);}),e.append(n);}t.append(e),i.then(n=>{var a;n&&(e.href=l(n),(a=e.querySelector("img"))==null||a.setAttribute("src",e.href));});}var A={refused:"This file did not pass a safety check.",tryAgain:"Try again",unchecked:"This file could not be checked."};function C(t,r,o,c){var a,d;let i=(a=o==null?void 0:o.words)!=null?a:A;t.removeAttribute("data-pending"),t.setAttribute("data-failed","");let l=(d=t.querySelector(".body"))!=null?d:t,e=document.createElement("span");if(e.className="refused",e.setAttribute("role","alert"),e.textContent=r==="ATTACHMENT_REFUSED"?i.refused:i.unchecked,l.append(e),r!=="ATTACHMENT_UNCHECKED")return;let n=document.createElement("button");n.type="button",n.className="retry",n.textContent=i.tryAgain,n.addEventListener("click",()=>{t.remove(),c();}),l.append(n);}var y=t=>{var o;let r=(o=/"code":"(\w+)"/.exec(t))==null?void 0:o[1];return r==="ATTACHMENT_REFUSED"||r==="ATTACHMENT_UNCHECKED"?{refusal:r}:null};window.prodantixMessengerFiles=u;})();//# sourceMappingURL=messenger-files.iife.js.map
|
|
2
2
|
//# sourceMappingURL=messenger-files.iife.js.map
|
package/dist/messenger.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var u=Object.defineProperty;var f=(e,t,r)=>t in e?u(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var c=(e,t,r)=>f(e,typeof t!="symbol"?t+"":t,r);var g=class extends Error{constructor(r,n,s){super(n,s);c(this,"code");this.code=r,this.name="ProdantixError";}};var o=class extends g{constructor(r,n,s){super("transport",r,s);c(this,"status");this.status=n,this.name="TransportError";}};function l(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function
|
|
1
|
+
'use strict';var u=Object.defineProperty;var f=(e,t,r)=>t in e?u(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var c=(e,t,r)=>f(e,typeof t!="symbol"?t+"":t,r);var g=class extends Error{constructor(r,n,s){super(n,s);c(this,"code");this.code=r,this.name="ProdantixError";}};var o=class extends g{constructor(r,n,s){super("transport",r,s);c(this,"status");this.status=n,this.name="TransportError";}};function l(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function d(e){return e.replace(/\/+$/,"")}var h="prodantix.messenger.config",S=e=>{let t=e.navigator?.languages;return Array.isArray(t)&&t.length>0?t.join(","):e.navigator?.language||e.document?.documentElement?.lang||void 0},p=(e,t)=>`${h}:${e}:${t??""}`;function E(e,t,r){let n=e?.get(p(t,r));if(!n)return null;try{let s=JSON.parse(n);return s?.apiKey===t?s.config:null}catch{return null}}async function T(e){let t=l(e.fetchImpl);if(!t)return e.onError?.(new o("no fetch available for the prodantix messenger")),null;let r=d(e.host),n=p(e.apiKey,e.locale),s=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let i=await t(`${r}/v1/messenger/config${s}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!i.ok)return e.onError?.(new o(`prodantix messenger config: ${i.status}`,i.status)),null;let a=JSON.parse(await i.text());return a.enabled?(e.storage?.set(n,JSON.stringify({apiKey:e.apiKey,config:a})),a):(e.storage?.remove(n),a)}catch(i){return e.onError?.(i),null}}exports.MESSENGER_CACHE_KEY=h;exports.cacheKeyFor=p;exports.cachedMessengerConfig=E;exports.fetchMessengerConfig=T;exports.localeCandidates=S;//# sourceMappingURL=messenger.cjs.map
|
|
2
2
|
//# sourceMappingURL=messenger.cjs.map
|
package/dist/messenger.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { H as HelpWords,
|
|
1
|
+
export { w as AttachmentWords, H as HelpWords, x as MESSENGER_CACHE_KEY, M as MessengerAttachments, i as MessengerConfig, y as MessengerConfigOptions, z as MessengerHelp, E as MessengerTickets, G as StarterPrompt, T as TicketWords, I as cacheKeyFor, J as cachedMessengerConfig, K as fetchMessengerConfig, O as localeCandidates } from './config-C8WD1Pge.cjs';
|
|
2
2
|
import './http-BCh716Vs.cjs';
|
package/dist/messenger.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { H as HelpWords,
|
|
1
|
+
export { w as AttachmentWords, H as HelpWords, x as MESSENGER_CACHE_KEY, M as MessengerAttachments, i as MessengerConfig, y as MessengerConfigOptions, z as MessengerHelp, E as MessengerTickets, G as StarterPrompt, T as TicketWords, I as cacheKeyFor, J as cachedMessengerConfig, K as fetchMessengerConfig, O as localeCandidates } from './config-Bhwwo-uC.js';
|
|
2
2
|
import './http-BCh716Vs.js';
|
package/dist/messenger.iife.js
CHANGED
|
@@ -1,9 +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 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"],me=["round","square"],ge=["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,ge,(S=c==null?void 0:c[0])!=null?S:C.bubbleShape),composerShape:A(e.composerShape,me,(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);
|
|
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 u=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var _=class extends Error{constructor(t,r,i){super(r,i);u(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);u(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 R=class{constructor(e){this.options=e;u(this,"fetchImpl");u(this,"fileFetchImpl");u(this,"host");u(this,"storage");u(this,"handle");u(this,"identity",null);u(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,t){if(!await this.ensureThread())return null;let r=this.handle;return r?this.fileRequest("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/attachments?name=${encodeURIComponent(e.name)}`,r.token,async i=>JSON.parse(await i.text()),e,t):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,s){var h,p,l,d;let o={authorization:`Bearer ${this.options.apiKey}`,[j]: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);let g=s==null?void 0:s(await c.text());if(g)return g;(p=(h=this.options).onError)==null||p.call(h,new w(`prodantix chat ${t}: ${c.status}`,c.status));}catch(c){(d=(l=this.options).onError)==null||d.call(l,c);}return null}async request(e,t,r={}){var s,o,h,p,l,d;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 c=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),g=await c.text();return c.ok?g?JSON.parse(g):{}:((p=(h=this.options).onError)==null||p.call(h,new w(`prodantix chat ${t}: ${c.status}`,c.status)),null)}catch(c){return (d=(l=this.options).onError)==null||d.call(l,c),null}}};var ue={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function M(n,e){var o,h,p,l,d,c;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=ue[(h=(o=t.find(g=>g.type==="weekday"))==null?void 0:o.value)!=null?h:""];if(!r)return false;let i=(l=(p=t.find(g=>g.type==="hour"))==null?void 0:p.value)!=null?l:"",a=(c=(d=t.find(g=>g.type==="minute"))==null?void 0:d.value)!=null?c:"",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"],me=["round","square"],ge=["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],h=typeof e.skin=="string"?e.skin:void 0,p=h===void 0?void 0:Ae[h],l=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,d=l===void 0?void 0:Le[l],c={bubbleFill:A(e.bubbleFill,fe,(g=d==null?void 0:d[1])!=null?g:C.bubbleFill),bubbleShape:A(e.bubbleShape,ge,(S=d==null?void 0:d[0])!=null?S:C.bubbleShape),composerShape:A(e.composerShape,me,(k=p==null?void 0:p[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=p==null?void 0:p[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 c.stampPlacement==="beside_name"&&c.namePlacement==="hidden"&&(c.stampPlacement="under_turn"),c}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}",Re={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Me={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:""},Ke={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}${Re[n]}${Me[e]}${$e[n]}${Ke[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 Oe={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
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
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,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.system{align-self:center;font-size:12px;color:var(--ink-3)}.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;if((c=e.querySelector(".empty"))==null||c.remove(),t.authorKind==="system"){let m=document.createElement("div");return m.className="turn system",m.dataset.turnId=t.id,m.textContent=t.body,e.append(m),m}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 mt=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,mt);};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 gt="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)=>`${gt}:${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);
|
|
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.system{align-self:center;font-size:12px;color:var(--ink-3)}.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>',K=class{constructor(e,t,r={},i={},a={}){this.host=e;this.client=t;u(this,"root");u(this,"strings");u(this,"settings");u(this,"appearance");u(this,"launcher");u(this,"badge");u(this,"panel",null);u(this,"scrim",null);u(this,"lastFocused",null);u(this,"unread",0);u(this,"pendingTurns",0);u(this,"openNow");u(this,"styles");u(this,"scheme");u(this,"picked",null);u(this,"objectUrls",[]);u(this,"helpLoader");u(this,"kit",null);u(this,"kitLoad",null);u(this,"filesLoader");u(this,"filesKit",null);u(this,"filesLoad",null);u(this,"ticketsLoader");u(this,"ticketsLoad");var s;this.strings={...Oe,...r},this.appearance={...N,...i},this.settings=$({...N,...i}),this.root=e.attachShadow({mode:(s=a.shadowMode)!=null?s:"closed"}),this.openNow=M(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 h=document.createElement("span");h.className="live",h.setAttribute("aria-hidden","true"),o.append(h,this.strings.replyTime),a.append(s,o);let p=document.createElement("button");p.className="close",p.type="button",p.setAttribute("aria-label",this.strings.closeLabel),p.innerHTML=lt,p.addEventListener("click",()=>this.close()),t.append(a,p);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 d=document.createElement("form");d.className="composer";let c=document.createElement("input");c.type="text",c.setAttribute("aria-label",this.strings.inputPlaceholder),c.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),d.append(c,g),d.addEventListener("submit",E=>{E.preventDefault(),this.submit(c,l);}),e.append(t,l,d),this.appearance.poweredBy&&e.append(Ue(this.appearance.poweredBy,this.client.avatarUrl("/messenger-mark.png"))),e.addEventListener("keydown",E=>this.onKeydown(E,e,p));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()),c.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},d,c,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,c,d),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,c),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,h)=>{let p=document.createElement("div");p.className="prompt";let l=document.createElement("div");l.className="promptwords",l.id=`prompt-${h}`;let d=document.createElement("template");d.innerHTML=o.html,it(d.content)?l.append(d.content):l.textContent=o.text;for(let g of l.querySelectorAll("a"))g.target="_blank",g.rel="noopener noreferrer";let c=document.createElement("button");c.className="promptpress",c.type="button",c.setAttribute("aria-labelledby",l.id),c.addEventListener("click",()=>{t.value=o.text,this.submit(t,e);}),p.append(l,c),r.append(p);}),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,h,p,l,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((l=(p=this.client).upload)==null?void 0:l.call(p,r,(h=this.filesKit)==null?void 0:h.uploadRefusalOf)):void 0;if(a&&"refusal"in a){(d=this.filesKit)==null||d.markRefused(i,a.refusal,this.appearance.attachments,()=>this.sendBody(e,t,r));return}let 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 d,c,g,S,k,f,y;if((d=e.querySelector(".empty"))==null||d.remove(),t.authorKind==="system"){let m=document.createElement("div");return m.className="turn system",m.dataset.turnId=t.id,m.textContent=t.body,e.append(m),m}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=(c=this.appearance.team)==null?void 0:c.find(v=>v.name===t.authorName))==null?void 0:g.tone:void 0;b&&(m.style.background=b);}s.append(m);}let h=document.createElement("div");if(h.className="body",i==="end_user"){let m=this.filesKit,b=v=>this.objectUrl(v);r&&(m==null||m.drawFile(h,r.name,r.type,r.size,Promise.resolve(r),b));for(let v of (S=t.attachments)!=null?S:[])m==null||m.drawFile(h,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 p=i!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(i==="ai"?et(l,t.body):l.textContent=t.body,p||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"),h.append(l,m)):h.append(m,l);}else t.body&&h.append(l);return a.stampPlacement==="under_turn"&&h.append(this.stamp(t)),s.append(h),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(h=>!h.closest("[hidden]")&&!h.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",O=class{constructor(e){this.options=e;u(this,"socket",null);u(this,"heartbeat",null);u(this,"ready",false);u(this,"closed",false);u(this,"heartbeatWindow",45e3);u(this,"factory");u(this,"setTimer");u(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 mt=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 R(n),i=new K(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(M(a,new Date)),s=setTimeout(o,mt);};o();let h=new Set,p,l=null,d=(v=n.pollIntervalMs)!=null?v:15e3,c=x=>{h.has(x.id)||x.authorKind==="end_user"||(h.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)c(T);h=new Set(x.turns.map(T=>T.id));}},S=()=>{p||d<=0||(p=setInterval(()=>void g(),d));},k=()=>{p&&clearInterval(p),p=void 0;},f=()=>{if(l||!n.socketHost)return;let x=r.socketAuth;x&&(l=new O({auth:x,host:n.socketHost,onClosed:T=>{l=null,S(),T&&f();},onReady:k,onTurn:c,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 gt="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)=>`${gt}:${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,h,p;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 d=JSON.parse(await l.text());return d.enabled?((h=n.storage)==null||h.set(r,JSON.stringify({apiKey:n.apiKey,config:d})),d):((o=n.storage)==null||o.remove(r),d)}catch(l){return (p=n.onError)==null||p.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 h;let o=(h=r())!=null?h: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),h=ae(s,i,o),p=await se({apiKey:i,host:a,locale:o,onError:f=>t(`${L} settings could not be read: ${String(f)}`),storage:s}),l=p!=null?p:h;if(!l)return t(`${L} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let d=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}),c=(f,...y)=>{if((f==="open"||f==="toggle")&&d.open(),f==="close"&&d.close(),f==="shutdown"&&d.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}d.identify(m);}};return bt((k=r==null?void 0:r.q)!=null?k:[],c),n.prodantix=Object.assign((f,...y)=>c(f,...y),{k:i,q:[]}),d}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
8
|
})();//# sourceMappingURL=messenger.iife.js.map
|
|
9
9
|
//# sourceMappingURL=messenger.iife.js.map
|
package/dist/messenger.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {e,d as
|
|
1
|
+
import {e,d,h as h$1}from'./chunk-ODN4ZELX.js';import'./chunk-5XGN7UAV.js';var p="prodantix.messenger.config",h=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("no fetch available for the prodantix messenger")),null;let a=h$1(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(`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,h 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 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
|
|
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 d(){let n=globalThis.AbortController;return n?new n:void 0}var Q=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 w(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=w(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=w(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.8.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},C=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=d(),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 ue(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(r=>String(r)).includes(t)}function de(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 ue(t,r);case "not_in":return Array.isArray(r)?!ue(t,r):false;case "gt":return _(t,r,(s,i)=>s>i);case "gte":return _(t,r,(s,i)=>s>=i);case "lt":return _(t,r,(s,i)=>s<i);case "lte":return _(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 _(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=>de(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 E(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]=E(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=d(),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=d(),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=d(),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=d(),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=d(),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=d(),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 we=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=d(),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 u={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function Ce(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??Q,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(Ce(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&&Ce(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=d(),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,_e=3e4,W=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,we)],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 C({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},...W(t.traits??{}),...t.set??{}};Object.keys(a).length>0&&(s.$set=a),this.capture(u.identify,{properties:s});}link(e,t,r){if(this.isCookieless())return;let s={$anon_distinct_id:t},i=W(r??{});Object.keys(i).length>0&&(s.$set=i),this.capture(u.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(u.createAlias,{properties:{alias:e}});}group(e,t,r){let s={$group_key:t,$group_type:e};r&&(s.$set=r),this.capture(u.group,{properties:s});}setPersonProperties(e,t){if(this.isCookieless())return;let r={};e&&(r.$set=e),t&&(r.$set_once=t),this.capture(u.set,{properties:r});}setPersonTraits(e){if(this.isCookieless())return;let t=W(e);Object.keys(t).length!==0&&this.capture(u.set,{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let 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?E(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(u.featureFlagCalled,{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return ge(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let r=await this.flagSnapshot(),s=r.flags.find(c=>c.key===e),i=await this.localContext(t,r.flags),a=s?E(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<_e?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<_e)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 Ee(){return globalThis.process}function We(n){Ee()?.on("beforeExit",()=>{n.flush();});}function Nn(n){let e=Ee(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},r=new D(t);return We(r),r}function On(n,e){let t=L(e),r=Qe(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 Qe(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=w(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.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {_,h as h$1,R,e}from'./chunk-
|
|
1
|
+
import {_,h as h$1,R,e}from'./chunk-YHIIKYUP.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
|