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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,11 @@ interface ChatStorage {
29
29
  set(key: string, value: string): void;
30
30
  remove(key: string): void;
31
31
  }
32
+ interface PageContext {
33
+ host: string;
34
+ path: string;
35
+ title: string;
36
+ }
32
37
  declare class ChatClient {
33
38
  private readonly options;
34
39
  private readonly fetchImpl?;
@@ -45,26 +50,51 @@ declare class ChatClient {
45
50
  } | null;
46
51
  identify(identity: ChatIdentity): void;
47
52
  ensureThread(subject?: string): Promise<boolean>;
48
- send(body: string): Promise<ChatTurn | null>;
53
+ send(body: string, pageContext?: PageContext): Promise<ChatTurn | null>;
49
54
  load(): Promise<ChatThread | null>;
50
55
  private readHandle;
51
56
  private request;
52
57
  }
53
58
 
54
59
  type MessengerSkin = 'concierge' | 'console' | 'quiet';
55
- type LauncherStyle = 'avatar_circle' | 'circle_filled' | 'circle_outlined' | 'pill_labelled' | 'pill_team' | 'squircle_filled';
56
60
  type BubbleStyle = 'hairline' | 'outlined' | 'rounded' | 'tailed';
57
- type NamePlacement = 'above' | 'avatar_only' | 'gutter' | 'hidden' | 'inline';
58
- type TimestampStyle = 'cluster' | 'latency' | 'none' | 'trailing' | 'with_name';
61
+ type LauncherShape = 'circle' | 'pill' | 'squircle';
62
+ type LauncherFill = 'filled' | 'outlined';
63
+ type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
64
+ type LauncherSize = 'large' | 'medium' | 'small';
65
+ type NamePlacement = 'above' | 'hidden' | 'inline';
66
+ type StampPlacement = 'beside_name' | 'none' | 'under_turn';
67
+ type StampContent = 'time' | 'time_and_latency';
59
68
  interface AppearanceSettings {
60
69
  bubbleStyle: BubbleStyle;
61
- launcherStyle: LauncherStyle;
70
+ dayDividers: boolean;
71
+ launcherContent: LauncherContent;
72
+ launcherFill: LauncherFill;
73
+ launcherShape: LauncherShape;
74
+ launcherSize: LauncherSize;
75
+ nameAvatar: boolean;
62
76
  namePlacement: NamePlacement;
63
77
  skin: MessengerSkin;
64
- timestampStyle: TimestampStyle;
78
+ stampContent: StampContent;
79
+ stampPlacement: StampPlacement;
65
80
  }
66
81
  declare const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings;
67
- declare function resolveAppearance(config: Partial<AppearanceSettings> | null | undefined): AppearanceSettings;
82
+ declare function resolveAppearance(config: unknown): AppearanceSettings;
83
+
84
+ type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
85
+ type Availability = {
86
+ timezone: string;
87
+ windows: readonly {
88
+ close: string;
89
+ days: readonly Weekday[];
90
+ open: string;
91
+ }[];
92
+ };
93
+
94
+ interface TeamFace {
95
+ initials: string;
96
+ tone: string;
97
+ }
68
98
 
69
99
  interface MessengerConfig extends AppearanceSettings {
70
100
  enabled: boolean;
@@ -74,9 +104,10 @@ interface MessengerConfig extends AppearanceSettings {
74
104
  accentColor: string;
75
105
  greeting: string;
76
106
  awayMessage: string;
77
- availability: unknown;
107
+ availability: Availability;
78
108
  version: string;
79
109
  starterPrompts: string[];
110
+ teamFaces: TeamFace[];
80
111
  socketUrl: string;
81
112
  }
82
113
  interface MessengerConfigOptions {
@@ -91,4 +122,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
91
122
  declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
92
123
  declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
93
124
 
94
- export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherStyle as L, type MessengerConfig as M, type NamePlacement as N, type TimestampStyle as T, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type MessengerSkin as f, MESSENGER_CACHE_KEY as g, type MessengerConfigOptions as h, cachedMessengerConfig as i, fetchMessengerConfig as j, resolveAppearance as r };
125
+ export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type LauncherFill as f, type LauncherShape as g, type LauncherSize as h, type MessengerSkin as i, type StampPlacement as j, MESSENGER_CACHE_KEY as k, type MessengerConfigOptions as l, cachedMessengerConfig as m, fetchMessengerConfig as n, resolveAppearance as r };
@@ -29,6 +29,11 @@ interface ChatStorage {
29
29
  set(key: string, value: string): void;
30
30
  remove(key: string): void;
31
31
  }
32
+ interface PageContext {
33
+ host: string;
34
+ path: string;
35
+ title: string;
36
+ }
32
37
  declare class ChatClient {
33
38
  private readonly options;
34
39
  private readonly fetchImpl?;
@@ -45,26 +50,51 @@ declare class ChatClient {
45
50
  } | null;
46
51
  identify(identity: ChatIdentity): void;
47
52
  ensureThread(subject?: string): Promise<boolean>;
48
- send(body: string): Promise<ChatTurn | null>;
53
+ send(body: string, pageContext?: PageContext): Promise<ChatTurn | null>;
49
54
  load(): Promise<ChatThread | null>;
50
55
  private readHandle;
51
56
  private request;
52
57
  }
53
58
 
54
59
  type MessengerSkin = 'concierge' | 'console' | 'quiet';
55
- type LauncherStyle = 'avatar_circle' | 'circle_filled' | 'circle_outlined' | 'pill_labelled' | 'pill_team' | 'squircle_filled';
56
60
  type BubbleStyle = 'hairline' | 'outlined' | 'rounded' | 'tailed';
57
- type NamePlacement = 'above' | 'avatar_only' | 'gutter' | 'hidden' | 'inline';
58
- type TimestampStyle = 'cluster' | 'latency' | 'none' | 'trailing' | 'with_name';
61
+ type LauncherShape = 'circle' | 'pill' | 'squircle';
62
+ type LauncherFill = 'filled' | 'outlined';
63
+ type LauncherContent = 'avatar' | 'glyph' | 'team_faces';
64
+ type LauncherSize = 'large' | 'medium' | 'small';
65
+ type NamePlacement = 'above' | 'hidden' | 'inline';
66
+ type StampPlacement = 'beside_name' | 'none' | 'under_turn';
67
+ type StampContent = 'time' | 'time_and_latency';
59
68
  interface AppearanceSettings {
60
69
  bubbleStyle: BubbleStyle;
61
- launcherStyle: LauncherStyle;
70
+ dayDividers: boolean;
71
+ launcherContent: LauncherContent;
72
+ launcherFill: LauncherFill;
73
+ launcherShape: LauncherShape;
74
+ launcherSize: LauncherSize;
75
+ nameAvatar: boolean;
62
76
  namePlacement: NamePlacement;
63
77
  skin: MessengerSkin;
64
- timestampStyle: TimestampStyle;
78
+ stampContent: StampContent;
79
+ stampPlacement: StampPlacement;
65
80
  }
