@prodantix/sdk 0.2.0 → 0.3.0-beta.379
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat.cjs +81 -18
- package/dist/chat.d.cts +27 -8
- package/dist/chat.d.ts +27 -8
- package/dist/chat.js +86 -23
- package/dist/chunk-ESOQKMEE.js +2 -0
- package/dist/{config-CWmtX8Gl.d.cts → config-D8-uiWM8.d.cts} +14 -5
- package/dist/{config-DDlHv52p.d.ts → config-DGUsxWOL.d.ts} +14 -5
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +28 -1
- package/dist/index.d.ts +28 -1
- package/dist/index.js +1 -1
- package/dist/messenger.d.cts +1 -1
- package/dist/messenger.d.ts +1 -1
- package/dist/messenger.iife.js +86 -23
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/web.cjs +1 -1
- package/dist/web.js +1 -1
- package/package.json +3 -3
- package/dist/chunk-5CBVQAZ2.js +0 -2
package/dist/index.d.cts
CHANGED
|
@@ -116,7 +116,34 @@ declare class MemoryStorage implements StorageAdapter {
|
|
|
116
116
|
setItem(key: string, value: string): void;
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
+
/** Which SDK sends an event: the web SDK alone, the Flutter package alone, or
|
|
120
|
+
* every SDK (TypeScript, Dart, Python). */
|
|
121
|
+
type SystemEventEmitter = 'every' | 'flutter' | 'web';
|
|
122
|
+
type SystemEvent = {
|
|
123
|
+
emittedBy: SystemEventEmitter;
|
|
124
|
+
meaning: string;
|
|
125
|
+
name: string;
|
|
126
|
+
properties: readonly string[];
|
|
127
|
+
};
|
|
128
|
+
declare const SYSTEM_EVENT: {
|
|
129
|
+
readonly autocapture: "$autocapture";
|
|
130
|
+
readonly createAlias: "$create_alias";
|
|
131
|
+
readonly featureFlagCalled: "$feature_flag_called";
|
|
132
|
+
readonly group: "$group";
|
|
133
|
+
readonly identify: "$identify";
|
|
134
|
+
readonly pageview: "$pageview";
|
|
135
|
+
readonly screen: "$screen";
|
|
136
|
+
readonly set: "$set";
|
|
137
|
+
};
|
|
138
|
+
type SystemEventName = (typeof SYSTEM_EVENT)[keyof typeof SYSTEM_EVENT];
|
|
139
|
+
/** Every event name the platform owns, what each one means and what it carries.
|
|
140
|
+
* The one list: the emitters read their names from `SYSTEM_EVENT`, the docs
|
|
141
|
+
* render this table, and the console explains a `$` name from it. */
|
|
142
|
+
declare const SYSTEM_EVENTS: readonly SystemEvent[];
|
|
143
|
+
declare const isSystemEventName: (name: string) => boolean;
|
|
144
|
+
declare const systemEvent: (name: string) => SystemEvent | undefined;
|
|
145
|
+
|
|
119
146
|
declare const SDK_NAME = "prodantix-js";
|
|
120
147
|
declare const SDK_VERSION = "0.0.1";
|
|
121
148
|
|
|
122
|
-
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
|
|
149
|
+
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, SYSTEM_EVENT, SYSTEM_EVENTS, StorageAdapter, type SystemEvent, type SystemEventEmitter, type SystemEventName, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, isSystemEventName, matches, systemEvent };
|
package/dist/index.d.ts
CHANGED
|
@@ -116,7 +116,34 @@ declare class MemoryStorage implements StorageAdapter {
|
|
|
116
116
|
setItem(key: string, value: string): void;
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
+
/** Which SDK sends an event: the web SDK alone, the Flutter package alone, or
|
|
120
|
+
* every SDK (TypeScript, Dart, Python). */
|
|
121
|
+
type SystemEventEmitter = 'every' | 'flutter' | 'web';
|
|
122
|
+
type SystemEvent = {
|
|
123
|
+
emittedBy: SystemEventEmitter;
|
|
124
|
+
meaning: string;
|
|
125
|
+
name: string;
|
|
126
|
+
properties: readonly string[];
|
|
127
|
+
};
|
|
128
|
+
declare const SYSTEM_EVENT: {
|
|
129
|
+
readonly autocapture: "$autocapture";
|
|
130
|
+
readonly createAlias: "$create_alias";
|
|
131
|
+
readonly featureFlagCalled: "$feature_flag_called";
|
|
132
|
+
readonly group: "$group";
|
|
133
|
+
readonly identify: "$identify";
|
|
134
|
+
readonly pageview: "$pageview";
|
|
135
|
+
readonly screen: "$screen";
|
|
136
|
+
readonly set: "$set";
|
|
137
|
+
};
|
|
138
|
+
type SystemEventName = (typeof SYSTEM_EVENT)[keyof typeof SYSTEM_EVENT];
|
|
139
|
+
/** Every event name the platform owns, what each one means and what it carries.
|
|
140
|
+
* The one list: the emitters read their names from `SYSTEM_EVENT`, the docs
|
|
141
|
+
* render this table, and the console explains a `$` name from it. */
|
|
142
|
+
declare const SYSTEM_EVENTS: readonly SystemEvent[];
|
|
143
|
+
declare const isSystemEventName: (name: string) => boolean;
|
|
144
|
+
declare const systemEvent: (name: string) => SystemEvent | undefined;
|
|
145
|
+
|
|
119
146
|
declare const SDK_NAME = "prodantix-js";
|
|
120
147
|
declare const SDK_VERSION = "0.0.1";
|
|
121
148
|
|
|
122
|
-
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
|
|
149
|
+
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, SYSTEM_EVENT, SYSTEM_EVENTS, StorageAdapter, type SystemEvent, type SystemEventEmitter, type SystemEventName, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, isSystemEventName, matches, systemEvent };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as ConfigError,
|
|
1
|
+
export{b as ConfigError,B as FetchTransport,s as FlagsClient,e as MemoryStorage,v as MessagesClient,C as ProdantixClient,a as ProdantixError,j as SDK_NAME,k as SDK_VERSION,x as SYSTEM_EVENT,y as SYSTEM_EVENTS,d as TransportError,c as ValidationError,q as assignVariant,n as bucket,D as createClient,p as evaluateAll,o as evaluateFlag,r as getVariant,z as isSystemEventName,m as matches,A as systemEvent}from'./chunk-ESOQKMEE.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/messenger.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { m as MESSENGER_CACHE_KEY, M as MessengerConfig, n as MessengerConfigOptions, o as cachedMessengerConfig, p as fetchMessengerConfig } from './config-D8-uiWM8.cjs';
|
|
2
2
|
import './http-BCh716Vs.cjs';
|
package/dist/messenger.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { m as MESSENGER_CACHE_KEY, M as MessengerConfig, n as MessengerConfigOptions, o as cachedMessengerConfig, p as fetchMessengerConfig } from './config-DGUsxWOL.js';
|
|
2
2
|
import './http-BCh716Vs.js';
|
package/dist/messenger.iife.js
CHANGED
|
@@ -1,45 +1,105 @@
|
|
|
1
|
-
(function(){'use strict';var Y=Object.defineProperty;var J=(n,e,t)=>e in n?Y(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var u=(n,e,t)=>J(n,typeof e!="symbol"?e+"":e,t);function k(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function C(n){return n.replace(/\/+$/,"")}var X="X-Prodantix-Conversation-Token",L="prodantix.chat.handle";function Q(){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 E=class{constructor(e){this.options=e;u(this,"fetchImpl");u(this,"host");u(this,"storage");u(this,"handle");u(this,"identity",null);var t;this.fetchImpl=k(e.fetchImpl),this.host=C(e.host),this.storage=(t=e.storage)!=null?t:Q(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}get socketAuth(){return this.handle?{conversationId:this.handle.conversationId,conversationToken:this.handle.token,projectKey:this.options.apiKey}:null}identify(e){this.identity=e;}async ensureThread(e){var r,i,a;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(i=this.identity)==null?void 0:i.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(a=this.storage)==null||a.set(L,JSON.stringify(this.handle)),true)}async send(e,t){var a;if(!await this.ensureThread())return null;let r=this.handle;if(!r)return null;let i=await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{body:e,pageContext:t},token:r.token});return (a=i==null?void 0:i.turn)!=null?a:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r;let e=(t=this.storage)==null?void 0:t.get(L);if(!e)return null;try{let i=JSON.parse(e);if(typeof i.conversationId=="string"&&typeof i.token=="string")return {conversationId:i.conversationId,token:i.token}}catch(i){}return (r=this.storage)==null||r.remove(L),null}async request(e,t,r={}){var o,s,l,c,d,p;let i=this.fetchImpl;if(!i)return (s=(o=this.options).onError)==null||s.call(o,new Error("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(a[X]=r.token);try{let f=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:a,method:e}),h=await f.text();return f.ok?h?JSON.parse(h):{}:((c=(l=this.options).onError)==null||c.call(l,new Error(`prodantix chat ${t}: ${f.status}`)),null)}catch(f){return (p=(d=this.options).onError)==null||p.call(d,f),null}}};var b={bubbleStyle:"tailed",dayDividers:true,launcherContent:"glyph",launcherFill:"outlined",launcherShape:"circle",launcherSize:"small",nameAvatar:true,namePlacement:"hidden",skin:"concierge",stampContent:"time",stampPlacement:"none"},V=["concierge","console","quiet"],Z=["hairline","outlined","rounded","tailed"],ee=["circle","pill","squircle"],te=["filled","outlined"],ne=["avatar","glyph","team_faces"],re=["large","medium","small"],ie=["above","hidden","inline"],ae=["beside_name","none","under_turn"],oe=["time","time_and_latency"],x=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,H=(n,e)=>typeof n=="boolean"?n:e,se={avatar_circle:["circle","outlined","avatar","large"],circle_filled:["circle","filled","glyph","medium"],circle_outlined:["circle","outlined","glyph","small"],pill_labelled:["pill","filled","glyph","medium"],pill_team:["pill","outlined","team_faces","medium"],squircle_filled:["squircle","filled","glyph","medium"]},le={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},ce={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]};function P(n){var c,d,p,f,h,y,v,m,g;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:se[t],i=typeof e.namePlacement=="string"?e.namePlacement:void 0,a=i===void 0?void 0:le[i],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:ce[o],l={bubbleStyle:x(e.bubbleStyle,Z,b.bubbleStyle),dayDividers:H(e.dayDividers,(c=s==null?void 0:s[0])!=null?c:b.dayDividers),launcherContent:x(e.launcherContent,ne,(d=r==null?void 0:r[2])!=null?d:b.launcherContent),launcherFill:x(e.launcherFill,te,(p=r==null?void 0:r[1])!=null?p:b.launcherFill),launcherShape:x(e.launcherShape,ee,(f=r==null?void 0:r[0])!=null?f:b.launcherShape),launcherSize:x(e.launcherSize,re,(h=r==null?void 0:r[3])!=null?h:b.launcherSize),nameAvatar:H(e.nameAvatar,(y=a==null?void 0:a[1])!=null?y:b.nameAvatar),namePlacement:x(e.namePlacement,ie,(v=a==null?void 0:a[0])!=null?v:b.namePlacement),skin:x(e.skin,V,b.skin),stampContent:x(e.stampContent,oe,(m=s==null?void 0:s[2])!=null?m:b.stampContent),stampPlacement:x(e.stampPlacement,ae,(g=s==null?void 0:s[1])!=null?g:b.stampPlacement)};return l.stampPlacement==="beside_name"&&l.namePlacement==="hidden"&&(l.stampPlacement="under_turn"),l.namePlacement==="inline"&&l.bubbleStyle==="hairline"&&(l.namePlacement="above"),l}var de={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function F(n,e){var s,l,c,d,p,f;let t=new Intl.DateTimeFormat(void 0,{hour:"2-digit",hour12:false,minute:"2-digit",timeZone:n.timezone,weekday:"short"}).formatToParts(e),r=de[(l=(s=t.find(h=>h.type==="weekday"))==null?void 0:s.value)!=null?l:""];if(!r)return false;let i=(d=(c=t.find(h=>h.type==="hour"))==null?void 0:c.value)!=null?d:"",a=(f=(p=t.find(h=>h.type==="minute"))==null?void 0:p.value)!=null?f:"",o=`${i}:${a}`;return n.windows.some(h=>h.days.includes(r)&&h.open<=o&&o<h.close)}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",ue={large:66,medium:56,small:46},he={circle:"width:var(--fab-size);height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);",pill:"width:auto;height:var(--fab-size);border-radius:calc(var(--fab-size) / 2);padding:0 22px;gap:10px;",squircle:"width:var(--fab-size);height:var(--fab-size);border-radius:16px;"},ge={filled:"background:var(--a);color:#fff;",outlined:"background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);"},me={avatar:".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);}",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;}.launcher .live{width:9px;height:9px;position:absolute;right:3px;bottom:3px;border-radius:50%;background:var(--online);box-shadow:0 0 0 2px var(--paper);}"},fe={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},be={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},xe={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},ye={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function $(n,e,t,r){return `.launcher{--fab-size:${ue[r]}px;${he[n]}${ge[e]}}${me[t]}${fe[n]}${be[e]}${xe[n]}${ye[n]}`}function z(n,e,t){let r=document.createDocumentFragment();if(n==="glyph"){let o=document.createElement("span");return o.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>`,r.append(...o.childNodes),r}if(n==="avatar")return r.append(O(t[0],e),R()),r;let i=document.createElement("span");i.className="faces";let a=t.length>0?t.slice(0,2):[void 0];for(let o of a)i.append(O(o,e));return r.append(i,R()),r}function O(n,e){let t=document.createElement("span");return t.className="av",t.setAttribute("aria-hidden","true"),t.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),n&&(t.style.background=n.tone),t}function R(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var ve={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",emptyBody:"We usually reply within a few minutes.",emptyTitle:"Ask us anything.",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",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`},_={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],teamFaces:[],...b},Se={concierge:".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}.composer{padding:12px 12px 14px;gap:8px}.composer input{border:0;background:var(--fill);height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",console:".panel{border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,.16)}.header{background:var(--paper);color:var(--ink);border-bottom:1px solid var(--hairline)}.close{color:var(--ink-2)}",quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{height:42px;padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.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)}.close{color:var(--ink-2)}"},ke={hairline:".turn{max-width:100%;padding:13px 0;border-top:1px solid var(--hairline);background:none;border-radius:0}.log>.turn:first-child{border-top:0}.turn.end_user{align-self:stretch;display:flex;flex-direction:column;align-items:flex-end}.turn.end_user .body{background:var(--fill);color:var(--ink);border-radius:8px;padding:9px 12px;max-width:85%}",outlined:".turn{background:none;border:1px solid var(--hairline);border-radius:12px}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}",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}"},Ce={above:"",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},Ee=".turn.agent,.turn.ai{display:flex;gap:10px;max-width:100%;background:none;padding:0}.turn .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}",Te='.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)}',we={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}"},Ae=".lat{font-size:11px;opacity:.7;margin-left:6px}";function Le(n){let e=P(n),t=n.launcherPosition==="bottom_left"?"left":"right",r=n.accentColor;return `${`
|
|
1
|
+
(function(){'use strict';var ae=Object.defineProperty;var ie=(n,e,t)=>e in n?ae(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var u=(n,e,t)=>ie(n,typeof e!="symbol"?e+"":e,t);function L(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function N(n){return n.replace(/\/+$/,"")}var oe="X-Prodantix-Conversation-Token",H="prodantix.chat.handle";function se(){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 P=class{constructor(e){this.options=e;u(this,"fetchImpl");u(this,"host");u(this,"storage");u(this,"handle");u(this,"identity",null);var t;this.fetchImpl=L(e.fetchImpl),this.host=N(e.host),this.storage=(t=e.storage)!=null?t:se(),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,a,i;if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e,userHash:(r=this.identity)==null?void 0:r.userHash,userId:(a=this.identity)==null?void 0:a.userId}});return !(t!=null&&t.conversationId)||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},(i=this.storage)==null||i.set(H,JSON.stringify(this.handle)),true)}async send(e,t){var i;if(!await this.ensureThread())return null;let r=this.handle;if(!r)return null;let a=await this.request("POST",`/v1/conversations/${encodeURIComponent(r.conversationId)}/turns`,{body:{body:e,pageContext:t},token:r.token});return (i=a==null?void 0:a.turn)!=null?i:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){var t,r;let e=(t=this.storage)==null?void 0:t.get(H);if(!e)return null;try{let a=JSON.parse(e);if(typeof a.conversationId=="string"&&typeof a.token=="string")return {conversationId:a.conversationId,token:a.token}}catch(a){}return (r=this.storage)==null||r.remove(H),null}async request(e,t,r={}){var o,s,p,l,d,c;let a=this.fetchImpl;if(!a)return (s=(o=this.options).onError)==null||s.call(o,new Error("no fetch available for prodantix chat")),null;let i={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(i[oe]=r.token);try{let h=await a(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:i,method:e}),g=await h.text();return h.ok?g?JSON.parse(g):{}:((l=(p=this.options).onError)==null||l.call(p,new Error(`prodantix chat ${t}: ${h.status}`)),null)}catch(h){return (c=(d=this.options).onError)==null||c.call(d,h),null}}};var le={Fri:"fri",Mon:"mon",Sat:"sat",Sun:"sun",Thu:"thu",Tue:"tue",Wed:"wed"};function _(n,e){var s,p,l,d,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=le[(p=(s=t.find(g=>g.type==="weekday"))==null?void 0:s.value)!=null?p:""];if(!r)return false;let a=(d=(l=t.find(g=>g.type==="hour"))==null?void 0:l.value)!=null?d:"",i=(h=(c=t.find(g=>g.type==="minute"))==null?void 0:c.value)!=null?h:"",o=`${a}:${i}`;return n.windows.some(g=>g.days.includes(r)&&g.open<=o&&o<g.close)}var y={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"},ce=["quiet","standard"],de=["round","square"],pe=["rounded","tailed"],he=["filled","outlined"],ue=["circle","pill","squircle"],ge=["filled","outlined"],me=["avatar","glyph","team_faces"],fe=["large","medium","small"],be=["above","hidden","inline"],ye=["beside_name","none","under_turn"],xe=["time","time_and_latency"],S=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t,D=(n,e)=>typeof n=="boolean"?n:e,ve={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"]},Se={above:["above",false],avatar_only:["hidden",true],gutter:["above",true],hidden:["hidden",false],inline:["inline",false]},Ce={cluster:[true,"none","time"],latency:[false,"beside_name","time_and_latency"],none:[false,"none","time"],trailing:[false,"under_turn","time"],with_name:[false,"beside_name","time"]},ke={concierge:["standard","round"],console:["standard","square"],quiet:["quiet","square"]},Ee={hairline:["rounded","outlined"],outlined:["rounded","outlined"],rounded:["rounded","filled"],tailed:["tailed","filled"]};function I(n){var g,x,v,b,m,C,k,w,f,E,U,K,B;let e=typeof n=="object"&&n!==null?n:{},t=typeof e.launcherStyle=="string"?e.launcherStyle:void 0,r=t===void 0?void 0:ve[t],a=typeof e.namePlacement=="string"?e.namePlacement:void 0,i=a===void 0?void 0:Se[a],o=typeof e.timestampStyle=="string"?e.timestampStyle:void 0,s=o===void 0?void 0:Ce[o],p=typeof e.skin=="string"?e.skin:void 0,l=p===void 0?void 0:ke[p],d=typeof e.bubbleStyle=="string"?e.bubbleStyle:void 0,c=d===void 0?void 0:Ee[d],h={bubbleFill:S(e.bubbleFill,he,(g=c==null?void 0:c[1])!=null?g:y.bubbleFill),bubbleShape:S(e.bubbleShape,pe,(x=c==null?void 0:c[0])!=null?x:y.bubbleShape),composerShape:S(e.composerShape,de,(v=l==null?void 0:l[1])!=null?v:y.composerShape),dayDividers:D(e.dayDividers,(b=s==null?void 0:s[0])!=null?b:y.dayDividers),launcherContent:S(e.launcherContent,me,(m=r==null?void 0:r[2])!=null?m:y.launcherContent),launcherFill:S(e.launcherFill,ge,(C=r==null?void 0:r[1])!=null?C:y.launcherFill),launcherShape:S(e.launcherShape,ue,(k=r==null?void 0:r[0])!=null?k:y.launcherShape),launcherSize:S(e.launcherSize,fe,(w=r==null?void 0:r[3])!=null?w:y.launcherSize),nameAvatar:D(e.nameAvatar,(f=i==null?void 0:i[1])!=null?f:y.nameAvatar),namePlacement:S(e.namePlacement,be,(E=i==null?void 0:i[0])!=null?E:y.namePlacement),skin:S(e.skin,ce,(U=l==null?void 0:l[0])!=null?U:y.skin),stampContent:S(e.stampContent,xe,(K=s==null?void 0:s[2])!=null?K:y.stampContent),stampPlacement:S(e.stampPlacement,ye,(B=s==null?void 0:s[1])!=null?B:y.stampPlacement)};return h.stampPlacement==="beside_name"&&h.namePlacement==="hidden"&&(h.stampPlacement="under_turn"),h}function G(n){var r,a,i,o;let e=n.split(/\s+/).filter(s=>s.length>0);return (e.length>1?`${(r=e[0])==null?void 0:r.slice(0,1)}${(a=e[1])==null?void 0:a.slice(0,1)}`:(o=(i=e[0])==null?void 0:i.slice(0,2))!=null?o:"").toUpperCase()}var we="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",Te={large:66,medium:56,small:46},Ae={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;"},Le={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);"},Ne={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;}"},Pe=".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}",_e={circle:"",pill:".badge{position:static;box-shadow:none}",squircle:""},Ie={filled:"",outlined:".badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;font-size:11.5px}"},Me={circle:"",pill:".launcher .label{font-size:14px;font-weight:600;white-space:nowrap;}",squircle:""},Fe={circle:"",pill:"@media (max-width:480px){.launcher{width:var(--fab-size);padding:0}.launcher .label{display:none}}",squircle:""};function q(n,e,t,r){return `.launcher{--fab-size:${Te[r]}px;${Ae[n]}${Le[e]}}${Ne[t]}${Pe}${_e[n]}${Ie[e]}${Me[n]}${Fe[n]}`}function W(n,e,t,r=a=>a){let a=document.createDocumentFragment();if(n==="glyph"||t.length===0){let i=document.createElement("span");return i.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="${we}"/></svg>`,a.append(...i.childNodes,O()),a}return n==="avatar"?(a.append(j(t[0],e,r),O()),a):(a.append(R(t,e,r),O()),a)}function R(n,e,t=r=>r){let r=document.createElement("span");r.className="faces";for(let a of n.slice(0,2))r.append(j(a,e,t));return r}function j(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 a=document.createElement("img");return a.alt="",a.src=t(n.avatarUrl),r.append(a),r}return r.textContent=n?n.initials:e.agentLabel.slice(0,2).toUpperCase(),r}function O(){let n=document.createElement("span");return n.className="live",n.setAttribute("aria-hidden","true"),n}var He={agentLabel:"Agent",aiLabel:"AI",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.",inputPlaceholder:"Type a message",launcherLabel:"Chat with us",replyTime:"Usually replying in a few minutes",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`},T={accentColor:"#5b5bff",availability:{timezone:"UTC",windows:[]},awayMessage:"",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],team:[],...y},Oe={quiet:".composer{position:relative;padding:10px 12px 12px}.composer input{padding-right:42px}.composer button{position:absolute;top:50%;right:16px;width:34px;min-width:34px;height:34px;padding:0;background:transparent;color:var(--ink);border-radius:7px;transform:translateY(-50%)}.composer button .sendglyph{display:block;width:18px;height:18px}.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 .status{color:var(--ink-3)}.header .av,.header .status .live{box-shadow:0 0 0 2px var(--paper)}.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}"},Re={round:".composer{padding:12px 12px 14px;gap:8px}.composer input{height:46px;border-radius:23px;padding:0 16px}.composer button{width:46px;min-width:46px;height:46px;padding:0;border-radius:23px}.composer button .sendglyph{display:block}.composer button .sendtext{display:none}",square:".composer input{height:44px;border-radius:8px;padding:0 12px}"},$e={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}"},ze={filled:"",outlined:".turn{background:none;border:1px solid var(--hairline)}.turn.end_user{background:none;border-color:var(--a);color:var(--ink)}"},Ue={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}"},Ke=".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}",Be='.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)}',De={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}"},Ge=".lat{font-size:11px;opacity:.7;margin-left:6px}",Y=`--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
2
|
+
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --ink-2: rgba(255,255,255,.70);
|
|
3
|
+
--online: oklch(72% 0.13 163.23);`;function qe(n){return n==="light"?"":n==="dark"?`:host { ${Y} }`:`@media (prefers-color-scheme: dark) {
|
|
4
|
+
:host {
|
|
5
|
+
${Y}
|
|
6
|
+
}
|
|
7
|
+
}`}function J(n,e="system"){let t=I(n),r=n.launcherPosition==="bottom_left"?"left":"right",a=n.accentColor;return `${`
|
|
2
8
|
:host {
|
|
3
|
-
|
|
9
|
+
/* The widget sits above the host page's own furniture. The reset above sends
|
|
10
|
+
z-index back to auto, so without this the launcher and panel stack at the
|
|
11
|
+
document floor and anything the page raises (a cookie bar, a dev chip)
|
|
12
|
+
draws over them: the WebMCP chip covered the launcher on clepit's landing.
|
|
13
|
+
Below the 32-bit ceiling so a host can still put something over us
|
|
14
|
+
deliberately. */
|
|
15
|
+
all: initial; z-index: 2147483000; --a: ${a};
|
|
4
16
|
--paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
|
|
5
|
-
--fill: #f1f5f9; --hairline: #e2e8f0; --
|
|
17
|
+
--fill: #f1f5f9; --hairline: #e2e8f0; --ink-2: rgba(0,0,0,.72);
|
|
6
18
|
--online: oklch(53.8% 0.1274 163.23);
|
|
7
|
-
color-scheme: light dark;
|
|
8
|
-
}
|
|
9
|
-
@media (prefers-color-scheme: dark) {
|
|
10
|
-
:host {
|
|
11
|
-
--paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
|
|
12
|
-
--fill: rgba(255,255,255,.06); --hairline: rgba(255,255,255,.13); --field: rgba(255,255,255,.22); --ink-2: rgba(255,255,255,.70);
|
|
13
|
-
--online: oklch(72% 0.13 163.23);
|
|
14
|
-
}
|
|
19
|
+
color-scheme: ${e==="system"?"light dark":e};
|
|
15
20
|
}
|
|
21
|
+
${qe(e)}
|
|
16
22
|
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
17
23
|
.launcher {
|
|
18
|
-
position: fixed; ${
|
|
24
|
+
z-index: 2147483000; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY}px; width: 56px; height: 56px;
|
|
19
25
|
border-radius: 28px; border: none; cursor: pointer;
|
|
20
26
|
display: inline-flex; align-items: center; justify-content: center;
|
|
21
|
-
background: ${
|
|
27
|
+
background: ${a}; color: #fff; font-size: 24px;
|
|
22
28
|
box-shadow: 0 4px 12px rgba(0,0,0,.2);
|
|
23
29
|
}
|
|
24
30
|
.launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
|
|
31
|
+
/* A BACKGROUND change, never a position change. Nothing else in the fleet
|
|
32
|
+
moves under the pointer: .button[data-variant] and .iconButton all hover by
|
|
33
|
+
background alone. This used to lift by translateY(-1px), which made the one
|
|
34
|
+
control a visitor is meant to click the only element in the product that
|
|
35
|
+
shifted when pointed at. */
|
|
36
|
+
.launcher { transition: background-color 120ms ease; }
|
|
37
|
+
.launcher:hover { background: color-mix(in srgb, #000 12%, ${a}); }
|
|
38
|
+
.launcher:active { background: color-mix(in srgb, #000 20%, ${a}); }
|
|
39
|
+
@media (prefers-reduced-motion: reduce) {
|
|
40
|
+
.launcher { transition: none; }
|
|
41
|
+
}
|
|
25
42
|
.badge {
|
|
26
43
|
position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
|
|
27
44
|
border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
|
|
28
45
|
display: flex; align-items: center; justify-content: center; padding: 0 4px;
|
|
29
46
|
}
|
|
47
|
+
/* renderBadge hides this with the hidden attribute, which is UA display:none
|
|
48
|
+
and is beaten by ANY author display. The rule above is one, so the badge
|
|
49
|
+
rendered for every visitor with no unread messages: an empty red circle on
|
|
50
|
+
the launcher, in production, for as long as it has shipped. The hiding code
|
|
51
|
+
read as if it worked, which is why nothing caught it. Keep this rule beside
|
|
52
|
+
the one that needs it. */
|
|
53
|
+
.badge[hidden] { display: none; }
|
|
30
54
|
.panel {
|
|
31
|
-
position: fixed; ${
|
|
55
|
+
z-index: 2147483001; position: fixed; ${r}: ${n.launcherOffsetX}px; bottom: ${n.launcherOffsetY+68}px; width: 360px; max-width: calc(100vw - 40px);
|
|
32
56
|
height: 520px; max-height: calc(100vh - 120px); background: var(--paper); color: var(--ink);
|
|
33
57
|
border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
|
|
34
58
|
display: flex; flex-direction: column; overflow: hidden;
|
|
35
59
|
}
|
|
36
|
-
.header { padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
|
|
60
|
+
.header { position: relative; padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
|
|
37
61
|
.header h2 { margin: 0; font-size: 15px; }
|
|
38
|
-
|
|
39
|
-
.
|
|
62
|
+
/* Sized from the Configure tab's own head: 36px faces overlapping by 12, the
|
|
63
|
+
status line 12.5px at 80% under the title. The ring is the header's own
|
|
64
|
+
ground so overlapping faces separate from it and from each other. */
|
|
65
|
+
.header .faces { display: flex; }
|
|
66
|
+
.header .av { width: 36px; height: 36px; box-shadow: 0 0 0 2px var(--a); }
|
|
67
|
+
.header .av + .av { margin-left: -12px; }
|
|
68
|
+
.headmain { display: flex; flex-direction: column; }
|
|
69
|
+
.header .status { display: flex; align-items: center; gap: 6px; margin: 5px 0 0; font-size: 12.5px; color: rgb(255 255 255 / 80%); }
|
|
70
|
+
/* The dot's ring is the PAPER, not the accent. An accent ring on the standard
|
|
71
|
+
skin is the header's own background and draws nothing, which is how this
|
|
72
|
+
shipped looking ringless beside a preview that had one. The faces above keep
|
|
73
|
+
the accent ring, which is a different job: separating two overlapping discs
|
|
74
|
+
from each other and from the header. */
|
|
75
|
+
.header .status .live { flex: none; width: 10px; height: 10px; border-radius: 50%; background: var(--online); box-shadow: 0 0 0 2px var(--paper); }
|
|
76
|
+
/* Hours, the same fact the launcher's dot carries. A green dot and a sentence
|
|
77
|
+
promising a reply in minutes are both claims about somebody being there, so
|
|
78
|
+
outside the project's hours neither is drawn: the away message in the thread
|
|
79
|
+
is what speaks then. */
|
|
80
|
+
.panel.closed .status { display: none; }
|
|
81
|
+
/* Pinned rather than laid out: the standard skin turns this header into a
|
|
82
|
+
column so the title can carry a line under it, and a close button that is
|
|
83
|
+
merely a flex sibling then stacks BELOW the title on the left, which is where
|
|
84
|
+
clepit's landing showed it. */
|
|
85
|
+
.header .close { position: absolute; top: 8px; right: 8px; }
|
|
86
|
+
/* The fleet's icon button: a padded square, a radius, and a hover that tints
|
|
87
|
+
the background. This carried none of them, so the messenger's close was the
|
|
88
|
+
one icon button in the product with no radius and no hover at all. The tint
|
|
89
|
+
is mixed from currentColor rather than a fixed white because the header is
|
|
90
|
+
the accent on some skins and the paper on others. */
|
|
91
|
+
.close {
|
|
92
|
+
display: inline-flex; align-items: center; justify-content: center;
|
|
93
|
+
width: 32px; height: 32px; padding: 0;
|
|
94
|
+
background: none; border: none; border-radius: 8px;
|
|
95
|
+
color: inherit; cursor: pointer; font-size: 18px; line-height: 1;
|
|
96
|
+
transition: background-color 120ms ease;
|
|
97
|
+
}
|
|
98
|
+
.close:hover { background: color-mix(in srgb, currentColor 14%, transparent); }
|
|
99
|
+
.close:focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
|
|
40
100
|
.log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
|
41
101
|
.turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
|
|
42
|
-
.turn.end_user { align-self: flex-end; background: ${
|
|
102
|
+
.turn.end_user { align-self: flex-end; background: ${a}; color: #fff; }
|
|
43
103
|
.turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
|
|
44
104
|
.author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
|
|
45
105
|
.away { background: var(--fill); border: 1px solid var(--hairline); border-radius: 8px; padding: 8px 12px; font-size: 13.5px; color: var(--ink-2); }
|
|
@@ -51,18 +111,21 @@
|
|
|
51
111
|
font-family: inherit; font-size: 13.5px; font-weight: 500; color: var(--ink);
|
|
52
112
|
background: none; border: 1px solid var(--hairline); border-radius: 8px; cursor: pointer;
|
|
53
113
|
}
|
|
54
|
-
.prompt:focus-visible { outline: 2px solid ${
|
|
114
|
+
.prompt:focus-visible { outline: 2px solid ${a}; outline-offset: 2px; }
|
|
55
115
|
.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: #7c3f3f; }
|
|
56
116
|
.av.bot { border-radius: 9px; background: var(--fill); color: var(--ink); }
|
|
117
|
+
.av img { width: 100%; height: 100%; display: block; object-fit: cover; border-radius: inherit; }
|
|
57
118
|
.composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid var(--hairline); }
|
|
58
|
-
.composer input { flex: 1; padding:
|
|
59
|
-
.composer input:focus-visible { outline: 2px solid ${
|
|
60
|
-
.composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${
|
|
119
|
+
.composer input { flex: 1; min-width: 0; height: 44px; padding: 0 12px; border: 0; border-radius: 8px; font-size: 14px; background: var(--fill); color: var(--ink); }
|
|
120
|
+
.composer input:focus-visible { outline: 2px solid ${a}; }
|
|
121
|
+
.composer button { display: inline-flex; align-items: center; justify-content: center; gap: 0; min-width: 64px; height: 44px; padding: 0 16px; background: ${a}; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-family: inherit; font-size: 14.5px; font-weight: 550; }
|
|
122
|
+
.composer button:hover { background: color-mix(in srgb, #000 12%, ${a}); }
|
|
123
|
+
.composer button:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
|
|
61
124
|
.composer button .sendglyph { display: none; width: 19px; height: 19px; }
|
|
62
125
|
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
63
126
|
@media (prefers-reduced-motion: no-preference) {
|
|
64
127
|
.panel { animation: rise 180ms ease-out; }
|
|
65
128
|
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
66
129
|
}
|
|
67
|
-
`}${Se[e.skin]}${$(e.launcherShape,e.launcherFill,e.launcherContent,e.launcherSize)}${ke[e.bubbleStyle]}${Ce[e.namePlacement]}${e.nameAvatar?Ee:""}${e.dayDividers?Te:""}${we[e.stampPlacement]}${e.stampContent==="time_and_latency"?Ae:""}`}var Pe=["end_user","agent","ai"];function _e(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var T=class{constructor(e,t,r={},i={}){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,"lastFocused",null);u(this,"unread",0);this.strings={...ve,...r},this.appearance={..._,...i},this.settings=P({..._,...i}),this.root=e.attachShadow({mode:"closed"});let a=document.createElement("style");if(a.textContent=Le({..._,...i}),this.root.append(a),this.launcher=document.createElement("button"),this.launcher.className="launcher",this.launcher.type="button",this.launcher.setAttribute("aria-haspopup","dialog"),this.launcher.setAttribute("aria-label",this.strings.launcherLabel),this.launcher.append(z(this.settings.launcherContent,this.strings,this.appearance.teamFaces)),this.settings.launcherShape==="pill"){let o=document.createElement("span");o.className="label",o.textContent=this.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(o);}this.launcher.addEventListener("click",()=>this.toggle()),this.badge=document.createElement("span"),this.badge.className="badge",this.badge.hidden=true,this.launcher.append(this.badge),this.root.append(this.launcher);}toggle(){this.panel?this.close():this.open();}async open(){if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className="panel",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("h2");r.textContent=this.strings.title;let i=document.createElement("button");i.className="close",i.type="button",i.setAttribute("aria-label",this.strings.closeLabel),i.textContent="\xD7",i.addEventListener("click",()=>this.close()),t.append(r,i);let a=document.createElement("div");a.className="log",a.setAttribute("role","log"),a.setAttribute("aria-live","polite"),a.setAttribute("aria-label",this.strings.title);let o=document.createElement("form");o.className="composer";let s=document.createElement("input");s.type="text",s.setAttribute("aria-label",this.strings.inputPlaceholder),s.placeholder=this.strings.inputPlaceholder;let l=document.createElement("button");l.type="submit",l.setAttribute("aria-label",this.strings.sendLabel),l.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 c=document.createElement("span");c.className="sendtext",c.textContent=this.strings.sendLabel,l.append(c),o.append(s,l),o.addEventListener("submit",p=>{p.preventDefault(),this.submit(s,a);}),e.append(t,a,o),e.addEventListener("keydown",p=>this.onKeydown(p,e,i)),this.root.append(e),this.panel=e,s.focus();let d=await this.client.load();d&&d.turns.length>0?this.renderThread(a,d):this.renderFirstRun(a,s),!F(this.appearance.availability,new Date)&&this.appearance.awayMessage.trim()&&this.renderAway(a);}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;let a=document.createElement("p");a.textContent=this.strings.emptyBody,r.append(i,a);for(let o of this.appearance.starterPrompts){let s=document.createElement("button");s.className="prompt",s.type="button",s.textContent=o,s.addEventListener("click",()=>{t.value=o,this.submit(t,e);}),r.append(s);}e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){var a;let r=e.value.trim();if(!r)return;e.value="",(a=t.querySelector(".empty"))==null||a.remove();let i=await this.client.send(r,_e());i&&this.appendTurn(t,i);}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){var d;(d=e.querySelector(".empty"))==null||d.remove();let r=Pe.includes(t.authorKind)?t.authorKind:"agent",i=this.settings,a=document.createElement("div");if(a.className=`turn ${r}`,r!=="end_user"&&i.nameAvatar){let p=document.createElement("span");p.className=r==="ai"?"av bot":"av",p.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel.slice(0,2).toUpperCase(),p.setAttribute("aria-hidden","true"),a.append(p);}let s=document.createElement("div");if(s.className="body",r!=="end_user"&&i.namePlacement!=="hidden"||r==="ai"&&i.namePlacement==="hidden"){let p=document.createElement("div");p.className=r==="ai"?"author ai":"author",p.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel,i.stampPlacement==="beside_name"&&p.append(this.stamp(t)),s.append(p);}let c=document.createElement("div");c.textContent=t.body,s.append(c),i.stampPlacement==="under_turn"&&s.append(this.stamp(t)),a.append(s),e.append(a),e.scrollTop=e.scrollHeight;}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, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let a=i[0],o=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function K(n){return `40${JSON.stringify(n)}`}function D(){return "3"}function U(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=N(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),i=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=N(i);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let a=N(i);return !Array.isArray(a)||typeof a[0]!="string"?{kind:"other"}:{kind:"event",name:a[0],payload:a[1]}}function N(n){try{return JSON.parse(n)}catch(e){return null}}var Ne="/socket.io/?EIO=4&transport=websocket",w=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:Ie,this.setTimer=(r=e.setTimer)!=null?r:((a,o)=>setTimeout(a,o)),this.clearTimer=(i=e.clearTimer)!=null?i:(a=>clearTimeout(a));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ne}`,t;try{t=this.factory(e);}catch(r){this.options.onClosed(false);return}this.socket=t,t.onmessage=r=>this.receive(String(r.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat();let e=this.socket;this.socket=null,e==null||e.close();}receive(e){var r,i,a,o;let t=U(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(K(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(D());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(a=this.socket)==null||a.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ie(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}function G(n){var y,v;let e=globalThis.document;if(!e)throw new Error("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 E(n),i=new T(t,r,n.strings,n.appearance),a=new Set,o,s=null,l=(v=n.pollIntervalMs)!=null?v:15e3,c=m=>{a.has(m.id)||m.authorKind==="end_user"||(a.add(m.id),i.onIncomingTurn(m));},d=async()=>{if(!r.hasThread)return;let m=await r.load();if(m){for(let g of m.turns)c(g);a=new Set(m.turns.map(g=>g.id));}},p=()=>{o||l<=0||(o=setInterval(()=>void d(),l));},f=()=>{o&&clearInterval(o),o=void 0;},h=()=>{if(s||!n.socketHost)return;let m=r.socketAuth;m&&(s=new w({auth:m,host:n.socketHost,onClosed:g=>{s=null,p(),g&&h();},onReady:f,onTurn:c,socketFactory:n.socketFactory}),s.open());};return p(),h(),{close:()=>i.close(),destroy:()=>{f(),s==null||s.close(),s=null,i.close(),t.remove();},identify:m=>r.identify(m),open:()=>{i.open().then(h);}}}var I="prodantix.messenger.config";function B(n,e){let t=n==null?void 0:n.get(I);if(!t)return null;try{let r=JSON.parse(t);return (r==null?void 0:r.apiKey)===e?r.config:null}catch(r){return null}}async function q(n){var i,a,o,s,l;let e=k(n.fetchImpl);if(!e)return (i=n.onError)==null||i.call(n,new Error("no fetch available for the prodantix messenger")),null;let t=C(n.host),r=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let c=await e(`${t}/v1/messenger/config${r}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!c.ok)return (a=n.onError)==null||a.call(n,new Error(`prodantix messenger config: ${c.status}`)),null;let d=JSON.parse(await c.text());return d.enabled?((s=n.storage)==null||s.set(I,JSON.stringify({apiKey:n.apiKey,config:d})),d):((o=n.storage)==null||o.remove(I),d)}catch(c){return (l=n.onError)==null||l.call(n,c),null}}var Me=["close","identify","open","shutdown","toggle"],S="[prodantix/messenger]";function He(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!Me.includes(r)||e(r,...i);}}function Fe(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function j(n,e={}){var f,h,y,v,m;let t=(f=e.warn)!=null?f:(g=>console.warn(g)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${S} no project key on the install snippet; nothing will load.`),null;let a=Fe((h=e.scriptSrc)!=null?h:Oe(n));if(!a)return t(`${S} could not tell which host served this script; nothing will load.`),null;let o=Re(n),s=B(o,i),l=await q({apiKey:i,host:a,locale:((v=(y=n.document)==null?void 0:y.documentElement)==null?void 0:v.lang)||void 0,onError:g=>t(`${S} settings could not be read: ${String(g)}`),storage:o}),c=l!=null?l:s;if(!c)return t(`${S} no settings available; the messenger will not render.`),null;if(!c.enabled)return null;let d=G({apiKey:i,appearance:c,distinctId:ze(n,o),host:a,socketHost:c.socketUrl||void 0}),p=(g,...A)=>{if((g==="open"||g==="toggle")&&d.open(),g==="close"&&d.close(),g==="shutdown"&&d.destroy(),g==="identify"){let M=$e(A[0]);if(!M){console.error(`${S} 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 He((m=r==null?void 0:r.q)!=null?m:[],p),n.prodantix=Object.assign((g,...A)=>p(g,...A),{k:i,q:[]}),d}function Oe(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function Re(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 $e(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 W="prodantix.messenger.anon";function ze(n,e){var i,a,o;let t=e==null?void 0:e.get(W);if(t)return t;let r=`anon_${(o=(a=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:a.call(i))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(W,r),r}j(globalThis);})();//# sourceMappingURL=messenger.iife.js.map
|
|
130
|
+
`}${Re[t.composerShape]}${Oe[t.skin]}${q(t.launcherShape,t.launcherFill,t.launcherContent,t.launcherSize)}${$e[t.bubbleShape]}${ze[t.bubbleFill]}${Ue[t.namePlacement]}${t.nameAvatar?Ke:""}${t.dayDividers?Be:""}${De[t.stampPlacement]}${t.stampContent==="time_and_latency"?Ge:""}`}var We=["end_user","agent","ai"];function je(){let n=globalThis.location;if(n)return {host:n.host,path:n.pathname,title:document.title}}var M=class{constructor(e,t,r={},a={},i={}){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,"lastFocused",null);u(this,"unread",0);u(this,"openNow");u(this,"style");u(this,"scheme");var o;this.strings={...He,...r},this.appearance={...T,...a},this.settings=I({...T,...a}),this.root=e.attachShadow({mode:(o=i.shadowMode)!=null?o:"closed"}),this.openNow=_(this.appearance.availability,new Date),this.scheme=i.scheme,this.style=document.createElement("style"),this.style.textContent=J(this.appearance,this.scheme),this.root.append(this.style),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(W(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.settings.launcherContent==="team_faces"?this.strings.agentLabel:this.strings.launcherLabel,this.launcher.append(e);}this.launcher.append(this.badge),this.launcher.classList.toggle("closed",!this.openNow);}update(e,t){this.appearance={...T,...e},this.settings=I(this.appearance),t!==void 0&&(this.scheme=t),this.style.textContent=J(this.appearance,this.scheme),this.drawLauncher(),this.panel&&(this.close(),this.open());}toggle(){this.panel?this.close():this.open();}setOpenNow(e){var t;this.openNow=e,this.launcher.classList.toggle("closed",!e),(t=this.panel)==null||t.classList.toggle("closed",!e);}async open(){var v;if(this.panel)return;this.lastFocused=this.host.ownerDocument.activeElement,this.unread=0,this.renderBadge();let e=document.createElement("section");e.className=this.openNow?"panel":"panel closed",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-label",this.strings.title);let t=document.createElement("div");t.className="header";let r=(v=this.appearance.team)!=null?v:[];r.length>0&&t.append(R(r,this.strings,b=>this.client.avatarUrl(b)));let a=document.createElement("div");a.className="headmain";let i=document.createElement("h2");i.textContent=this.strings.title;let o=document.createElement("p");o.className="status";let s=document.createElement("span");s.className="live",s.setAttribute("aria-hidden","true"),o.append(s,this.strings.replyTime),a.append(i,o);let p=document.createElement("button");p.className="close",p.type="button",p.setAttribute("aria-label",this.strings.closeLabel),p.textContent="\xD7",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 h=document.createElement("button");h.type="submit",h.setAttribute("aria-label",this.strings.sendLabel),h.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 g=document.createElement("span");g.className="sendtext",g.textContent=this.strings.sendLabel,h.append(g),d.append(c,h),d.addEventListener("submit",b=>{b.preventDefault(),this.submit(c,l);}),e.append(t,l,d),e.addEventListener("keydown",b=>this.onKeydown(b,e,p)),this.root.append(e),this.panel=e,c.focus();let x=await this.client.load();x&&x.turns.length>0?this.renderThread(l,x):this.renderFirstRun(l,c),this.openNow||this.renderAway(l);}renderFirstRun(e,t){let r=document.createElement("div");r.className="empty";let a=document.createElement("h3");a.textContent=this.appearance.greeting.trim()||this.strings.emptyTitle;let i=document.createElement("p");i.textContent=this.strings.emptyBody,r.append(a,i);for(let o of this.appearance.starterPrompts){let s=document.createElement("button");s.className="prompt",s.type="button",s.textContent=o,s.addEventListener("click",()=>{t.value=o,this.submit(t,e);}),r.append(s);}e.replaceChildren(r);}renderAway(e){let t=document.createElement("div");t.className="away",t.textContent=this.appearance.awayMessage.trim()||this.strings.awayBody,e.prepend(t);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(e){if(this.panel){let t=this.panel.querySelector(".log");t instanceof HTMLElement&&this.appendTurn(t,e);return}e.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(e,t){var i;let r=e.value.trim();if(!r)return;e.value="",(i=t.querySelector(".empty"))==null||i.remove();let a=await this.client.send(r,je());a&&this.appendTurn(t,a);}renderThread(e,t){e.replaceChildren();for(let r of t.turns)this.appendTurn(e,r);}appendTurn(e,t){var d;(d=e.querySelector(".empty"))==null||d.remove();let r=We.includes(t.authorKind)?t.authorKind:"agent",a=this.settings,i=document.createElement("div");if(i.className=`turn ${r}`,r!=="end_user"&&a.nameAvatar){let c=document.createElement("span");if(c.className=r==="ai"?"av bot":"av",c.setAttribute("aria-hidden","true"),r==="agent"&&t.authorAvatarUrl){let h=document.createElement("img");h.alt="",h.src=this.client.avatarUrl(t.authorAvatarUrl),c.append(h);}else c.textContent=r==="ai"?this.strings.aiLabel:G(this.agentName(t));i.append(c);}let s=document.createElement("div");s.className="body";let p=r!=="end_user"&&a.namePlacement!=="hidden",l=document.createElement("div");if(l.textContent=t.body,p||r==="ai"&&a.namePlacement==="hidden"){let c=document.createElement("div");c.className=r==="ai"?"author ai":"author",c.textContent=r==="ai"?this.strings.aiLabel:this.agentName(t),a.stampPlacement==="beside_name"&&c.append(this.stamp(t)),a.namePlacement==="inline"?(c.classList.add("below"),s.append(l,c)):s.append(c,l);}else s.append(l);a.stampPlacement==="under_turn"&&s.append(this.stamp(t)),i.append(s),e.append(i),e.scrollTop=e.scrollHeight;}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 a=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(a.length===0)return;let i=a[0],o=a[a.length-1],s=this.root.activeElement;e.shiftKey&&s===i?(e.preventDefault(),o.focus()):!e.shiftKey&&s===o?(e.preventDefault(),i.focus()):s===null&&(e.preventDefault(),r.focus());}renderBadge(){this.unread>0?(this.badge.hidden=false,this.badge.textContent=String(this.unread),this.launcher.setAttribute("aria-label",`${this.strings.launcherLabel}, ${this.strings.unreadLabel(this.unread)}`)):(this.badge.hidden=true,this.badge.textContent="",this.launcher.setAttribute("aria-label",this.strings.launcherLabel));}};function X(n){return `40${JSON.stringify(n)}`}function V(){return "3"}function Q(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let o=$(t);return {kind:"open",pingInterval:typeof(o==null?void 0:o.pingInterval)=="number"?o.pingInterval:25e3,pingTimeout:typeof(o==null?void 0:o.pingTimeout)=="number"?o.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let r=t.charAt(0),a=t.slice(1);if(r==="0")return {kind:"connected"};if(r==="1")return {kind:"disconnect"};if(r==="4"){let o=$(a);return {kind:"connectError",message:typeof(o==null?void 0:o.message)=="string"?o.message:"refused"}}if(r!=="2")return {kind:"other"};let i=$(a);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function $(n){try{return JSON.parse(n)}catch(e){return null}}var Ye="/socket.io/?EIO=4&transport=websocket",F=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,a;this.factory=(t=e.socketFactory)!=null?t:Je,this.setTimer=(r=e.setTimer)!=null?r:((i,o)=>setTimeout(i,o)),this.clearTimer=(a=e.clearTimer)!=null?a:(i=>clearTimeout(i));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ye}`,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,a,i,o;let t=Q(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(X(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(a=this.socket)==null||a.send(V());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(i=this.socket)==null||i.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(o=t.payload)==null?void 0:o.turn;s&&this.options.onTurn(s);}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>{var t;return (t=this.socket)==null?void 0:t.close()},this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Je(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var Xe=6e4;function Z(n){var m,C,k,w;let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=(m=n.mountPoint)!=null?m:e.createElement("div");n.mountPoint||e.body.append(t);let r=new P(n),a=new M(t,r,n.strings,n.appearance),i=(k=(C=n.appearance)==null?void 0:C.availability)!=null?k:T.availability,o,s=()=>{a.setOpenNow(_(i,new Date)),o=setTimeout(s,Xe);};s();let p=new Set,l,d=null,c=(w=n.pollIntervalMs)!=null?w:15e3,h=f=>{p.has(f.id)||f.authorKind==="end_user"||(p.add(f.id),a.onIncomingTurn(f));},g=async()=>{if(!r.hasThread)return;let f=await r.load();if(f){for(let E of f.turns)h(E);p=new Set(f.turns.map(E=>E.id));}},x=()=>{l||c<=0||(l=setInterval(()=>void g(),c));},v=()=>{l&&clearInterval(l),l=void 0;},b=()=>{if(d||!n.socketHost)return;let f=r.socketAuth;f&&(d=new F({auth:f,host:n.socketHost,onClosed:E=>{d=null,x(),E&&b();},onReady:v,onTurn:h,socketFactory:n.socketFactory}),d.open());};return x(),b(),{close:()=>a.close(),destroy:()=>{v(),clearTimeout(o),d==null||d.close(),d=null,a.close(),t.remove();},identify:f=>r.identify(f),open:()=>{a.open().then(b);}}}var z="prodantix.messenger.config";function ee(n,e){let t=n==null?void 0:n.get(z);if(!t)return null;try{let r=JSON.parse(t);return (r==null?void 0:r.apiKey)===e?r.config:null}catch(r){return null}}async function te(n){var a,i,o,s,p;let e=L(n.fetchImpl);if(!e)return (a=n.onError)==null||a.call(n,new Error("no fetch available for the prodantix messenger")),null;let t=N(n.host),r=n.locale?`?locale=${encodeURIComponent(n.locale)}`:"";try{let l=await e(`${t}/v1/messenger/config${r}`,{headers:{authorization:`Bearer ${n.apiKey}`},method:"GET"});if(!l.ok)return (i=n.onError)==null||i.call(n,new Error(`prodantix messenger config: ${l.status}`)),null;let d=JSON.parse(await l.text());return d.enabled?((s=n.storage)==null||s.set(z,JSON.stringify({apiKey:n.apiKey,config:d})),d):((o=n.storage)==null||o.remove(z),d)}catch(l){return (p=n.onError)==null||p.call(n,l),null}}var Ve=["close","identify","open","shutdown","toggle"],A="[prodantix/messenger]";function Qe(n,e){for(let t of n){let[r,...a]=t!=null?t:[];typeof r!="string"||!Ve.includes(r)||e(r,...a);}}function Ze(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function re(n,e={}){var h,g,x,v,b;let t=(h=e.warn)!=null?h:(m=>console.warn(m)),r=n.prodantix,a=r==null?void 0:r.k;if(!a)return t(`${A} no project key on the install snippet; nothing will load.`),null;let i=Ze((g=e.scriptSrc)!=null?g:et(n));if(!i)return t(`${A} could not tell which host served this script; nothing will load.`),null;let o=tt(n),s=ee(o,a),p=await te({apiKey:a,host:i,locale:((v=(x=n.document)==null?void 0:x.documentElement)==null?void 0:v.lang)||void 0,onError:m=>t(`${A} settings could not be read: ${String(m)}`),storage:o}),l=p!=null?p:s;if(!l)return t(`${A} no settings available; the messenger will not render.`),null;if(!l.enabled)return null;let d=Z({apiKey:a,appearance:l,distinctId:rt(n,o),host:i,socketHost:l.socketUrl||void 0}),c=(m,...C)=>{if((m==="open"||m==="toggle")&&d.open(),m==="close"&&d.close(),m==="shutdown"&&d.destroy(),m==="identify"){let k=nt(C[0]);if(!k){console.error(`${A} identify needs { userId, userHash }: the hash is HMAC-SHA256 of the user id under the project signing secret, computed on your server. Without it the visitor stays anonymous.`);return}d.identify(k);}};return Qe((b=r==null?void 0:r.q)!=null?b:[],c),n.prodantix=Object.assign((m,...C)=>c(m,...C),{k:a,q:[]}),d}function et(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function tt(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 nt(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 ne="prodantix.messenger.anon";function rt(n,e){var a,i,o;let t=e==null?void 0:e.get(ne);if(t)return t;let r=`anon_${(o=(i=(a=n.crypto)==null?void 0:a.randomUUID)==null?void 0:i.call(a))!=null?o:Math.random().toString(36).slice(2)}`;return e==null||e.set(ne,r),r}re(globalThis);})();//# sourceMappingURL=messenger.iife.js.map
|
|
68
131
|
//# sourceMappingURL=messenger.iife.js.map
|
package/dist/node.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var pe=Object.defineProperty;var fe=(n,e,t)=>e in n?pe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>fe(n,typeof e!="symbol"?e+"":e,t);var u=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},g=class extends u{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends u{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function m(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function l(){let n=globalThis.AbortController;return n?new n:void 0}var D=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var V={now:()=>new Date};function k(n){return n.toISOString()}function ge(){return globalThis.crypto}function me(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 ye(){let n=ge();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 me(e)}var j={uuid:ye};var ve=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ke=/^(?:\$|[a-z])[a-z0-9_.]*$/;function b(n){let e=0;for(let t of n)e+=1;return e}function G(n){return ve.test(n)}function be(n){return ke.test(n)}function J(n){let e=b(n);if(e<1||e>200)throw new g("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=b(n);if(e<1||e>200)throw new g("event_name","event_name must be between 1 and 200 characters");if(!be(n))throw new g("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var H="prodantix-js",z="0.0.1";var xe=n=>{};function Q(n){if(!n.apiKey||!G(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties,s=n.storage??new v;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??V,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??j,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:P(n.apiKey),onError:n.onError??xe,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??H,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function P(n){return n.slice(0,16)}function B(n,e,t){U(n.eventName),J(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:k(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var f=Symbol("absent");function Se(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:f}function p(n){return n===f?"undefined":String(n)}function W(n){return n===f?Number.NaN:Number(n)}function X(n){return n!==f&&n!==null&&n!==""}function Y(n,e){if(!Array.isArray(e))return false;let t=p(n);return e.map(s=>String(s)).includes(t)}function Z(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(t);case "eq":return p(t)===p(s===void 0?f:s);case "neq":return p(t)!==p(s===void 0?f:s);case "contains":return p(t).includes(p(s===void 0?f:s));case "in":return Y(t,s);case "not_in":return Array.isArray(s)?!Y(t,s):false;case "gt":return x(t,s,(r,i)=>r>i);case "gte":return x(t,s,(r,i)=>r>=i);case "lt":return x(t,s,(r,i)=>r<i);case "lte":return x(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function x(n,e,t){let s=W(n),r=e===void 0?Number.NaN:W(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function ee(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function R(n,e){return n.targeting.length===0||n.targeting.every(t=>Z(t,e))}function te(n,e){let t=ee(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function N(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=N(i,e,t,s)&&R(i,t)&&te(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?N(n,e,t,[n.key])?R(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ee(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 ne(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function $(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!N(n,e,t,[n.key])||!R(n,t))return r;let i=te(n,t);return s.find(a=>a.key===i)??r}function se(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function re(n){return `40${JSON.stringify(n)}`}function ie(){return "3"}function oe(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=O(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=O(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=O(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function O(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",Ee=250,I=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Ce,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=oe(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(re({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(ie());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ee));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ce(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var E=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=l(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function M(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function q(n,e){return `pdx.${n}.${e}`}var ae="consent";function L(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function Fe(n,e){return L(n.getItem(q(e,ae)))}function we(n,e,t){let s=q(e,ae);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=M(this.shared.getItem(this.key("anonymous_id"))),t=M(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=M(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return Fe(this.shared,this.namespace)}setConsent(e){we(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return q(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var w=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 Te={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function _e(n){return `pdx.${n}.session`}var T=class{constructor(e,t,s,r,i=Te){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return _e(this.namespace)}};function ce(n){return n>=400&&n<500&&n!==429}var _=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=m(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??D,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(ce(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&ce(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Ae="queue",Pe=1e3,de=3e4,K=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},A=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new C(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new T(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new w(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new _({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new E({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=B({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...K(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=K(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture("$group",{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture("$set",{properties:s});}setPersonTraits(e){let t=K(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?$(r,s.flags,i):null,d=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return ne(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?$(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&se(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<de?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<de)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new I({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Pe);try{await this.transport.send({body:{events:e,sent_at:k(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}.${Ae}`}};var Re=200;function le(){return globalThis.process}function Ne(n){le()?.on("beforeExit",()=>{n.flush();});}function zt(n){let e=le(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new A(t);return Ne(s),s}function Qt(n,e){let t=P(e),s=$e(n,`pdx_${t}`);if(s===void 0)return null;let r=Oe(s);if(r===void 0)return null;let i=ue(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:L(r[`pdx.${t}.consent`]),sessionId:Me(r[`pdx.${t}.session`])}}function $e(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Oe(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function ue(n){if(typeof n!="string")return;let e=b(n);return e>=1&&e<=Re?n:void 0}function Me(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:ue(e.id)??null}catch{return null}}exports.createNodeClient=zt;exports.readSharedIdentity=Qt;//# sourceMappingURL=node.cjs.map
|
|
1
|
+
'use strict';var fe=Object.defineProperty;var ge=(n,e,t)=>e in n?fe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>ge(n,typeof e!="symbol"?e+"":e,t);var p=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},v=class extends p{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends p{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends p{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function y(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function u(){let n=globalThis.AbortController;return n?new n:void 0}var V=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var k=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var j={now:()=>new Date};function b(n){return n.toISOString()}function me(){return globalThis.crypto}function ye(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ve(){let n=me();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return ye(e)}var G={uuid:ve};var ke=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var be=/^(?:\$|[a-z])[a-z0-9_.]*$/;function x(n){let e=0;for(let t of n)e+=1;return e}function J(n){return ke.test(n)}function xe(n){return be.test(n)}function H(n){let e=x(n);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=x(n);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!xe(n))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var B="prodantix-js",z="0.0.1";var Ee=n=>{};function Q(n){if(!n.apiKey||!J(n.apiKey))throw new v("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new v("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties,s=n.storage??new k;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??j,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??G,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:$(n.apiKey),onError:n.onError??Ee,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??B,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function $(n){return n.slice(0,16)}function W(n,e,t){U(n.eventName),H(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:b(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function Se(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:g}function f(n){return n===g?"undefined":String(n)}function Y(n){return n===g?Number.NaN:Number(n)}function X(n){return n!==g&&n!==null&&n!==""}function Z(n,e){if(!Array.isArray(e))return false;let t=f(n);return e.map(s=>String(s)).includes(t)}function ee(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(t);case "eq":return f(t)===f(s===void 0?g:s);case "neq":return f(t)!==f(s===void 0?g:s);case "contains":return f(t).includes(f(s===void 0?g:s));case "in":return Z(t,s);case "not_in":return Array.isArray(s)?!Z(t,s):false;case "gt":return E(t,s,(r,i)=>r>i);case "gte":return E(t,s,(r,i)=>r>=i);case "lt":return E(t,s,(r,i)=>r<i);case "lte":return E(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function E(n,e,t){let s=Y(n),r=e===void 0?Number.NaN:Y(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function te(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function N(n,e){return n.targeting.length===0||n.targeting.every(t=>ee(t,e))}function ne(n,e){let t=te(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function R(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(l=>l.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=R(i,e,t,s)&&N(i,t)&&ne(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?R(n,e,t,[n.key])?N(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:te(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function se(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function O(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!R(n,e,t,[n.key])||!N(n,t))return r;let i=ne(n,t);return s.find(a=>a.key===i)??r}function re(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ie(n){return `40${JSON.stringify(n)}`}function oe(){return "3"}function ae(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=M(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=M(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=M(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function M(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",we=250,I=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Ce,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=ae(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ie({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(oe());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},we));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ce(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var w=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let l=JSON.parse(await a.text());return {flags:l.flags??{},variants:l.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=u(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),l={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(l.socketUrl=a.socketUrl),l}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function q(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function L(n,e){return `pdx.${n}.${e}`}var ce="consent";function K(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function Fe(n,e){return K(n.getItem(L(e,ce)))}function Te(n,e,t){let s=L(e,ce);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=q(this.shared.getItem(this.key("anonymous_id"))),t=q(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=q(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return Fe(this.shared,this.namespace)}setConsent(e){Te(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return L(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var T=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var _e={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function Ae(n){return `pdx.${n}.session`}var _=class{constructor(e,t,s,r,i=_e){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return Ae(this.namespace)}};var d={createAlias:"$create_alias",featureFlagCalled:"$feature_flag_called",group:"$group",identify:"$identify",set:"$set"};function de(n){return n>=400&&n<500&&n!==429}var A=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=y(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??V,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(de(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&de(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=u(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Pe="queue",$e=1e3,le=3e4,D=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},P=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new C(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new _(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new T(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new p("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new A({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new w({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=W({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...D(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=D(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture(d.identify,{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture(d.createAlias,{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture(d.group,{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture(d.set,{properties:s});}setPersonTraits(e){let t=D(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 s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?O(r,s.flags,i):null,l=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(l)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture(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 se(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(l=>l.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?O(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&re(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<le?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<le)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new I({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain($e);try{await this.transport.send({body:{events:e,sent_at:b(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Pe}`}};var Ne=200;function ue(){return globalThis.process}function Re(n){ue()?.on("beforeExit",()=>{n.flush();});}function Yt(n){let e=ue(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new P(t);return Re(s),s}function Xt(n,e){let t=$(e),s=Oe(n,`pdx_${t}`);if(s===void 0)return null;let r=Me(s);if(r===void 0)return null;let i=pe(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:K(r[`pdx.${t}.consent`]),sessionId:qe(r[`pdx.${t}.session`])}}function Oe(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Me(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function pe(n){if(typeof n!="string")return;let e=x(n);return e>=1&&e<=Ne?n:void 0}function qe(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:pe(e.id)??null}catch{return null}}exports.createNodeClient=Yt;exports.readSharedIdentity=Xt;//# sourceMappingURL=node.cjs.map
|
|
2
2
|
//# sourceMappingURL=node.cjs.map
|
package/dist/node.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {C,l as l$1,t,i}from'./chunk-ESOQKMEE.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.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 C(e);return p(r),r}function w(t$1,n){let e=l$1(n),r=m(t$1,`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:t(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=i(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
|