@prodantix/sdk 0.0.1-beta.323 → 0.0.1-beta.324
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chat.cjs +41 -0
- package/dist/chat.d.cts +87 -0
- package/dist/chat.d.ts +87 -0
- package/dist/chat.js +41 -0
- package/dist/chunk-AMUIQXH2.js +2 -0
- package/dist/chunk-STIKBPFF.js +2 -0
- package/dist/http-BCh716Vs.d.cts +14 -0
- package/dist/http-BCh716Vs.d.ts +14 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/node.js +1 -1
- package/dist/{transport-By6wsdny.d.ts → transport-B7A4sAOI.d.ts} +2 -14
- package/dist/{transport-B3PxeUxW.d.cts → transport-BOmEPpCa.d.cts} +2 -14
- package/dist/web.d.cts +2 -1
- package/dist/web.d.ts +2 -1
- package/dist/web.js +1 -1
- package/package.json +7 -1
- package/dist/chunk-FIZWZVZG.js +0 -2
package/dist/chat.cjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
'use strict';var b=Object.defineProperty;var x=(r,e,t)=>e in r?b(r,e,{enumerable:true,configurable:true,writable:true,value:t}):r[e]=t;var l=(r,e,t)=>x(r,typeof e!="symbol"?e+"":e,t);function g(r){if(r)return r;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function m(r){return r.replace(/\/+$/,"")}var v="X-Prodantix-Conversation-Token",f="prodantix.chat.handle";function y(){let r=globalThis.localStorage;if(r)return {get:e=>r.getItem(e),remove:e=>r.removeItem(e),set:(e,t)=>r.setItem(e,t)}}var u=class{constructor(e){this.options=e;l(this,"fetchImpl");l(this,"host");l(this,"storage");l(this,"handle");this.fetchImpl=g(e.fetchImpl),this.host=m(e.host),this.storage=e.storage??y(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}async ensureThread(e){if(this.handle)return true;let t=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:e}});return !t?.conversationId||!t.token?false:(this.handle={conversationId:t.conversationId,token:t.token},this.storage?.set(f,JSON.stringify(this.handle)),true)}async send(e){if(!await this.ensureThread())return null;let t=this.handle;return t?(await this.request("POST",`/v1/conversations/${encodeURIComponent(t.conversationId)}/turns`,{body:{body:e},token:t.token}))?.turn??null:null}async load(){let e=this.handle;return e?this.request("GET",`/v1/conversations/${encodeURIComponent(e.conversationId)}`,{token:e.token}):null}readHandle(){let e=this.storage?.get(f);if(!e)return null;try{let t=JSON.parse(e);if(typeof t.conversationId=="string"&&typeof t.token=="string")return {conversationId:t.conversationId,token:t.token}}catch{}return this.storage?.remove(f),null}async request(e,t,o={}){let n=this.fetchImpl;if(!n)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let a={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};o.token&&(a[v]=o.token);try{let i=await n(`${this.host}${t}`,{body:o.body===void 0?void 0:JSON.stringify(o.body),headers:a,method:e}),s=await i.text();return i.ok?s?JSON.parse(s):{}:(this.options.onError?.(new Error(`prodantix chat ${t}: ${i.status}`)),null)}catch(i){return this.options.onError?.(i),null}}};var C={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",title:"Support",unreadLabel:r=>`${r} unread`},T=`
|
|
2
|
+
:host { all: initial; }
|
|
3
|
+
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
4
|
+
.launcher {
|
|
5
|
+
position: fixed; right: 20px; bottom: 20px; width: 56px; height: 56px;
|
|
6
|
+
border-radius: 28px; border: none; cursor: pointer;
|
|
7
|
+
background: #16a34a; color: #fff; font-size: 24px;
|
|
8
|
+
box-shadow: 0 4px 12px rgba(0,0,0,.2);
|
|
9
|
+
}
|
|
10
|
+
.launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
|
|
11
|
+
.badge {
|
|
12
|
+
position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
|
|
13
|
+
border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
|
|
14
|
+
display: flex; align-items: center; justify-content: center; padding: 0 4px;
|
|
15
|
+
}
|
|
16
|
+
.panel {
|
|
17
|
+
position: fixed; right: 20px; bottom: 88px; width: 360px; max-width: calc(100vw - 40px);
|
|
18
|
+
height: 520px; max-height: calc(100vh - 120px); background: #fff; color: #0f172a;
|
|
19
|
+
border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
|
|
20
|
+
display: flex; flex-direction: column; overflow: hidden;
|
|
21
|
+
}
|
|
22
|
+
.header { padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
|
|
23
|
+
.header h2 { margin: 0; font-size: 15px; }
|
|
24
|
+
.close { background: none; border: none; color: #fff; cursor: pointer; font-size: 18px; }
|
|
25
|
+
.close:focus-visible { outline: 2px solid #fff; }
|
|
26
|
+
.log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
|
27
|
+
.turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
|
|
28
|
+
.turn.end_user { align-self: flex-end; background: #16a34a; color: #fff; }
|
|
29
|
+
.turn.agent, .turn.ai { align-self: flex-start; background: #f1f5f9; color: #0f172a; }
|
|
30
|
+
.author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
|
|
31
|
+
.composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid #e2e8f0; }
|
|
32
|
+
.composer input { flex: 1; padding: 8px 10px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 14px; }
|
|
33
|
+
.composer input:focus-visible { outline: 2px solid #16a34a; }
|
|
34
|
+
.composer button { padding: 8px 14px; background: #16a34a; color: #fff; border: none; border-radius: 8px; cursor: pointer; }
|
|
35
|
+
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
36
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
37
|
+
.panel { animation: rise 180ms ease-out; }
|
|
38
|
+
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
39
|
+
}
|
|
40
|
+
`,E=["end_user","agent","ai"],h=class{constructor(e,t,o={}){this.host=e;this.client=t;l(this,"root");l(this,"strings");l(this,"launcher");l(this,"badge");l(this,"panel",null);l(this,"lastFocused",null);l(this,"unread",0);this.strings={...C,...o},this.root=e.attachShadow({mode:"closed"});let n=document.createElement("style");n.textContent=T,this.root.append(n),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 o=document.createElement("h2");o.textContent=this.strings.title;let n=document.createElement("button");n.className="close",n.type="button",n.setAttribute("aria-label",this.strings.closeLabel),n.textContent="\xD7",n.addEventListener("click",()=>this.close()),t.append(o,n);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 i=document.createElement("form");i.className="composer";let s=document.createElement("input");s.type="text",s.setAttribute("aria-label",this.strings.inputPlaceholder),s.placeholder=this.strings.inputPlaceholder;let c=document.createElement("button");c.type="submit",c.textContent=this.strings.sendLabel,i.append(s,c),i.addEventListener("submit",d=>{d.preventDefault(),this.submit(s,a);}),e.append(t,a,i),e.addEventListener("keydown",d=>this.onKeydown(d,e,n)),this.root.append(e),this.panel=e,s.focus();let p=await this.client.load();p&&this.renderThread(a,p);}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){let o=e.value.trim();if(!o)return;e.value="";let n=await this.client.send(o);n&&this.appendTurn(t,n);}renderThread(e,t){e.replaceChildren();for(let o of t.turns)this.appendTurn(e,o);}appendTurn(e,t){let o=E.includes(t.authorKind)?t.authorKind:"agent",n=document.createElement("div");if(n.className=`turn ${o}`,o!=="end_user"){let i=document.createElement("div");i.className="author",i.textContent=o==="ai"?this.strings.aiLabel:this.strings.agentLabel,n.append(i);}let a=document.createElement("div");a.textContent=t.body,n.append(a),e.append(n),e.scrollTop=e.scrollHeight;}onKeydown(e,t,o){if(e.key==="Escape"){e.preventDefault(),this.close();return}if(e.key!=="Tab")return;let n=t.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(n.length===0)return;let a=n[0],i=n[n.length-1],s=this.root.activeElement;e.shiftKey&&s===a?(e.preventDefault(),i.focus()):!e.shiftKey&&s===i?(e.preventDefault(),a.focus()):s===null&&(e.preventDefault(),o.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 M(r){let e=globalThis.document;if(!e)throw new Error("prodantix chat requires a document; mount it in the browser");let t=r.mountPoint??e.createElement("div");r.mountPoint||e.body.append(t);let o=new u(r),n=new h(t,o,r.strings),a=new Set,i,s=r.pollIntervalMs??15e3;return s>0&&(i=setInterval(async()=>{if(!o.hasThread)return;let c=await o.load();if(!c)return;let p=new Set(c.turns.map(d=>d.id));for(let d of c.turns)!a.has(d.id)&&d.authorKind!=="end_user"&&n.onIncomingTurn(d);a=p;},s)),{close:()=>n.close(),destroy:()=>{i&&clearInterval(i),n.close(),t.remove();},open:()=>void n.open()}}exports.ChatClient=u;exports.ChatPanel=h;exports.mountChat=M;//# sourceMappingURL=chat.cjs.map
|
|
41
|
+
//# sourceMappingURL=chat.cjs.map
|
package/dist/chat.d.cts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
2
|
+
|
|
3
|
+
interface ChatTurn {
|
|
4
|
+
id: string;
|
|
5
|
+
authorKind: 'end_user' | 'agent' | 'ai';
|
|
6
|
+
authorId: string | null;
|
|
7
|
+
body: string;
|
|
8
|
+
createdAt: string;
|
|
9
|
+
}
|
|
10
|
+
interface ChatThread {
|
|
11
|
+
id: string;
|
|
12
|
+
status: string;
|
|
13
|
+
turns: ChatTurn[];
|
|
14
|
+
}
|
|
15
|
+
interface ChatClientOptions {
|
|
16
|
+
apiKey: string;
|
|
17
|
+
host: string;
|
|
18
|
+
distinctId: string;
|
|
19
|
+
storage?: ChatStorage;
|
|
20
|
+
fetchImpl?: FetchLike;
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
}
|
|
23
|
+
interface ChatStorage {
|
|
24
|
+
get(key: string): string | null;
|
|
25
|
+
set(key: string, value: string): void;
|
|
26
|
+
remove(key: string): void;
|
|
27
|
+
}
|
|
28
|
+
declare class ChatClient {
|
|
29
|
+
private readonly options;
|
|
30
|
+
private readonly fetchImpl?;
|
|
31
|
+
private readonly host;
|
|
32
|
+
private readonly storage?;
|
|
33
|
+
private handle;
|
|
34
|
+
constructor(options: ChatClientOptions);
|
|
35
|
+
get hasThread(): boolean;
|
|
36
|
+
ensureThread(subject?: string): Promise<boolean>;
|
|
37
|
+
send(body: string): Promise<ChatTurn | null>;
|
|
38
|
+
load(): Promise<ChatThread | null>;
|
|
39
|
+
private readHandle;
|
|
40
|
+
private request;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface ChatStrings {
|
|
44
|
+
launcherLabel: string;
|
|
45
|
+
title: string;
|
|
46
|
+
inputPlaceholder: string;
|
|
47
|
+
sendLabel: string;
|
|
48
|
+
closeLabel: string;
|
|
49
|
+
agentLabel: string;
|
|
50
|
+
aiLabel: string;
|
|
51
|
+
unreadLabel: (count: number) => string;
|
|
52
|
+
}
|
|
53
|
+
declare class ChatPanel {
|
|
54
|
+
private readonly host;
|
|
55
|
+
private readonly client;
|
|
56
|
+
private readonly root;
|
|
57
|
+
private readonly strings;
|
|
58
|
+
private readonly launcher;
|
|
59
|
+
private readonly badge;
|
|
60
|
+
private panel;
|
|
61
|
+
private lastFocused;
|
|
62
|
+
private unread;
|
|
63
|
+
constructor(host: HTMLElement, client: ChatClient, strings?: Partial<ChatStrings>);
|
|
64
|
+
private toggle;
|
|
65
|
+
open(): Promise<void>;
|
|
66
|
+
close(): void;
|
|
67
|
+
onIncomingTurn(turn: ChatTurn): void;
|
|
68
|
+
private submit;
|
|
69
|
+
private renderThread;
|
|
70
|
+
private appendTurn;
|
|
71
|
+
private onKeydown;
|
|
72
|
+
private renderBadge;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface MountChatOptions extends ChatClientOptions {
|
|
76
|
+
mountPoint?: HTMLElement;
|
|
77
|
+
strings?: Partial<ChatStrings>;
|
|
78
|
+
pollIntervalMs?: number;
|
|
79
|
+
}
|
|
80
|
+
interface ChatHandle {
|
|
81
|
+
open(): void;
|
|
82
|
+
close(): void;
|
|
83
|
+
destroy(): void;
|
|
84
|
+
}
|
|
85
|
+
declare function mountChat(options: MountChatOptions): ChatHandle;
|
|
86
|
+
|
|
87
|
+
export { ChatClient, type ChatClientOptions, type ChatHandle, ChatPanel, type ChatStorage, type ChatStrings, type ChatThread, type ChatTurn, type MountChatOptions, mountChat };
|
package/dist/chat.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
2
|
+
|
|
3
|
+
interface ChatTurn {
|
|
4
|
+
id: string;
|
|
5
|
+
authorKind: 'end_user' | 'agent' | 'ai';
|
|
6
|
+
authorId: string | null;
|
|
7
|
+
body: string;
|
|
8
|
+
createdAt: string;
|
|
9
|
+
}
|
|
10
|
+
interface ChatThread {
|
|
11
|
+
id: string;
|
|
12
|
+
status: string;
|
|
13
|
+
turns: ChatTurn[];
|
|
14
|
+
}
|
|
15
|
+
interface ChatClientOptions {
|
|
16
|
+
apiKey: string;
|
|
17
|
+
host: string;
|
|
18
|
+
distinctId: string;
|
|
19
|
+
storage?: ChatStorage;
|
|
20
|
+
fetchImpl?: FetchLike;
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
}
|
|
23
|
+
interface ChatStorage {
|
|
24
|
+
get(key: string): string | null;
|
|
25
|
+
set(key: string, value: string): void;
|
|
26
|
+
remove(key: string): void;
|
|
27
|
+
}
|
|
28
|
+
declare class ChatClient {
|
|
29
|
+
private readonly options;
|
|
30
|
+
private readonly fetchImpl?;
|
|
31
|
+
private readonly host;
|
|
32
|
+
private readonly storage?;
|
|
33
|
+
private handle;
|
|
34
|
+
constructor(options: ChatClientOptions);
|
|
35
|
+
get hasThread(): boolean;
|
|
36
|
+
ensureThread(subject?: string): Promise<boolean>;
|
|
37
|
+
send(body: string): Promise<ChatTurn | null>;
|
|
38
|
+
load(): Promise<ChatThread | null>;
|
|
39
|
+
private readHandle;
|
|
40
|
+
private request;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface ChatStrings {
|
|
44
|
+
launcherLabel: string;
|
|
45
|
+
title: string;
|
|
46
|
+
inputPlaceholder: string;
|
|
47
|
+
sendLabel: string;
|
|
48
|
+
closeLabel: string;
|
|
49
|
+
agentLabel: string;
|
|
50
|
+
aiLabel: string;
|
|
51
|
+
unreadLabel: (count: number) => string;
|
|
52
|
+
}
|
|
53
|
+
declare class ChatPanel {
|
|
54
|
+
private readonly host;
|
|
55
|
+
private readonly client;
|
|
56
|
+
private readonly root;
|
|
57
|
+
private readonly strings;
|
|
58
|
+
private readonly launcher;
|
|
59
|
+
private readonly badge;
|
|
60
|
+
private panel;
|
|
61
|
+
private lastFocused;
|
|
62
|
+
private unread;
|
|
63
|
+
constructor(host: HTMLElement, client: ChatClient, strings?: Partial<ChatStrings>);
|
|
64
|
+
private toggle;
|
|
65
|
+
open(): Promise<void>;
|
|
66
|
+
close(): void;
|
|
67
|
+
onIncomingTurn(turn: ChatTurn): void;
|
|
68
|
+
private submit;
|
|
69
|
+
private renderThread;
|
|
70
|
+
private appendTurn;
|
|
71
|
+
private onKeydown;
|
|
72
|
+
private renderBadge;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface MountChatOptions extends ChatClientOptions {
|
|
76
|
+
mountPoint?: HTMLElement;
|
|
77
|
+
strings?: Partial<ChatStrings>;
|
|
78
|
+
pollIntervalMs?: number;
|
|
79
|
+
}
|
|
80
|
+
interface ChatHandle {
|
|
81
|
+
open(): void;
|
|
82
|
+
close(): void;
|
|
83
|
+
destroy(): void;
|
|
84
|
+
}
|
|
85
|
+
declare function mountChat(options: MountChatOptions): ChatHandle;
|
|
86
|
+
|
|
87
|
+
export { ChatClient, type ChatClientOptions, type ChatHandle, ChatPanel, type ChatStorage, type ChatStrings, type ChatThread, type ChatTurn, type MountChatOptions, mountChat };
|
package/dist/chat.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import {a,b as b$1,e}from'./chunk-STIKBPFF.js';var b="X-Prodantix-Conversation-Token",f="prodantix.chat.handle";function x(){let s=globalThis.localStorage;if(s)return {get:t=>s.getItem(t),remove:t=>s.removeItem(t),set:(t,e)=>s.setItem(t,e)}}var h=class{constructor(t){this.options=t;a(this,"fetchImpl");a(this,"host");a(this,"storage");a(this,"handle");this.fetchImpl=b$1(t.fetchImpl),this.host=e(t.host),this.storage=t.storage??x(),this.handle=this.readHandle();}get hasThread(){return this.handle!==null}async ensureThread(t){if(this.handle)return true;let e=await this.request("POST","/v1/conversations",{body:{distinctId:this.options.distinctId,subject:t}});return !e?.conversationId||!e.token?false:(this.handle={conversationId:e.conversationId,token:e.token},this.storage?.set(f,JSON.stringify(this.handle)),true)}async send(t){if(!await this.ensureThread())return null;let e=this.handle;return e?(await this.request("POST",`/v1/conversations/${encodeURIComponent(e.conversationId)}/turns`,{body:{body:t},token:e.token}))?.turn??null:null}async load(){let t=this.handle;return t?this.request("GET",`/v1/conversations/${encodeURIComponent(t.conversationId)}`,{token:t.token}):null}readHandle(){let t=this.storage?.get(f);if(!t)return null;try{let e=JSON.parse(t);if(typeof e.conversationId=="string"&&typeof e.token=="string")return {conversationId:e.conversationId,token:e.token}}catch{}return this.storage?.remove(f),null}async request(t,e,r={}){let n=this.fetchImpl;if(!n)return this.options.onError?.(new Error("no fetch available for prodantix chat")),null;let o={authorization:`Bearer ${this.options.apiKey}`,"content-type":"application/json"};r.token&&(o[b]=r.token);try{let a=await n(`${this.host}${e}`,{body:r.body===void 0?void 0:JSON.stringify(r.body),headers:o,method:t}),i=await a.text();return a.ok?i?JSON.parse(i):{}:(this.options.onError?.(new Error(`prodantix chat ${e}: ${a.status}`)),null)}catch(a){return this.options.onError?.(a),null}}};var v={agentLabel:"Agent",aiLabel:"AI",closeLabel:"Close chat",inputPlaceholder:"Type a message",launcherLabel:"Open support chat",sendLabel:"Send",title:"Support",unreadLabel:s=>`${s} unread`},y=`
|
|
2
|
+
:host { all: initial; }
|
|
3
|
+
* { box-sizing: border-box; font-family: system-ui, sans-serif; }
|
|
4
|
+
.launcher {
|
|
5
|
+
position: fixed; right: 20px; bottom: 20px; width: 56px; height: 56px;
|
|
6
|
+
border-radius: 28px; border: none; cursor: pointer;
|
|
7
|
+
background: #16a34a; color: #fff; font-size: 24px;
|
|
8
|
+
box-shadow: 0 4px 12px rgba(0,0,0,.2);
|
|
9
|
+
}
|
|
10
|
+
.launcher:focus-visible { outline: 3px solid #0b0e14; outline-offset: 2px; }
|
|
11
|
+
.badge {
|
|
12
|
+
position: absolute; top: -4px; right: -4px; min-width: 20px; height: 20px;
|
|
13
|
+
border-radius: 10px; background: #dc2626; color: #fff; font-size: 12px;
|
|
14
|
+
display: flex; align-items: center; justify-content: center; padding: 0 4px;
|
|
15
|
+
}
|
|
16
|
+
.panel {
|
|
17
|
+
position: fixed; right: 20px; bottom: 88px; width: 360px; max-width: calc(100vw - 40px);
|
|
18
|
+
height: 520px; max-height: calc(100vh - 120px); background: #fff; color: #0f172a;
|
|
19
|
+
border-radius: 12px; box-shadow: 0 8px 32px rgba(0,0,0,.24);
|
|
20
|
+
display: flex; flex-direction: column; overflow: hidden;
|
|
21
|
+
}
|
|
22
|
+
.header { padding: 14px 16px; background: #0b0e14; color: #fff; display: flex; align-items: center; justify-content: space-between; }
|
|
23
|
+
.header h2 { margin: 0; font-size: 15px; }
|
|
24
|
+
.close { background: none; border: none; color: #fff; cursor: pointer; font-size: 18px; }
|
|
25
|
+
.close:focus-visible { outline: 2px solid #fff; }
|
|
26
|
+
.log { flex: 1; overflow-y: auto; padding: 12px; display: flex; flex-direction: column; gap: 8px; }
|
|
27
|
+
.turn { max-width: 80%; padding: 8px 12px; border-radius: 12px; font-size: 14px; }
|
|
28
|
+
.turn.end_user { align-self: flex-end; background: #16a34a; color: #fff; }
|
|
29
|
+
.turn.agent, .turn.ai { align-self: flex-start; background: #f1f5f9; color: #0f172a; }
|
|
30
|
+
.author { font-size: 11px; opacity: .7; margin-bottom: 2px; }
|
|
31
|
+
.composer { display: flex; gap: 8px; padding: 12px; border-top: 1px solid #e2e8f0; }
|
|
32
|
+
.composer input { flex: 1; padding: 8px 10px; border: 1px solid #cbd5e1; border-radius: 8px; font-size: 14px; }
|
|
33
|
+
.composer input:focus-visible { outline: 2px solid #16a34a; }
|
|
34
|
+
.composer button { padding: 8px 14px; background: #16a34a; color: #fff; border: none; border-radius: 8px; cursor: pointer; }
|
|
35
|
+
.composer button:focus-visible { outline: 2px solid #0b0e14; }
|
|
36
|
+
@media (prefers-reduced-motion: no-preference) {
|
|
37
|
+
.panel { animation: rise 180ms ease-out; }
|
|
38
|
+
@keyframes rise { from { transform: translateY(8px); opacity: 0; } to { transform: none; opacity: 1; } }
|
|
39
|
+
}
|
|
40
|
+
`,C=["end_user","agent","ai"],u=class{constructor(t,e,r={}){this.host=t;this.client=e;a(this,"root");a(this,"strings");a(this,"launcher");a(this,"badge");a(this,"panel",null);a(this,"lastFocused",null);a(this,"unread",0);this.strings={...v,...r},this.root=t.attachShadow({mode:"closed"});let n=document.createElement("style");n.textContent=y,this.root.append(n),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 t=document.createElement("section");t.className="panel",t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-label",this.strings.title);let e=document.createElement("div");e.className="header";let r=document.createElement("h2");r.textContent=this.strings.title;let n=document.createElement("button");n.className="close",n.type="button",n.setAttribute("aria-label",this.strings.closeLabel),n.textContent="\xD7",n.addEventListener("click",()=>this.close()),e.append(r,n);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 i=document.createElement("input");i.type="text",i.setAttribute("aria-label",this.strings.inputPlaceholder),i.placeholder=this.strings.inputPlaceholder;let c=document.createElement("button");c.type="submit",c.textContent=this.strings.sendLabel,a.append(i,c),a.addEventListener("submit",d=>{d.preventDefault(),this.submit(i,o);}),t.append(e,o,a),t.addEventListener("keydown",d=>this.onKeydown(d,t,n)),this.root.append(t),this.panel=t,i.focus();let p=await this.client.load();p&&this.renderThread(o,p);}close(){this.panel&&(this.panel.remove(),this.panel=null,this.lastFocused instanceof HTMLElement?this.lastFocused.focus():this.launcher.focus());}onIncomingTurn(t){if(this.panel){let e=this.panel.querySelector(".log");e instanceof HTMLElement&&this.appendTurn(e,t);return}t.authorKind!=="end_user"&&(this.unread+=1,this.renderBadge());}async submit(t,e){let r=t.value.trim();if(!r)return;t.value="";let n=await this.client.send(r);n&&this.appendTurn(e,n);}renderThread(t,e){t.replaceChildren();for(let r of e.turns)this.appendTurn(t,r);}appendTurn(t,e){let r=C.includes(e.authorKind)?e.authorKind:"agent",n=document.createElement("div");if(n.className=`turn ${r}`,r!=="end_user"){let a=document.createElement("div");a.className="author",a.textContent=r==="ai"?this.strings.aiLabel:this.strings.agentLabel,n.append(a);}let o=document.createElement("div");o.textContent=e.body,n.append(o),t.append(n),t.scrollTop=t.scrollHeight;}onKeydown(t,e,r){if(t.key==="Escape"){t.preventDefault(),this.close();return}if(t.key!=="Tab")return;let n=e.querySelectorAll('button, input, [tabindex]:not([tabindex="-1"])');if(n.length===0)return;let o=n[0],a=n[n.length-1],i=this.root.activeElement;t.shiftKey&&i===o?(t.preventDefault(),a.focus()):!t.shiftKey&&i===a?(t.preventDefault(),o.focus()):i===null&&(t.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 H(s){let t=globalThis.document;if(!t)throw new Error("prodantix chat requires a document; mount it in the browser");let e=s.mountPoint??t.createElement("div");s.mountPoint||t.body.append(e);let r=new h(s),n=new u(e,r,s.strings),o=new Set,a,i=s.pollIntervalMs??15e3;return i>0&&(a=setInterval(async()=>{if(!r.hasThread)return;let c=await r.load();if(!c)return;let p=new Set(c.turns.map(d=>d.id));for(let d of c.turns)!o.has(d.id)&&d.authorKind!=="end_user"&&n.onIncomingTurn(d);o=p;},i)),{close:()=>n.close(),destroy:()=>{a&&clearInterval(a),n.close(),e.remove();},open:()=>void n.open()}}export{h as ChatClient,u as ChatPanel,H as mountChat};//# sourceMappingURL=chat.js.map
|
|
41
|
+
//# sourceMappingURL=chat.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a,b as b$1,e,c,d as d$1}from'./chunk-STIKBPFF.js';var u=class extends Error{constructor(s,r,i){super(r,i);a(this,"code");this.code=s,this.name="ProdantixError";}},y=class extends u{constructor(e){super("config",e),this.name="ConfigError";}},m=class extends u{constructor(s,r){super("validation",r);a(this,"field");this.field=s,this.name="ValidationError";}},d=class extends u{constructor(s,r,i){super("transport",s,i);a(this,"status");this.status=r,this.name="TransportError";}};var g=class{constructor(){a(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,s){this.store.set(e,s);}};function ne(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new g}return new g}var k="prodantix-js",_="0.0.1";var h=Symbol("absent");function z(t,e){if(t==="distinct_id")return e.distinctId;let s=e.properties??{};if(Object.prototype.hasOwnProperty.call(s,t))return s[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:h}function p(t){return t===h?"undefined":String(t)}function C(t){return t===h?Number.NaN:Number(t)}function P(t){return t!==h&&t!==null&&t!==""}function R(t,e){if(!Array.isArray(e))return false;let s=p(t);return e.map(r=>String(r)).includes(s)}function M(t,e){let s=z(t.attribute,e),r=t.value;switch(t.op){case "is_set":return P(s);case "is_not_set":return !P(s);case "eq":return p(s)===p(r===void 0?h:r);case "neq":return p(s)!==p(r===void 0?h:r);case "contains":return p(s).includes(p(r===void 0?h:r));case "in":return R(s,r);case "not_in":return Array.isArray(r)?!R(s,r):false;case "gt":return v(s,r,(i,o)=>i>o);case "gte":return v(s,r,(i,o)=>i>=o);case "lt":return v(s,r,(i,o)=>i<o);case "lte":return v(s,r,(i,o)=>i<=o);default:return false}}function v(t,e,s){let r=C(t),i=e===void 0?Number.NaN:C(e);return Number.isNaN(r)||Number.isNaN(i)?false:s(r,i)}function J(t,e){let s=`${t}:${e}`,r=2166136261;for(let i=0;i<s.length;i++)r^=s.charCodeAt(i),r=Math.imul(r,16777619);return (r>>>0)%100}function Q(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(s=>M(s,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:J(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function q(t,e){let s={};for(let r of t)s[r.key]=Q(r,e).enabled;return s}var x=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=b$1(e$1.fetch),this.host=e(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async fetchAll(e){let s=this.fetch;if(!s)throw new d("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,i=c(),o=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{let a=await s(r,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:i?.signal});if(!a.ok)throw new d(`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 d("no fetch implementation available in this runtime");let s=`${this.host}/v1/flags/snapshot`,r=c(),i=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let o=await e(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.signal});if(!o.ok)throw new d(`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{i!==void 0&&clearTimeout(i);}}};var b=class{constructor(e$1){a(this,"fetch");a(this,"host");a(this,"projectKey");a(this,"requestTimeoutMs");this.fetch=b$1(e$1.fetch),this.host=e(e$1.host),this.projectKey=e$1.projectKey,this.requestTimeoutMs=e$1.requestTimeoutMs??1e4;}async inbox(e){let s=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,i=await this.request(s,r,{headers:this.authHeaders(),method:"GET"});if(!i.ok)throw new d(`inbox request failed with status ${i.status}`,i.status);return JSON.parse(await i.text()).messages??[]}async markRead(e,s){let r=this.requireFetch(),i=`${this.host}/v1/messages/read`,o=await this.request(r,i,{body:JSON.stringify({distinct_id:s,message_id:e}),headers:{...this.authHeaders(),"content-type":"application/json"},method:"POST"});if(!o.ok)throw new d(`mark-read request failed with status ${o.status}`,o.status)}requireFetch(){if(!this.fetch)throw new d("no fetch implementation available in this runtime");return this.fetch}authHeaders(){return {authorization:`Bearer ${this.projectKey}`}}async request(e,s,r){let i=c(),o=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(s,{...r,signal:i?.signal})}finally{o!==void 0&&clearTimeout(o);}}};function $(t){return t>=400&&t<500&&t!==429}var I=class{constructor(e={}){a(this,"fetch");a(this,"maxRetries");a(this,"requestTimeoutMs");a(this,"baseDelayMs");a(this,"maxDelayMs");a(this,"sleep");a(this,"random");this.fetch=b$1(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$1,this.random=e.random??Math.random;}async send(e){let s=this.fetch;if(!s)throw new d("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),i;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(s,e,r);if(a.ok)return;if($(a.status))throw new d(`ingest rejected batch with status ${a.status}`,a.status);i=new d(`ingest transient status ${a.status}`,a.status);}catch(a){if(a instanceof d&&a.status!==void 0&&$(a.status))throw a;i=a;}o<this.maxRetries&&await this.sleep(this.backoff(o));}throw new d("ingest delivery failed after retries",void 0,{cause:i})}async attempt(e,s,r){let i=c(),o=i?setTimeout(()=>i.abort(),this.requestTimeoutMs):void 0;try{return await e(s.url,{body:r,headers:{authorization:`Bearer ${s.projectKey}`,"content-type":"application/json"},method:"POST",signal:i?.signal})}finally{o!==void 0&&clearTimeout(o);}}backoff(e){return Math.min(this.maxDelayMs,this.baseDelayMs*2**e)+this.random()*this.baseDelayMs}};var A={now:()=>new Date};function E(t){return t.toISOString()}function U(){return globalThis.crypto}function B(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;let e=[];for(let s=0;s<16;s+=1)e.push(t[s].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 H(){let t=U();if(t?.randomUUID)return t.randomUUID();let e=new Uint8Array(16);if(t?.getRandomValues)t.getRandomValues(e);else for(let s=0;s<16;s+=1)e[s]=Math.floor(Math.random()*256);return B(e)}var N={uuid:H};var G=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var X=/^(?:\$|[a-z])[a-z0-9_.]*$/;function O(t){let e=0;for(let s of t)e+=1;return e}function D(t){return G.test(t)}function Y(t){return X.test(t)}function K(t){let e=O(t);if(e<1||e>200)throw new m("distinct_id","distinct_id must be between 1 and 200 characters")}function L(t){let e=O(t);if(e<1||e>200)throw new m("event_name","event_name must be between 1 and 200 characters");if(!Y(t))throw new m("event_name","event_name must match /^(\\$|[a-z])[a-z0-9_.]*$/")}var Z=t=>{};function j(t){if(!t.apiKey||!D(t.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new y("host is required (the ingest base URL)");let e$1=e(t.host),s=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??A,defaultProperties:typeof s=="function"?s:()=>s??{},flagsHost:t.flagsHost?e(t.flagsHost):e$1,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e$1,ids:t.ids??N,locale:t.locale,maxQueueSize:t.maxQueueSize??1e3,maxRetries:t.maxRetries??3,namespace:t.apiKey.slice(0,16),onError:t.onError??Z,os:t.os,requestTimeoutMs:t.requestTimeoutMs??1e4,sdkName:t.sdkName??k,sdkVersion:t.sdkVersion??_,storage:t.storage??new g,transport:t.transport}}function V(t,e,s){L(t.eventName),K(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??s.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:E(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var w=class{constructor(e,s,r){this.storage=e;this.ids=s;this.namespace=r;a(this,"anonymousId");a(this,"distinctId");a(this,"identified");let i=e.getItem(this.key("anonymous_id"));i?this.anonymousId=i:(this.anonymousId=s.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 F=class{constructor(e,s){this.maxSize=e;this.onOverflow=s;a(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 s=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,s)}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 W="queue",ee=1e3,te=3e4,T=class{constructor(e){a(this,"config");a(this,"identity");a(this,"queue");a(this,"transport");a(this,"flagsClient");a(this,"messagesClient");a(this,"context");a(this,"flushTimer");a(this,"flushing",false);a(this,"cachedFlags");a(this,"cachedSnapshot");this.config=j(e),this.identity=new w(this.config.storage,this.config.ids,this.config.namespace),this.queue=new F(this.config.maxQueueSize,({dropped:s})=>{this.config.onError(new u("queue_overflow",`event queue overflow: dropped ${s.length} oldest event(s)`));}),this.transport=this.config.transport??new I({maxRetries:this.config.maxRetries,requestTimeoutMs:this.config.requestTimeoutMs}),this.flagsClient=new x({host:this.config.flagsHost,projectKey:this.config.apiKey,requestTimeoutMs:this.config.requestTimeoutMs}),this.messagesClient=new b({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,s={}){try{let r={...this.config.defaultProperties(),...s.properties??{}},i=V({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:s.sessionId,timestamp:s.timestamp},this.config.clock,this.config.ids);this.enqueue(i);}catch(r){this.config.onError(r);}}identify(e,s={}){let r=this.identity.getAnonymousId(),i=!this.identity.isIdentified(),o=this.identity.identify(e),a={};i&&o.changed&&(a.$anon_distinct_id=r),s.set&&(a.$set=s.set),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,s,r){let i={$group_key:s,$group_type:e};r&&(i.$set=r),this.capture("$group",{properties:i});}setPersonProperties(e,s){let r={};e&&(r.$set=e),s&&(r.$set_once=s),this.capture("$set",{properties:r});}async getAllFlags(){let e=this.identity.getDistinctId(),s=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:s},s}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 s=await this.flagSnapshot();return q(s.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,s){return (await this.getLocalFlags(s))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<te)return this.cachedSnapshot.snapshot;let s=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:s},s}async getInbox(){return this.messagesClient.inbox(this.identity.getDistinctId())}async markMessageRead(e){await this.messagesClient.markRead(e,this.identity.getDistinctId());}async flush(){if(this.flushing||this.queue.size===0)return;this.flushing=true;let e=this.queue.drain(ee);try{await this.transport.send({body:{events:e,sent_at:E(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(s){this.queue.requeue(e),this.persistQueue(),this.config.onError(s);}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 s=JSON.parse(e);Array.isArray(s)&&this.queue.restore(s);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),s=e;typeof s.unref=="function"&&s.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${W}`}};function We(t){return new T(t)}export{u as a,y as b,m as c,d,g as e,ne as f,H as g,k as h,_ as i,M as j,J as k,Q as l,q as m,x as n,b as o,I as p,T as q,We as r};//# sourceMappingURL=chunk-AMUIQXH2.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-AMUIQXH2.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var n=Object.defineProperty;var o=(e,t,r)=>t in e?n(e,t,{enumerable:true,configurable:true,writable:true,value:r}):e[t]=r;var i=(e,t,r)=>o(e,typeof t!="symbol"?t+"":t,r);function l(e){if(e)return e;let t=globalThis.fetch;if(typeof t=="function")return t.bind(globalThis)}function c(){let e=globalThis.AbortController;return e?new e:void 0}var u=e=>new Promise(t=>{setTimeout(t,e);});function a(e){return e.replace(/\/+$/,"")}export{i as a,l as b,c,u as d,a as e};//# sourceMappingURL=chunk-STIKBPFF.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-STIKBPFF.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
interface FetchResponseLike {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
status: number;
|
|
4
|
+
text(): Promise<string>;
|
|
5
|
+
}
|
|
6
|
+
interface FetchInit {
|
|
7
|
+
body?: string;
|
|
8
|
+
headers: Record<string, string>;
|
|
9
|
+
method: string;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
13
|
+
|
|
14
|
+
export type { FetchLike as F };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
interface FetchResponseLike {
|
|
2
|
+
ok: boolean;
|
|
3
|
+
status: number;
|
|
4
|
+
text(): Promise<string>;
|
|
5
|
+
}
|
|
6
|
+
interface FetchInit {
|
|
7
|
+
body?: string;
|
|
8
|
+
headers: Record<string, string>;
|
|
9
|
+
method: string;
|
|
10
|
+
signal?: AbortSignal;
|
|
11
|
+
}
|
|
12
|
+
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
13
|
+
|
|
14
|
+
export type { FetchLike as F };
|
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { J as JsonValue, f as InboxMessage, S as StorageAdapter } from './client-B1bcIuD8.cjs';
|
|
2
2
|
export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse, I as IdFactory, e as IdentifyOptions, g as InboxResponse, L as LocalFlagContext, P as ProdantixClient, h as ProdantixConfig, T as Transport, i as TransportRequest, j as createClient } from './client-B1bcIuD8.cjs';
|
|
3
|
-
import { F as FetchLike } from './
|
|
4
|
-
export {
|
|
3
|
+
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
4
|
+
export { F as FetchTransport } from './transport-BOmEPpCa.cjs';
|
|
5
5
|
|
|
6
6
|
type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
|
|
7
7
|
declare class ProdantixError extends Error {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { J as JsonValue, f as InboxMessage, S as StorageAdapter } from './client-B1bcIuD8.js';
|
|
2
2
|
export { C as CaptureOptions, a as Clock, E as EventBatch, b as EventContext, c as EventEnvelope, d as EventProperties, F as FlagsResponse, I as IdFactory, e as IdentifyOptions, g as InboxResponse, L as LocalFlagContext, P as ProdantixClient, h as ProdantixConfig, T as Transport, i as TransportRequest, j as createClient } from './client-B1bcIuD8.js';
|
|
3
|
-
import { F as FetchLike } from './
|
|
4
|
-
export {
|
|
3
|
+
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
4
|
+
export { F as FetchTransport } from './transport-B7A4sAOI.js';
|
|
5
5
|
|
|
6
6
|
type ProdantixErrorCode = 'config' | 'queue_overflow' | 'transport' | 'validation';
|
|
7
7
|
declare class ProdantixError extends Error {
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{
|
|
1
|
+
export{b as ConfigError,p as FetchTransport,n as FlagsClient,e as MemoryStorage,o as MessagesClient,q as ProdantixClient,a as ProdantixError,h as SDK_NAME,i as SDK_VERSION,d as TransportError,c as ValidationError,k as bucket,r as createClient,m as evaluateAll,l as evaluateFlag,j as matches}from'./chunk-AMUIQXH2.js';import'./chunk-STIKBPFF.js';//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/node.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {q}from'./chunk-AMUIQXH2.js';import'./chunk-STIKBPFF.js';function t(){return globalThis.process}function s(o){t()?.on("beforeExit",()=>{o.flush();});}function f(o){let e=t(),r={...o,os:o.os??(e?.platform?e.platform.slice(0,50):void 0)},n=new q(r);return s(n),n}export{f as createNodeClient};//# sourceMappingURL=node.js.map
|
|
2
2
|
//# sourceMappingURL=node.js.map
|
|
@@ -1,18 +1,6 @@
|
|
|
1
|
+
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
1
2
|
import { T as Transport, i as TransportRequest } from './client-B1bcIuD8.js';
|
|
2
3
|
|
|
3
|
-
interface FetchResponseLike {
|
|
4
|
-
ok: boolean;
|
|
5
|
-
status: number;
|
|
6
|
-
text(): Promise<string>;
|
|
7
|
-
}
|
|
8
|
-
interface FetchInit {
|
|
9
|
-
body?: string;
|
|
10
|
-
headers: Record<string, string>;
|
|
11
|
-
method: string;
|
|
12
|
-
signal?: AbortSignal;
|
|
13
|
-
}
|
|
14
|
-
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
15
|
-
|
|
16
4
|
interface FetchTransportOptions {
|
|
17
5
|
baseDelayMs?: number;
|
|
18
6
|
fetch?: FetchLike;
|
|
@@ -36,4 +24,4 @@ declare class FetchTransport implements Transport {
|
|
|
36
24
|
private backoff;
|
|
37
25
|
}
|
|
38
26
|
|
|
39
|
-
export {
|
|
27
|
+
export { FetchTransport as F, type FetchTransportOptions as a };
|
|
@@ -1,18 +1,6 @@
|
|
|
1
|
+
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
1
2
|
import { T as Transport, i as TransportRequest } from './client-B1bcIuD8.cjs';
|
|
2
3
|
|
|
3
|
-
interface FetchResponseLike {
|
|
4
|
-
ok: boolean;
|
|
5
|
-
status: number;
|
|
6
|
-
text(): Promise<string>;
|
|
7
|
-
}
|
|
8
|
-
interface FetchInit {
|
|
9
|
-
body?: string;
|
|
10
|
-
headers: Record<string, string>;
|
|
11
|
-
method: string;
|
|
12
|
-
signal?: AbortSignal;
|
|
13
|
-
}
|
|
14
|
-
type FetchLike = (url: string, init: FetchInit) => Promise<FetchResponseLike>;
|
|
15
|
-
|
|
16
4
|
interface FetchTransportOptions {
|
|
17
5
|
baseDelayMs?: number;
|
|
18
6
|
fetch?: FetchLike;
|
|
@@ -36,4 +24,4 @@ declare class FetchTransport implements Transport {
|
|
|
36
24
|
private backoff;
|
|
37
25
|
}
|
|
38
26
|
|
|
39
|
-
export {
|
|
27
|
+
export { FetchTransport as F, type FetchTransportOptions as a };
|
package/dist/web.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { P as ProdantixClient, T as Transport, i as TransportRequest, h as ProdantixConfig } from './client-B1bcIuD8.cjs';
|
|
2
|
-
import {
|
|
2
|
+
import { a as FetchTransportOptions } from './transport-BOmEPpCa.cjs';
|
|
3
|
+
import { F as FetchLike } from './http-BCh716Vs.cjs';
|
|
3
4
|
|
|
4
5
|
interface AutocaptureOptions {
|
|
5
6
|
clicks?: boolean;
|
package/dist/web.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { P as ProdantixClient, T as Transport, i as TransportRequest, h as ProdantixConfig } from './client-B1bcIuD8.js';
|
|
2
|
-
import {
|
|
2
|
+
import { a as FetchTransportOptions } from './transport-B7A4sAOI.js';
|
|
3
|
+
import { F as FetchLike } from './http-BCh716Vs.js';
|
|
3
4
|
|
|
4
5
|
interface AutocaptureOptions {
|
|
5
6
|
clicks?: boolean;
|
package/dist/web.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {p,g as g$1,f as f$1,q as q$1}from'./chunk-AMUIQXH2.js';import {a,b,e}from'./chunk-STIKBPFF.js';function w(){return globalThis.location}function S(){return globalThis.document}function D(){return globalThis.window??globalThis}function V(e){return typeof e=="object"&&e!==null&&typeof e.tagName=="string"}function O(){let e=w(),t=S(),n={};return e&&(n.$current_url=e.href,n.$pathname=e.pathname,n.$host=e.host),t&&(t.title&&(n.$title=t.title),t.referrer&&(n.$referrer=t.referrer)),n}function H(e){let t={$el_tag:e.tagName.toLowerCase(),$event_type:"click"},n=e.textContent?.trim();n&&(t.$el_text=n.slice(0,255)),e.id&&(t.$el_id=e.id),typeof e.className=="string"&&e.className&&(t.$el_classes=e.className);let i=e.getAttribute("href");return i&&(t.$el_href=i),t}function $(e){let t=globalThis.history,n=D(),i="",r=()=>{let a=w(),l=a?`${a.pathname}${a.search}`:"";l!==i&&(i=l,e.capture("$pageview",{properties:O()}));};if(r(),!t||!n)return ()=>{};let s=t.pushState.bind(t),p=t.replaceState.bind(t);return t.pushState=(...a)=>{s(...a),r();},t.replaceState=(...a)=>{p(...a),r();},n.addEventListener("popstate",r),()=>{t.pushState=s,t.replaceState=p,n.removeEventListener("popstate",r);}}function K(e){let t=S();if(!t)return ()=>{};let n=i=>{let r=i.target;V(r)&&e.capture("$autocapture",{properties:{...O(),...H(r)}});};return t.addEventListener("click",n,true),()=>t.removeEventListener("click",n,true)}function I(e,t={}){let n=[];return (t.pageviews??true)&&n.push($(e)),(t.clicks??true)&&n.push(K(e)),()=>{for(let i of n)i();}}function F(){return globalThis.document?.visibilityState==="hidden"}function B(e){let t=globalThis.navigator,n=globalThis.Blob;if(!t?.sendBeacon||!n)return false;let i=JSON.stringify({...e.body,api_key:e.projectKey});try{let r=new n([i],{type:"application/json"});return t.sendBeacon(e.url,r)}catch{return false}}var c=class{constructor(t={}){a(this,"fetchTransport");this.fetchTransport=new p(t);}async send(t){F()&&B(t)||await this.fetchTransport.send(t);}};var R={maskAllInputs:true,maskAllText:false},W=new Set(["email","password","tel"]);function A(e){return e.replace(/\S/g,"*")}function d(e,t,n){return z(t)||n.maskAllInputs?A(e):e}function f(e,t){return t.maskAllText?A(e):e}function z(e){return W.has((e??"").toLowerCase())}var U=5e3,m=class{constructor(t){this.options=t;a(this,"buffer",[]);a(this,"seq",0);a(this,"maxEvents");this.maxEvents=Math.min(Math.max(1,t.maxEvents),U);}add(t){return this.buffer.push(t),this.buffer.length>=this.maxEvents?this.flush():null}flush(){if(this.buffer.length===0)return null;let t=this.buffer;this.buffer=[];let n={distinct_id:this.options.distinctId(),events:t,masked:this.options.masked,schema_version:1,seq:this.seq,session_id:this.options.sessionId,timestamp:new Date(this.options.now()).toISOString()};return this.seq+=1,n}};var v=1,k=3,q=9,h=class{constructor(){a(this,"next",1);}allocate(){let t=this.next;return this.next+=1,t}},j=new Set(["NOSCRIPT","SCRIPT"]);function g(e,t,n,i){if(e.nodeType===k){let r=t.allocate();return i?.(e,r),{id:r,textContent:f(e.textValue??"",n),type:"text"}}if(e.nodeType===q){let r=t.allocate();return i?.(e,r),{childNodes:M(e,t,n,i),id:r,type:"document"}}if(e.nodeType===v){let r=e.tagName??"";if(j.has(r))return null;let s=t.allocate();return i?.(e,s),{attributes:X(e,n),childNodes:M(e,t,n,i),id:s,tagName:r,type:"element"}}return null}function M(e,t,n,i){let r=[];for(let s of e.childNodes??[]){let p=g(s,t,n,i);p&&r.push(p);}return r}function X(e,t){let n={};for(let i of e.attributes??[])n[i.name]=i.value;return e.inputValue!==void 0&&(n.value=d(e.inputValue,e.inputType,t)),n}async function P(e$1,t){let n=`${e(t.replayHost)}/v1/replay`;return (await t.fetch(n,{body:JSON.stringify(e$1),headers:{authorization:`Bearer ${t.apiKey}`,"content-type":"application/json"},method:"POST"})).ok}var C=new Set(["INPUT","SELECT","TEXTAREA"]),y=class{constructor(t){this.options=t;a(this,"allocator",new h);a(this,"mirror",new Map);a(this,"chunker");a(this,"fetchImpl");a(this,"observer");a(this,"timer");a(this,"started",false);this.chunker=new m({distinctId:t.distinctId,masked:t.mask.maskAllInputs,maxEvents:t.maxEvents,now:t.now,sessionId:t.sessionId}),this.fetchImpl=b(t.fetch);}start(){if(this.started)return;let t=Y(),n=t?.documentElement;!t||!n||!this.fetchImpl||(this.started=true,this.captureFullSnapshot(n),this.observeMutations(n),this.observeInteractions(t),this.timer=setInterval(()=>this.upload(this.chunker.flush()),this.options.flushIntervalMs));}stop(){this.started&&(this.started=false,this.observer?.disconnect(),this.timer&&clearInterval(this.timer),this.upload(this.chunker.flush()));}captureFullSnapshot(t){let n=g(this.adapt(t),this.allocator,this.options.mask,(i,r)=>{let s=i.ref;s&&this.mirror.set(s,r);});n&&this.push(2,{node:n});}observeMutations(t){let n=globalThis.MutationObserver;n&&(this.observer=new n(i=>{for(let r of i)this.handleMutation(r);}),this.observer.observe(t,{attributes:true,characterData:true,childList:true,subtree:true}));}handleMutation(t){if(t.type==="characterData"){let n=this.mirror.get(t.target);n!==void 0&&this.push(3,{texts:[{id:n,value:f(t.target.textContent??"",this.options.mask)}]});return}if(t.type==="attributes"&&t.attributeName){let n=this.mirror.get(t.target),i=t.target;n!==void 0&&this.push(3,{attributes:[{attributes:{[t.attributeName]:i.getAttribute(t.attributeName)??""},id:n}]});return}if(t.type==="childList"){let n=this.mirror.get(t.target);if(n===void 0)return;for(let i of Array.from(t.addedNodes)){let r=g(this.adapt(i),this.allocator,this.options.mask,(s,p)=>{let a=s.ref;a&&this.mirror.set(a,p);});r&&this.push(3,{adds:[{node:r,parentId:n}]});}for(let i of Array.from(t.removedNodes)){let r=this.mirror.get(i);r!==void 0&&(this.push(3,{removes:[{id:r,parentId:n}]}),this.mirror.delete(i));}}}observeInteractions(t){t.addEventListener("input",n=>{let i=n.target;if(!i||!C.has(i.tagName))return;let r=this.mirror.get(i);r!==void 0&&this.push(3,{input:{id:r,value:d(i.value??"",i.type,this.options.mask)}});},true),t.addEventListener("scroll",n=>{let i=n.target,r=i?this.mirror.get(i):void 0;this.push(3,{scroll:{id:r??0,x:i?.scrollLeft??0,y:i?.scrollTop??0}});},true);}adapt(t){let n={childNodes:[],nodeType:t.nodeType,ref:t};if(t.nodeType===k)return n.textValue=t.textContent??"",n;if(t.nodeType===v){let i=t;if(n.tagName=i.tagName,n.attributes=Array.from(i.attributes).map(r=>({name:r.name,value:r.value})),C.has(i.tagName)){let r=i;n.inputType=r.type,n.inputValue=r.value??"";}}return n.childNodes=Array.from(t.childNodes).map(i=>this.adapt(i)),n}push(t,n){let i=this.chunker.add({data:n,timestamp:this.options.now(),type:t});i&&this.upload(i);}upload(t){!t||!this.fetchImpl||P(t,{apiKey:this.options.apiKey,fetch:this.fetchImpl,replayHost:this.options.replayHost}).catch(n=>this.options.onError?.(n));}};function Y(){return globalThis.document}function _(e){let t=new y({apiKey:e.apiKey,distinctId:e.distinctId,flushIntervalMs:e.flushIntervalMs??5e3,mask:{...R,...e.mask},maxEvents:e.maxEvents??200,now:e.now??(()=>Date.now()),onError:e.onError,replayHost:e.replayHost,sessionId:e.sessionId??g$1()});return t.start(),t}function G(){return globalThis.navigator}function J(e){let t=e?.userAgentData?.platform??e?.platform;return t?t.slice(0,50):void 0}function Q(e){let t=()=>{e.flush();};globalThis.document?.addEventListener?.("visibilitychange",t),globalThis.addEventListener?.("pagehide",t);}function It(e){let{autocaptureOptions:t,replayHost:n,sessionReplay:i,sessionReplayOptions:r,...s}=e,p=G(),a={...s,locale:s.locale??(p?.language?p.language.slice(0,20):void 0),os:s.os??J(p),storage:s.storage??f$1(),transport:s.transport??new c({maxRetries:s.maxRetries,requestTimeoutMs:s.requestTimeoutMs})},l=new q$1(a);return Q(l),(e.autocapture??true)&&I(l,t),i&&n&&_({apiKey:a.apiKey,distinctId:()=>l.distinctId,onError:a.onError,replayHost:n,...r}),l}export{c as WebTransport,It as createWebClient,I as installAutocapture,_ as installSessionReplay};//# sourceMappingURL=web.js.map
|
|
2
2
|
//# sourceMappingURL=web.js.map
|
package/package.json
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
"description": "Prodantix analytics + feature-flag client SDK (isomorphic, zero-dependency)",
|
|
3
3
|
"devDependencies": {
|
|
4
4
|
"@bomdisoft/typescript-config": "0.0.0",
|
|
5
|
+
"@happy-dom/global-registrator": "^20.10.3",
|
|
5
6
|
"@types/bun": "^1.3.14",
|
|
6
7
|
"@types/node": "^25.9.3",
|
|
7
8
|
"tsup": "8.5.1",
|
|
@@ -13,6 +14,11 @@
|
|
|
13
14
|
"require": "./dist/index.cjs",
|
|
14
15
|
"types": "./dist/index.d.ts"
|
|
15
16
|
},
|
|
17
|
+
"./chat": {
|
|
18
|
+
"import": "./dist/chat.js",
|
|
19
|
+
"require": "./dist/chat.cjs",
|
|
20
|
+
"types": "./dist/chat.d.ts"
|
|
21
|
+
},
|
|
16
22
|
"./node": {
|
|
17
23
|
"import": "./dist/node.js",
|
|
18
24
|
"require": "./dist/node.cjs",
|
|
@@ -47,5 +53,5 @@
|
|
|
47
53
|
"sideEffects": false,
|
|
48
54
|
"type": "module",
|
|
49
55
|
"types": "./dist/index.d.ts",
|
|
50
|
-
"version": "0.0.1-beta.
|
|
56
|
+
"version": "0.0.1-beta.324"
|
|
51
57
|
}
|
package/dist/chunk-FIZWZVZG.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
var z=Object.defineProperty;var J=(t,e,s)=>e in t?z(t,e,{enumerable:true,configurable:true,writable:true,value:s}):t[e]=s;var i=(t,e,s)=>J(t,typeof e!="symbol"?e+"":e,s);var d=class extends Error{constructor(s,r,n){super(r,n);i(this,"code");this.code=s,this.name="ProdantixError";}},y=class extends d{constructor(e){super("config",e),this.name="ConfigError";}},f=class extends d{constructor(s,r){super("validation",r);i(this,"field");this.field=s,this.name="ValidationError";}},l=class extends d{constructor(s,r,n){super("transport",s,n);i(this,"status");this.status=r,this.name="TransportError";}};var m=class{constructor(){i(this,"store",new Map);}getItem(e){return this.store.get(e)??null}removeItem(e){this.store.delete(e);}setItem(e,s){this.store.set(e,s);}};function le(){try{let t=globalThis.localStorage;if(t){let e="__pdx_probe__";return t.setItem(e,"1"),t.removeItem(e),t}}catch{return new m}return new m}var T="prodantix-js",S="0.0.1";var u=Symbol("absent");function Q(t,e){if(t==="distinct_id")return e.distinctId;let s=e.properties??{};if(Object.prototype.hasOwnProperty.call(s,t))return s[t];let r=e.attributes??{};return Object.prototype.hasOwnProperty.call(r,t)?r[t]:u}function c(t){return t===u?"undefined":String(t)}function C(t){return t===u?Number.NaN:Number(t)}function _(t){return t!==u&&t!==null&&t!==""}function P(t,e){if(!Array.isArray(e))return false;let s=c(t);return e.map(r=>String(r)).includes(s)}function R(t,e){let s=Q(t.attribute,e),r=t.value;switch(t.op){case "is_set":return _(s);case "is_not_set":return !_(s);case "eq":return c(s)===c(r===void 0?u:r);case "neq":return c(s)!==c(r===void 0?u:r);case "contains":return c(s).includes(c(r===void 0?u:r));case "in":return P(s,r);case "not_in":return Array.isArray(r)?!P(s,r):false;case "gt":return v(s,r,(n,o)=>n>o);case "gte":return v(s,r,(n,o)=>n>=o);case "lt":return v(s,r,(n,o)=>n<o);case "lte":return v(s,r,(n,o)=>n<=o);default:return false}}function v(t,e,s){let r=C(t),n=e===void 0?Number.NaN:C(e);return Number.isNaN(r)||Number.isNaN(n)?false:s(r,n)}function U(t,e){let s=`${t}:${e}`,r=2166136261;for(let n=0;n<s.length;n++)r^=s.charCodeAt(n),r=Math.imul(r,16777619);return (r>>>0)%100}function B(t,e){return t.enabled?t.targeting.length>0&&!t.targeting.every(s=>R(s,e))?{enabled:false,reason:"targeting"}:t.rolloutPercentage>=100?{enabled:true,reason:"rollout_full"}:U(t.key,e.distinctId)<t.rolloutPercentage?{enabled:true,reason:"rollout"}:{enabled:false,reason:"rollout_excluded"}:{enabled:false,reason:"disabled"}}function M(t,e){let s={};for(let r of t)s[r.key]=B(r,e).enabled;return s}function g(t){if(t)return t;let e=globalThis.fetch;if(typeof e=="function")return e.bind(globalThis)}function p(){let t=globalThis.AbortController;return t?new t:void 0}var A=t=>new Promise(e=>{setTimeout(e,t);});function h(t){return t.replace(/\/+$/,"")}var b=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=g(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async fetchAll(e){let s=this.fetch;if(!s)throw new l("no fetch implementation available in this runtime");let r=`${this.host}/v1/flags?distinct_id=${encodeURIComponent(e)}`,n=p(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{let a=await s(r,{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 s=`${this.host}/v1/flags/snapshot`,r=p(),n=r?setTimeout(()=>r.abort(),this.requestTimeoutMs):void 0;try{let o=await e(s,{headers:{authorization:`Bearer ${this.projectKey}`},method:"GET",signal:r?.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 x=class{constructor(e){i(this,"fetch");i(this,"host");i(this,"projectKey");i(this,"requestTimeoutMs");this.fetch=g(e.fetch),this.host=h(e.host),this.projectKey=e.projectKey,this.requestTimeoutMs=e.requestTimeoutMs??1e4;}async inbox(e){let s=this.requireFetch(),r=`${this.host}/v1/messages?distinct_id=${encodeURIComponent(e)}`,n=await this.request(s,r,{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,s){let r=this.requireFetch(),n=`${this.host}/v1/messages/read`,o=await this.request(r,n,{body:JSON.stringify({distinct_id:s,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,s,r){let n=p(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(s,{...r,signal:n?.signal})}finally{o!==void 0&&clearTimeout(o);}}};function q(t){return t>=400&&t<500&&t!==429}var I=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=g(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??A,this.random=e.random??Math.random;}async send(e){let s=this.fetch;if(!s)throw new l("no fetch implementation available in this runtime");let r=JSON.stringify(e.body),n;for(let o=0;o<=this.maxRetries;o+=1){try{let a=await this.attempt(s,e,r);if(a.ok)return;if(q(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&&q(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,s,r){let n=p(),o=n?setTimeout(()=>n.abort(),this.requestTimeoutMs):void 0;try{return await e(s.url,{body:r,headers:{authorization:`Bearer ${s.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 $={now:()=>new Date};function E(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 s=0;s<16;s+=1)e.push(t[s].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 s=0;s<16;s+=1)e[s]=Math.floor(Math.random()*256);return G(e)}var N={uuid:X};var Y=/^pdx_pub_(?:(?:live|test)_)?[a-z0-9]{32}$/;var Z=/^(?:\$|[a-z])[a-z0-9_.]*$/;function O(t){let e=0;for(let s of t)e+=1;return e}function D(t){return Y.test(t)}function W(t){return Z.test(t)}function K(t){let e=O(t);if(e<1||e>200)throw new f("distinct_id","distinct_id must be between 1 and 200 characters")}function L(t){let e=O(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 ee=t=>{};function j(t){if(!t.apiKey||!D(t.apiKey))throw new y("apiKey must be a public project key of the form pdx_pub_<32 lowercase alphanumerics>");if(!t.host)throw new y("host is required (the ingest base URL)");let e=h(t.host),s=t.defaultProperties;return {apiKey:t.apiKey,autocapture:t.autocapture??false,clock:t.clock??$,defaultProperties:typeof s=="function"?s:()=>s??{},flagsHost:t.flagsHost?h(t.flagsHost):e,flushAt:t.flushAt??20,flushIntervalMs:t.flushIntervalMs??1e4,host:e,ids:t.ids??N,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??T,sdkVersion:t.sdkVersion??S,storage:t.storage??new m,transport:t.transport}}function V(t,e,s){L(t.eventName),K(t.distinctId);let r={distinct_id:t.distinctId,event_id:t.eventId??s.uuid(),event_name:t.eventName,properties:t.properties??{},schema_version:1,timestamp:E(t.timestamp??e.now())};return t.context&&(r.context=t.context),t.sessionId&&(r.session_id=t.sessionId),r}var w=class{constructor(e,s,r){this.storage=e;this.ids=s;this.namespace=r;i(this,"anonymousId");i(this,"distinctId");i(this,"identified");let n=e.getItem(this.key("anonymous_id"));n?this.anonymousId=n:(this.anonymousId=s.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 F=class{constructor(e,s){this.maxSize=e;this.onOverflow=s;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 s=e===void 0?this.events.length:Math.min(e,this.events.length);return this.events.splice(0,s)}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="queue",se=1e3,re=3e4,k=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=j(e),this.identity=new w(this.config.storage,this.config.ids,this.config.namespace),this.queue=new F(this.config.maxQueueSize,({dropped:s})=>{this.config.onError(new d("queue_overflow",`event queue overflow: dropped ${s.length} oldest event(s)`));}),this.transport=this.config.transport??new I({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 x({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,s={}){try{let r={...this.config.defaultProperties(),...s.properties??{}},n=V({context:this.context,distinctId:this.identity.getDistinctId(),eventName:e,properties:r,sessionId:s.sessionId,timestamp:s.timestamp},this.config.clock,this.config.ids);this.enqueue(n);}catch(r){this.config.onError(r);}}identify(e,s={}){let r=this.identity.getAnonymousId(),n=!this.identity.isIdentified(),o=this.identity.identify(e),a={};n&&o.changed&&(a.$anon_distinct_id=r),s.set&&(a.$set=s.set),this.capture("$identify",{properties:a});}alias(e){this.capture("$create_alias",{properties:{alias:e}});}group(e,s,r){let n={$group_key:s,$group_type:e};r&&(n.$set=r),this.capture("$group",{properties:n});}setPersonProperties(e,s){let r={};e&&(r.$set=e),s&&(r.$set_once=s),this.capture("$set",{properties:r});}async getAllFlags(){let e=this.identity.getDistinctId(),s=await this.flagsClient.fetchAll(e);return this.cachedFlags={distinctId:e,flags:s},s}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 s=await this.flagSnapshot();return M(s.flags,{attributes:e.attributes,distinctId:this.identity.getDistinctId(),properties:e.properties})}async isFeatureEnabledLocal(e,s){return (await this.getLocalFlags(s))[e]??false}async flagSnapshot(){let e=this.config.clock.now().getTime();if(this.cachedSnapshot&&e-this.cachedSnapshot.fetchedAt<re)return this.cachedSnapshot.snapshot;let s=await this.flagsClient.snapshot();return this.cachedSnapshot={fetchedAt:e,snapshot:s},s}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(se);try{await this.transport.send({body:{events:e,sent_at:E(this.config.clock.now())},projectKey:this.config.apiKey,url:`${this.config.host}/v1/events`}),this.persistQueue();}catch(s){this.queue.requeue(e),this.persistQueue(),this.config.onError(s);}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 s=JSON.parse(e);Array.isArray(s)&&this.queue.restore(s);}catch(e){this.config.onError(e);}}startTimer(){if(this.config.flushIntervalMs<=0)return;let e=setInterval(()=>{this.flush();},this.config.flushIntervalMs),s=e;typeof s.unref=="function"&&s.unref(),this.flushTimer=e;}stopTimer(){this.flushTimer!==void 0&&(clearInterval(this.flushTimer),this.flushTimer=void 0);}persistKey(){return `pdx.${this.config.namespace}.${te}`}};function rt(t){return new k(t)}export{i as a,d as b,y as c,f as d,l as e,g as f,h as g,m as h,le as i,X as j,T as k,S as l,R as m,U as n,B as o,M as p,b as q,x as r,I as s,k as t,rt as u};//# sourceMappingURL=chunk-FIZWZVZG.js.map
|
|
2
|
-
//# sourceMappingURL=chunk-FIZWZVZG.js.map
|