@bitpalm/ai-agents 0.6.0 → 0.7.0

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/react.d.cts CHANGED
@@ -1,3 +1,124 @@
1
+ interface ChatCard {
2
+ kind?: string;
3
+ title: string;
4
+ image?: string;
5
+ subtitle?: string;
6
+ fields?: {
7
+ label: string;
8
+ value: string;
9
+ }[];
10
+ cta?: {
11
+ label: string;
12
+ url: string;
13
+ };
14
+ }
15
+ interface ChatMessage {
16
+ role: "user" | "assistant";
17
+ text: string;
18
+ createdAt?: string;
19
+ cards?: ChatCard[];
20
+ /** Photos the user sent, as links. */
21
+ images?: string[];
22
+ /** Written by a person of the team, not by the agent. */
23
+ fromHuman?: boolean;
24
+ }
25
+ interface QuickLink {
26
+ id: string;
27
+ label: string;
28
+ /** Send this as the user's message. */
29
+ message?: string;
30
+ /** Or open this address. */
31
+ url?: string;
32
+ }
33
+ interface AgentConfig {
34
+ name: string;
35
+ logoUrl: string | null;
36
+ primaryColor: string;
37
+ welcomeMessage: string;
38
+ inputPlaceholder: string;
39
+ quickLinks: QuickLink[];
40
+ photoUploads: boolean;
41
+ /** When required is true, show text linked to url in your chat UI. */
42
+ branding: {
43
+ required: boolean;
44
+ text: string;
45
+ url: string;
46
+ };
47
+ }
48
+ interface ChatClientOptions {
49
+ /** App key from the dashboard, starts with bp_pk_. */
50
+ key: string;
51
+ /** Defaults to https://agents.bitpalm.ai. */
52
+ baseUrl?: string;
53
+ /**
54
+ * Id that holds the conversation together. Leave it out: the client
55
+ * creates a random one and remembers it. If you set it, make it
56
+ * unguessable. Never use a plain user id, anyone with the app key could
57
+ * read that user's chats.
58
+ */
59
+ visitorId?: string;
60
+ /** Language for greeting, placeholder and quick links, like "de". */
61
+ locale?: string;
62
+ /** Where visitor and conversation are remembered. Defaults to localStorage when there is one. */
63
+ storage?: Pick<Storage, "getItem" | "setItem" | "removeItem"> | null;
64
+ }
65
+ interface SendOptions {
66
+ /** Facts for this answer, like the cart or the user's plan. At most 4 KB. */
67
+ context?: Record<string, unknown>;
68
+ /** Ids of photos from upload(). */
69
+ fileIds?: string[];
70
+ /** Called as the answer grows: the new piece and the whole answer so far. */
71
+ onDelta?: (piece: string, answer: string) => void;
72
+ signal?: AbortSignal;
73
+ }
74
+ interface SendResult {
75
+ text: string;
76
+ conversationId: string;
77
+ cards?: ChatCard[];
78
+ /**
79
+ * Your team has the conversation now. The agent stays silent in it until
80
+ * the team closes it, the team's replies come with history().
81
+ */
82
+ handoff?: boolean;
83
+ }
84
+ interface Identity {
85
+ name?: string;
86
+ email?: string;
87
+ phone?: string;
88
+ company?: string;
89
+ externalUserId?: string;
90
+ }
91
+ /** An error of the API, with its code, like "invalid_key" or "rate_limited". */
92
+ declare class BitPalmApiError extends Error {
93
+ readonly code: string;
94
+ readonly status: number;
95
+ constructor(code: string, message: string, status: number);
96
+ }
97
+ interface ChatClient {
98
+ readonly visitorId: string;
99
+ readonly conversationId: string | null;
100
+ /** True while your team has the conversation. Updated by send() and history(). */
101
+ readonly handoff: boolean;
102
+ /** Name, greeting, quick links and whether "Powered by BitPalm" has to show. */
103
+ agent(options?: {
104
+ url?: string;
105
+ }): Promise<AgentConfig>;
106
+ send(message: string, options?: SendOptions): Promise<SendResult>;
107
+ /** The messages of the current conversation, or of the latest one of this visitor. */
108
+ history(): Promise<ChatMessage[]>;
109
+ /** Tells BitPalm who the logged-in user is. */
110
+ identify(identity: Identity): Promise<void>;
111
+ /** A photo for the next message, when the agent takes photos. */
112
+ upload(file: Blob, fileName?: string): Promise<{
113
+ id: string;
114
+ url: string;
115
+ }>;
116
+ /** Thumbs up or down for the agent's answer number index (0 is the first answer). */
117
+ feedback(index: number, value: "up" | "down"): Promise<void>;
118
+ /** Starts a new conversation. */
119
+ reset(): void;
120
+ }
121
+
1
122
  /**
2
123
  * Widget color theme. "auto" follows the website: theme classes or
3
124
  * attributes like class="dark" or data-theme="dark" on <html> or <body>,
@@ -158,5 +279,30 @@ interface BitPalmAgentProps extends BitPalmAgentOptions {
158
279
  * ```
159
280
  */
160
281
  declare function BitPalmAgent(props: BitPalmAgentProps): null;
282
+ type ChatStatus = "idle" | "streaming" | "error";
283
+ interface UseBitPalmChatOptions extends ChatClientOptions {
284
+ /** Load the last conversation of this visitor on start. Defaults to true. */
285
+ loadHistory?: boolean;
286
+ }
287
+ /**
288
+ * Your own chat UI in React, with BitPalm behind it. Keeps the messages,
289
+ * streams the answer into the last one and remembers the conversation.
290
+ *
291
+ * @example
292
+ * ```tsx
293
+ * const { messages, send, status, agent } = useBitPalmChat({ key: "bp_pk_…" });
294
+ * ```
295
+ */
296
+ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
297
+ messages: ChatMessage[];
298
+ send: (text: string, sendOptions?: Omit<SendOptions, "onDelta">) => Promise<SendResult | null>;
299
+ status: ChatStatus;
300
+ error: BitPalmApiError | null;
301
+ agent: AgentConfig | null;
302
+ handoff: boolean;
303
+ refresh: () => Promise<void>;
304
+ reset: () => void;
305
+ client: ChatClient;
306
+ };
161
307
 
162
- export { BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps };
308
+ export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type ChatCard, type ChatClient, type ChatClientOptions, type ChatMessage, type ChatStatus, type QuickLink, type SendOptions, type SendResult, type UseBitPalmChatOptions, useBitPalmChat };
package/dist/react.d.ts CHANGED
@@ -1,3 +1,124 @@
1
+ interface ChatCard {
2
+ kind?: string;
3
+ title: string;
4
+ image?: string;
5
+ subtitle?: string;
6
+ fields?: {
7
+ label: string;
8
+ value: string;
9
+ }[];
10
+ cta?: {
11
+ label: string;
12
+ url: string;
13
+ };
14
+ }
15
+ interface ChatMessage {
16
+ role: "user" | "assistant";
17
+ text: string;
18
+ createdAt?: string;
19
+ cards?: ChatCard[];
20
+ /** Photos the user sent, as links. */
21
+ images?: string[];
22
+ /** Written by a person of the team, not by the agent. */
23
+ fromHuman?: boolean;
24
+ }
25
+ interface QuickLink {
26
+ id: string;
27
+ label: string;
28
+ /** Send this as the user's message. */
29
+ message?: string;
30
+ /** Or open this address. */
31
+ url?: string;
32
+ }
33
+ interface AgentConfig {
34
+ name: string;
35
+ logoUrl: string | null;
36
+ primaryColor: string;
37
+ welcomeMessage: string;
38
+ inputPlaceholder: string;
39
+ quickLinks: QuickLink[];
40
+ photoUploads: boolean;
41
+ /** When required is true, show text linked to url in your chat UI. */
42
+ branding: {
43
+ required: boolean;
44
+ text: string;
45
+ url: string;
46
+ };
47
+ }
48
+ interface ChatClientOptions {
49
+ /** App key from the dashboard, starts with bp_pk_. */
50
+ key: string;
51
+ /** Defaults to https://agents.bitpalm.ai. */
52
+ baseUrl?: string;
53
+ /**
54
+ * Id that holds the conversation together. Leave it out: the client
55
+ * creates a random one and remembers it. If you set it, make it
56
+ * unguessable. Never use a plain user id, anyone with the app key could
57
+ * read that user's chats.
58
+ */
59
+ visitorId?: string;
60
+ /** Language for greeting, placeholder and quick links, like "de". */
61
+ locale?: string;
62
+ /** Where visitor and conversation are remembered. Defaults to localStorage when there is one. */
63
+ storage?: Pick<Storage, "getItem" | "setItem" | "removeItem"> | null;
64
+ }
65
+ interface SendOptions {
66
+ /** Facts for this answer, like the cart or the user's plan. At most 4 KB. */
67
+ context?: Record<string, unknown>;
68
+ /** Ids of photos from upload(). */
69
+ fileIds?: string[];
70
+ /** Called as the answer grows: the new piece and the whole answer so far. */
71
+ onDelta?: (piece: string, answer: string) => void;
72
+ signal?: AbortSignal;
73
+ }
74
+ interface SendResult {
75
+ text: string;
76
+ conversationId: string;
77
+ cards?: ChatCard[];
78
+ /**
79
+ * Your team has the conversation now. The agent stays silent in it until
80
+ * the team closes it, the team's replies come with history().
81
+ */
82
+ handoff?: boolean;
83
+ }
84
+ interface Identity {
85
+ name?: string;
86
+ email?: string;
87
+ phone?: string;
88
+ company?: string;
89
+ externalUserId?: string;
90
+ }
91
+ /** An error of the API, with its code, like "invalid_key" or "rate_limited". */
92
+ declare class BitPalmApiError extends Error {
93
+ readonly code: string;
94
+ readonly status: number;
95
+ constructor(code: string, message: string, status: number);
96
+ }
97
+ interface ChatClient {
98
+ readonly visitorId: string;
99
+ readonly conversationId: string | null;
100
+ /** True while your team has the conversation. Updated by send() and history(). */
101
+ readonly handoff: boolean;
102
+ /** Name, greeting, quick links and whether "Powered by BitPalm" has to show. */
103
+ agent(options?: {
104
+ url?: string;
105
+ }): Promise<AgentConfig>;
106
+ send(message: string, options?: SendOptions): Promise<SendResult>;
107
+ /** The messages of the current conversation, or of the latest one of this visitor. */
108
+ history(): Promise<ChatMessage[]>;
109
+ /** Tells BitPalm who the logged-in user is. */
110
+ identify(identity: Identity): Promise<void>;
111
+ /** A photo for the next message, when the agent takes photos. */
112
+ upload(file: Blob, fileName?: string): Promise<{
113
+ id: string;
114
+ url: string;
115
+ }>;
116
+ /** Thumbs up or down for the agent's answer number index (0 is the first answer). */
117
+ feedback(index: number, value: "up" | "down"): Promise<void>;
118
+ /** Starts a new conversation. */
119
+ reset(): void;
120
+ }
121
+
1
122
  /**
2
123
  * Widget color theme. "auto" follows the website: theme classes or
3
124
  * attributes like class="dark" or data-theme="dark" on <html> or <body>,
@@ -158,5 +279,30 @@ interface BitPalmAgentProps extends BitPalmAgentOptions {
158
279
  * ```
159
280
  */
