@prodantix/sdk 0.1.0 → 0.2.0-beta.358
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +36 -3
- package/dist/chat.cjs +5 -2
- package/dist/chat.d.cts +5 -15
- package/dist/chat.d.ts +5 -15
- package/dist/chat.js +7 -4
- package/dist/chunk-5CBVQAZ2.js +2 -0
- package/dist/chunk-V77KYPOF.js +2 -0
- package/dist/client-BO7f6q5k.d.cts +134 -0
- package/dist/client-BQlU_3Dc.d.ts +134 -0
- package/dist/{config-OP9Csae6.d.cts → config-CWmtX8Gl.d.cts} +40 -9
- package/dist/{config-B-cTz9n1.d.ts → config-DDlHv52p.d.ts} +40 -9
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +17 -5
- package/dist/index.d.ts +17 -5
- package/dist/index.js +1 -1
- package/dist/messenger.cjs +1 -1
- package/dist/messenger.d.cts +1 -1
- package/dist/messenger.d.ts +1 -1
- package/dist/messenger.iife.js +5 -2
- package/dist/messenger.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.d.cts +18 -2
- package/dist/node.d.ts +18 -2
- package/dist/node.js +1 -1
- package/dist/{transport-dWp3NUMj.d.ts → transport-CqAmRbpQ.d.ts} +1 -1
- package/dist/{transport-DhhzvwpV.d.cts → transport-Cy42FY5A.d.cts} +1 -1
- package/dist/types-DjMXp6Wg.d.cts +118 -0
- package/dist/types-DjMXp6Wg.d.ts +118 -0
- package/dist/web.cjs +1 -1
- package/dist/web.d.cts +60 -3
- package/dist/web.d.ts +60 -3
- package/dist/web.js +1 -1
- package/package.json +13 -13
- package/dist/chunk-7J6AQICL.js +0 -2
- package/dist/client-BBUAoQg2.d.cts +0 -160
- package/dist/client-BBUAoQg2.d.ts +0 -160
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
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';
|
|
3
4
|
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
4
|
-
export { F as FetchTransport } from './transport-
|
|
5
|
+
export { F as FetchTransport } from './transport-CqAmRbpQ.js';
|
|
5
6
|
|
|
6
7
|
type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
|
|
7
8
|
declare class ProdantixError extends Error {
|
|
@@ -20,7 +21,7 @@ declare class TransportError extends ProdantixError {
|
|
|
20
21
|
constructor(message: string, status?: number, options?: ErrorOptions);
|
|
21
22
|
}
|
|
22
23
|
|
|
23
|
-
type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set';
|
|
24
|
+
type FlagOp = 'eq' | 'neq' | 'in' | 'not_in' | 'contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_set' | 'is_not_set' | 'in_cohort' | 'not_in_cohort';
|
|
24
25
|
interface FlagCondition {
|
|
25
26
|
attribute: string;
|
|
26
27
|
op: FlagOp;
|
|
@@ -28,6 +29,7 @@ interface FlagCondition {
|
|
|
28
29
|
}
|
|
29
30
|
interface FlagEvalContext {
|
|
30
31
|
attributes?: Record<string, JsonValue>;
|
|
32
|
+
cohorts?: string[];
|
|
31
33
|
distinctId: string;
|
|
32
34
|
properties?: Record<string, JsonValue>;
|
|
33
35
|
}
|
|
@@ -38,11 +40,16 @@ interface FlagVariation {
|
|
|
38
40
|
value: unknown;
|
|
39
41
|
weight: number;
|
|
40
42
|
}
|
|
43
|
+
interface FlagPrerequisite {
|
|
44
|
+
flagKey: string;
|
|
45
|
+
variationKey: string;
|
|
46
|
+
}
|
|
41
47
|
interface FlagRule {
|
|
42
48
|
description?: string;
|
|
43
49
|
enabled: boolean;
|
|
44
50
|
intent?: string;
|
|
45
51
|
key: string;
|
|
52
|
+
prerequisites?: FlagPrerequisite[];
|
|
46
53
|
rolloutPercentage: number;
|
|
47
54
|
targeting: FlagCondition[];
|
|
48
55
|
type?: string;
|
|
@@ -51,6 +58,7 @@ interface FlagRule {
|
|
|
51
58
|
interface FlagSnapshot {
|
|
52
59
|
flags: FlagRule[];
|
|
53
60
|
generatedAt: string;
|
|
61
|
+
socketUrl?: string;
|
|
54
62
|
}
|
|
55
63
|
interface FlagDecision {
|
|
56
64
|
enabled: boolean;
|
|
@@ -75,7 +83,11 @@ declare class FlagsClient {
|
|
|
75
83
|
private readonly requestTimeoutMs;
|
|
76
84
|
constructor(options: FlagsClientOptions);
|
|
77
85
|
fetchAll(distinctId: string): Promise<Record<string, boolean>>;
|
|
86
|
+
fetchDecisions(distinctId: string): Promise<FlagsResponse>;
|
|
78
87
|
snapshot(): Promise<FlagSnapshot>;
|
|
88
|
+
/** The cohorts a distinct id belongs to, for local evaluation of cohort
|
|
89
|
+
* conditions against the same membership store the server reads. */
|
|
90
|
+
memberships(distinctId: string): Promise<string[]>;
|
|
79
91
|
}
|
|
80
92
|
|
|
81
93
|
interface MessagesClientOptions {
|
|
@@ -107,4 +119,4 @@ declare class MemoryStorage implements StorageAdapter {
|
|
|
107
119
|
declare const SDK_NAME = "prodantix-js";
|
|
108
120
|
declare const SDK_VERSION = "0.0.1";
|
|
109
121
|
|
|
110
|
-
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
|
|
122
|
+
export { ConfigError, type FlagCondition, type FlagDecision, type FlagEvalContext, type FlagOp, type FlagRule, type FlagSnapshot, type FlagVariation, FlagsClient, FlagsResponse, InboxMessage, JsonValue, MemoryStorage, MessagesClient, ProdantixError, type ProdantixErrorCode, SDK_NAME, SDK_VERSION, StorageAdapter, TransportError, ValidationError, assignVariant, bucket, evaluateAll, evaluateFlag, getVariant, matches };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{b as ConfigError,
|
|
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
|
package/dist/messenger.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';function
|
|
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
|
package/dist/messenger.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
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';
|
package/dist/messenger.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
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';
|
package/dist/messenger.iife.js
CHANGED
|
@@ -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
|
|
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
|
package/dist/node.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var U=Object.defineProperty;var B=(t,e,r)=>e in t?U(t,e,{enumerable:true,configurable:true,writable:true,value:r}):t[e]=r;var i=(t,e,r)=>B(t,typeof e!="symbol"?e+"":e,r);var c=class extends Error{constructor(r,s,n){super(s,n);i(this,"code");this.code=r,this.name="ProdantixError";}},g=class extends c{constructor(e){super("config",e),this.name="ConfigError";}},f=class extends c{constructor(r,s){super("validation",s);i(this,"field");this.field=r,this.name="ValidationError";}},l=class extends c{constructor(r,s,n){super("transport",r,n);i(this,"status");this.status=s,this.name="TransportError";}};function m(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 P=t=>new Promise(e=>{setTimeout(e,t);});function u(t){return t.replace(/\/+$/,"")}var y=class{constructor(){i(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 S={now:()=>new Date};function v(t){return t.toISOString()}function H(){return globalThis.crypto}function G(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 X(){let t=H();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 G(e)}var C={uuid:X};var Y=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Z=/^(?:\$|[a-z])[a-z0-9_.]*$/;function _(t){let e=0;for(let r of t)e+=1;return e}function R(t){return Y.test(t)}function W(t){return Z.test(t)}function $(t){let e=_(t);if(e<1||e>200)throw new f("distinct_id","distinct_id must be between 1 and 200 characters")}function M(t){let e=_(t);if(e<1||e>200)throw new f("event_name","event_name must be between 1 and 200 characters");if(!W(t))throw new f("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var A="prodantix-js",q="0.0.1";var ee=t=>{};function N(t){if(!t.apiKey||!R(t.apiKey))throw new g("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new g("host is required (the ingest base URL)");let e=u(t.host),r=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??S,defaultProperties:typeof r=="function"?r:()=>r??{},flagsHost:t.flagsHost?u(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??C,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??ee,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??A,sdkVersion:t.sdkVersion??q,storage:t.storage??new y,transport:t.transport}}function O(t,e,r){M(t.eventName),$(t.distinctId);let s={distinct_id:t.distinctId,event_id:t.eventId??r.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:v(t.timestamp??e.now())};return t.context&&(s.context=t.context),t.sessionId&&(s.session_id=t.sessionId),s}var h=Symbol("absent");function te(t,e){if(t==="distinct_id")return e.distinctId;let r=e.properties??{};if(Object.prototype.hasOwnProperty.call(r,t))return r[t];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,t)?s[t]:h}function p(t){return t===h?"undefined":String(t)}function L(t){return t===h?Number.NaN:Number(t)}function D(t){return t!==h&&t!==null&&t!==""}function K(t,e){if(!Array.isArray(e))return false;let r=p(t);return e.map(s=>String(s)).includes(r)}function j(t,e){let r=te(t.attribute,e),s=t.value;switch(t.op){case "is_set":return D(r);case "is_not_set":return !D(r);case "eq":return p(r)===p(s===void 0?h:s);case "neq":return p(r)!==p(s===void 0?h:s);case "contains":return p(r).includes(p(s===void 0?h:s));case "in":return K(r,s);case "not_in":return Array.isArray(s)?!K(r,s):false;case "gt":return x(r,s,(n,o)=>n>o);case "gte":return x(r,s,(n,o)=>n>=o);case "lt":return x(r,s,(n,o)=>n<o);case "lte":return x(r,s,(n,o)=>n<=o);default:return false}}function x(t,e,r){let s=L(t),n=e===void 0?Number.NaN:L(e);return Number.isNaN(s)||Number.isNaN(n)?false:r(s,n)}function re(t,e){let r=`${t}:${e}`,s=2166136261;for(let n=0;n<r.length;n++)s^=r.charCodeAt(n),s=Math.imul(s,16777619);return (s>>>0)%100}function se(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(r=>j(r,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:re(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function V(t,e){let r={};for(let s of t)r[s.key]=se(s,e).enabled;return r}var b=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let r=this.fetch;if(!r)throw new l("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await r(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:n?.signal});if(!a.ok)throw new l(`flags request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).flags??{}}finally{o!==void 0&&clearTimeout(o);}}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`,s=d(),n=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let o=await e(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!o.ok)throw new l(`flag snapshot request failed with status ${o.status}`,o.status);let a=JSON.parse(await o.text());return {flags:a.flags??[],generatedAt:a.generatedAt}}finally{n!==void 0&&clearTimeout(n);}}};var I=class{constructor(e,r,s){this.storage=e;this.ids=r;this.namespace=s;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=r.uuid(),e.setItem(this.key("anonymous_id"),this.anonymousId));let o=e.getItem(this.key("distinct_id"));o?(this.distinctId=o,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){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=u(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let r=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(r,s,{headers:this.authHeaders(),method:"GET"});if(!n.ok)throw new l(`inbox request failed with status ${n.status}`,n.status);return JSON.parse(await n.text()).messages??[]}async markRead(e,r){let s=this.requireFetch(),n=`${this.host}/v1/messages/read`,o=await this.request(s,n,{body:JSON.stringify({distinct_id:r,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!o.ok)throw new l(`mark-read request failed with status ${o.status}`,o.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,s){let n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r,{...s,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};var F=class{constructor(e,r){this.maxSize=e;this.onOverflow=r;i(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 z(t){return t>=400&&t<500&&t!==429}var k=class{constructor(e={}){i(this,"fetch");i(this,"maxRetries");i(this,"requestTimeoutMs");i(this,"baseDelayMs");i(this,"maxDelayMs");i(this,"sleep");i(this,"random");this.fetch=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??P,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 s=JSON.stringify(e.body),n;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(r,e,s);if(a.ok)return;if(z(a.status))throw new l(`ingest rejected batch with status ${a.status}`,a.status);n=new l(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof l&&a.status!==void 0&&z(a.status))throw a;n=a;}o<this.maxRetries&&await this.sleep(this.backoff(o));}throw new l("ingest delivery failed after retries",void 0,{cause:n})}async attempt(e,r,s){let n=d(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(r.url,{body:s,headers:{authorization:`Bearer ${r.projectKey}`,"content-type":"application/json"},method:"POST",signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var ne="queue",ie=1e3,oe=3e4,J=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},w=class{constructor(e){i(this,"config");i(this,"identity");i(this,"queue");i(this,"transport");i(this,"flagsClient");i(this,"messagesClient");i(this,"context");i(this,"flushTimer");i(this,"flushing",false);i(this,"cachedFlags");i(this,"cachedSnapshot");this.config=N(e),this.identity=new I(this.config.storage,this.config.ids,this.config.namespace),this.queue=new F(this.config.maxQueueSize,({dropped:r})=>{this.config.onError(new c("queue_overflow",`event queue overflow: dropped ${r.length} oldest event(s)`));}),this.transport=this.config.transport??new k({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new b({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 s={...this.config.defaultProperties(),...r.properties??{}},n=O({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:s,sessionId:r.sessionId,timestamp:r.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(s){this.config.onError(s);}}identify(e,r={}){let s=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),o=this.identity.identify(e),a={};n&&o.changed&&(a.$anon_distinct_id=s);let T={...J(r.traits??{}),...r.set??{}};Object.keys(T).length>0&&(a.$set=T),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,r,s){let n={$group_key:r,$group_type:e};s&&(n.$set=s),this.capture("$group",{properties:n});}setPersonProperties(e,r){let s={};e&&(s.$set=e),r&&(s.$set_once=r),this.capture("$set",{properties:s});}setPersonTraits(e){let r=J(e);Object.keys(r).length!==0&&this.capture("$set",{properties:{$set:r}});}async getAllFlags(){let e=this.identity.getDistinctId(),r=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:r},r}async isFeatureEnabled(e){return (await this.getAllFlags())[e]??false}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let r=await this.flagSnapshot();return V(r.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,r){return (await this.getLocalFlags(r))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<oe)return this.cachedSnapshot.snapshot;let r=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:r},r}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(ie);try{await this.transport.send({body:{events:e,sent_at:v(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;}async shutdown(){this.stopTimer(),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}.${ne}`}};function Q(){return globalThis.process}function ae(t){Q()?.on("beforeExit",()=>{t.flush();});}function lt(t){let e=Q(),r={...t,os:t.os??(e?.platform?e.platform.slice(0,50):void 0)},s=new w(r);return ae(s),s}exports.createNodeClient=lt;//# sourceMappingURL=node.cjs.map
|
|
1
|
+
'use strict';var pe=Object.defineProperty;var fe=(n,e,t)=>e in n?pe(n,e,{enumerable:true,configurable:true,writable:true,value:t}):n[e]=t;var o=(n,e,t)=>fe(n,typeof e!="symbol"?e+"":e,t);var u=class extends Error{constructor(t,s,r){super(s,r);o(this,"code");this.code=t,this.name="ProdantixError";}},y=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},g=class extends u{constructor(t,s){super("validation",s);o(this,"field");this.field=t,this.name="ValidationError";}},c=class extends u{constructor(t,s,r){super("transport",t,r);o(this,"status");this.status=s,this.name="TransportError";}};function m(n){if(n)return n;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function l(){let n=globalThis.AbortController;return n?new n:void 0}var D=n=>new Promise(e=>{setTimeout(e,n);});function h(n){return n.replace(/\/+$/,"")}var v=class{constructor(){o(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,t){this.store.set(e,t);}};var V={now:()=>new Date};function k(n){return n.toISOString()}function ge(){return globalThis.crypto}function me(n){n[6]=n[6]&15|64,n[8]=n[8]&63|128;let e=[];for(let t=0;t<16;t+=1)e.push(n[t].toString(16).padStart(2,"0"));return `${e[0]}${e[1]}${e[2]}${e[3]}-${e[4]}${e[5]}-${e[6]}${e[7]}-${e[8]}${e[9]}-${e[10]}${e[11]}${e[12]}${e[13]}${e[14]}${e[15]}`}function ye(){let n=ge();if(n?.randomUUID)return n.randomUUID();let e=new Uint8Array(16);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<16;t+=1)e[t]=Math.floor(Math.random()*256);return me(e)}var j={uuid:ye};var ve=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var ke=/^(?:\$|[a-z])[a-z0-9_.]*$/;function b(n){let e=0;for(let t of n)e+=1;return e}function G(n){return ve.test(n)}function be(n){return ke.test(n)}function J(n){let e=b(n);if(e<1||e>200)throw new g("distinct_id","distinct_id must be between 1 and 200 characters")}function U(n){let e=b(n);if(e<1||e>200)throw new g("event_name","event_name must be between 1 and 200 characters");if(!be(n))throw new g("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var H="prodantix-js",z="0.0.1";var xe=n=>{};function Q(n){if(!n.apiKey||!G(n.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!n.host)throw new y("host is required (the ingest base URL)");let e=h(n.host),t=n.defaultProperties,s=n.storage??new v;return {apiKey:n.apiKey,autocapture:n.autocapture??false,clock:n.clock??V,consent:n.consent,defaultProperties:typeof t=="function"?t:()=>t??{},flagsHost:n.flagsHost?h(n.flagsHost):e,flushAt:n.flushAt??20,flushIntervalMs:n.flushIntervalMs??1e4,host:e,ids:n.ids??j,locale:n.locale,maxQueueSize:n.maxQueueSize??1e3,maxRetries:n.maxRetries??3,namespace:P(n.apiKey),onError:n.onError??xe,os:n.os,requestTimeoutMs:n.requestTimeoutMs??1e4,sdkName:n.sdkName??H,sdkVersion:n.sdkVersion??z,sessionTracking:n.sessionTracking??false,sharedStorage:n.sharedStorage??s,socketFactory:n.socketFactory,storage:s,streamFlags:n.streamFlags??false,transport:n.transport}}function P(n){return n.slice(0,16)}function B(n,e,t){U(n.eventName),J(n.distinctId);let s={distinct_id:n.distinctId,event_id:n.eventId??t.uuid(),event_name:n.eventName,properties:n.properties??{},schema_version:1,timestamp:k(n.timestamp??e.now())};return n.context&&(s.context=n.context),n.sessionId&&(s.session_id=n.sessionId),s}var f=Symbol("absent");function Se(n,e){if(n==="distinct_id")return e.distinctId;let t=e.properties??{};if(Object.prototype.hasOwnProperty.call(t,n))return t[n];let s=e.attributes??{};return Object.prototype.hasOwnProperty.call(s,n)?s[n]:f}function p(n){return n===f?"undefined":String(n)}function W(n){return n===f?Number.NaN:Number(n)}function X(n){return n!==f&&n!==null&&n!==""}function Y(n,e){if(!Array.isArray(e))return false;let t=p(n);return e.map(s=>String(s)).includes(t)}function Z(n,e){let t=Se(n.attribute,e),s=n.value;switch(n.op){case "is_set":return X(t);case "is_not_set":return !X(t);case "eq":return p(t)===p(s===void 0?f:s);case "neq":return p(t)!==p(s===void 0?f:s);case "contains":return p(t).includes(p(s===void 0?f:s));case "in":return Y(t,s);case "not_in":return Array.isArray(s)?!Y(t,s):false;case "gt":return x(t,s,(r,i)=>r>i);case "gte":return x(t,s,(r,i)=>r>=i);case "lt":return x(t,s,(r,i)=>r<i);case "lte":return x(t,s,(r,i)=>r<=i);case "in_cohort":return typeof s=="string"&&s!==""&&(e.cohorts??[]).includes(s);case "not_in_cohort":return typeof s=="string"&&s!==""&&!(e.cohorts??[]).includes(s);default:return false}}function x(n,e,t){let s=W(n),r=e===void 0?Number.NaN:W(e);return Number.isNaN(s)||Number.isNaN(r)?false:t(s,r)}function ee(n,e){let t=`${n}:${e}`,s=2166136261;for(let r=0;r<t.length;r++)s^=t.charCodeAt(r),s=Math.imul(s,16777619);return (s>>>0)%100}function R(n,e){return n.targeting.length===0||n.targeting.every(t=>Z(t,e))}function te(n,e){let t=ee(n.key,e.distinctId),s=n.variations??[];if(s.length===0)return n.rolloutPercentage>=100||t<n.rolloutPercentage?"true":"false";let r=0;for(let i=s.length-1;i>=0;i--)if(r+=s[i].weight,t<r)return s[i].key;return s[0].key}function N(n,e,t,s){for(let r of n.prerequisites??[]){if(s.includes(r.flagKey))return false;let i=e.find(d=>d.key===r.flagKey);if(!i||!i.enabled)return false;s.push(i.key);let a=N(i,e,t,s)&&R(i,t)&&te(i,t)===r.variationKey;if(s.pop(),!a)return false}return true}function S(n,e,t){return n.enabled?N(n,e,t,[n.key])?R(n,t)?n.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:ee(n.key,t.distinctId)<n.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"targeting"}:{enabled:false,reason:"prerequisite"}:{enabled:false,reason:"disabled"}}function ne(n,e){let t={};for(let s of n)t[s.key]=S(s,n,e).enabled;return t}function $(n,e,t){let s=n.variations??[],r=s[0];if(!r)return null;if(!n.enabled||!N(n,e,t,[n.key])||!R(n,t))return r;let i=te(n,t);return s.find(a=>a.key===i)??r}function se(n){return n.some(e=>e.targeting.some(t=>t.op==="in_cohort"||t.op==="not_in_cohort"))}function re(n){return `40${JSON.stringify(n)}`}function ie(){return "3"}function oe(n){let e=n.charAt(0),t=n.slice(1);if(e==="2")return {kind:"ping"};if(e==="1")return {kind:"disconnect"};if(e==="0"){let a=O(t);return {kind:"open",pingInterval:typeof a?.pingInterval=="number"?a.pingInterval:25e3,pingTimeout:typeof a?.pingTimeout=="number"?a.pingTimeout:2e4}}if(e!=="4")return {kind:"other"};let s=t.charAt(0),r=t.slice(1);if(s==="0")return {kind:"connected"};if(s==="1")return {kind:"disconnect"};if(s==="4"){let a=O(r);return {kind:"connectError",message:typeof a?.message=="string"?a.message:"refused"}}if(s!=="2")return {kind:"other"};let i=O(r);return !Array.isArray(i)||typeof i[0]!="string"?{kind:"other"}:{kind:"event",name:i[0],payload:i[1]}}function O(n){try{return JSON.parse(n)}catch{return null}}var Ie="/socket.io/?EIO=4&transport=websocket",Ee=250,I=class{constructor(e){this.options=e;o(this,"socket",null);o(this,"heartbeat",null);o(this,"pending",null);o(this,"lastKey","");o(this,"ready",false);o(this,"closed",false);o(this,"heartbeatWindow",45e3);o(this,"factory");o(this,"setTimer");o(this,"clearTimer");this.factory=e.socketFactory??Ce,this.setTimer=e.setTimer??((t,s)=>setTimeout(t,s)),this.clearTimer=e.clearTimer??(t=>clearTimeout(t));}open(){if(this.socket||this.closed)return;let e=`${this.options.host.replace(/^http/,"ws").replace(/\/+$/,"")}${Ie}`,t;try{t=this.factory(e);}catch{this.options.onClosed(false);return}this.socket=t,t.onmessage=s=>this.receive(String(s.data)),t.onerror=()=>t.close(),t.onclose=()=>this.fell();}close(){this.closed=true,this.stopHeartbeat(),this.pending!==null&&this.clearTimer(this.pending),this.pending=null;let e=this.socket;this.socket=null,e?.close();}receive(e){let t=oe(e);if(t.kind==="open"){this.armHeartbeat(t.pingInterval+t.pingTimeout),this.socket?.send(re({projectKey:this.options.projectKey}));return}if(t.kind==="ping"){this.armHeartbeat(),this.socket?.send(ie());return}if(t.kind==="connectError"||t.kind==="disconnect"){this.stopHeartbeat(),this.socket?.close();return}if(t.kind==="event"){if(t.name==="ready"){this.ready=true;return}if(t.name==="flagChange"){let s=t.payload?.key;this.lastKey=typeof s=="string"?s:"",this.pending===null&&(this.pending=this.setTimer(()=>{this.pending=null,this.options.onChange(this.lastKey);},Ee));}}}fell(){this.stopHeartbeat();let e=this.ready;this.socket=null,this.ready=false,this.closed||this.options.onClosed(e);}armHeartbeat(e){e!==void 0&&(this.heartbeatWindow=e),this.stopHeartbeat(),this.heartbeat=this.setTimer(()=>this.socket?.close(),this.heartbeatWindow);}stopHeartbeat(){this.heartbeat!==null&&this.clearTimer(this.heartbeat),this.heartbeat=null;}};function Ce(n){let e=globalThis.WebSocket;if(!e)throw new Error("no WebSocket");return new e(n)}var E=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){return (await this.fetchDecisions(e)).flags}async fetchDecisions(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`flags request failed with status ${a.status}`,a.status);let d=JSON.parse(await a.text());return {flags:d.flags??{},variants:d.variants??{}}}finally{i!==void 0&&clearTimeout(i);}}async snapshot(){let e=this.fetch;if(!e)throw new c("no fetch implementation available in this runtime");let t=`${this.host}/v1/flags/snapshot`,s=l(),r=s?setTimeout(()=>s.abort(),this.requestTimeoutMs):void 0;try{let i=await e(t,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:s?.signal});if(!i.ok)throw new c(`flag snapshot request failed with status ${i.status}`,i.status);let a=JSON.parse(await i.text()),d={flags:a.flags??[],generatedAt:a.generatedAt};return typeof a.socketUrl=="string"&&a.socketUrl!==""&&(d.socketUrl=a.socketUrl),d}finally{r!==void 0&&clearTimeout(r);}}async memberships(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/memberships?distinct_id=${encodeURIComponent(e)}`,r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let a=await t(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!a.ok)throw new c(`memberships request failed with status ${a.status}`,a.status);return JSON.parse(await a.text()).cohorts??[]}finally{i!==void 0&&clearTimeout(i);}}};function M(n){if(typeof n!="string")return;let e=Array.from(n).length;return e>=1&&e<=200?n:void 0}function q(n,e){return `pdx.${n}.${e}`}var ae="consent";function L(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e.identityLink;return typeof t=="boolean"?{identityLink:t}:null}catch{return null}}function Fe(n,e){return L(n.getItem(q(e,ae)))}function we(n,e,t){let s=q(e,ae);if(typeof t.identityLink!="boolean"){n.removeItem(s);return}n.setItem(s,JSON.stringify({identityLink:t.identityLink}));}var C=class{constructor(e,t,s,r){this.storage=e;this.shared=t;this.ids=s;this.namespace=r;o(this,"anonymousId");o(this,"distinctId");o(this,"identified");this.refresh();}refresh(){let e=M(this.shared.getItem(this.key("anonymous_id"))),t=M(this.storage.getItem(this.key("anonymous_id")));e?(this.anonymousId=e,t!==e&&this.storage.setItem(this.key("anonymous_id"),e)):t?(this.anonymousId=t,this.shared.setItem(this.key("anonymous_id"),t)):(this.anonymousId=this.ids.uuid(),this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId));let s=M(this.storage.getItem(this.key("distinct_id")));s?(this.distinctId=s,this.identified=true):(this.distinctId=this.anonymousId,this.identified=false);}getAnonymousId(){return this.anonymousId}getDistinctId(){return this.distinctId}isIdentified(){return this.identified}snapshot(){return {anonymousId:this.anonymousId,distinctId:this.distinctId,identified:this.identified}}consent(){return Fe(this.shared,this.namespace)}setConsent(e){we(this.shared,this.namespace,e);}identify(e){let t=!this.identified||this.distinctId!==e,s=this.storage.getItem(this.key("linked_anonymous_id")),r=t||s!==this.anonymousId;return this.distinctId=e,this.identified=true,t&&this.storage.setItem(this.key("distinct_id"),e),!r||this.consent()?.identityLink===false?{changed:t}:(this.storage.setItem(this.key("linked_anonymous_id"),this.anonymousId),{anonymousToLink:this.anonymousId,changed:t})}reset(){this.anonymousId=this.ids.uuid(),this.distinctId=this.anonymousId,this.identified=false,this.shared.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.setItem(this.key("anonymous_id"),this.anonymousId),this.storage.removeItem(this.key("distinct_id")),this.storage.removeItem(this.key("linked_anonymous_id"));}key(e){return q(this.namespace,e)}};var F=class{constructor(e){o(this,"fetch");o(this,"host");o(this,"projectKey");o(this,"requestTimeoutMs");this.fetch=m(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let t=this.requireFetch(),s=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,r=await this.request(t,s,{headers:this.authHeaders(),method:"GET"});if(!r.ok)throw new c(`inbox request failed with status ${r.status}`,r.status);return JSON.parse(await r.text()).messages??[]}async markRead(e,t){let s=this.requireFetch(),r=`${this.host}/v1/messages/read`,i=await this.request(s,r,{body:JSON.stringify({distinct_id:t,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!i.ok)throw new c(`mark-read request failed with status ${i.status}`,i.status)}requireFetch(){if(!this.fetch)throw new c("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,t,s){let r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t,{...s,signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}};var w=class{constructor(e,t){this.maxSize=e;this.onOverflow=t;o(this,"events",[]);}get size(){return this.events.length}enqueue(e){this.events.push(e),this.enforceCap();}restore(e){this.events.push(...e),this.enforceCap();}requeue(e){this.events.unshift(...e),this.enforceCap();}drain(e){let t=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,t)}snapshot(){return [...this.events]}enforceCap(){if(this.events.length<=this.maxSize)return;let e=this.events.splice(0,this.events.length-this.maxSize);this.onOverflow?.({dropped:e});}};var Te={idleMs:18e5,maxMs:864e5,throttleMs:1e4};function _e(n){return `pdx.${n}.session`}var T=class{constructor(e,t,s,r,i=Te){this.storage=e;this.ids=t;this.clock=s;this.namespace=r;this.options=i;}current(){return this.touch().id}startedAt(){return this.touch().startedAt}reset(){this.storage.removeItem(this.key());}touch(){let e=this.clock.now().getTime(),t=this.live(this.read(),e);if(t===void 0)return this.write({id:this.ids.uuid(),lastActivityAt:e,startedAt:e});if(e-t.lastActivityAt<=this.options.throttleMs)return t;let s=this.live(this.read(),e),r=s!==void 0&&s.id!==t.id?s:t;return this.write({...r,lastActivityAt:e})}live(e,t){if(e!==void 0&&!(t-e.lastActivityAt>this.options.idleMs||t-e.startedAt>this.options.maxMs))return e}write(e){return this.storage.setItem(this.key(),JSON.stringify(e)),e}read(){let e=this.storage.getItem(this.key());if(e)try{let t=JSON.parse(e);return typeof t.id=="string"&&typeof t.startedAt=="number"&&typeof t.lastActivityAt=="number"?{id:t.id,lastActivityAt:t.lastActivityAt,startedAt:t.startedAt}:void 0}catch{return}}key(){return _e(this.namespace)}};function ce(n){return n>=400&&n<500&&n!==429}var _=class{constructor(e={}){o(this,"fetch");o(this,"maxRetries");o(this,"requestTimeoutMs");o(this,"baseDelayMs");o(this,"maxDelayMs");o(this,"sleep");o(this,"random");this.fetch=m(e.fetch),this.maxRetries=e.maxRetries??3,this.requestTimeoutMs=e.requestTimeoutMs??1e4,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.sleep=e.sleep??D,this.random=e.random??Math.random;}async send(e){let t=this.fetch;if(!t)throw new c("no fetch implementation available in this runtime");let s=JSON.stringify(e.body),r;for(let i=0;i<=this.maxRetries;i+=1){try{let a=await this.attempt(t,e,s);if(a.ok)return;if(ce(a.status))throw new c(`ingest rejected batch with status ${a.status}`,a.status);r=new c(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof c&&a.status!==void 0&&ce(a.status))throw a;r=a;}i<this.maxRetries&&await this.sleep(this.backoff(i));}throw new c("ingest delivery failed after retries",void 0,{cause:r})}async attempt(e,t,s){let r=l(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{return await e(t.url,{body:s,headers:{authorization:`Bearer ${t.projectKey}`,"content-type":"application/json"},method:"POST",signal:r?.signal})}finally{i!==void 0&&clearTimeout(i);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var Ae="queue",Pe=1e3,de=3e4,K=n=>{let e={};return n.avatar!==void 0&&(e.$avatar=n.avatar),n.email!==void 0&&(e.$email=n.email),n.name!==void 0&&(e.$name=n.name),n.phone!==void 0&&(e.$phone=n.phone),e},A=class{constructor(e){o(this,"config");o(this,"identity");o(this,"session");o(this,"queue");o(this,"transport");o(this,"flagsClient");o(this,"messagesClient");o(this,"context");o(this,"flushTimer");o(this,"flushing",false);o(this,"cachedFlags");o(this,"cachedSnapshot");o(this,"membershipCache");o(this,"stream");o(this,"shutDown",false);o(this,"exposures",new Set);this.config=Q(e),this.identity=new C(this.config.storage,this.config.sharedStorage,this.config.ids,this.config.namespace),this.config.consent!==void 0&&this.identity.setConsent(this.config.consent),this.session=this.config.sessionTracking?new T(this.config.sharedStorage,this.config.ids,this.config.clock,this.config.namespace):void 0,this.queue=new w(this.config.maxQueueSize,({dropped:t})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${t.length} oldest event(s)`));}),this.transport=this.config.transport??new _({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new E({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new F({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.context={sdk:this.config.sdkName,sdk_version:this.config.sdkVersion},this.config.os&&(this.context.os=this.config.os),this.config.locale&&(this.context.locale=this.config.locale),this.restoreQueue(),this.startTimer();}get distinctId(){return this.identity.getDistinctId()}get anonymousId(){return this.identity.getAnonymousId()}get isIdentified(){return this.identity.isIdentified()}get sessionId(){return this.session?.current()}get sessionStartedAt(){return this.session?.startedAt()}capture(e,t={}){try{this.identity.refresh();let s={...this.config.defaultProperties(),...t.properties??{}},r=B({context:this.context,distinctId:t.distinctId??this.identity.getDistinctId(),eventName:e,properties:s,sessionId:t.sessionId??this.session?.current(),timestamp:t.timestamp},this.config.clock,this.config.ids);this.enqueue(r);}catch(s){this.config.onError(s);}}identify(e,t={}){this.identity.refresh();let s=this.identity.identify(e),r={};s.anonymousToLink!==void 0&&(r.$anon_distinct_id=s.anonymousToLink);let i={...K(t.traits??{}),...t.set??{}};Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{properties:r});}link(e,t,s){let r={$anon_distinct_id:t},i=K(s??{});Object.keys(i).length>0&&(r.$set=i),this.capture("$identify",{distinctId:e,properties:r});}setConsent(e){this.identity.setConsent(e);}consent(){return this.identity.consent()}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,t,s){let r={$group_key:t,$group_type:e};s&&(r.$set=s),this.capture("$group",{properties:r});}setPersonProperties(e,t){let s={};e&&(s.$set=e),t&&(s.$set_once=t),this.capture("$set",{properties:s});}setPersonTraits(e){let t=K(e);Object.keys(t).length!==0&&this.capture("$set",{properties:{$set:t}});}async getAllFlags(){let e=this.identity.getDistinctId(),t=await this.flagsClient.fetchDecisions(e);return this.cachedFlags={distinctId:e,flags:t.flags,variants:t.variants??{}},t.flags}async isFeatureEnabled(e){let s=(await this.getAllFlags())[e]??false;return this.recordExposure(e,this.cachedFlags?.variants[e]?.key??String(s)),s}async getVariant(e){let t=await this.getAllFlags(),s=this.cachedFlags?.variants[e]??null;return this.recordExposure(e,s?.key??String(t[e]??false)),s}async getVariantLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(he=>he.key===e),i=await this.localContext(t,s.flags),a=r?$(r,s.flags,i):null,d=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,a?.key??String(d)),a?{key:a.key,value:a.value}:null}recordExposure(e,t){let s=`${this.identity.getDistinctId()} ${e} ${t}`;this.exposures.has(s)||(this.exposures.add(s),this.capture("$feature_flag_called",{properties:{$feature_flag:e,$feature_flag_response:t}}));}getCachedFlag(e){if(!(!this.cachedFlags||this.cachedFlags.distinctId!==this.distinctId))return this.cachedFlags.flags[e]}async getLocalFlags(e={}){let t=await this.flagSnapshot();return ne(t.flags,await this.localContext(e,t.flags))}async isFeatureEnabledLocal(e,t={}){let s=await this.flagSnapshot(),r=s.flags.find(d=>d.key===e),i=await this.localContext(t,s.flags),a=r?S(r,s.flags,i).enabled:false;return this.recordExposure(e,(r?$(r,s.flags,i)?.key:void 0)??String(a)),a}async localContext(e,t){let s=this.identity.getDistinctId(),r=e.cohorts;if(r===void 0&&se(t)){let i=this.config.clock.now().getTime();this.membershipCache&&this.membershipCache.distinctId===s&&i-this.membershipCache.fetchedAt<de?r=this.membershipCache.cohorts:(r=await this.flagsClient.memberships(s),this.membershipCache={cohorts:r,distinctId:s,fetchedAt:i});}return {attributes:e.attributes,cohorts:r,distinctId:s,properties:e.properties}}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<de)return this.cachedSnapshot.snapshot;let t=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:t},this.maybeStream(t),t}maybeStream(e){if(!this.config.streamFlags||this.shutDown||this.stream||!e.socketUrl)return;let t=new I({host:e.socketUrl,onChange:()=>{this.cachedSnapshot=void 0,this.flagSnapshot().catch(s=>this.config.onError(s));},onClosed:s=>{this.stream=void 0,s&&this.maybeStream(e);},projectKey:this.config.apiKey,socketFactory:this.config.socketFactory});this.stream=t,t.open();}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(Pe);try{await this.transport.send({body:{events:e,sent_at:k(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(t){this.queue.requeue(e),this.persistQueue(),this.config.onError(t);}finally{this.flushing=false;}}reset(){this.session?.reset(),this.identity.reset(),this.cachedFlags=void 0,this.cachedSnapshot=void 0,this.membershipCache=void 0;}async shutdown(){this.shutDown=true,this.stopTimer(),this.stream?.close(),this.stream=void 0,await this.flush();}enqueue(e){this.queue.enqueue(e),this.persistQueue(),this.queue.size>=this.config.flushAt&&this.flush();}persistQueue(){try{this.config.storage.setItem(this.persistKey(),JSON.stringify(this.queue.snapshot()));}catch(e){this.config.onError(e);}}restoreQueue(){try{let e=this.config.storage.getItem(this.persistKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&this.queue.restore(t);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),t=e;typeof t.unref=="function"&&t.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${Ae}`}};var Re=200;function le(){return globalThis.process}function Ne(n){le()?.on("beforeExit",()=>{n.flush();});}function zt(n){let e=le(),t={...n,os:n.os??(e?.platform?e.platform.slice(0,50):void 0),streamFlags:n.streamFlags??true},s=new A(t);return Ne(s),s}function Qt(n,e){let t=P(e),s=$e(n,`pdx_${t}`);if(s===void 0)return null;let r=Oe(s);if(r===void 0)return null;let i=ue(r[`pdx.${t}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:L(r[`pdx.${t}.consent`]),sessionId:Me(r[`pdx.${t}.session`])}}function $e(n,e){let t=`${e}=`;for(let s of n.split(";")){let r=s.trim();if(r.startsWith(t))return r.slice(t.length)}}function Oe(n){try{let e=JSON.parse(decodeURIComponent(n));return e===null||typeof e!="object"||Array.isArray(e)?void 0:e}catch{return}}function ue(n){if(typeof n!="string")return;let e=b(n);return e>=1&&e<=Re?n:void 0}function Me(n){if(typeof n!="string")return null;try{let e=JSON.parse(n);return e===null||typeof e!="object"||typeof e.startedAt!="number"||typeof e.lastActivityAt!="number"?null:ue(e.id)??null}catch{return null}}exports.createNodeClient=zt;exports.readSharedIdentity=Qt;//# sourceMappingURL=node.cjs.map
|
|
2
2
|
//# sourceMappingURL=node.cjs.map
|
package/dist/node.d.cts
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { P as ProdantixClient } from './client-BO7f6q5k.cjs';
|
|
2
|
+
import { b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.cjs';
|
|
2
3
|
|
|
4
|
+
/** What the web SDK's cookie says about the visitor on this request: the
|
|
5
|
+
* anonymous id every subdomain of the site shares, the session it is in, and
|
|
6
|
+
* the answer they gave about the join (null when they were never asked). */
|
|
7
|
+
interface SharedIdentity {
|
|
8
|
+
anonymousId: string;
|
|
9
|
+
consent: Consent | null;
|
|
10
|
+
sessionId: string | null;
|
|
11
|
+
}
|
|
3
12
|
declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
|
|
13
|
+
/**
|
|
14
|
+
* Reads the visitor the web SDK's cookie names, from a request's `Cookie`
|
|
15
|
+
* header. A sign-in that completes in a redirect has no page to identify from,
|
|
16
|
+
* so the server reads the browser's anonymous id here and links it with
|
|
17
|
+
* `ProdantixClient.link`. Null when the cookie is absent or not the SDK's own.
|
|
18
|
+
*/
|
|
19
|
+
declare function readSharedIdentity(cookieHeader: string, apiKey: string): SharedIdentity | null;
|
|
4
20
|
|
|
5
|
-
export { createNodeClient };
|
|
21
|
+
export { Consent, type SharedIdentity, createNodeClient, readSharedIdentity };
|
package/dist/node.d.ts
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { P as ProdantixClient } from './client-BQlU_3Dc.js';
|
|
2
|
+
import { b as Consent, P as ProdantixConfig } from './types-DjMXp6Wg.js';
|
|
2
3
|
|
|
4
|
+
/** What the web SDK's cookie says about the visitor on this request: the
|
|
5
|
+
* anonymous id every subdomain of the site shares, the session it is in, and
|
|
6
|
+
* the answer they gave about the join (null when they were never asked). */
|
|
7
|
+
interface SharedIdentity {
|
|
8
|
+
anonymousId: string;
|
|
9
|
+
consent: Consent | null;
|
|
10
|
+
sessionId: string | null;
|
|
11
|
+
}
|
|
3
12
|
declare function createNodeClient(options: ProdantixConfig): ProdantixClient;
|
|
13
|
+
/**
|
|
14
|
+
* Reads the visitor the web SDK's cookie names, from a request's `Cookie`
|
|
15
|
+
* header. A sign-in that completes in a redirect has no page to identify from,
|
|
16
|
+
* so the server reads the browser's anonymous id here and links it with
|
|
17
|
+
* `ProdantixClient.link`. Null when the cookie is absent or not the SDK's own.
|
|
18
|
+
*/
|
|
19
|
+
declare function readSharedIdentity(cookieHeader: string, apiKey: string): SharedIdentity | null;
|
|
4
20
|
|
|
5
|
-
export { createNodeClient };
|
|
21
|
+
export { Consent, type SharedIdentity, createNodeClient, readSharedIdentity };
|
package/dist/node.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {y as y$1,l as l$1,t,i}from'./chunk-5CBVQAZ2.js';import'./chunk-V77KYPOF.js';import'./chunk-VG77TYVX.js';import'./chunk-5XGN7UAV.js';var a=200;function f(){return globalThis.process}function p(t){f()?.on("beforeExit",()=>{t.flush();});}function h(t){let n=f(),e={...t,os:t.os??(n?.platform?n.platform.slice(0,50):void 0),streamFlags:t.streamFlags??true},r=new y$1(e);return p(r),r}function w(t$1,n){let e=l$1(n),r=m(t$1,`pdx_${e}`);if(r===void 0)return null;let o=g(r);if(o===void 0)return null;let i=l(o[`pdx.${e}.anonymous_id`]);return i===void 0?null:{anonymousId:i,consent:t(o[`pdx.${e}.consent`]),sessionId:y(o[`pdx.${e}.session`])}}function m(t,n){let e=`${n}=`;for(let r of t.split(";")){let o=r.trim();if(o.startsWith(e))return o.slice(e.length)}}function g(t){try{let n=JSON.parse(decodeURIComponent(t));return n===null||typeof n!="object"||Array.isArray(n)?void 0:n}catch{return}}function l(t){if(typeof t!="string")return;let n=i(t);return n>=1&&n<=a?t:void 0}function y(t){if(typeof t!="string")return null;try{let n=JSON.parse(t);return n===null||typeof n!="object"||typeof n.startedAt!="number"||typeof n.lastActivityAt!="number"?null:l(n.id)??null}catch{return null}}export{h as createNodeClient,w as readSharedIdentity};//# sourceMappingURL=node.js.map
|
|
2
2
|
//# sourceMappingURL=node.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
2
|
-
import { T as Transport, i as TransportRequest } from './
|
|
2
|
+
import { T as Transport, i as TransportRequest } from './types-DjMXp6Wg.js';
|
|
3
3
|
|
|
4
4
|
interface FetchTransportOptions {
|
|
5
5
|
baseDelayMs?: number;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
2
|
-
import { T as Transport, i as TransportRequest } from './
|
|
2
|
+
import { T as Transport, i as TransportRequest } from './types-DjMXp6Wg.cjs';
|
|
3
3
|
|
|
4
4
|
interface FetchTransportOptions {
|
|
5
5
|
baseDelayMs?: number;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
type JsonPrimitive = string | number | boolean | null;
|
|
2
|
+
type JsonValue = JsonPrimitive | JsonValue[] | {
|
|
3
|
+
[key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
type EventProperties = Record<string, JsonValue>;
|
|
6
|
+
interface EventContext {
|
|
7
|
+
locale?: string;
|
|
8
|
+
os?: string;
|
|
9
|
+
sdk?: string;
|
|
10
|
+
sdk_version?: string;
|
|
11
|
+
}
|
|
12
|
+
interface EventEnvelope {
|
|
13
|
+
context?: EventContext;
|
|
14
|
+
distinct_id: string;
|
|
15
|
+
event_id: string;
|
|
16
|
+
event_name: string;
|
|
17
|
+
properties: EventProperties;
|
|
18
|
+
schema_version: 1;
|
|
19
|
+
session_id?: string;
|
|
20
|
+
timestamp: string;
|
|
21
|
+
}
|
|
22
|
+
interface EventBatch {
|
|
23
|
+
api_key?: string;
|
|
24
|
+
events: EventEnvelope[];
|
|
25
|
+
sent_at: string;
|
|
26
|
+
}
|
|
27
|
+
interface FlagVariant {
|
|
28
|
+
key: string;
|
|
29
|
+
value: unknown;
|
|
30
|
+
}
|
|
31
|
+
interface FlagsResponse {
|
|
32
|
+
flags: Record<string, boolean>;
|
|
33
|
+
variants?: Record<string, FlagVariant>;
|
|
34
|
+
}
|
|
35
|
+
interface InboxMessage {
|
|
36
|
+
body: string;
|
|
37
|
+
createdAt: string;
|
|
38
|
+
id: string;
|
|
39
|
+
read: boolean;
|
|
40
|
+
title: string;
|
|
41
|
+
}
|
|
42
|
+
interface InboxResponse {
|
|
43
|
+
messages: InboxMessage[];
|
|
44
|
+
}
|
|
45
|
+
interface Clock {
|
|
46
|
+
now(): Date;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* What the visitor answered about their anonymous trail being joined to the
|
|
50
|
+
* person they sign in as. Unset means allowed: the answer is the customer's
|
|
51
|
+
* banner to collect, and a site that never asks keeps the platform's default.
|
|
52
|
+
*/
|
|
53
|
+
interface Consent {
|
|
54
|
+
identityLink?: boolean;
|
|
55
|
+
}
|
|
56
|
+
interface IdFactory {
|
|
57
|
+
uuid(): string;
|
|
58
|
+
}
|
|
59
|
+
interface StorageAdapter {
|
|
60
|
+
getItem(key: string): string | null;
|
|
61
|
+
removeItem(key: string): void;
|
|
62
|
+
setItem(key: string, value: string): void;
|
|
63
|
+
}
|
|
64
|
+
interface TransportRequest {
|
|
65
|
+
body: EventBatch;
|
|
66
|
+
projectKey: string;
|
|
67
|
+
url: string;
|
|
68
|
+
}
|
|
69
|
+
interface Transport {
|
|
70
|
+
send(request: TransportRequest): Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
/** The browser's `WebSocket`, narrowed to what the SDK uses so a test can hand
|
|
73
|
+
* in a fake without a DOM. Assigning the handlers rather than using
|
|
74
|
+
* `addEventListener` keeps the surface to four properties. */
|
|
75
|
+
interface SocketLike {
|
|
76
|
+
send(data: string): void;
|
|
77
|
+
close(): void;
|
|
78
|
+
onopen: (() => void) | null;
|
|
79
|
+
onclose: (() => void) | null;
|
|
80
|
+
onerror: (() => void) | null;
|
|
81
|
+
onmessage: ((event: {
|
|
82
|
+
data: string;
|
|
83
|
+
}) => void) | null;
|
|
84
|
+
}
|
|
85
|
+
type SocketFactory = (url: string) => SocketLike;
|
|
86
|
+
interface ProdantixConfig {
|
|
87
|
+
apiKey: string;
|
|
88
|
+
autocapture?: boolean;
|
|
89
|
+
clock?: Clock;
|
|
90
|
+
/** The visitor's answer, for an app that already holds it. Written to the
|
|
91
|
+
* shared store when the client is built, so the answer survives the page. */
|
|
92
|
+
consent?: Consent;
|
|
93
|
+
defaultProperties?: EventProperties | (() => EventProperties);
|
|
94
|
+
flagsHost?: string;
|
|
95
|
+
flushAt?: number;
|
|
96
|
+
flushIntervalMs?: number;
|
|
97
|
+
host: string;
|
|
98
|
+
ids?: IdFactory;
|
|
99
|
+
locale?: string;
|
|
100
|
+
maxQueueSize?: number;
|
|
101
|
+
maxRetries?: number;
|
|
102
|
+
onError?: (error: unknown) => void;
|
|
103
|
+
os?: string;
|
|
104
|
+
requestTimeoutMs?: number;
|
|
105
|
+
sdkName?: string;
|
|
106
|
+
sdkVersion?: string;
|
|
107
|
+
sessionTracking?: boolean;
|
|
108
|
+
sharedStorage?: StorageAdapter;
|
|
109
|
+
/** The socket constructor the flag stream uses; the test seam. */
|
|
110
|
+
socketFactory?: SocketFactory;
|
|
111
|
+
storage?: StorageAdapter;
|
|
112
|
+
/** Hold a Socket.IO subscription to flag changes and refetch the snapshot on
|
|
113
|
+
* push. Off unless asked; the node entry turns it on. */
|
|
114
|
+
streamFlags?: boolean;
|
|
115
|
+
transport?: Transport;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export type { Clock as C, EventBatch as E, FlagsResponse as F, InboxMessage as I, JsonValue as J, ProdantixConfig as P, SocketFactory as S, Transport as T, StorageAdapter as a, Consent as b, EventContext as c, EventEnvelope as d, EventProperties as e, FlagVariant as f, IdFactory as g, InboxResponse as h, TransportRequest as i };
|