66
81
  declare const DEFAULT_APPEARANCE_SETTINGS: AppearanceSettings;
67
- declare function resolveAppearance(config: Partial<AppearanceSettings> | null | undefined): AppearanceSettings;
82
+ declare function resolveAppearance(config: unknown): AppearanceSettings;
83
+
84
+ type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
85
+ type Availability = {
86
+ timezone: string;
87
+ windows: readonly {
88
+ close: string;
89
+ days: readonly Weekday[];
90
+ open: string;
91
+ }[];
92
+ };
93
+
94
+ interface TeamFace {
95
+ initials: string;
96
+ tone: string;
97
+ }
68
98
 
69
99
  interface MessengerConfig extends AppearanceSettings {
70
100
  enabled: boolean;
@@ -74,9 +104,10 @@ interface MessengerConfig extends AppearanceSettings {
74
104
  accentColor: string;
75
105
  greeting: string;
76
106
  awayMessage: string;
77
- availability: unknown;
107
+ availability: Availability;
78
108
  version: string;
79
109
  starterPrompts: string[];
110
+ teamFaces: TeamFace[];
80
111
  socketUrl: string;
81
112
  }
82
113
  interface MessengerConfigOptions {
@@ -91,4 +122,4 @@ declare const MESSENGER_CACHE_KEY = "prodantix.messenger.config";
91
122
  declare function cachedMessengerConfig(storage: ChatStorage | undefined, apiKey: string): MessengerConfig | null;
92
123
  declare function fetchMessengerConfig(options: MessengerConfigOptions): Promise<MessengerConfig | null>;
93
124
 
94
- export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherStyle as L, type MessengerConfig as M, type NamePlacement as N, type TimestampStyle as T, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type MessengerSkin as f, MESSENGER_CACHE_KEY as g, type MessengerConfigOptions as h, cachedMessengerConfig as i, fetchMessengerConfig as j, resolveAppearance as r };
125
+ export { type AppearanceSettings as A, type BubbleStyle as B, ChatClient as C, DEFAULT_APPEARANCE_SETTINGS as D, type LauncherContent as L, type MessengerConfig as M, type NamePlacement as N, type StampContent as S, type ChatTurn as a, type ChatIdentity as b, type ChatClientOptions as c, type ChatStorage as d, type ChatThread as e, type LauncherFill as f, type LauncherShape as g, type LauncherSize as h, type MessengerSkin as i, type StampPlacement as j, MESSENGER_CACHE_KEY as k, type MessengerConfigOptions as l, cachedMessengerConfig as m, fetchMessengerConfig as n, resolveAppearance as r };
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var ie=Object.defineProperty;var oe=(t,e,r)=>e in t?ie(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var o=(t,e,r)=>oe(t,typeof e!="symbol"?e+"":e,r);var u=class extends Error{constructor(r,n,s){super(n,s);o(this,"code");this.code=r,this.name="ProdantixError";}},m=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},p=class extends u{constructor(r,n){super("validation",n);o(this,"field");this.field=r,this.name="ValidationError";}},l=class extends u{constructor(r,n,s){super("transport",r,s);o(this,"status");this.status=n,this.name="TransportError";}};function y(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function d(){let t=globalThis.AbortController;return t?new t:void 0}var K=t=>new Promise(e=>{setTimeout(e,t);});function h(t){return t.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,r){this.store.set(e,r);}};var D={now:()=>new Date};function I(t){return t.toISOString()}function ae(){return globalThis.crypto}function le(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let r=0;r<16;r+=1)e.push(t[r].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 ce(){let t=ae();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let r=0;r<16;r+=1)e[r]=Math.floor(Math.random()*256);return le(e)}var L={uuid:ce};var ue=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var de=/^(?:\$|[a-z])[a-z0-9_.]*$/;function V(t){let e=0;for(let r of t)e+=1;return e}function j(t){return ue.test(t)}function pe(t){return de.test(t)}function G(t){let e=V(t);if(e<1||e>200)throw new p("distinct_id","distinct_id must be between 1 and 200 characters")}function U(t){let e=V(t);if(e<1||e>200)throw new p("event_name","event_name must be between 1 and 200 characters");if(!pe(t))throw new p("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var P="prodantix-js",R="0.0.1";var he=t=>{};function z(t){if(!t.apiKey||!j(t.apiKey))throw new m("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new m("host is required (the ingest base URL)");let e=h(t.host),r=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??D,defaultProperties:typeof r=="function"?r:()=>r??{},flagsHost:t.flagsHost?h(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??L,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??he,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??P,sdkVersion:t.sdkVersion??R,socketFactory:t.socketFactory,storage:t.storage??new v,streamFlags:t.streamFlags??false,transport:t.transport}}function H(t,e,r){U(t.eventName),G(t.distinctId);let n={distinct_id:t.distinctId,event_id:t.eventId??r.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:I(t.timestamp??e.now())};return t.context&&(n.context=t.context),t.sessionId&&(n.session_id=t.sessionId),n}var g=Symbol("absent");function fe(t,e){if(t==="distinct_id")return e.distinctId;let r=e.properties??{};if(Object.prototype.hasOwnProperty.call(r,t))return r[t];let n=e.attributes??{};return Object.prototype.hasOwnProperty.call(n,t)?n[t]:g}function f(t){return t===g?"undefined":String(t)}function J(t){return t===g?Number.NaN:Number(t)}function B(t){return t!==g&&t!==null&&t!==""}function Q(t,e){if(!Array.isArray(e))return false;let r=f(t);return e.map(n=>String(n)).includes(r)}function N(t,e){let r=fe(t.attribute,e),n=t.value;switch(t.op){case "is_set":return B(r);case "is_not_set":return !B(r);case "eq":return f(r)===f(n===void 0?g:n);case "neq":return f(r)!==f(n===void 0?g:n);case "contains":return f(r).includes(f(n===void 0?g:n));case "in":return Q(r,n);case "not_in":return Array.isArray(n)?!Q(r,n):false;case "gt":return S(r,n,(s,i)=>s>i);case "gte":return S(r,n,(s,i)=>s>=i);case "lt":return S(r,n,(s,i)=>s<i);case "lte":return S(r,n,(s,i)=>s<=i);case "in_cohort":return typeof n=="string"&&n!==""&&(e.cohorts??[]).includes(n);case "not_in_cohort":return typeof n=="string"&&n!==""&&!(e.cohorts??[]).includes(n);default:return false}}function S(t,e,r){let n=J(t),s=e===void 0?Number.NaN:J(e);return Number.isNaN(n)||Number.isNaN(s)?false:r(n,s)}function $(t,e){let r=`${t}:${e}`,n=2166136261;for(let s=0;s<r.length;s++)n^=r.charCodeAt(s),n=Math.imul(n,16777619);return (n>>>0)%100}function A(t,e){return t.targeting.length===0||t.targeting.every(r=>N(r,e))}function W(t,e){let r=$(t.key,e.distinctId),n=t.variations??[];if(n.length===0)return t.rolloutPercentage>=100||r<t.rolloutPercentage?"true":"false";let s=0;for(let i=n.length-1;i>=0;i--)if(s+=n[i].weight,r<s)return n[i].key;return n[0].key}function O(t,e,r,n){for(let s of t.prerequisites??[]){if(n.includes(s.flagKey))return false;let i=e.find(c=>c.key===s.flagKey);if(!i||!i.enabled)return false;n.push(i.key);let a=O(i,e,r,n)&&A(i,r)&&W(i,r)===s.variationKey;if(n.pop(),!a)return false}return true}function b(t,e,r){return t.enabled?O(t,e,r,[t.key])?A(t,r)?t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:$(t.key,r.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function ge(t,e){return b(t,[],e)}function M(t,e){let r={};for(let n of t)r[n.key]=b(n,t,e).enabled;return r}function k(t,e,r){let n=t.variations??[],s=n[0];if(!s)return null;if(!t.enabled||!O(t,e,r,[t.key])||!A(t,r))return s;let i=W(t,r);return n.find(a=>a.key===i)??s}function me(t,e){return k(t,[],e)}function ye(t,e,r){let n=t.find(s=>s.key===e);return n?k(n,t,r)?.value??null:null}function X(t){return t.some(e=>e.targeting.some(r=>r.op==="in_cohort"||r.op==="not_in_cohort"))}function Y(t){return `40${JSON.stringify(t)}`}function Z(){return "3"}function ee(t){let e=t.charAt(0),r=t.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=q(r);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 n=r.charAt(0),s=r.slice(1);if(n==="0")return {kind:"connected"};if(n==="1")return {kind:"disconnect"};if(n==="4"){let a=q(s);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(n!=="2")return {kind:"other"};let i=q(s);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function q(t){try{return JSON.parse(t)}catch{return null}}var ve="/socket.io/?EIO=4&transport=websocket",be=250,C=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??ke,this.setTimer=e.setTimer??((r,n)=>setTimeout(r,n)),this.clearTimer=e.clearTimer??(r=>clearTimeout(r));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${ve}`,r;try{r=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=r,r.onmessage=n=>this.receive(String(n.data)),r.onerror=()=>r.close(),r.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 r=ee(e);if(r.kind==="open"){this.armHeartbeat(r.pingInterval+r.pingTimeout),this.socket?.send(Y({projectKey:this.options.projectKey}));return}if(r.kind==="ping"){this.armHeartbeat(),this.socket?.send(Z());return}if(r.kind==="connectError"||r.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(r.kind==="event"){if(r.name==="ready"){this.ready=true;return}if(r.name==="flagChange"){let n=r.payload?.key;this.lastKey=typeof n=="string"?n:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},be));}}}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 ke(t){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(t)}var x=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 r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,s=d(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await r(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);let c=JSON.parse(await a.text());return {flags:c.flags??{},variants:c.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags/snapshot`,n=d(),s=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let i=await e(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!i.ok)throw new l(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),c={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(c.socketUrl=a.socketUrl),c}finally{s!==void 0&&clearTimeout(s);}}async memberships(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let n=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,s=d(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let a=await r(n,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!a.ok)throw new l(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};var T=class{constructor(e,r,n){this.storage=e;this.ids=r;this.namespace=n;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");let s=e.getItem(this.key("anonymous_id"));s?this.anonymousId=s:(this.anonymousId=r.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let i=e.getItem(this.key("distinct_id"));i?(this.distinctId=i,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}identify(e){return this.identified&&this.distinctId===e?{changed:false}:(this.distinctId=e,this.identified=true,this.storage.setItem(this.key("distinct_id"),e),{changed:true})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id"));}key(e){return `pdx.${this.namespace}.${e}`}};var E=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 r=this.requireFetch(),n=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,s=await this.request(r,n,{headers:this.authHeaders(),method:"GET"});if(!s.ok)throw new l(`inbox request failed with status ${s.status}`,s.status);return JSON.parse(await s.text()).messages??[]}async markRead(e,r){let n=this.requireFetch(),s=`${this.host}/v1/messages/read`,i=await this.request(n,s,{body:JSON.stringify({distinct_id:r,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new l(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new l("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,r,n){let s=d(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(r,{...n,signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var w=class{constructor(e,r){this.maxSize=e;this.onOverflow=r;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 r=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,r)}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});}};function te(t){return t>=400&&t<500&&t!==429}var F=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??K,this.random=e.random??Math.random;}async send(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let n=JSON.stringify(e.body),s;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(r,e,n);if(a.ok)return;if(te(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);s=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&te(a.status))throw a;s=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new l("ingest delivery failed after retries",void 0,{cause:s})}async attempt(e,r,n){let s=d(),i=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{return await e(r.url,{body:n,headers:{authorization:`Bearer ${r.projectKey}`,"content-type":"application/json"},method:"POST",signal:s?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var xe="queue",Ee=1e3,re=3e4,ne=t=>{let e={};return t.avatar!==void 0&&(e.$avatar=t.avatar),t.email!==void 0&&(e.$email=t.email),t.name!==void 0&&(e.$name=t.name),t.phone!==void 0&&(e.$phone=t.phone),e},_=class{constructor(e){o(this,"config");o(this,"identity");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=z(e),this.identity=new T(this.config.storage,this.config.ids,this.config.namespace),this.queue=new w(this.config.maxQueueSize,({dropped:r})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${r.length} oldest event(s)`));}),this.transport=this.config.transport??new F({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new E({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}capture(e,r={}){try{let n={...this.config.defaultProperties(),...r.properties??{}},s=H({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:n,sessionId:r.sessionId,timestamp:r.timestamp},this.config.clock,this.config.ids);this.enqueue(s);}catch(n){this.config.onError(n);}}identify(e,r={}){let n=this.identity.getAnonymousId(),s=!this.identity.isIdentified(),i=this.identity.identify(e),a={};s&&i.changed&&(a.$anon_distinct_id=n);let c={...ne(r.traits??{}),...r.set??{}};Object.keys(c).length>0&&(a.$set=c),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,r,n){let s={$group_key:r,$group_type:e};n&&(s.$set=n),this.capture("$group",{properties:s});}setPersonProperties(e,r){let n={};e&&(n.$set=e),r&&(n.$set_once=r),this.capture("$set",{properties:n});}setPersonTraits(e){let r=ne(e);Object.keys(r).length!==0&&this.capture("$set",{properties:{$set:r}});}async getAllFlags(){let e=this.identity.getDistinctId(),r=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:r.flags,variants:r.variants??{}},r.flags}async isFeatureEnabled(e){let n=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(n)),n}async getVariant(e){let r=await this.getAllFlags(),n=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,n?.key??String(r[e]??false)),n}async getVariantLocal(e,r={}){let n=await this.flagSnapshot(),s=n.flags.find(se=>se.key===e),i=await this.localContext(r,n.flags),a=s?k(s,n.flags,i):null,c=s?b(s,n.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(c)),a?{key:a.key,value:a.value}:null}recordExposure(e,r){let n=`${this.identity.getDistinctId()} ${e} ${r}`;this.exposures.has(n)||(this.exposures.add(n),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:r}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let r=await this.flagSnapshot();return M(r.flags,await this.localContext(e,r.flags))}async isFeatureEnabledLocal(e,r={}){let n=await this.flagSnapshot(),s=n.flags.find(c=>c.key===e),i=await this.localContext(r,n.flags),a=s?b(s,n.flags,i).enabled:false;return this.recordExposure(e,(s?k(s,n.flags,i)?.key:void 0)??String(a)),a}async localContext(e,r){let n=this.identity.getDistinctId(),s=e.cohorts;if(s===void 0&&X(r)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===n&&i-this.membershipCache.fetchedAt<re?s=this.membershipCache.cohorts:(s=await this.flagsClient.memberships(n),this.membershipCache={cohorts:s,distinctId:n,fetchedAt:i});}return {attributes:e.attributes,cohorts:s,distinctId:n,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<re)return this.cachedSnapshot.snapshot;let r=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:r},this.maybeStream(r),r}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let r=new C({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(n=>this.config.onError(n));},onClosed:n=>{this.stream=void 0,n&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=r,r.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(Ee);try{await this.transport.send({body:{events:e,sent_at:I(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(r){this.queue.requeue(e),this.persistQueue(),this.config.onError(r);}finally{this.flushing=false;}}reset(){this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let r=JSON.parse(e);Array.isArray(r)&&this.queue.restore(r);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),r=e;typeof r.unref=="function"&&r.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${xe}`}};function Fe(t){return new _(t)}exports.ConfigError=m;exports.FetchTransport=F;exports.FlagsClient=x;exports.MemoryStorage=v;exports.MessagesClient=E;exports.ProdantixClient=_;exports.ProdantixError=u;exports.SDK_NAME=P;exports.SDK_VERSION=R;exports.TransportError=l;exports.ValidationError=p;exports.assignVariant=me;exports.bucket=$;exports.createClient=Fe;exports.evaluateAll=M;exports.evaluateFlag=ge;exports.getVariant=ye;exports.matches=N;//# sourceMappingURL=index.cjs.map
1
+ 'use strict';var le=Object.defineProperty;var de=(n,e,t)=>e in n?le(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>de(n,typeof e!="symbol"?e+"":e,t);var d=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},m=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},h=class extends d{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends d{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 j=n=>new Promise(e=>{setTimeout(e,n);});function p(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 G={now:()=>new Date};function I(n){return n.toISOString()}function ue(){return globalThis.crypto}function he(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 pe(){let n=ue();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 he(e)}var J={uuid:pe};var fe=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ge=/^(?:\$|[a-z])[a-z0-9_.]*$/;function U(n){let e=0;for(let t of n)e+=1;return e}function H(n){return fe.test(n)}function me(n){return ge.test(n)}function z(n){let e=U(n);if(e<1||e>200)throw new h("distinct_id","distinct_id must be between 1 and 200 characters")}function B(n){let e=U(n);if(e<1||e>200)throw new h("event_name","event_name must be between 1 and 200 characters");if(!me(n))throw new h("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var P="prodantix-js",R="0.0.1";var ye=n=>{};function Q(n){if(!n.apiKey||!H(n.apiKey))throw new m("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new m("host is required (the ingest base URL)");let e=p(n.host),t=n.defaultProperties,s=n.storage??new v;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??G,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?p(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:ve(n.apiKey),onError:n.onError??ye,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??P,sdkVersion:n.sdkVersion??R,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function ve(n){return n.slice(0,16)}function W(n,e,t){B(n.eventName),z(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:I(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var g=Symbol("absent");function ke(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:g}function f(n){return n===g?"undefined":String(n)}function X(n){return n===g?Number.NaN:Number(n)}function Y(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 N(n,e){let t=ke(n.attribute,e),s=n.value;switch(n.op){case "is_set":return Y(t);case "is_not_set":return !Y(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 F(t,s,(r,i)=>r>i);case "gte":return F(t,s,(r,i)=>r>=i);case "lt":return F(t,s,(r,i)=>r<i);case "lte":return F(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 F(n,e,t){let s=X(n),r=e===void 0?Number.NaN:X(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function O(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 M(n,e){return n.targeting.length===0||n.targeting.every(t=>N(t,e))}function ee(n,e){let t=O(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,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=$(i,e,t,s)&&M(i,t)&&ee(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function k(n,e,t){return n.enabled?$(n,e,t,[n.key])?M(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:O(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 be(n,e){return k(n,[],e)}function q(n,e){let t={};for(let s of n)t[s.key]=k(s,n,e).enabled;return t}function b(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!$(n,e,t,[n.key])||!M(n,t))return r;let i=ee(n,t);return s.find(a=>a.key===i)??r}function xe(n,e){return b(n,[],e)}function Ee(n,e,t){let s=n.find(r=>r.key===e);return s?b(s,n,t)?.value??null:null}function te(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function ne(n){return `40${JSON.stringify(n)}`}function se(){return "3"}function re(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=K(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=K(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=K(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function K(n){try{return JSON.parse(n)}catch{return null}}var Se="/socket.io/?EIO=4&transport=websocket",Ie=250,C=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??Fe,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(/\/+$/,"")}${Se}`,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=re(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(ne({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(se());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);},Ie));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Fe(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var x=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=p(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new 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 L(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function D(n,e){return `pdx.${n}.${e}`}var ie="consent";function Ce(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 Te(n,e){return Ce(n.getItem(D(e,ie)))}function we(n,e,t){let s=D(e,ie);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var T=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=L(this.shared.getItem(this.key("anonymous_id"))),t=L(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=L(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 Te(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 D(this.namespace,e)}};var E=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=y(e.fetch),this.host=p(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 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 _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)}};function oe(n){return n>=400&&n<500&&n!==429}var S=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??j,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(oe(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&&oe(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",Re=1e3,ae=3e4,V=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 T(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new _(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 d("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new S({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new E({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={...V(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=V(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=V(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(ce=>ce.key===e),i=await this.localContext(t,s.flags),a=r?b(r,s.flags,i):null,l=r?k(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("$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 q(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?k(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?b(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&&te(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<ae?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<ae)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 C({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(Re);try{await this.transport.send({body:{events:e,sent_at:I(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}`}};function Ne(n){return new A(n)}exports.ConfigError=m;exports.FetchTransport=S;exports.FlagsClient=x;exports.MemoryStorage=v;exports.MessagesClient=E;exports.ProdantixClient=A;exports.ProdantixError=d;exports.SDK_NAME=P;exports.SDK_VERSION=R;exports.TransportError=c;exports.ValidationError=h;exports.assignVariant=xe;exports.bucket=O;exports.createClient=Ne;exports.evaluateAll=q;exports.evaluateFlag=be;exports.getVariant=Ee;exports.matches=N;//# sourceMappingURL=index.cjs.map
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
- export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-y1xyVF6C.cjs';
2
- import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-68Sc11g8.cjs';
3
- export { C as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, e as FlagVariant, f as IdFactory, g as InboxResponse, P as ProdantixConfig, T as Transport, h as TransportRequest } from './types-68Sc11g8.cjs';
1
+ export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-BO7f6q5k.cjs';
2
+ import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-DjMXp6Wg.cjs';
3
+ export { C as Clock, b as Consent, E as EventBatch, c as EventContext, d as EventEnvelope, e as EventProperties, f as FlagVariant, g as IdFactory, h as InboxResponse, P as ProdantixConfig, T as Transport, i as TransportRequest } from './types-DjMXp6Wg.cjs';
4
4
  import { F as FetchLike } from './http-BCh716Vs.cjs';
5
- export { F as FetchTransport } from './transport-Bj4nXmgt.cjs';
5
+ export { F as FetchTransport } from './transport-Cy42FY5A.cjs';
6
6
 
7
7
  type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
8
8
  declare class ProdantixError extends Error {
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-Ca6xJESF.js';
2
- import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-68Sc11g8.js';
3
- export { C as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, e as FlagVariant, f as IdFactory, g as InboxResponse, P as ProdantixConfig, T as Transport, h as TransportRequest } from './types-68Sc11g8.js';
1
+ export { C as CaptureOptions, I as IdentifyOptions, L as LocalFlagContext, P as ProdantixClient, c as createClient } from './client-BQlU_3Dc.js';
2
+ import { J as JsonValue, F as FlagsResponse, I as InboxMessage, a as StorageAdapter } from './types-DjMXp6Wg.js';
3
+ export { C as Clock, b as Consent, E as EventBatch, c as EventContext, d as EventEnvelope, e as EventProperties, f as FlagVariant, g as IdFactory, h as InboxResponse, P as ProdantixConfig, T as Transport, i as TransportRequest } from './types-DjMXp6Wg.js';
4
4
  import { F as FetchLike } from './http-BCh716Vs.js';
5
- export { F as FetchTransport } from './transport-CTPih3Jj.js';
5
+ export { F as FetchTransport } from './transport-CqAmRbpQ.js';
6
6
 
7
7
  type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
8
8
  declare class ProdantixError extends Error {
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as ConfigError,r as FetchTransport,p as FlagsClient,e as MemoryStorage,q as MessagesClient,s as ProdantixClient,a as ProdantixError,h as SDK_NAME,i as SDK_VERSION,d as TransportError,c as ValidationError,n as assignVariant,k as bucket,t as createClient,m as evaluateAll,l as evaluateFlag,o as getVariant,j as matches}from'./chunk-CSIP3PZ7.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
1
+ export{b as ConfigError,x as FetchTransport,s as FlagsClient,e as MemoryStorage,v as MessagesClient,y as ProdantixClient,a as ProdantixError,j as SDK_NAME,k as SDK_VERSION,d as TransportError,c as ValidationError,q as assignVariant,n as bucket,z as createClient,p as evaluateAll,o as evaluateFlag,r as getVariant,m as matches}from'./chunk-5CBVQAZ2.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- 'use strict';function a(e){if(e)return e;let r=globalThis.fetch;if(typeof r=="function")return r.bind(globalThis)}function c(e){return e.replace(/\/+$/,"")}var s="prodantix.messenger.config";function f(e,r){let n=e?.get(s);if(!n)return null;try{let o=JSON.parse(n);return o?.apiKey===r?o.config:null}catch{return null}}async function h(e){let r=a(e.fetchImpl);if(!r)return e.onError?.(new Error("no fetch available for the prodantix messenger")),null;let n=c(e.host),o=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let t=await r(`${n}/v1/messenger/config${o}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!t.ok)return e.onError?.(new Error(`prodantix messenger config: ${t.status}`)),null;let i=JSON.parse(await t.text());return i.enabled?(e.storage?.set(s,JSON.stringify({apiKey:e.apiKey,config:i})),i):(e.storage?.remove(s),i)}catch(t){return e.onError?.(t),null}}exports.MESSENGER_CACHE_KEY=s;exports.cachedMessengerConfig=f;exports.fetchMessengerConfig=h;//# sourceMappingURL=messenger.cjs.map
1
+ 'use strict';function s(e){if(e)return e;let r=globalThis.fetch;if(typeof r=="function")return r.bind(globalThis)}function c(e){return e.replace(/\/+$/,"")}var a="prodantix.messenger.config";function f(e,r){let n=e?.get(a);if(!n)return null;try{let o=JSON.parse(n);return o?.apiKey===r?o.config:null}catch{return null}}async function h(e){let r=s(e.fetchImpl);if(!r)return e.onError?.(new Error("no fetch available for the prodantix messenger")),null;let n=c(e.host),o=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let t=await r(`${n}/v1/messenger/config${o}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!t.ok)return e.onError?.(new Error(`prodantix messenger config: ${t.status}`)),null;let i=JSON.parse(await t.text());return i.enabled?(e.storage?.set(a,JSON.stringify({apiKey:e.apiKey,config:i})),i):(e.storage?.remove(a),i)}catch(t){return e.onError?.(t),null}}exports.MESSENGER_CACHE_KEY=a;exports.cachedMessengerConfig=f;exports.fetchMessengerConfig=h;//# sourceMappingURL=messenger.cjs.map
2
2
  //# sourceMappingURL=messenger.cjs.map
@@ -1,2 +1,2 @@
1
- export { g as MESSENGER_CACHE_KEY, M as MessengerConfig, h as MessengerConfigOptions, i as cachedMessengerConfig, j as fetchMessengerConfig } from './config-OP9Csae6.cjs';
1
+ export { k as MESSENGER_CACHE_KEY, M as MessengerConfig, l as MessengerConfigOptions, m as cachedMessengerConfig, n as fetchMessengerConfig } from './config-CWmtX8Gl.cjs';
2
2
  import './http-BCh716Vs.cjs';
@@ -1,2 +1,2 @@
1
- export { g as MESSENGER_CACHE_KEY, M as MessengerConfig, h as MessengerConfigOptions, i as cachedMessengerConfig, j as fetchMessengerConfig } from './config-B-cTz9n1.js';
1
+ export { k as MESSENGER_CACHE_KEY, M as MessengerConfig, l as MessengerConfigOptions, m as cachedMessengerConfig, n as fetchMessengerConfig } from './config-DDlHv52p.js';
2
2
  import './http-BCh716Vs.js';
@@ -1,14 +1,16 @@
1
- (function(){'use strict';var D=Object.defineProperty;var B=(n,e,t)=>e in n?D(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var l=(n,e,t)=>B(n,typeof e!="symbol"?e+"":e,t);function S(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function C(n){return n.replace(/\/+$/,"")}var U="X-Prodantix-Conversation-Token",N="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;l(this,"fetchImpl");l(this,"host");l(this,"storage");l(this,"handle");l(this,"identity",null);var t;this.fetchImpl=S(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,o;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},(o=this.storage)==null||o.set(N,JSON.stringify(this.handle)),true)}async send(e){var i;if(!await this.ensureThread())return null;let t=this.handle;if(!t)return null;let r=await this.request("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/turns`,{body:{body:e},token:t.token});return (i=r==null?void 0:r.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(N);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(N),null}async request(e,t,r={}){var a,s,u,c,d,p;let i=this.fetchImpl;if(!i)return (s=(a=this.options).onError)==null||s.call(a,new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(o[U]=r.token);try{let m=await i(`${this.host}${t}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:e}),f=await m.text();return m.ok?f?JSON.parse(f):{}:((c=(u=this.options).onError)==null||c.call(u,new Error(`prodantix chat ${t}: ${m.status}`)),null)}catch(m){return (p=(d=this.options).onError)==null||p.call(d,m),null}}};var b={bubbleStyle:"tailed",launcherStyle:"circle_outlined",namePlacement:"avatar_only",skin:"concierge",timestampStyle:"cluster"},j=["concierge","console","quiet"],W=["avatar_circle","circle_filled","circle_outlined","pill_labelled","pill_team","squircle_filled"],Y=["hairline","outlined","rounded","tailed"],J=["above","avatar_only","gutter","hidden","inline"],X=["cluster","latency","none","trailing","with_name"],v=(n,e,t)=>typeof n=="string"&&e.includes(n)?n:t;function I(n){let e={bubbleStyle:v(n==null?void 0:n.bubbleStyle,Y,b.bubbleStyle),launcherStyle:v(n==null?void 0:n.launcherStyle,W,b.launcherStyle),namePlacement:v(n==null?void 0:n.namePlacement,J,b.namePlacement),skin:v(n==null?void 0:n.skin,j,b.skin),timestampStyle:v(n==null?void 0:n.timestampStyle,X,b.timestampStyle)};return (e.namePlacement==="avatar_only"||e.namePlacement==="hidden")&&(e.timestampStyle==="with_name"||e.timestampStyle==="latency")&&(e.timestampStyle="trailing"),e.namePlacement==="inline"&&e.bubbleStyle==="hairline"&&(e.namePlacement="above"),e}var Q={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",greeting:"",launcherOffsetX:20,launcherOffsetY:20,launcherPosition:"bottom_right",starterPrompts:[],...b},V={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)}"},Z={avatar_circle:".launcher{width:60px;height:60px;border-radius:30px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2)}",circle_filled:".launcher{width:56px;height:56px;border-radius:28px;background:var(--a);color:#fff}",circle_outlined:".launcher{width:46px;height:46px;border-radius:23px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink-2);box-shadow:0 1px 2px rgba(0,0,0,.08);font-size:21px}.badge{background:var(--a);top:-7px;right:-7px;min-width:19px;height:19px;border-radius:10px;font-size:11.5px}",pill_labelled:".launcher{width:auto;height:52px;border-radius:26px;padding:0 22px;gap:10px;background:var(--a);color:#fff;font-size:14.5px;font-weight:600}",pill_team:".launcher{width:auto;height:54px;border-radius:27px;padding:0 20px 0 8px;gap:10px;background:var(--paper);border:1px solid var(--hairline);color:var(--ink);font-size:14px;font-weight:600}.badge{position:static;background:var(--a)}",squircle_filled:".launcher{width:56px;height:56px;border-radius:16px;background:var(--a);color:#fff}"},ee={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}"},te={above:"",avatar_only:".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}",gutter:".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}",hidden:".turn.agent .author,.turn.ai .author:not(.ai){display:none}",inline:".author{display:inline;margin-right:6px;font-weight:650}"},ne={cluster:'.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)}',latency:".stamp{font-size:11px;opacity:.7;margin-left:6px}.lat{font-size:11px;opacity:.7;margin-left:6px}",none:"",trailing:".stamp{display:block;font-size:11px;opacity:.7;margin-top:4px}.turn.end_user .stamp{text-align:right}",with_name:".stamp{font-size:11px;opacity:.7;margin-left:6px}"};function re(n){let e=I(n),t=n.launcherPosition==="bottom_left"?"left":"right",r=n.accentColor;return `${`
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 `${`
2
2
  :host {
3
3
  all: initial; --a: ${r};
4
4
  --paper: #fff; --ink: #0f172a; --ink-3: var(--ink-3);
5
5
  --fill: #f1f5f9; --hairline: #e2e8f0; --field: #cbd5e1; --ink-2: rgba(0,0,0,.72);
6
+ --online: oklch(53.8% 0.1274 163.23);
6
7
  color-scheme: light dark;
7
8
  }
8
9
  @media (prefers-color-scheme: dark) {
9
10
  :host {
10
11
  --paper: oklch(24.6% 0.015 257); --ink: #fff; --ink-3: rgba(255,255,255,.55);
11
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);
12
14
  }
13
15
  }
14
16
  * { box-sizing: border-box; font-family: system-ui, sans-serif; }
@@ -40,6 +42,7 @@
40
42
  .turn.end_user { align-self: flex-end; background: ${r}; color: #fff; }
41
43
  .turn.agent, .turn.ai { align-self: flex-start; background: var(--fill); color: var(--ink); }
42
44
  .author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
45
+ .away { background: var(--fill); border: 1px solid var(--hairline); border-radius: 8px; padding: 8px 12px; font-size: 13.5px; color: var(--ink-2); }
43
46
  .empty { display: flex; flex-direction: column; gap: 8px; padding: 20px 16px; }
44
47
  .empty h3 { margin: 0; font-size: 18px; font-weight: 640; letter-spacing: -.015em; }
45
48
  .empty p { margin: 0 0 8px; font-size: 13.5px; color: var(--ink-2); }
@@ -61,5 +64,5 @@
61
64
  .panel { animation: rise 180ms ease-out; }
62
65
  @keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
63
66
  }
64
- `}${V[e.skin]}${Z[e.launcherStyle]}${ee[e.bubbleStyle]}${te[e.namePlacement]}${ne[e.timestampStyle]}`}var ie=["end_user","agent","ai"],T=class{constructor(e,t,r={},i={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"settings");l(this,"appearance");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"lastFocused",null);l(this,"unread",0);this.strings={...Q,...r},this.appearance={..._,...i},this.settings=I({..._,...i}),this.root=e.attachShadow({mode:"closed"});let o=document.createElement("style");o.textContent=re({..._,...i}),this.root.append(o),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.textContent="\u{1F4AC}",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 o=document.createElement("div");o.className="log",o.setAttribute("role","log"),o.setAttribute("aria-live","polite"),o.setAttribute("aria-label",this.strings.title);let a=document.createElement("form");a.className="composer";let s=document.createElement("input");s.type="text",s.setAttribute("aria-label",this.strings.inputPlaceholder),s.placeholder=this.strings.inputPlaceholder;let u=document.createElement("button");u.type="submit",u.setAttribute("aria-label",this.strings.sendLabel),u.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,u.append(c),a.append(s,u),a.addEventListener("submit",p=>{p.preventDefault(),this.submit(s,o);}),e.append(t,o,a),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(o,d):this.renderFirstRun(o,s);}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 o=document.createElement("p");o.textContent=this.strings.emptyBody,r.append(i,o);for(let a of this.appearance.starterPrompts){let s=document.createElement("button");s.className="prompt",s.type="button",s.textContent=a,s.addEventListener("click",()=>{t.value=a,this.submit(t,e);}),r.append(s);}e.replaceChildren(r);}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 o;let r=e.value.trim();if(!r)return;e.value="",(o=t.querySelector(".empty"))==null||o.remove();let i=await this.client.send(r);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=ie.includes(t.authorKind)?t.authorKind:"agent",i=this.settings,o=document.createElement("div");if(o.className=`turn ${r}`,r!=="end_user"&&(i.namePlacement==="avatar_only"||i.namePlacement==="gutter")){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"),o.append(p);}let s=document.createElement("div");if(s.className="body",r!=="end_user"&&i.namePlacement!=="hidden"&&!(i.namePlacement==="avatar_only"&&r==="agent")||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.timestampStyle==="with_name"||i.timestampStyle==="latency")&&p.append(this.stamp(t)),s.append(p);}let c=document.createElement("div");c.textContent=t.body,s.append(c),i.timestampStyle==="trailing"&&s.append(this.stamp(t)),o.append(s),e.append(o),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 o=i[0],a=i[i.length-1],s=this.root.activeElement;e.shiftKey&&s===o?(e.preventDefault(),a.focus()):!e.shiftKey&&s===a?(e.preventDefault(),o.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 O(n){return `40${JSON.stringify(n)}`}function H(){return "3"}function $(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=P(t);return {kind:"open",pingInterval:typeof(a==null?void 0:a.pingInterval)=="number"?a.pingInterval:25e3,pingTimeout:typeof(a==null?void 0:a.pingTimeout)=="number"?a.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 a=P(i);return {kind:"connectError",message:typeof(a==null?void 0:a.message)=="string"?a.message:"refused"}}if(r!=="2")return {kind:"other"};let o=P(i);return !Array.isArray(o)||typeof o[0]!="string"?{kind:"other"}:{kind:"event",name:o[0],payload:o[1]}}function P(n){try{return JSON.parse(n)}catch(e){return null}}var oe="/socket.io/?EIO=4&transport=websocket",w=class{constructor(e){this.options=e;l(this,"socket",null);l(this,"heartbeat",null);l(this,"ready",false);l(this,"closed",false);l(this,"heartbeatWindow",45e3);l(this,"factory");l(this,"setTimer");l(this,"clearTimer");var t,r,i;this.factory=(t=e.socketFactory)!=null?t:ae,this.setTimer=(r=e.setTimer)!=null?r:((o,a)=>setTimeout(o,a)),this.clearTimer=(i=e.clearTimer)!=null?i:(o=>clearTimeout(o));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${oe}`,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,o,a;let t=$(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),(r=this.socket)==null||r.send(O(this.options.auth));return}if(t.kind==="ping"){this.armHeartbeat(),(i=this.socket)==null||i.send(H());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),(o=this.socket)==null||o.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true,this.options.onReady();return}if(t.name==="conversation.turn"){let s=(a=t.payload)==null?void 0:a.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 ae(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}function F(n){var x,y;let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=(x=n.mountPoint)!=null?x:e.createElement("div");n.mountPoint||e.body.append(t);let r=new E(n),i=new T(t,r,n.strings,n.appearance),o=new Set,a,s=null,u=(y=n.pollIntervalMs)!=null?y:15e3,c=g=>{o.has(g.id)||g.authorKind==="end_user"||(o.add(g.id),i.onIncomingTurn(g));},d=async()=>{if(!r.hasThread)return;let g=await r.load();if(g){for(let h of g.turns)c(h);o=new Set(g.turns.map(h=>h.id));}},p=()=>{a||u<=0||(a=setInterval(()=>void d(),u));},m=()=>{a&&clearInterval(a),a=void 0;},f=()=>{if(s||!n.socketHost)return;let g=r.socketAuth;g&&(s=new w({auth:g,host:n.socketHost,onClosed:h=>{s=null,p(),h&&f();},onReady:m,onTurn:c,socketFactory:n.socketFactory}),s.open());};return p(),f(),{close:()=>i.close(),destroy:()=>{m(),s==null||s.close(),s=null,i.close(),t.remove();},identify:g=>r.identify(g),open:()=>{i.open().then(f);}}}var L="prodantix.messenger.config";function R(n,e){let t=n==null?void 0:n.get(L);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 K(n){var i,o,a,s,u;let e=S(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 (o=n.onError)==null||o.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(L,JSON.stringify({apiKey:n.apiKey,config:d})),d):((a=n.storage)==null||a.remove(L),d)}catch(c){return (u=n.onError)==null||u.call(n,c),null}}var se=["close","identify","open","shutdown","toggle"],k="[prodantix/messenger]";function le(n,e){for(let t of n){let[r,...i]=t!=null?t:[];typeof r!="string"||!se.includes(r)||e(r,...i);}}function ce(n){if(!n)return null;try{return new URL(n).origin}catch(e){return null}}async function G(n,e={}){var m,f,x,y,g;let t=(m=e.warn)!=null?m:(h=>console.warn(h)),r=n.prodantix,i=r==null?void 0:r.k;if(!i)return t(`${k} no project key on the install snippet; nothing will load.`),null;let o=ce((f=e.scriptSrc)!=null?f:de(n));if(!o)return t(`${k} could not tell which host served this script; nothing will load.`),null;let a=pe(n),s=R(a,i),u=await K({apiKey:i,host:o,locale:((y=(x=n.document)==null?void 0:x.documentElement)==null?void 0:y.lang)||void 0,onError:h=>t(`${k} settings could not be read: ${String(h)}`),storage:a}),c=u!=null?u:s;if(!c)return t(`${k} no settings available; the messenger will not render.`),null;if(!c.enabled)return null;let d=F({apiKey:i,appearance:c,distinctId:he(n,a),host:o,socketHost:c.socketUrl||void 0}),p=(h,...A)=>{if((h==="open"||h==="toggle")&&d.open(),h==="close"&&d.close(),h==="shutdown"&&d.destroy(),h==="identify"){let M=ue(A[0]);if(!M){console.error(`${k} 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 le((g=r==null?void 0:r.q)!=null?g:[],p),n.prodantix=Object.assign((h,...A)=>p(h,...A),{k:i,q:[]}),d}function de(n){var t;let e=(t=n.document)==null?void 0:t.currentScript;return e==null?void 0:e.src}function pe(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 ue(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 z="prodantix.messenger.anon";function he(n,e){var i,o,a;let t=e==null?void 0:e.get(z);if(t)return t;let r=`anon_${(a=(o=(i=n.crypto)==null?void 0:i.randomUUID)==null?void 0:o.call(i))!=null?a:Math.random().toString(36).slice(2)}`;return e==null||e.set(z,r),r}G(globalThis);})();//# sourceMappingURL=messenger.iife.js.map
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
65
68
  //# sourceMappingURL=messenger.iife.js.map
package/dist/messenger.js CHANGED
@@ -1,2 +1,2 @@
1
- import {a,d}from'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';var s="prodantix.messenger.config";function l(e,n){let t=e?.get(s);if(!t)return null;try{let a=JSON.parse(t);return a?.apiKey===n?a.config:null}catch{return null}}async function f(e){let n=a(e.fetchImpl);if(!n)return e.onError?.(new Error("no fetch available for the prodantix messenger")),null;let t=d(e.host),a$1=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let r=await n(`${t}/v1/messenger/config${a$1}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!r.ok)return e.onError?.(new Error(`prodantix messenger config: ${r.status}`)),null;let o=JSON.parse(await r.text());return o.enabled?(e.storage?.set(s,JSON.stringify({apiKey:e.apiKey,config:o})),o):(e.storage?.remove(s),o)}catch(r){return e.onError?.(r),null}}export{s as MESSENGER_CACHE_KEY,l as cachedMessengerConfig,f as fetchMessengerConfig};//# sourceMappingURL=messenger.js.map
1
+ import {a,d}from'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';var i="prodantix.messenger.config";function l(e,t){let n=e?.get(i);if(!n)return null;try{let a=JSON.parse(n);return a?.apiKey===t?a.config:null}catch{return null}}async function f(e){let t=a(e.fetchImpl);if(!t)return e.onError?.(new Error("no fetch available for the prodantix messenger")),null;let n=d(e.host),a$1=e.locale?`?locale=${encodeURIComponent(e.locale)}`:"";try{let r=await t(`${n}/v1/messenger/config${a$1}`,{headers:{authorization:`Bearer ${e.apiKey}`},method:"GET"});if(!r.ok)return e.onError?.(new Error(`prodantix messenger config: ${r.status}`)),null;let o=JSON.parse(await r.text());return o.enabled?(e.storage?.set(i,JSON.stringify({apiKey:e.apiKey,config:o})),o):(e.storage?.remove(i),o)}catch(r){return e.onError?.(r),null}}export{i as MESSENGER_CACHE_KEY,l as cachedMessengerConfig,f as fetchMessengerConfig};//# sourceMappingURL=messenger.js.map
2
2
  //# sourceMappingURL=messenger.js.map