160
281
  declare function BitPalmAgent(props: BitPalmAgentProps): null;
282
+ type ChatStatus = "idle" | "streaming" | "error";
283
+ interface UseBitPalmChatOptions extends ChatClientOptions {
284
+ /** Load the last conversation of this visitor on start. Defaults to true. */
285
+ loadHistory?: boolean;
286
+ }
287
+ /**
288
+ * Your own chat UI in React, with BitPalm behind it. Keeps the messages,
289
+ * streams the answer into the last one and remembers the conversation.
290
+ *
291
+ * @example
292
+ * ```tsx
293
+ * const { messages, send, status, agent } = useBitPalmChat({ key: "bp_pk_…" });
294
+ * ```
295
+ */
296
+ declare function useBitPalmChat(options: UseBitPalmChatOptions): {
297
+ messages: ChatMessage[];
298
+ send: (text: string, sendOptions?: Omit<SendOptions, "onDelta">) => Promise<SendResult | null>;
299
+ status: ChatStatus;
300
+ error: BitPalmApiError | null;
301
+ agent: AgentConfig | null;
302
+ handoff: boolean;
303
+ refresh: () => Promise<void>;
304
+ reset: () => void;
305
+ client: ChatClient;
306
+ };
161
307
 
162
- export { BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps };
308
+ export { type AgentConfig, BitPalmAgent, type BitPalmAgentInstance, type BitPalmAgentOptions, type BitPalmAgentProps, BitPalmApiError, type ChatCard, type ChatClient, type ChatClientOptions, type ChatMessage, type ChatStatus, type QuickLink, type SendOptions, type SendResult, type UseBitPalmChatOptions, useBitPalmChat };
package/dist/react.js CHANGED
@@ -1,2 +1,13 @@
1
- import{useEffect as ht,useRef as yt}from"react";function ot(n){if(n===!1)return"off";if(typeof n=="string"){let t=n.trim().toLowerCase();if(["false","off","0","no","none"].includes(t))return"off";if(t==="events")return"events"}return"bubble"}function it(n,t){let a=n.createElement("div");a.setAttribute("data-bitpalm-trigger",""),a.style.cssText=`max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${t.zIndex-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`,a.style.position="fixed",a.style.right="24px",a.style.bottom=`${t.bottom}px`;let r=n.createElement("p");r.style.cssText="font-size:14px;color:#1f2937;margin:0;",r.textContent=t.message;let m=n.createElement("div");m.style.cssText="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;";let u=n.createElement("button");return u.type="button",u.setAttribute("aria-label","Close"),u.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",u.textContent="\u2715",u.onclick=g=>{g.stopPropagation(),t.onDismiss()},a.onclick=()=>t.onEngage(),a.append(r,m,u),a}var xt=["dark","dark-mode","dark-theme","theme-dark"],St=["light","light-mode","light-theme","theme-light"],at=["data-theme","data-color-scheme","data-color-mode","data-mode","data-bs-theme"],lt="(prefers-color-scheme: dark)";function re(n){return n==="light"||n==="dark"?n:"auto"}function st(n){if(!n)return null;if(xt.some(t=>n.classList.contains(t)))return"dark";if(St.some(t=>n.classList.contains(t)))return"light";for(let t of at){let a=(n.getAttribute(t)||"").toLowerCase();if(a.includes("dark"))return"dark";if(a.includes("light"))return"light"}return null}function Te(n){let t=n/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function rt(n,t){if(!n)return null;let a=t.getComputedStyle(n).backgroundColor.match(/rgba?\(([^)]+)\)/);if(!a)return null;let[r,m,u,g=1]=a[1].split(/[\s,/]+/).filter(Boolean).map(Number);return[r,m,u,g].some(l=>Number.isNaN(l))||g<.5?null:.2126*Te(r)+.7152*Te(m)+.0722*Te(u)<.2?"dark":"light"}function Lt(n,t){let a=t.getComputedStyle(n.documentElement).colorScheme||"",r=n.querySelector('meta[name="color-scheme"]')?.getAttribute("content")||"",m=`${a} ${r}`.toLowerCase();return m.includes("dark")?m.includes("light")?t.matchMedia?.(lt).matches?"dark":"light":"dark":null}function J(n=document,t=window){return st(n.documentElement)??st(n.body)??rt(n.body,t)??rt(n.documentElement,t)??Lt(n,t)??"light"}function xe(n,t=document,a=window){let r=J(t,a),m=!1,u=()=>{m=!1;let c=J(t,a);c!==r&&(r=c,n(c))},g=()=>{m||(m=!0,typeof a.requestAnimationFrame=="function"?a.requestAnimationFrame(u):setTimeout(u,16))},T=typeof MutationObserver<"u"?new MutationObserver(g):null,l={attributes:!0,attributeFilter:["class","style",...at]};T?.observe(t.documentElement,l),t.body&&T?.observe(t.body,l);let h=typeof a.matchMedia=="function"?a.matchMedia(lt):null;return h?.addEventListener?.("change",g),()=>{T?.disconnect(),h?.removeEventListener?.("change",g)}}var At="https://agents.bitpalm.ai",v="_bp_",It=new Set(["password","file","checkbox","radio","submit","button","reset","image"]),_t=8e3,ct=4096,dt=`${v}identify_signature`,mt=`${v}identify_fingerprint`,ut=`${v}identify_sent_at`,ft="0 4px 14px rgba(0,0,0,0.18)";function Mt(n){return[n.external_user_id||"",n.email||"",n.phone||"",n.name||"",n.company||"",n.signature||"",n.signed_at!=null?String(n.signed_at):"",n.signature_version||"",n.identify_source||""].join("|").toLowerCase()}function d(n,t=180){return n?n.replace(/\s+/g," ").trim().slice(0,t):""}function Ct(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function N(n,t){for(let a of t)if(n.includes(a))return!0;return!1}function C(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function I(n){let t=d(n,50);if(!t)return"";let a=t.startsWith("+"),r=t.replace(/\D/g,"");return r.length<6?"":`${a?"+":""}${r.slice(0,20)}`}function gt(n){let t=d(n,140).toLowerCase();return!t||!C(t)?"":t}function W(n,t){for(let a of t){let r=n.querySelector(a),m=d(r?.value);if(m)return m}return""}function Pt(n){return d(n.getAttribute("data-bp-field")||n.getAttribute("data-bitpalm-field"),64).toLowerCase().replace(/[_\s]+/g,"-")}function Bt(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function kt(n,t){let a=[],r=(l,h=140)=>{let c=d(l,h);c&&a.push(c)};r(t.name),r(t.id),r(t.getAttribute("autocomplete")),r(t.getAttribute("placeholder")),r(t.getAttribute("aria-label")),r(t.getAttribute("data-field")),r(t.getAttribute("data-name")),r(t.getAttribute("data-label")),r(t.getAttribute("data-bp-field")),r(t.getAttribute("data-bitpalm-field"));let m=new Set,u=l=>{let h=d(l,200);!h||m.has(h)||(m.add(h),a.push(h))};for(let l of Array.from(t.labels||[]))u(l.textContent);if(t.id){let l=n.querySelector(`label[for="${Bt(t.id)}"]`);u(l?.textContent)}let g=t.closest("label");u(g?.textContent);let T=t.getAttribute("aria-labelledby");if(T)for(let l of T.split(/\s+/)){if(!l)continue;let h=n.ownerDocument.getElementById(l);u(h?.textContent)}return a}function Ht(n){let t=d(W(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),a=I(W(n,["[data-bp-phone]","[data-bitpalm-phone]"])),r=d(W(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),m=d(W(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),u=d(W(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),g=d(W(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let c of Array.from(n.elements)){if(!(c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)||c.disabled||c instanceof HTMLInputElement&&It.has(c.type.toLowerCase()))continue;let y=Pt(c),F=c.hasAttribute("data-bp-email")||c.hasAttribute("data-bitpalm-email")||c.hasAttribute("data-bp-phone")||c.hasAttribute("data-bitpalm-phone")||c.hasAttribute("data-bp-name")||c.hasAttribute("data-bitpalm-name")||c.hasAttribute("data-bp-full-name")||c.hasAttribute("data-bitpalm-full-name")||c.hasAttribute("data-bp-first-name")||c.hasAttribute("data-bitpalm-first-name")||c.hasAttribute("data-bp-last-name")||c.hasAttribute("data-bitpalm-last-name")||c.hasAttribute("data-bp-company")||c.hasAttribute("data-bitpalm-company")||!!y;if(c instanceof HTMLInputElement&&c.type.toLowerCase()==="hidden"&&!F)continue;let f=d(c.value);if(!f)continue;let _=c instanceof HTMLInputElement?c.type.toLowerCase():"",s=Ct(kt(n,c).join(" "));if(!t&&y==="email"&&C(f)){t=f.toLowerCase();continue}if(!a&&(y==="phone"||y==="tel"||y==="mobile"||y==="whatsapp")){let S=I(f);if(S){a=S;continue}}if(!g&&y==="company"){g=d(f,160);continue}if(!m&&(y==="first-name"||y==="firstname")){m=d(f,100);continue}if(!u&&(y==="last-name"||y==="lastname"||y==="surname")){u=d(f,100);continue}if(!r&&(y==="name"||y==="full-name"||y==="fullname")){!C(f)&&!I(f)&&(r=d(f,140));continue}let G=_==="email"||N(s,[" email "," e mail "," mail "," email adresse "," mailadresse "," correo "]),O=_==="tel"||N(s,[" phone "," phone number "," mobile "," tel "," telefon "," telefonnummer "," whatsapp "," handy "," kontakt "," nummer "]),ae=N(s,[" company "," company name "," firma "," firmenname "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),p=N(s,[" first name "," firstname "," given name "," givenname "," vorname "," fname "]),P=N(s,[" last name "," lastname "," family name "," familyname "," surname "," nachname "," lname "]),U=N(s,[" full name "," fullname "," contact name "," name "])&&!G&&!O;if(!t&&G&&C(f)){t=f.toLowerCase();continue}if(!a&&O){let S=I(f);if(S){a=S;continue}}if(!g&&ae){g=d(f,160);continue}if(!m&&p){m=d(f,100);continue}if(!u&&P){u=d(f,100);continue}if(!r&&U&&!C(f)&&!I(f)){r=d(f,140);continue}!t&&C(f)&&(t=f.toLowerCase())}if(r&&(C(r)||I(r))&&(r=""),g&&(C(g)||I(g))&&(g=""),r||(r=d([m,u].filter(Boolean).join(" "),140)),r&&t&&r.toLowerCase()===t.toLowerCase()&&(r=""),!!!(t||a)&&!!!(r&&g))return null;let h={...r?{name:r}:{},...t?{email:t}:{},...a?{phone:a}:{},...g?{company:g}:{}};return Object.keys(h).length>0?h:null}function $t(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function Se(n,t=1200){if(typeof window<"u"&&"requestIdleCallback"in window){window.requestIdleCallback(n,{timeout:t});return}setTimeout(n,Math.min(t,300))}function Le(){if(typeof window>"u")return!1;let n=typeof navigator<"u"?navigator.userAgent:"";if(/Android|iPhone|iPad|iPod|IEMobile|Windows Phone|Mobile/i.test(n))return!0;let a=window.matchMedia("(pointer: coarse)").matches,r=window.matchMedia("(hover: none)").matches,m=Math.min(window.screen?.width||window.innerWidth,window.screen?.height||window.innerHeight);return a&&r&&m<=900}function pt(n){let{slug:t,locale:a=$t(),baseUrl:r=At,token:m,zIndex:u=9999,autoIdentify:g=!0,launcher:T=!0}=n,l=document,h=re(n.theme),c=h==="auto"?J():h,y=null,F=ot(n.triggers),f=F,_=null,s=l.createElement("iframe");s.setAttribute("data-bitpalm-chat","");let G=`${r}/t/${t}/widget`,O=new URLSearchParams({locale:a,theme:c});m&&O.set("token",m),f==="off"&&O.set("triggers","off"),s.src=`${G}?${O.toString()}`,s.allow="clipboard-write; microphone",s.setAttribute("allowtransparency","true"),s.loading="lazy",s.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${u};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;let ae=new URL(s.src).origin,p=l.createElement("div");if(p.setAttribute("role","button"),p.setAttribute("aria-label","Chat"),p.setAttribute("data-bitpalm-launcher",""),p.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${u-1};background:#171717;box-shadow:${ft};transition:transform .2s,opacity .3s;opacity:0;`,p.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',p.onmouseenter=()=>{p.style.transform="scale(1.05)"},p.onmouseleave=()=>{p.style.transform="scale(1)"},p.onclick=()=>q(),T&&l.body.appendChild(p),!l.getElementById("_bp_fade")){let e=l.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",l.head.appendChild(e)}let P=null,U=!1,S=!1,Ae=!1,le=!1,K=!1,V=()=>{Ae||(Ae=!0,l.body.appendChild(s))},X=!1,ce=0,Z={overflow:"",overscrollBehavior:""},E={overflow:"",overscrollBehavior:"",position:"",top:"",left:"",right:"",width:""},Ie=()=>{if(X||!Le())return;let o=l.documentElement,i=l.body;ce=window.scrollY||window.pageYOffset||0,Z.overflow=o.style.overflow,Z.overscrollBehavior=o.style.overscrollBehavior,E.overflow=i.style.overflow,E.overscrollBehavior=i.style.overscrollBehavior,E.position=i.style.position,E.top=i.style.top,E.left=i.style.left,E.right=i.style.right,E.width=i.style.width,o.style.overflow="hidden",o.style.overscrollBehavior="none",i.style.overflow="hidden",i.style.overscrollBehavior="none",i.style.position="fixed",i.style.top=`-${ce}px`,i.style.left="0",i.style.right="0",i.style.width="100%",X=!0},R=()=>{if(!X)return;let e=l.documentElement,o=l.body;e.style.overflow=Z.overflow,e.style.overscrollBehavior=Z.overscrollBehavior,o.style.overflow=E.overflow,o.style.overscrollBehavior=E.overscrollBehavior,o.style.position=E.position,o.style.top=E.top,o.style.left=E.left,o.style.right=E.right,o.style.width=E.width,window.scrollTo(0,ce),X=!1},_e=()=>{let e=Le();s.style.display==="none"&&(s.style.display=""),e?(s.style.width="100vw",s.style.height="100dvh",s.style.left="0",s.style.top="0",s.style.bottom="0",s.style.right="0",Ie()):(s.style.width="420px",s.style.height="620px",s.style.bottom="24px",s.style.right="24px",s.style.left="",s.style.top="",R()),s.style.opacity="1",s.style.pointerEvents="auto"},M=()=>{P&&(P.remove(),P=null)},Q=()=>{_!==null&&(_=null,j("trigger_hidden"))},Me=()=>{s.contentWindow?.postMessage({type:"bitpalm-triggers",enabled:f!=="off"},"*")},ee=()=>{},de=()=>{},D=!1,B=new Map;function j(e,o){let i=B.get(e);if(i)for(let b of i)try{b(o)}catch{}}let Ce=e=>{if(e.origin===ae){if(e.data?.type==="bitpalm-widget-config"){S=!1,U=!0,s.style.display==="none"&&(s.style.display=""),e.data.primaryColor&&(p.style.background=e.data.primaryColor,p.style.boxShadow=e.data.chatShadow==="none"?"none":ft);let o=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){p.innerHTML="";let i=l.createElement("span");i.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${o}`;let w=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");w?(w.querySelectorAll("script,foreignObject").forEach(H=>H.remove()),w.querySelectorAll("*").forEach(H=>{for(let $ of[...H.attributes])($.name.startsWith("on")||$.value&&$.value.includes("javascript:"))&&H.removeAttribute($.name)}),w.setAttribute("width","24"),w.setAttribute("height","24"),w.style.display="block",i.appendChild(w)):i.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',p.appendChild(i)}else{let i=p.querySelector("svg");i&&(i.style.stroke=o)}T&&(p.style.display="flex",requestAnimationFrame(()=>{p.style.opacity="1"})),Me()}if(e.data?.type==="bitpalm-widget-resize"){let o=e.data.width>0,i=D;D=o,o&&!i&&j("widget_opened"),!o&&i&&j("widget_closed");let b=Le();o?(s.style.width=b?"100vw":`${e.data.width}px`,s.style.height=b?"100dvh":`${e.data.height}px`,b?(s.style.left="0",s.style.top="0",s.style.bottom="0",s.style.right="0",Ie()):R(),s.style.opacity="1",s.style.pointerEvents="auto"):(R(),s.style.width="1px",s.style.height="1px",s.style.left="",s.style.top="",s.style.opacity="0",s.style.pointerEvents="none"),p.style.display=o||!T?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){if(S||!U||f==="off")return;let o=typeof e.data.message=="string"?e.data.message:"";if(!o)return;if(f==="events"){_=o,j("trigger_shown",{message:o,triggerId:e.data.triggerId,triggerType:e.data.triggerType});return}M(),P=it(l,{message:o,zIndex:u,bottom:T?90:24,onDismiss:()=>{M(),s.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},onEngage:()=>{if(M(),p.style.display="none",_e(),V(),!le){K=!0;return}s.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:o},"*")}}),l.body.appendChild(P)}e.data?.type==="bitpalm-trigger-hide"&&(M(),Q()),e.data?.type==="bitpalm-request-context"&&ee(),e.data?.type==="bitpalm-chat-event"&&e.data.event&&j(e.data.event,e.data.data),e.data?.type==="bitpalm-widget-blocked"&&(S=!0,U=!1,p.style.display="none",M(),Q(),R(),s.style.display="none")}};window.addEventListener("message",Ce);let L=!1;try{L=localStorage.getItem(`${v}optout`)==="1"}catch{}let te=`${v}vid`,x="";if(!L){try{x=localStorage.getItem(te)||""}catch{}if(!x){let e=l.cookie.match(new RegExp(`(?:^|; )${te}=([^;]+)`));x=e?decodeURIComponent(e[1]):""}x||(x=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(te,x)}catch{}try{l.cookie=`${te}=${encodeURIComponent(x)};path=/;max-age=31536000;SameSite=Lax`}catch{}}L||Se(()=>{try{let e=new URLSearchParams(location.search),o={};for(let A of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let w=e.get(A);w&&(o[A]=w)}let i=JSON.stringify({tenant_slug:t,visitor_id:x,url:location.href,referrer:l.referrer||void 0,...Object.keys(o).length>0?{utm:o}:{}}),b=`${r}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(b,new Blob([i],{type:"application/json"})):fetch(b,{method:"POST",body:i,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}},2e3);let me="",ue="",fe=0;try{me=sessionStorage.getItem(dt)||"",ue=sessionStorage.getItem(mt)||"";let e=parseInt(sessionStorage.getItem(ut)||"0",10);Number.isFinite(e)&&e>0&&(fe=e)}catch{}let Pe=(e,o="")=>{if(L||!x)return;let i={},b=d(e.name,140),A=gt(e.email),w=I(e.phone),H=d(e.company,160),$=d(e.external_user_id,140),et=d(e.signature,260),ve=Number(e.signed_at);if(b&&(i.name=b),A&&(i.email=A),w&&(i.phone=w),H&&(i.company=H),$&&(i.external_user_id=$),et&&(i.signature=et),Number.isFinite(ve)&&ve>0&&(i.signed_at=Math.floor(ve)),(e.signature_version==="v1"||i.signature)&&(i.signature_version="v1"),(e.identify_source==="manual"||e.identify_source==="form")&&(i.identify_source=e.identify_source),!i.name&&!i.email&&!i.phone&&!i.company&&!i.external_user_id)return;let se=Mt(i),we=[o.toLowerCase(),se].filter(Boolean).join("|"),Ee=Date.now();if(!(Ee-fe<_t&&(we===me||se===ue))){me=we,ue=se,fe=Ee;try{sessionStorage.setItem(dt,we),sessionStorage.setItem(mt,se),sessionStorage.setItem(ut,String(Ee))}catch{}try{let tt=JSON.stringify({tenant_slug:t,visitor_id:x,url:location.href,referrer:l.referrer||void 0,...i}),nt=`${r}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(nt,new Blob([tt],{type:"application/json"})):fetch(nt,{method:"POST",body:tt,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}},Be=e=>{if(L||!g||!x)return;let o=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(o instanceof HTMLFormElement))return;let i=(o.getAttribute("data-bp-identify")||o.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(i==="off"||i==="false"||i==="0")return;let b=Ht(o);if(!b)return;let A=[o.getAttribute("id")||"",o.getAttribute("name")||"",o.getAttribute("action")||""].join("|");Pe({...b,identify_source:"form"},A)};!L&&g&&l.addEventListener("submit",Be,!0);let z=parseInt(sessionStorage.getItem(`${v}pages`)||"0")+1;sessionStorage.setItem(`${v}pages`,String(z));let k=JSON.parse(sessionStorage.getItem(`${v}hist`)||"[]");k.push(location.href),k.length>20&&(k=k.slice(-20)),sessionStorage.setItem(`${v}hist`,JSON.stringify(k));let ke=Date.now(),ne=parseInt(sessionStorage.getItem(`${v}site_start`)||"0");ne||(ne=ke,sessionStorage.setItem(`${v}site_start`,String(ne)));let He=[];ee=()=>{let e=!1;try{e=!!localStorage.getItem(`${v}visited`)}catch{e=!1}if(s.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:l.title,returning:e,pageCount:z,pageHistory:k,loadedAt:ke,siteStart:ne,locale:a,visitorId:L?"":x},"*"),qe(),!e&&!L)try{localStorage.setItem(`${v}visited`,"1")}catch{}},s.addEventListener("load",()=>{le=!0,ee(),[120,450,1100].forEach(e=>{let o=setTimeout(()=>ee(),e);He.push(o)}),K&&(K=!1,de())}),l.readyState==="loading"?l.addEventListener("DOMContentLoaded",()=>Se(V,1600),{once:!0}):Se(V,1600);let $e=history.pushState.bind(history),Oe=history.replaceState.bind(history),oe=()=>{z++,sessionStorage.setItem(`${v}pages`,String(z));let e=JSON.parse(sessionStorage.getItem(`${v}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),k=e,sessionStorage.setItem(`${v}hist`,JSON.stringify(e)),s.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:l.title,pageCount:z,pageHistory:e,loadedAt:Date.now()},"*"),!L)try{let o=JSON.stringify({tenant_slug:t,visitor_id:x,url:location.href}),i=`${r}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(i,new Blob([o],{type:"application/json"})):fetch(i,{method:"POST",body:o,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){$e(...e),oe()},history.replaceState=function(...e){Oe(...e),oe()},window.addEventListener("popstate",oe);let Re=-1,ge,De=()=>{clearTimeout(ge),ge=setTimeout(()=>{let e=Math.max(l.documentElement.scrollHeight,l.body.scrollHeight)-window.innerHeight,o=e>0?Math.round(window.scrollY/e*100):100;o!==Re&&(Re=o,s.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:o},"*"))},500)};window.addEventListener("scroll",De,{passive:!0});let Ne=e=>{e.clientY<=0&&s.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};l.addEventListener("mouseout",Ne);let pe,We=!1,he=()=>{clearTimeout(pe),!We&&(pe=setTimeout(()=>{We=!0,s.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},Fe=["mousemove","keydown","scroll","touchstart"];Fe.forEach(e=>l.addEventListener(e,he,{passive:!0})),he(),de=()=>{s.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=s.src.split("#")[0];s.src=`${e}#bp-open-${Date.now()}`};let q=()=>{if(p.style.display="none",M(),_e(),V(),!le){K=!0;return}if(_!==null){let e=_;Q(),s.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:e},"*");return}de()},Ue=e=>{f=e,e==="off"&&(M(),Q()),Me()},bt=()=>Ue("off"),vt=()=>Ue(F==="off"?"bubble":F),ye=()=>{R(),s.contentWindow?.postMessage({type:"bitpalm-close"},"*")},je=e=>{!e||typeof e!="object"||Pe({external_user_id:d(e.externalUserId,140)||void 0,name:d(e.name,140)||void 0,email:gt(e.email)||void 0,phone:I(e.phone)||void 0,company:d(e.company,160)||void 0,signature:d(e.signature,260)||void 0,signed_at:Number.isFinite(Number(e.signedAt))?Math.floor(Number(e.signedAt)):void 0,signature_version:e.signatureVersion==="v1"?"v1":void 0,identify_source:"manual"},"manual")},wt=()=>{D?ye():q()},Et=()=>D,ze=e=>{if(!e||typeof e!="string")return;let o=e.trim().slice(0,1e4);o&&(D||q(),setTimeout(()=>{s.contentWindow?.postMessage({type:"bitpalm-send-message",message:o},"*")},D?50:500))};function qe(){s.contentWindow?.postMessage({type:"bitpalm-theme",theme:c},"*")}let ie=e=>{e!==c&&(c=e,qe())},Ye=e=>{h=re(e),y?.(),y=null,h==="auto"?(y=xe(ie),ie(J())):ie(h)};h==="auto"&&(y=xe(ie));let Je=e=>{let o=e.detail;if(!o||typeof o!="object")return;let i=d(o.slug,120);i&&i!==t||Ye(re(o.theme))};window.addEventListener("bitpalm-theme",Je);let Y={},Ge=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;Y={...Y,...e};let o=JSON.stringify(Y);o.length>ct&&console.warn(`[BitPalm] Custom context exceeds ${ct} bytes (${o.length}). It may be truncated.`),s.contentWindow?.postMessage({type:"bitpalm-custom-context",data:Y},"*")},Tt=()=>{Y={},s.contentWindow?.postMessage({type:"bitpalm-custom-context",data:{}},"*")},Ke=e=>{let i=e.detail;if(!i||typeof i!="object")return;let b=d(i.slug,120);if(b&&b!==t)return;let{slug:A,...w}=i;Ge(w)};window.addEventListener("bitpalm-context",Ke);let Ve=e=>{let i=e.detail;if(!i||typeof i!="object")return;let b=d(i.slug,120);b&&b!==t||je(i)};window.addEventListener("bitpalm-identify",Ve);let be=e=>{let o=e.detail,i=d(o?.slug,120);return!i||i===t},Xe=e=>{be(e)&&q()},Ze=e=>{be(e)&&ye()},Qe=e=>{if(!be(e))return;let o=e.detail?.message;typeof o=="string"&&ze(o)};return window.addEventListener("bitpalm-open",Xe),window.addEventListener("bitpalm-close",Ze),window.addEventListener("bitpalm-send",Qe),{open:q,close:ye,toggle:wt,isOpen:Et,identify:je,context:Ge,resetContext:Tt,send:ze,on:(e,o)=>(B.has(e)||B.set(e,new Set),B.get(e).add(o),()=>B.get(e)?.delete(o)),off:(e,o)=>{B.get(e)?.delete(o)},setTheme:Ye,disableTriggers:bt,enableTriggers:vt,destroy:()=>{window.removeEventListener("message",Ce),window.removeEventListener("scroll",De),window.removeEventListener("popstate",oe),l.removeEventListener("mouseout",Ne),l.removeEventListener("submit",Be,!0),Fe.forEach(e=>l.removeEventListener(e,he)),clearTimeout(ge),clearTimeout(pe),He.forEach(e=>clearTimeout(e)),history.pushState=$e,history.replaceState=Oe,window.removeEventListener("bitpalm-identify",Ve),window.removeEventListener("bitpalm-context",Ke),window.removeEventListener("bitpalm-theme",Je),window.removeEventListener("bitpalm-open",Xe),window.removeEventListener("bitpalm-close",Ze),window.removeEventListener("bitpalm-send",Qe),y?.(),B.clear(),R(),M(),p.remove(),s.remove()}}}function Jt(n){let t=yt(null),a=yt(!1);return ht(()=>{t.current?.setTheme(n.theme??"auto")},[n.theme]),ht(()=>{if(a.current)return;a.current=!0;let{onReady:r,...m}=n;return t.current=pt(m),r?.(t.current),()=>{t.current?.destroy(),t.current=null,a.current=!1}},[]),null}export{Jt as BitPalmAgent};
1
+ import{useCallback as _e,useEffect as Me,useRef as fe,useState as J}from"react";function ct(n){if(n===!1)return"off";if(typeof n=="string"){let t=n.trim().toLowerCase();if(["false","off","0","no","none"].includes(t))return"off";if(t==="events")return"events"}return"bubble"}function dt(n,t){let i=n.createElement("div");i.setAttribute("data-bitpalm-trigger",""),i.style.cssText=`max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${t.zIndex-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`,i.style.position="fixed",i.style.right="24px",i.style.bottom=`${t.bottom}px`;let s=n.createElement("p");s.style.cssText="font-size:14px;color:#1f2937;margin:0;",s.textContent=t.message;let m=n.createElement("div");m.style.cssText="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;";let g=n.createElement("button");return g.type="button",g.setAttribute("aria-label","Close"),g.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",g.textContent="\u2715",g.onclick=p=>{p.stopPropagation(),t.onDismiss()},i.onclick=()=>t.onEngage(),i.append(s,m,g),i}var _t=["dark","dark-mode","dark-theme","theme-dark"],Mt=["light","light-mode","light-theme","theme-light"],ft=["data-theme","data-color-scheme","data-color-mode","data-mode","data-bs-theme"],gt="(prefers-color-scheme: dark)";function ue(n){return n==="light"||n==="dark"?n:"auto"}function ut(n){if(!n)return null;if(_t.some(t=>n.classList.contains(t)))return"dark";if(Mt.some(t=>n.classList.contains(t)))return"light";for(let t of ft){let i=(n.getAttribute(t)||"").toLowerCase();if(i.includes("dark"))return"dark";if(i.includes("light"))return"light"}return null}function Ae(n){let t=n/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4}function mt(n,t){if(!n)return null;let i=t.getComputedStyle(n).backgroundColor.match(/rgba?\(([^)]+)\)/);if(!i)return null;let[s,m,g,p=1]=i[1].split(/[\s,/]+/).filter(Boolean).map(Number);return[s,m,g,p].some(c=>Number.isNaN(c))||p<.5?null:.2126*Ae(s)+.7152*Ae(m)+.0722*Ae(g)<.2?"dark":"light"}function Bt(n,t){let i=t.getComputedStyle(n.documentElement).colorScheme||"",s=n.querySelector('meta[name="color-scheme"]')?.getAttribute("content")||"",m=`${i} ${s}`.toLowerCase();return m.includes("dark")?m.includes("light")?t.matchMedia?.(gt).matches?"dark":"light":"dark":null}function Z(n=document,t=window){return ut(n.documentElement)??ut(n.body)??mt(n.body,t)??mt(n.documentElement,t)??Bt(n,t)??"light"}function Le(n,t=document,i=window){let s=Z(t,i),m=!1,g=()=>{m=!1;let d=Z(t,i);d!==s&&(s=d,n(d))},p=()=>{m||(m=!0,typeof i.requestAnimationFrame=="function"?i.requestAnimationFrame(g):setTimeout(g,16))},b=typeof MutationObserver<"u"?new MutationObserver(p):null,c={attributes:!0,attributeFilter:["class","style",...ft]};b?.observe(t.documentElement,c),t.body&&b?.observe(t.body,c);let w=typeof i.matchMedia=="function"?i.matchMedia(gt):null;return w?.addEventListener?.("change",p),()=>{b?.disconnect(),w?.removeEventListener?.("change",p)}}var $t="https://agents.bitpalm.ai",I="_bp_",Ot=new Set(["password","file","checkbox","radio","submit","button","reset","image"]),Rt=8e3,pt=4096,ht=`${I}identify_signature`,yt=`${I}identify_fingerprint`,bt=`${I}identify_sent_at`,vt="0 4px 14px rgba(0,0,0,0.18)";function Ht(n){return[n.external_user_id||"",n.email||"",n.phone||"",n.name||"",n.company||"",n.signature||"",n.signed_at!=null?String(n.signed_at):"",n.signature_version||"",n.identify_source||""].join("|").toLowerCase()}function h(n,t=180){return n?n.replace(/\s+/g," ").trim().slice(0,t):""}function Dt(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function z(n,t){for(let i of t)if(n.includes(i))return!0;return!1}function H(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function $(n){let t=h(n,50);if(!t)return"";let i=t.startsWith("+"),s=t.replace(/\D/g,"");return s.length<6?"":`${i?"+":""}${s.slice(0,20)}`}function wt(n){let t=h(n,140).toLowerCase();return!t||!H(t)?"":t}function Y(n,t){for(let i of t){let s=n.querySelector(i),m=h(s?.value);if(m)return m}return""}function Ut(n){return h(n.getAttribute("data-bp-field")||n.getAttribute("data-bitpalm-field"),64).toLowerCase().replace(/[_\s]+/g,"-")}function Nt(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Wt(n,t){let i=[],s=(c,w=140)=>{let d=h(c,w);d&&i.push(d)};s(t.name),s(t.id),s(t.getAttribute("autocomplete")),s(t.getAttribute("placeholder")),s(t.getAttribute("aria-label")),s(t.getAttribute("data-field")),s(t.getAttribute("data-name")),s(t.getAttribute("data-label")),s(t.getAttribute("data-bp-field")),s(t.getAttribute("data-bitpalm-field"));let m=new Set,g=c=>{let w=h(c,200);!w||m.has(w)||(m.add(w),i.push(w))};for(let c of Array.from(t.labels||[]))g(c.textContent);if(t.id){let c=n.querySelector(`label[for="${Nt(t.id)}"]`);g(c?.textContent)}let p=t.closest("label");g(p?.textContent);let b=t.getAttribute("aria-labelledby");if(b)for(let c of b.split(/\s+/)){if(!c)continue;let w=n.ownerDocument.getElementById(c);g(w?.textContent)}return i}function jt(n){let t=h(Y(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),i=$(Y(n,["[data-bp-phone]","[data-bitpalm-phone]"])),s=h(Y(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),m=h(Y(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),g=h(Y(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),p=h(Y(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let d of Array.from(n.elements)){if(!(d instanceof HTMLInputElement||d instanceof HTMLTextAreaElement||d instanceof HTMLSelectElement)||d.disabled||d instanceof HTMLInputElement&&Ot.has(d.type.toLowerCase()))continue;let y=Ut(d),L=d.hasAttribute("data-bp-email")||d.hasAttribute("data-bitpalm-email")||d.hasAttribute("data-bp-phone")||d.hasAttribute("data-bitpalm-phone")||d.hasAttribute("data-bp-name")||d.hasAttribute("data-bitpalm-name")||d.hasAttribute("data-bp-full-name")||d.hasAttribute("data-bitpalm-full-name")||d.hasAttribute("data-bp-first-name")||d.hasAttribute("data-bitpalm-first-name")||d.hasAttribute("data-bp-last-name")||d.hasAttribute("data-bitpalm-last-name")||d.hasAttribute("data-bp-company")||d.hasAttribute("data-bitpalm-company")||!!y;if(d instanceof HTMLInputElement&&d.type.toLowerCase()==="hidden"&&!L)continue;let l=h(d.value);if(!l)continue;let u=d instanceof HTMLInputElement?d.type.toLowerCase():"",o=Dt(Wt(n,d).join(" "));if(!t&&y==="email"&&H(l)){t=l.toLowerCase();continue}if(!i&&(y==="phone"||y==="tel"||y==="mobile"||y==="whatsapp")){let C=$(l);if(C){i=C;continue}}if(!p&&y==="company"){p=h(l,160);continue}if(!m&&(y==="first-name"||y==="firstname")){m=h(l,100);continue}if(!g&&(y==="last-name"||y==="lastname"||y==="surname")){g=h(l,100);continue}if(!s&&(y==="name"||y==="full-name"||y==="fullname")){!H(l)&&!$(l)&&(s=h(l,140));continue}let v=u==="email"||z(o,[" email "," e mail "," mail "," email adresse "," mailadresse "," correo "]),_=u==="tel"||z(o,[" phone "," phone number "," mobile "," tel "," telefon "," telefonnummer "," whatsapp "," handy "," kontakt "," nummer "]),T=z(o,[" company "," company name "," firma "," firmenname "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),f=z(o,[" first name "," firstname "," given name "," givenname "," vorname "," fname "]),S=z(o,[" last name "," lastname "," family name "," familyname "," surname "," nachname "," lname "]),E=z(o,[" full name "," fullname "," contact name "," name "])&&!v&&!_;if(!t&&v&&H(l)){t=l.toLowerCase();continue}if(!i&&_){let C=$(l);if(C){i=C;continue}}if(!p&&T){p=h(l,160);continue}if(!m&&f){m=h(l,100);continue}if(!g&&S){g=h(l,100);continue}if(!s&&E&&!H(l)&&!$(l)){s=h(l,140);continue}!t&&H(l)&&(t=l.toLowerCase())}if(s&&(H(s)||$(s))&&(s=""),p&&(H(p)||$(p))&&(p=""),s||(s=h([m,g].filter(Boolean).join(" "),140)),s&&t&&s.toLowerCase()===t.toLowerCase()&&(s=""),!!!(t||i)&&!!!(s&&p))return null;let w={...s?{name:s}:{},...t?{email:t}:{},...i?{phone:i}:{},...p?{company:p}:{}};return Object.keys(w).length>0?w:null}function Ft(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function ke(n,t=1200){if(typeof window<"u"&&"requestIdleCallback"in window){window.requestIdleCallback(n,{timeout:t});return}setTimeout(n,Math.min(t,300))}function Pe(){if(typeof window>"u")return!1;let n=typeof navigator<"u"?navigator.userAgent:"";if(/Android|iPhone|iPad|iPod|IEMobile|Windows Phone|Mobile/i.test(n))return!0;let i=window.matchMedia("(pointer: coarse)").matches,s=window.matchMedia("(hover: none)").matches,m=Math.min(window.screen?.width||window.innerWidth,window.screen?.height||window.innerHeight);return i&&s&&m<=900}function xt(n){let{slug:t,locale:i=Ft(),baseUrl:s=$t,token:m,zIndex:g=9999,autoIdentify:p=!0,launcher:b=!0}=n,c=document,w=ue(n.theme),d=w==="auto"?Z():w,y=null,L=ct(n.triggers),l=L,u=null,o=c.createElement("iframe");o.setAttribute("data-bitpalm-chat","");let v=`${s}/t/${t}/widget`,_=new URLSearchParams({locale:i,theme:d});m&&_.set("token",m),l==="off"&&_.set("triggers","off"),o.src=`${v}?${_.toString()}`,o.allow="clipboard-write; microphone",o.setAttribute("allowtransparency","true"),o.loading="lazy",o.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${g};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;let T=new URL(o.src).origin,f=c.createElement("div");if(f.setAttribute("role","button"),f.setAttribute("aria-label","Chat"),f.setAttribute("data-bitpalm-launcher",""),f.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${g-1};background:#171717;box-shadow:${vt};transition:transform .2s,opacity .3s;opacity:0;`,f.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',f.onmouseenter=()=>{f.style.transform="scale(1.05)"},f.onmouseleave=()=>{f.style.transform="scale(1)"},f.onclick=()=>Q(),b&&c.body.appendChild(f),!c.getElementById("_bp_fade")){let e=c.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",c.head.appendChild(e)}let S=null,E=!1,C=!1,D=!1,G=!1,ee=!1,te=()=>{D||(D=!0,c.body.appendChild(o))},ne=!1,ge=0,oe={overflow:"",overscrollBehavior:""},k={overflow:"",overscrollBehavior:"",position:"",top:"",left:"",right:"",width:""},Be=()=>{if(ne||!Pe())return;let r=c.documentElement,a=c.body;ge=window.scrollY||window.pageYOffset||0,oe.overflow=r.style.overflow,oe.overscrollBehavior=r.style.overscrollBehavior,k.overflow=a.style.overflow,k.overscrollBehavior=a.style.overscrollBehavior,k.position=a.style.position,k.top=a.style.top,k.left=a.style.left,k.right=a.style.right,k.width=a.style.width,r.style.overflow="hidden",r.style.overscrollBehavior="none",a.style.overflow="hidden",a.style.overscrollBehavior="none",a.style.position="fixed",a.style.top=`-${ge}px`,a.style.left="0",a.style.right="0",a.style.width="100%",ne=!0},F=()=>{if(!ne)return;let e=c.documentElement,r=c.body;e.style.overflow=oe.overflow,e.style.overscrollBehavior=oe.overscrollBehavior,r.style.overflow=k.overflow,r.style.overscrollBehavior=k.overscrollBehavior,r.style.position=k.position,r.style.top=k.top,r.style.left=k.left,r.style.right=k.right,r.style.width=k.width,window.scrollTo(0,ge),ne=!1},$e=()=>{let e=Pe();o.style.display==="none"&&(o.style.display=""),e?(o.style.width="100vw",o.style.height="100dvh",o.style.left="0",o.style.top="0",o.style.bottom="0",o.style.right="0",Be()):(o.style.width="420px",o.style.height="620px",o.style.bottom="24px",o.style.right="24px",o.style.left="",o.style.top="",F()),o.style.opacity="1",o.style.pointerEvents="auto"},R=()=>{S&&(S.remove(),S=null)},re=()=>{u!==null&&(u=null,K("trigger_hidden"))},Oe=()=>{o.contentWindow?.postMessage({type:"bitpalm-triggers",enabled:l!=="off"},"*")},ie=()=>{},pe=()=>{},q=!1,U=new Map;function K(e,r){let a=U.get(e);if(a)for(let x of a)try{x(r)}catch{}}let Re=e=>{if(e.origin===T){if(e.data?.type==="bitpalm-widget-config"){C=!1,E=!0,o.style.display==="none"&&(o.style.display=""),e.data.primaryColor&&(f.style.background=e.data.primaryColor,f.style.boxShadow=e.data.chatShadow==="none"?"none":vt);let r=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){f.innerHTML="";let a=c.createElement("span");a.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${r}`;let A=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");A?(A.querySelectorAll("script,foreignObject").forEach(W=>W.remove()),A.querySelectorAll("*").forEach(W=>{for(let j of[...W.attributes])(j.name.startsWith("on")||j.value&&j.value.includes("javascript:"))&&W.removeAttribute(j.name)}),A.setAttribute("width","24"),A.setAttribute("height","24"),A.style.display="block",a.appendChild(A)):a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',f.appendChild(a)}else{let a=f.querySelector("svg");a&&(a.style.stroke=r)}b&&(f.style.display="flex",requestAnimationFrame(()=>{f.style.opacity="1"})),Oe()}if(e.data?.type==="bitpalm-widget-resize"){let r=e.data.width>0,a=q;q=r,r&&!a&&K("widget_opened"),!r&&a&&K("widget_closed");let x=Pe();r?(o.style.width=x?"100vw":`${e.data.width}px`,o.style.height=x?"100dvh":`${e.data.height}px`,x?(o.style.left="0",o.style.top="0",o.style.bottom="0",o.style.right="0",Be()):F(),o.style.opacity="1",o.style.pointerEvents="auto"):(F(),o.style.width="1px",o.style.height="1px",o.style.left="",o.style.top="",o.style.opacity="0",o.style.pointerEvents="none"),f.style.display=r||!b?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){if(C||!E||l==="off")return;let r=typeof e.data.message=="string"?e.data.message:"";if(!r)return;if(l==="events"){u=r,K("trigger_shown",{message:r,triggerId:e.data.triggerId,triggerType:e.data.triggerType});return}R(),S=dt(c,{message:r,zIndex:g,bottom:b?90:24,onDismiss:()=>{R(),o.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},onEngage:()=>{if(R(),f.style.display="none",$e(),te(),!G){ee=!0;return}o.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:r},"*")}}),c.body.appendChild(S)}e.data?.type==="bitpalm-trigger-hide"&&(R(),re()),e.data?.type==="bitpalm-request-context"&&ie(),e.data?.type==="bitpalm-chat-event"&&e.data.event&&K(e.data.event,e.data.data),e.data?.type==="bitpalm-widget-blocked"&&(C=!0,E=!1,f.style.display="none",R(),re(),F(),o.style.display="none")}};window.addEventListener("message",Re);let M=!1;try{M=localStorage.getItem(`${I}optout`)==="1"}catch{}let se=`${I}vid`,P="";if(!M){try{P=localStorage.getItem(se)||""}catch{}if(!P){let e=c.cookie.match(new RegExp(`(?:^|; )${se}=([^;]+)`));P=e?decodeURIComponent(e[1]):""}P||(P=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(se,P)}catch{}try{c.cookie=`${se}=${encodeURIComponent(P)};path=/;max-age=31536000;SameSite=Lax`}catch{}}M||ke(()=>{try{let e=new URLSearchParams(location.search),r={};for(let B of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let A=e.get(B);A&&(r[B]=A)}let a=JSON.stringify({tenant_slug:t,visitor_id:P,url:location.href,referrer:c.referrer||void 0,...Object.keys(r).length>0?{utm:r}:{}}),x=`${s}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(x,new Blob([a],{type:"application/json"})):fetch(x,{method:"POST",body:a,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}},2e3);let he="",ye="",be=0;try{he=sessionStorage.getItem(ht)||"",ye=sessionStorage.getItem(yt)||"";let e=parseInt(sessionStorage.getItem(bt)||"0",10);Number.isFinite(e)&&e>0&&(be=e)}catch{}let He=(e,r="")=>{if(M||!P)return;let a={},x=h(e.name,140),B=wt(e.email),A=$(e.phone),W=h(e.company,160),j=h(e.external_user_id,140),st=h(e.signature,260),Te=Number(e.signed_at);if(x&&(a.name=x),B&&(a.email=B),A&&(a.phone=A),W&&(a.company=W),j&&(a.external_user_id=j),st&&(a.signature=st),Number.isFinite(Te)&&Te>0&&(a.signed_at=Math.floor(Te)),(e.signature_version==="v1"||a.signature)&&(a.signature_version="v1"),(e.identify_source==="manual"||e.identify_source==="form")&&(a.identify_source=e.identify_source),!a.name&&!a.email&&!a.phone&&!a.company&&!a.external_user_id)return;let de=Ht(a),Ce=[r.toLowerCase(),de].filter(Boolean).join("|"),Ie=Date.now();if(!(Ie-be<Rt&&(Ce===he||de===ye))){he=Ce,ye=de,be=Ie;try{sessionStorage.setItem(ht,Ce),sessionStorage.setItem(yt,de),sessionStorage.setItem(bt,String(Ie))}catch{}try{let at=JSON.stringify({tenant_slug:t,visitor_id:P,url:location.href,referrer:c.referrer||void 0,...a}),lt=`${s}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(lt,new Blob([at],{type:"application/json"})):fetch(lt,{method:"POST",body:at,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}},De=e=>{if(M||!p||!P)return;let r=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(r instanceof HTMLFormElement))return;let a=(r.getAttribute("data-bp-identify")||r.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(a==="off"||a==="false"||a==="0")return;let x=jt(r);if(!x)return;let B=[r.getAttribute("id")||"",r.getAttribute("name")||"",r.getAttribute("action")||""].join("|");He({...x,identify_source:"form"},B)};!M&&p&&c.addEventListener("submit",De,!0);let V=parseInt(sessionStorage.getItem(`${I}pages`)||"0")+1;sessionStorage.setItem(`${I}pages`,String(V));let N=JSON.parse(sessionStorage.getItem(`${I}hist`)||"[]");N.push(location.href),N.length>20&&(N=N.slice(-20)),sessionStorage.setItem(`${I}hist`,JSON.stringify(N));let Ue=Date.now(),ae=parseInt(sessionStorage.getItem(`${I}site_start`)||"0");ae||(ae=Ue,sessionStorage.setItem(`${I}site_start`,String(ae)));let Ne=[];ie=()=>{let e=!1;try{e=!!localStorage.getItem(`${I}visited`)}catch{e=!1}if(o.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:c.title,returning:e,pageCount:V,pageHistory:N,loadedAt:Ue,siteStart:ae,locale:i,visitorId:M?"":P},"*"),Qe(),!e&&!M)try{localStorage.setItem(`${I}visited`,"1")}catch{}},o.addEventListener("load",()=>{G=!0,ie(),[120,450,1100].forEach(e=>{let r=setTimeout(()=>ie(),e);Ne.push(r)}),ee&&(ee=!1,pe())}),c.readyState==="loading"?c.addEventListener("DOMContentLoaded",()=>ke(te,1600),{once:!0}):ke(te,1600);let We=history.pushState.bind(history),je=history.replaceState.bind(history),le=()=>{V++,sessionStorage.setItem(`${I}pages`,String(V));let e=JSON.parse(sessionStorage.getItem(`${I}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),N=e,sessionStorage.setItem(`${I}hist`,JSON.stringify(e)),o.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:c.title,pageCount:V,pageHistory:e,loadedAt:Date.now()},"*"),!M)try{let r=JSON.stringify({tenant_slug:t,visitor_id:P,url:location.href}),a=`${s}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(a,new Blob([r],{type:"application/json"})):fetch(a,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){We(...e),le()},history.replaceState=function(...e){je(...e),le()},window.addEventListener("popstate",le);let Fe=-1,ve,qe=()=>{clearTimeout(ve),ve=setTimeout(()=>{let e=Math.max(c.documentElement.scrollHeight,c.body.scrollHeight)-window.innerHeight,r=e>0?Math.round(window.scrollY/e*100):100;r!==Fe&&(Fe=r,o.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:r},"*"))},500)};window.addEventListener("scroll",qe,{passive:!0});let ze=e=>{e.clientY<=0&&o.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};c.addEventListener("mouseout",ze);let we,Ye=!1,xe=()=>{clearTimeout(we),!Ye&&(we=setTimeout(()=>{Ye=!0,o.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},Je=["mousemove","keydown","scroll","touchstart"];Je.forEach(e=>c.addEventListener(e,xe,{passive:!0})),xe(),pe=()=>{o.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=o.src.split("#")[0];o.src=`${e}#bp-open-${Date.now()}`};let Q=()=>{if(f.style.display="none",R(),$e(),te(),!G){ee=!0;return}if(u!==null){let e=u;re(),o.contentWindow?.postMessage({type:"bitpalm-trigger-engaged",message:e},"*");return}pe()},Ge=e=>{l=e,e==="off"&&(R(),re()),Oe()},It=()=>Ge("off"),At=()=>Ge(L==="off"?"bubble":L),Ee=()=>{F(),o.contentWindow?.postMessage({type:"bitpalm-close"},"*")},Ke=e=>{!e||typeof e!="object"||He({external_user_id:h(e.externalUserId,140)||void 0,name:h(e.name,140)||void 0,email:wt(e.email)||void 0,phone:$(e.phone)||void 0,company:h(e.company,160)||void 0,signature:h(e.signature,260)||void 0,signed_at:Number.isFinite(Number(e.signedAt))?Math.floor(Number(e.signedAt)):void 0,signature_version:e.signatureVersion==="v1"?"v1":void 0,identify_source:"manual"},"manual")},Lt=()=>{q?Ee():Q()},kt=()=>q,Ve=e=>{if(!e||typeof e!="string")return;let r=e.trim().slice(0,1e4);r&&(q||Q(),setTimeout(()=>{o.contentWindow?.postMessage({type:"bitpalm-send-message",message:r},"*")},q?50:500))};function Qe(){o.contentWindow?.postMessage({type:"bitpalm-theme",theme:d},"*")}let ce=e=>{e!==d&&(d=e,Qe())},Xe=e=>{w=ue(e),y?.(),y=null,w==="auto"?(y=Le(ce),ce(Z())):ce(w)};w==="auto"&&(y=Le(ce));let Ze=e=>{let r=e.detail;if(!r||typeof r!="object")return;let a=h(r.slug,120);a&&a!==t||Xe(ue(r.theme))};window.addEventListener("bitpalm-theme",Ze);let X={},et=e=>{if(!e||typeof e!="object"||Array.isArray(e))return;X={...X,...e};let r=JSON.stringify(X);r.length>pt&&console.warn(`[BitPalm] Custom context exceeds ${pt} bytes (${r.length}). It may be truncated.`),o.contentWindow?.postMessage({type:"bitpalm-custom-context",data:X},"*")},Pt=()=>{X={},o.contentWindow?.postMessage({type:"bitpalm-custom-context",data:{}},"*")},tt=e=>{let a=e.detail;if(!a||typeof a!="object")return;let x=h(a.slug,120);if(x&&x!==t)return;let{slug:B,...A}=a;et(A)};window.addEventListener("bitpalm-context",tt);let nt=e=>{let a=e.detail;if(!a||typeof a!="object")return;let x=h(a.slug,120);x&&x!==t||Ke(a)};window.addEventListener("bitpalm-identify",nt);let Se=e=>{let r=e.detail,a=h(r?.slug,120);return!a||a===t},ot=e=>{Se(e)&&Q()},rt=e=>{Se(e)&&Ee()},it=e=>{if(!Se(e))return;let r=e.detail?.message;typeof r=="string"&&Ve(r)};return window.addEventListener("bitpalm-open",ot),window.addEventListener("bitpalm-close",rt),window.addEventListener("bitpalm-send",it),{open:Q,close:Ee,toggle:Lt,isOpen:kt,identify:Ke,context:et,resetContext:Pt,send:Ve,on:(e,r)=>(U.has(e)||U.set(e,new Set),U.get(e).add(r),()=>U.get(e)?.delete(r)),off:(e,r)=>{U.get(e)?.delete(r)},setTheme:Xe,disableTriggers:It,enableTriggers:At,destroy:()=>{window.removeEventListener("message",Re),window.removeEventListener("scroll",qe),window.removeEventListener("popstate",le),c.removeEventListener("mouseout",ze),c.removeEventListener("submit",De,!0),Je.forEach(e=>c.removeEventListener(e,xe)),clearTimeout(ve),clearTimeout(we),Ne.forEach(e=>clearTimeout(e)),history.pushState=We,history.replaceState=je,window.removeEventListener("bitpalm-identify",nt),window.removeEventListener("bitpalm-context",tt),window.removeEventListener("bitpalm-theme",Ze),window.removeEventListener("bitpalm-open",ot),window.removeEventListener("bitpalm-close",rt),window.removeEventListener("bitpalm-send",it),y?.(),U.clear(),F(),R(),f.remove(),o.remove()}}}function qt(n){let t=n.split(`
2
+ `).filter(i=>i.startsWith("data:")).map(i=>i.slice(5).trimStart()).join(`
3
+ `);if(!t)return null;try{let i=JSON.parse(t);return i&&typeof i.type=="string"?i:null}catch{return null}}function me(n){let t=[],i=n.replace(/\r\n/g,`
4
+ `),s=i.indexOf(`
5
+
6
+ `);for(;s>=0;){let m=qt(i.slice(0,s));m&&t.push(m),i=i.slice(s+2),s=i.indexOf(`
7
+
8
+ `)}return{events:t,rest:i}}function Et(n){return me(`${n}
9
+
10
+ `).events}var O=class extends Error{constructor(i,s,m){super(s);this.code=i;this.status=m;this.name="BitPalmApiError"}},zt="https://agents.bitpalm.ai";function Yt(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Jt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`v-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}async function Gt(n){let t=await n.json().catch(()=>null);return new O(t?.error?.code??"server_error",t?.error?.message??`Request failed (${n.status})`,n.status)}function St(n){if(!n?.key?.startsWith("bp_pk_"))throw new Error("createChatClient needs an app key (bp_pk_\u2026) from the BitPalm dashboard.");let t=(n.baseUrl??zt).replace(/\/+$/,""),i=n.storage===void 0?Yt():n.storage,s=`bitpalm:${n.key.slice(0,14)}`,m=l=>{try{return i?.getItem(`${s}:${l}`)??null}catch{return null}},g=(l,u)=>{try{u===null?i?.removeItem(`${s}:${l}`):i?.setItem(`${s}:${l}`,u)}catch{}},p=n.visitorId??m("visitor")??Jt();n.visitorId||g("visitor",p);let b=m("conversation"),c=!1,w={Authorization:`Bearer ${n.key}`},d=async(l,u)=>{let o=await fetch(`${t}${l}`,{...u,headers:{...w,...u?.headers??{}}});if(!o.ok)throw await Gt(o);return o},y=l=>{b=l,g("conversation",l)},L=(l,u,o)=>{for(let v of l)if(v.type==="delta")u.text+=v.text,o?.(v.text,u.text);else if(v.type==="replace")u.text=v.text,o?.("",u.text);else if(v.type==="done")u.result={text:u.text,conversationId:v.conversationId,...v.cards?{cards:v.cards}:{},...v.handoff?{handoff:!0}:{}};else if(v.type==="error")throw new O("server_error",v.message,500)};return{visitorId:p,get conversationId(){return b},get handoff(){return c},async agent(l){let u=new URLSearchParams({locale:n.locale??"en"});return l?.url&&u.set("url",l.url),(await d(`/api/v1/agent?${u.toString()}`)).json()},async send(l,u={}){let o=await d("/api/v1/chat",{method:"POST",headers:{"Content-Type":"application/json"},signal:u.signal,body:JSON.stringify({message:l,visitorId:p,conversationId:b??void 0,context:u.context,fileIds:u.fileIds})}),v={text:"",result:null},_=o.body&&typeof o.body.getReader=="function"?o.body.getReader():null;if(_){let f=new TextDecoder,S="";for(;;){let{done:E,value:C}=await _.read();if(E)break;let D=me(S+f.decode(C,{stream:!0}));S=D.rest,L(D.events,v,u.onDelta)}L(me(`${S}
11
+
12
+ `).events,v,u.onDelta)}else L(Et(await o.text()),v,u.onDelta);let T=v.result??{text:v.text,conversationId:b??""};return T.conversationId&&y(T.conversationId),c=T.handoff===!0,T},async history(){let l=new URLSearchParams({visitorId:p});b&&l.set("conversationId",b);let u=await(await d(`/api/v1/chat/history?${l.toString()}`)).json();return u.conversationId&&y(u.conversationId),c=u.handoff===!0,u.messages},async identify(l){await d("/api/v1/identify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...l,visitorId:p})})},async upload(l,u="photo.jpg"){let o=new FormData;o.append("file",l,u),o.append("visitorId",p),b&&o.append("conversationId",b);let v=await(await d("/api/v1/chat/upload",{method:"POST",body:o})).json();return{id:v.id,url:v.url}},async feedback(l,u){if(!b)throw new O("bad_request","There is no conversation yet.",400);await d("/api/v1/chat/feedback",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({visitorId:p,conversationId:b,messageIndex:l,feedback:u})})},reset(){y(null),c=!1}}}function un(n){let t=fe(null),i=fe(!1);return Me(()=>{t.current?.setTheme(n.theme??"auto")},[n.theme]),Me(()=>{if(i.current)return;i.current=!0;let{onReady:s,...m}=n;return t.current=xt(m),s?.(t.current),()=>{t.current?.destroy(),t.current=null,i.current=!1}},[]),null}function Tt(n,t){return[...n.slice(0,-1),t]}function Ct(n){let t=n[n.length-1];return t?.role==="assistant"&&!t.text&&!t.cards?.length?n.slice(0,-1):n}function mn(n){let[t]=J(()=>St(n)),[i,s]=J([]),[m,g]=J("idle"),[p,b]=J(null),[c,w]=J(null),[d,y]=J(!1),L=fe(!1),l=fe(0),u=n.loadHistory!==!1;Me(()=>{let T=!0;return t.agent().then(f=>T&&w(f)).catch(()=>{}),u&&t.history().then(f=>{T&&(s(S=>S.length?S:f),y(t.handoff))}).catch(()=>{}),()=>{T=!1}},[t,u]);let o=_e(async(T,f={})=>{let S=T.trim();if(!S&&!f.fileIds?.length)return null;s(E=>[...E,{role:"user",text:S},{role:"assistant",text:""}]),g("streaming"),b(null),L.current=!0,l.current+=1;try{let E=await t.send(S,{...f,onDelta:(C,D)=>s(G=>Tt(G,{role:"assistant",text:D}))});return s(C=>Ct(Tt(C,{role:"assistant",text:E.text,...E.cards?{cards:E.cards}:{}}))),y(E.handoff===!0),g("idle"),E}catch(E){let C=E instanceof O?E:new O("network_error",String(E),0);return s(Ct),b(C),g("error"),null}finally{L.current=!1}},[t]),v=_e(async()=>{if(L.current)return;let T=l.current,f=await t.history();L.current||l.current!==T||(s(f),y(t.handoff))},[t]),_=_e(()=>{t.reset(),s([]),b(null),y(!1),g("idle")},[t]);return{messages:i,send:o,status:m,error:p,agent:c,handoff:d,refresh:v,reset:_,client:t}}export{un as BitPalmAgent,O as BitPalmApiError,mn as useBitPalmChat};
2
13
  //# sourceMappingURL=react.js.map