@dashx/react 0.3.6 → 0.4.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/CHANGELOG.md CHANGED
@@ -2,6 +2,37 @@
2
2
 
3
3
  All notable changes to `@dashx/react` are documented in this file. Format loosely follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow [SemVer](https://semver.org/).
4
4
 
5
+ ## [0.4.0] — 2026-07-29
6
+
7
+ ### Changed
8
+
9
+ - **BREAKING — In-App Chat no longer creates conversations; the caller supplies one.** `useInAppChat` and both widgets participate in an EXISTING conversation:
10
+
11
+ ```diff
12
+ - useInAppChat({ identityId, idempotencyKey, initialMessage? })
13
+ + useInAppChat({ identityId, conversationId })
14
+ ```
15
+
16
+ `idempotencyKey` and `initialMessage` are gone, along with the create-on-mount behaviour. `<InAppChat>` and `<InAppChatButton>` take a required `conversationId` prop in place of `idempotencyKey`/`initialMessage`.
17
+
18
+ **Why.** Creating a chat is now server-only in DashX: identity-token callers are rejected outright, and the operation requires an `accountUid` naming the visitor — a claim no browser should be able to make. The conversation's `data`/`issueProperties` are metadata the agent console trusts, so they must be derived server-side. `@dashx/browser@0.10.0` therefore removes `startInAppChatConversation`, which is what this hook used.
19
+
20
+ **Migration.** Create the conversation in your backend (for JVM services, `dashx-java` ≥ 1.5.0 exposes `DashX.startInAppChatConversation(input)`), return the id to your client, and pass it in:
21
+
22
+ ```tsx
23
+ const { conversationId } = useMyBackendChatSession(); // your endpoint
24
+ <InAppChatButton identityId="<chat-identity-id>" conversationId={conversationId} />
25
+ ```
26
+
27
+ `conversationId` accepts `null` while you're still fetching it — the hook stays idle (no subscription, no history fetch) rather than guessing, so you can render the widget unconditionally.
28
+ - **`conversationId` is no longer returned from the hook.** The caller now owns it, so echoing it back was noise. Everything else in the response is unchanged: `messages`, `isLoading`, `isConnected`, `error`, `sendMessage`.
29
+ - `sendMessage(text)` returns `false` when there is no `conversationId` yet (or the hook is disabled) — same contract as before, so callers that keep the composer populated on `false` need no change.
30
+ - **`@dashx/browser` dependency raised to `^0.10.0`** (a regular `dependencies` entry, as before), which is the release that removes the creation method.
31
+
32
+ ### Unchanged
33
+
34
+ - History fetch, realtime subscribe, optimistic send + reconciliation, reconnect refetch, and the notification hook all behave exactly as before. `<InAppChatButton>` still activates lazily on first open, so a launcher the visitor never opens does no chat work.
35
+
5
36
  ## [0.3.0] — 2026-06-18
6
37
 
7
38
  ### Added
@@ -1,8 +1,7 @@
1
1
  import type { InAppChatMessageData } from '@dashx/browser';
2
2
  type UseInAppChatHookProps = {
3
3
  identityId: string;
4
- idempotencyKey: string;
5
- initialMessage?: string;
4
+ conversationId: string | null;
6
5
  enabled?: boolean;
7
6
  onInboundMessage?: (message: InAppChatMessageData) => void;
8
7
  };
@@ -16,7 +15,6 @@ type InAppChatMessage = {
16
15
  isPending?: boolean;
17
16
  };
18
17
  type UseInAppChatHookResponse = {
19
- conversationId: string | null;
20
18
  messages: InAppChatMessage[];
21
19
  isLoading: boolean;
22
20
  isConnected: boolean;
@@ -24,18 +22,22 @@ type UseInAppChatHookResponse = {
24
22
  sendMessage: (text: string) => boolean;
25
23
  };
26
24
  /**
27
- * Two-way InApp Chat for a visitor.
25
+ * Two-way InApp Chat within an EXISTING conversation.
26
+ *
27
+ * This hook participates; it never creates. Creating a conversation is a
28
+ * server-only operation — DashX rejects identity-token callers and requires an
29
+ * `accountUid` the browser has no authority to assert, and the conversation's
30
+ * metadata must be derived server-side. So the flow is: your backend creates the
31
+ * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.
28
32
  *
29
33
  * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
30
- * `identityToken` (and matching `identityUid`). The chat mutations require
31
- * identity-token auth — if the chat starts before an identity is resolved, they
32
- * are rejected and the hook surfaces an auth error. It does NOT auto-retry when
33
- * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
34
- * visitor token), so only render the chat once `identityToken` is available —
35
- * e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
36
- * this by starting lazily when the visitor opens it, by which point the provider
37
- * has applied the token.
34
+ * `identityToken` (and matching `identityUid`). Fetching history, sending, and
35
+ * subscribing all require identity-token auth — if they run before an identity is
36
+ * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry
37
+ * when a token arrives later (its inputs are `identityId`/`conversationId`, not the
38
+ * visitor token), so only render the chat once `identityToken` is available — e.g.
39
+ * `{identityToken && <InAppChat … />}`.
38
40
  */
39
- declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
41
+ declare const useInAppChat: ({ identityId, conversationId, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
40
42
  export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
41
43
  export default useInAppChat;
@@ -1,2 +1,2 @@
1
- "use strict";var L=Object.create;var A=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var K=Object.getPrototypeOf,N=Object.prototype.hasOwnProperty;var O=(e,n)=>{for(var s in n)A(e,s,{get:n[s],enumerable:!0})},k=(e,n,s,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of X(n))!N.call(e,t)&&t!==s&&A(e,t,{get:()=>n[t],enumerable:!(i=$(n,t))||i.enumerable});return e};var m=(e,n,s)=>(s=e!=null?L(K(e)):{},k(n||!e||!e.__esModule?A(s,"default",{value:e,enumerable:!0}):s,e)),T=e=>k(A({},"__esModule",{value:!0}),e);var G={};O(G,{default:()=>B});module.exports=T(G);var x=m(require("uuid-random")),r=require("react"),H=m(require("./use-dashx-provider.js")),w=require("../providers/DashXProvider.js");const W="in_app_chat:conversation:",y=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),z=(e,n)=>{const s=new Map,i=t=>t.externalUid||t.id;return[...e,...n].forEach(t=>{const o=s.get(i(t));(!o||o.isPending)&&s.set(i(t),t)}),[...s.values()].sort((t,o)=>t.createdAt!==o.createdAt?t.createdAt<o.createdAt?-1:1:(t.turnSeq??0)-(o.turnSeq??0))},j=({identityId:e,idempotencyKey:n,initialMessage:s,enabled:i=!0,onInboundMessage:t})=>{const o=(0,H.default)(),{isConnected:P,initializeWebSocket:b}=(0,w.useWebSocket)(),[E,v]=(0,r.useState)(null),[_,R]=(0,r.useState)([]),[q,f]=(0,r.useState)(!0),[D,d]=(0,r.useState)(null),c=(0,r.useRef)(0),M=(0,r.useRef)(null),U=(0,r.useRef)(t);U.current=t;const u=(0,r.useCallback)(p=>{R(a=>z(a,p))},[]);(0,r.useEffect)(()=>{const p=c.current+=1,a=()=>p!==c.current;if(v(null),R([]),d(null),M.current=null,!i)return f(!1),()=>{c.current+=1};f(!0),b();let g;return(async()=>{try{const h=await o.startInAppChatConversation({identityId:e,clientIdempotencyKey:n,...s?{content:{text:s},clientMessageId:`${n.slice(0,122)}-intro`}:{}});if(a())return;const l=h.id;v(l),M.current=l;const C=async()=>{const I=await o.fetchInAppChatMessages({conversationId:l});a()||u(I.map(y))},S=o.subscribeToChannel(`${W}${l}`,I=>{a()||(u([y(I)]),U.current?.(I))},{onReconnectAck:()=>{a()||(d(null),C().catch(()=>{}))}});g=S.unsubscribe;try{await S.ready}catch{a()||d("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(a())return;await C()}catch{a()||d("Failed to start chat")}finally{a()||f(!1)}})(),()=>{c.current+=1,g?.()}},[o,e,n,s,i,b,u]);const F=(0,r.useCallback)(p=>{const a=M.current;if(!p.trim()||!a)return!1;const g=c.current,h=(0,x.default)(),l={id:h,externalUid:`in_app_chat:${h}`,renderedContent:{text:p},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return u([l]),(async()=>{try{const C=await o.sendInAppChatMessage({conversationId:a,identityId:e,content:{text:p},clientMessageId:h});if(g!==c.current)return;u([y(C)])}catch{g===c.current&&d("Failed to send message")}})(),!0},[o,e,u]);return{conversationId:E,messages:_,isLoading:q,isConnected:P,error:D,sendMessage:F}};var B=j;
1
+ "use strict";var E=Object.create;var C=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var D=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var L=(e,n)=>{for(var s in n)C(e,s,{get:n[s],enumerable:!0})},R=(e,n,s,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of q(n))!F.call(e,t)&&t!==s&&C(e,t,{get:()=>n[t],enumerable:!(o=_(n,t))||o.enumerable});return e};var U=(e,n,s)=>(s=e!=null?E(D(e)):{},R(n||!e||!e.__esModule?C(s,"default",{value:e,enumerable:!0}):s,e)),X=e=>R(C({},"__esModule",{value:!0}),e);var O={};L(O,{default:()=>N});module.exports=X(O);var S=U(require("uuid-random")),a=require("react"),k=U(require("./use-dashx-provider.js")),m=require("../providers/DashXProvider.js");const $="in_app_chat:conversation:",M=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),v=(e,n)=>{const s=new Map,o=t=>t.externalUid||t.id;return[...e,...n].forEach(t=>{const i=s.get(o(t));(!i||i.isPending)&&s.set(o(t),t)}),[...s.values()].sort((t,i)=>t.createdAt!==i.createdAt?t.createdAt<i.createdAt?-1:1:(t.turnSeq??0)-(i.turnSeq??0))},K=({identityId:e,conversationId:n,enabled:s=!0,onInboundMessage:o})=>{const t=(0,k.default)(),{isConnected:i,initializeWebSocket:I}=(0,m.useWebSocket)(),[H,y]=(0,a.useState)([]),[x,f]=(0,a.useState)(!0),[P,d]=(0,a.useState)(null),p=(0,a.useRef)(0),b=(0,a.useRef)(o);b.current=o;const u=(0,a.useCallback)(c=>{y(r=>v(r,c))},[]);(0,a.useEffect)(()=>{const c=p.current+=1,r=()=>c!==p.current;if(y([]),d(null),!s||!n)return f(!1),()=>{p.current+=1};f(!0),I();let l;return(async()=>{try{const g=async()=>{const A=await t.fetchInAppChatMessages({conversationId:n});r()||u(A.map(M))},h=t.subscribeToChannel(`${$}${n}`,A=>{r()||(u([M(A)]),b.current?.(A))},{onReconnectAck:()=>{r()||(d(null),g().catch(()=>{}))}});l=h.unsubscribe;try{await h.ready}catch{r()||d("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(r())return;await g()}catch{r()||d("Failed to load chat")}finally{r()||f(!1)}})(),()=>{p.current+=1,l?.()}},[t,e,n,s,I,u]);const w=(0,a.useCallback)(c=>{if(!c.trim()||!n||!s)return!1;const r=p.current,l=(0,S.default)(),g={id:l,externalUid:`in_app_chat:${l}`,renderedContent:{text:c},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return u([g]),(async()=>{try{const h=await t.sendInAppChatMessage({conversationId:n,identityId:e,content:{text:c},clientMessageId:l});if(r!==p.current)return;u([M(h)])}catch{r===p.current&&d("Failed to send message")}})(),!0},[t,e,n,s,u]);return{messages:H,isLoading:x,isConnected:i,error:P,sendMessage:w}};var N=K;
2
2
  //# sourceMappingURL=use-in-app-chat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/hooks/use-in-app-chat.ts"],
4
- "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // Caller-supplied conversation key; the server uses it so repeat opens with\n // the same key resolve to the same conversation thread.\n idempotencyKey: string;\n // Optional automated first message sent when the conversation is first\n // created (e.g. \"Help with order #123\"). Sent via `startInAppChatConversation`\n // with a stable client message id, so it lands exactly once across reopens.\n initialMessage?: string;\n // When false, the hook is idle: no conversation is started, subscribed, or\n // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor\n // first opens the launcher, while keeping the hook mounted afterwards so its\n // subscription (and thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n conversationId: string | null;\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no conversation yet). Synchronous so the caller can clear the\n // composer immediately on `true`; callers keep the input populated on `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat for a visitor.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). The chat mutations require\n * identity-token auth \u2014 if the chat starts before an identity is resolved, they\n * are rejected and the hook surfaces an auth error. It does NOT auto-retry when\n * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014\n * e.g. `{identityToken && <InAppChat \u2026 />}`. `<InAppChatButton>` largely sidesteps\n * this by starting lazily when the visitor opens it, by which point the provider\n * has applied the token.\n */\nconst useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [conversationId, setConversationId] = useState<string | null>(null);\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/key change and on unmount so stale start/fetch/send\n // resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n const conversationIdRef = useRef<string | null>(null);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setConversationId(null);\n setMessages([]);\n setError(null);\n conversationIdRef.current = null;\n\n // Idle until enabled (e.g. before the launcher's first open): don't create a\n // conversation, subscribe, or fetch.\n if (!enabled) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const conversation = await dashX.startInAppChatConversation({\n identityId,\n clientIdempotencyKey: idempotencyKey,\n // Stable client message id \u2192 the automated message is inserted once,\n // even if the conversation is reopened (the server dedups repeat sends).\n // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is\n // truncated so the suffixed id stays within the 1-128 char limit.\n ...(initialMessage\n ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }\n : {}),\n });\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
- "mappings": "0jBAAA,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Y,CAChF,EAIA,IAAOjD,EAAQiB",
6
- "names": ["use_in_app_chat_exports", "__export", "use_in_app_chat_default", "__toCommonJS", "import_uuid_random", "import_react", "import_use_dashx_provider", "import_DashXProvider", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "useDashXProvider", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "uuid", "optimistic", "serverMessage"]
4
+ "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // The conversation to participate in. This hook does NOT create conversations:\n // creating one is server-only (DashX rejects identity-token callers), so your\n // backend creates it and hands you the id. Pass `null` while you don't have one\n // yet \u2014 the hook stays idle rather than guessing.\n conversationId: string | null;\n // When false, the hook is idle: nothing is subscribed or fetched. Lets\n // `<InAppChatButton>` defer the subscription until the visitor first opens the\n // launcher, while keeping the hook mounted afterwards so its subscription (and\n // thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no `conversationId`, or disabled). Synchronous so the caller can\n // clear the composer immediately on `true`; callers keep the input populated on\n // `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat within an EXISTING conversation.\n *\n * This hook participates; it never creates. Creating a conversation is a\n * server-only operation \u2014 DashX rejects identity-token callers and requires an\n * `accountUid` the browser has no authority to assert, and the conversation's\n * metadata must be derived server-side. So the flow is: your backend creates the\n * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). Fetching history, sending, and\n * subscribing all require identity-token auth \u2014 if they run before an identity is\n * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry\n * when a token arrives later (its inputs are `identityId`/`conversationId`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014 e.g.\n * `{identityToken && <InAppChat \u2026 />}`.\n */\nconst useInAppChat = ({ identityId, conversationId, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/conversation change and on unmount so stale\n // fetch/send resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setMessages([]);\n setError(null);\n\n // Idle until enabled (e.g. before the launcher's first open) and until the\n // caller has a conversation to join: don't subscribe or fetch.\n if (!enabled || !conversationId) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${conversationId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to load chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, conversationId, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n // Not ready (no conversation supplied yet, or the hook is disabled) \u2014 report\n // back so the caller can keep the typed text instead of clearing it on a\n // no-op send.\n if (!text.trim() || !conversationId || !enabled) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, conversationId, enabled, appendMessages],\n );\n\n return { messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAiB,0BACjBC,EAAyD,iBAGzDC,EAA6B,sCAC7BC,EAA6B,yCA+C7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB,CACpBC,EACAC,IACuB,CACvB,MAAMC,EAAQ,IAAI,IACZC,EAASL,GAA8BA,EAAQ,aAAeA,EAAQ,GAE5E,OAAC,GAAGE,EAAU,GAAGC,CAAQ,EAAE,QAASH,GAAY,CAC9C,MAAMM,EAAiBF,EAAM,IAAIC,EAAML,CAAO,CAAC,GAC3C,CAACM,GAAkBA,EAAe,YACpCF,EAAM,IAAIC,EAAML,CAAO,EAAGA,CAAO,CAErC,CAAC,EAEM,CAA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GAAG,EAGI,EACT,EACA,CAACT,EAAOJ,EAAYC,EAAgBC,EAASc,CAAc,CAC7D,EAEA,MAAO,CAAE,SAAAR,EAAU,UAAAE,EAAW,YAAAJ,EAAa,MAAAM,EAAO,YAAAa,CAAY,CAChE,EAIA,IAAO3C,EAAQiB",
6
+ "names": ["use_in_app_chat_exports", "__export", "use_in_app_chat_default", "__toCommonJS", "import_uuid_random", "import_react", "import_use_dashx_provider", "import_DashXProvider", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "conversationId", "enabled", "onInboundMessage", "dashX", "useDashXProvider", "isConnected", "initializeWebSocket", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "uuid", "optimistic", "serverMessage"]
7
7
  }
@@ -10,7 +10,7 @@ declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHea
10
10
  type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'> & {
11
11
  notifications?: boolean | InAppChatNotificationOptions;
12
12
  };
13
- declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
13
+ declare const InAppChatWrapper: ({ identityId, conversationId, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
14
14
  export type { InAppChatProps, InAppChatWrapperProps };
15
15
  export { InAppChat };
16
16
  export default InAppChatWrapper;
@@ -1,2 +1,2 @@
1
- "use strict";var S=Object.create;var u=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var z=(t,a)=>{for(var r in a)u(t,r,{get:a[r],enumerable:!0})},A=(t,a,r,p)=>{if(a&&typeof a=="object"||typeof a=="function")for(let s of H(a))!U.call(t,s)&&s!==r&&u(t,s,{get:()=>a[s],enumerable:!(p=k(a,s))||p.enumerable});return t};var m=(t,a,r)=>(r=t!=null?S(R(t)):{},A(a||!t||!t.__esModule?u(r,"default",{value:t,enumerable:!0}):r,t)),M=t=>A(u({},"__esModule",{value:!0}),t);var B={};z(B,{InAppChat:()=>b,default:()=>K});module.exports=M(B);var e=require("react/jsx-runtime"),l=m(require("@radix-ui/react-scroll-area")),d=require("react"),c=require("lucide-react"),o=require("../components"),f=require("../utils/cn.js"),I=m(require("../hooks/use-auto-scroll.js")),v=m(require("../hooks/use-in-app-chat.js")),w=m(require("../hooks/use-in-app-chat-notifications.js"));const O=t=>{const a=t.renderedContent;return typeof a=="string"?a:a?.text??""},E=t=>t.aiRole?.toUpperCase()==="USER",b=({messages:t,isLoading:a,error:r,sendMessage:p,withChatHeader:s=!1,withPopoverClose:h=!1,borderless:g=!1,title:N="Chat"})=>{const[i,x]=(0,d.useState)(""),{scrollAreaRef:P,scrollToBottom:y}=(0,I.default)();(0,d.useEffect)(()=>{setTimeout(()=>y({smooth:!0}),0)},[t.length,y]);const C=()=>{i.trim()&&p(i)&&x("")},T=n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),C())};return(0,e.jsx)(o.Theme,{asChild:!0,children:(0,e.jsxs)(o.Flex,{direction:"column",className:(0,f.cn)("h-full",!g&&"border border-gray-400/40"),children:[s&&(0,e.jsxs)(o.Flex,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[(0,e.jsx)(o.Heading,{size:3,children:N}),h&&(0,e.jsx)(o.Popover.Close,{children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:(0,e.jsx)(c.X,{})})})]}),(0,e.jsx)(o.Flex,{direction:"column",className:"grow overflow-auto bg-gray-50",children:(0,e.jsxs)(l.Root,{ref:P,className:"h-full grow p-6",children:[(0,e.jsx)(l.Viewport,{className:"h-full",children:(0,e.jsxs)(o.Flex,{direction:"column",gap:3,children:[t.map(n=>(0,e.jsx)("div",{className:(0,f.cn)("max-w-[80%] rounded-lg py-2 px-3",E(n)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:(0,e.jsx)(o.Text,{as:"p",size:2,children:O(n)})},n.externalUid||n.id)),a&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),r&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:r})]})}),(0,e.jsx)(l.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:(0,e.jsx)(l.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),(0,e.jsx)(l.Corner,{})]})}),(0,e.jsx)("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:(0,e.jsxs)(o.Flex,{gap:2,align:"end",className:"w-full",children:[(0,e.jsx)("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:(0,e.jsx)(o.TextArea,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:T,onChange:n=>x(n),roundness:"none",autogrow:!0})}),(0,e.jsx)("div",{className:"mr-[7px] mb-[7px]",children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:C,isDisabled:!i.trim(),children:(0,e.jsx)(c.Send,{size:20})})})]})})]})})},F=({identityId:t,idempotencyKey:a,initialMessage:r,notifications:p=!0,...s})=>{const h=(0,w.default)({isOpen:!0,enabled:p!==!1,options:{requestPermissionOn:"manual",...typeof p=="object"?p:void 0}}),g=(0,v.default)({identityId:t,idempotencyKey:a,initialMessage:r,onInboundMessage:h.handleInboundMessage});return(0,e.jsx)(b,{...g,...s})};var K=F;
1
+ "use strict";var S=Object.create;var u=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var R=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty;var z=(t,a)=>{for(var r in a)u(t,r,{get:a[r],enumerable:!0})},C=(t,a,r,p)=>{if(a&&typeof a=="object"||typeof a=="function")for(let s of H(a))!U.call(t,s)&&s!==r&&u(t,s,{get:()=>a[s],enumerable:!(p=k(a,s))||p.enumerable});return t};var m=(t,a,r)=>(r=t!=null?S(R(t)):{},C(a||!t||!t.__esModule?u(r,"default",{value:t,enumerable:!0}):r,t)),M=t=>C(u({},"__esModule",{value:!0}),t);var B={};z(B,{InAppChat:()=>f,default:()=>K});module.exports=M(B);var e=require("react/jsx-runtime"),l=m(require("@radix-ui/react-scroll-area")),d=require("react"),c=require("lucide-react"),o=require("../components"),g=require("../utils/cn.js"),A=m(require("../hooks/use-auto-scroll.js")),I=m(require("../hooks/use-in-app-chat.js")),v=m(require("../hooks/use-in-app-chat-notifications.js"));const O=t=>{const a=t.renderedContent;return typeof a=="string"?a:a?.text??""},E=t=>t.aiRole?.toUpperCase()==="USER",f=({messages:t,isLoading:a,error:r,sendMessage:p,withChatHeader:s=!1,withPopoverClose:h=!1,borderless:w=!1,title:N="Chat"})=>{const[i,b]=(0,d.useState)(""),{scrollAreaRef:P,scrollToBottom:x}=(0,A.default)();(0,d.useEffect)(()=>{setTimeout(()=>x({smooth:!0}),0)},[t.length,x]);const y=()=>{i.trim()&&p(i)&&b("")},T=n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),y())};return(0,e.jsx)(o.Theme,{asChild:!0,children:(0,e.jsxs)(o.Flex,{direction:"column",className:(0,g.cn)("h-full",!w&&"border border-gray-400/40"),children:[s&&(0,e.jsxs)(o.Flex,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[(0,e.jsx)(o.Heading,{size:3,children:N}),h&&(0,e.jsx)(o.Popover.Close,{children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:(0,e.jsx)(c.X,{})})})]}),(0,e.jsx)(o.Flex,{direction:"column",className:"grow overflow-auto bg-gray-50",children:(0,e.jsxs)(l.Root,{ref:P,className:"h-full grow p-6",children:[(0,e.jsx)(l.Viewport,{className:"h-full",children:(0,e.jsxs)(o.Flex,{direction:"column",gap:3,children:[t.map(n=>(0,e.jsx)("div",{className:(0,g.cn)("max-w-[80%] rounded-lg py-2 px-3",E(n)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:(0,e.jsx)(o.Text,{as:"p",size:2,children:O(n)})},n.externalUid||n.id)),a&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),r&&(0,e.jsx)(o.Text,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:r})]})}),(0,e.jsx)(l.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:(0,e.jsx)(l.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),(0,e.jsx)(l.Corner,{})]})}),(0,e.jsx)("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:(0,e.jsxs)(o.Flex,{gap:2,align:"end",className:"w-full",children:[(0,e.jsx)("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:(0,e.jsx)(o.TextArea,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:T,onChange:n=>b(n),roundness:"none",autogrow:!0})}),(0,e.jsx)("div",{className:"mr-[7px] mb-[7px]",children:(0,e.jsx)(o.Button,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:y,isDisabled:!i.trim(),children:(0,e.jsx)(c.Send,{size:20})})})]})})]})})},F=({identityId:t,conversationId:a,notifications:r=!0,...p})=>{const s=(0,v.default)({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),h=(0,I.default)({identityId:t,conversationId:a,onInboundMessage:s.handleInboundMessage});return(0,e.jsx)(f,{...h,...p})};var K=F;
2
2
  //# sourceMappingURL=InAppChat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChat.tsx"],
4
- "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:border-none! [&_textarea]:outline-none!\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
- "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,YAAAC,IAAA,eAAAC,E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B,CAIlI,MAAMC,KAAW,EAAAC,SAA0B,CACzC,OAAQ,GACR,QAASH,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKI,KAAO,EAAAC,SAAa,CACxB,WAAAR,EACA,eAAAC,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,SAAO,OAACvC,EAAA,CAAW,GAAGyC,EAAO,GAAGH,EAAO,CACzC,EAMA,IAAOrC,EAAQgC",
6
- "names": ["InAppChat_exports", "__export", "InAppChat", "InAppChat_default", "__toCommonJS", "import_jsx_runtime", "ScrollArea", "import_react", "import_lucide_react", "import_components", "import_cn", "import_use_auto_scroll", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "messageText", "message", "content", "isOutgoing", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "useAutoScroll", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "notifications", "props", "notifier", "useInAppChatNotifications", "chat", "useInAppChat"]
4
+ "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:border-none! [&_textarea]:outline-none!\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\n// `conversationId` is required (inherited from the hook's props): this widget\n// participates in a conversation your BACKEND created \u2014 it cannot create one, because\n// creating a chat is server-only in DashX. Pass `null` while you're still fetching the\n// id and the widget renders its empty/loading state instead of guessing.\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, conversationId, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n conversationId,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,eAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GAqEU,IAAAK,EAAA,6BArEVC,EAA4B,0CAC5BC,EAA2C,iBAC3CC,EAAwB,wBAGxBC,EAAsE,yBACtEC,EAAmB,0BACnBC,EAA0B,0CAC1BC,EAIO,0CACPC,EAEO,wDASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFb,EAAY,CAAC,CACjB,SAAAgB,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa,KAAI,YAAS,EAAE,EACzC,CAAE,cAAAC,EAAe,eAAAC,CAAe,KAAI,EAAAC,SA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Y,WAAW,UAAU,6BACrD,mBAACA,EAAW,MAAX,CAAiB,UAAU,iCAAiC,EAC/D,KACA,OAACA,EAAW,OAAX,EAAkB,GACrB,EACF,KAEA,OAAC,OAAI,UAAU,gDACb,oBAAC,QAAK,IAAK,EAAG,MAAM,MAAM,UAAU,SAClC,oBAAC,OAAI,UAAU,8DACb,mBAAC,YACC,aAAW,UACX,KAAK,aACL,YAAY,uBACZ,MAAOoB,EACP,UAAWM,EACX,SAAWE,GAASP,EAAcO,CAAI,EACtC,UAAU,OACV,SAAQ,GACV,EACF,KACA,OAAC,OAAI,UAAU,oBACb,mBAAC,UACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAASH,EACT,WAAY,CAACL,EAAW,KAAK,EAE7B,mBAAC,QAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAiBMS,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlH,MAAMC,KAAW,EAAAC,SAA0B,CACzC,OAAQ,GACR,QAASH,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKI,KAAO,EAAAC,SAAa,CACxB,WAAAP,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,SAAO,OAACtC,EAAA,CAAW,GAAGwC,EAAO,GAAGH,EAAO,CACzC,EAMA,IAAOpC,EAAQgC",
6
+ "names": ["InAppChat_exports", "__export", "InAppChat", "InAppChat_default", "__toCommonJS", "import_jsx_runtime", "ScrollArea", "import_react", "import_lucide_react", "import_components", "import_cn", "import_use_auto_scroll", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "messageText", "message", "content", "isOutgoing", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "useAutoScroll", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "conversationId", "notifications", "props", "notifier", "useInAppChatNotifications", "chat", "useInAppChat"]
7
7
  }
@@ -7,6 +7,6 @@ type InAppChatButtonProps = InAppChatWrapperProps & {
7
7
  /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
8
8
  theme?: ThemeProps;
9
9
  };
10
- declare const InAppChatButton: ({ identityId, idempotencyKey, initialMessage, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
10
+ declare const InAppChatButton: ({ identityId, conversationId, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
11
11
  export type { InAppChatButtonProps };
12
12
  export default InAppChatButton;
@@ -1,2 +1,2 @@
1
- "use strict";var R=Object.create;var i=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var L=Object.getOwnPropertyNames;var S=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var o in e)i(t,o,{get:e[o],enumerable:!0})},c=(t,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of L(e))!w.call(t,r)&&r!==o&&i(t,r,{get:()=>e[r],enumerable:!(a=x(e,r))||a.enumerable});return t};var g=(t,e,o)=>(o=t!=null?R(S(t)):{},c(e||!t||!t.__esModule?i(o,"default",{value:t,enumerable:!0}):o,t)),N=t=>c(i({},"__esModule",{value:!0}),t);var W={};M(W,{default:()=>F});module.exports=N(W);var p=require("react/jsx-runtime"),s=require("react"),C=require("lucide-react"),n=require("../components"),P=require("./InAppChat.js"),d=g(require("../hooks/use-in-app-chat.js")),b=g(require("../hooks/use-in-app-chat-notifications.js"));const q={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},z=({identityId:t,idempotencyKey:e,initialMessage:o,notifications:a=!0,position:r="bottom-right",theme:I,...A})=>{const[h,l]=(0,s.useState)(!1),u=(0,s.useRef)(!1);h&&(u.current=!0);const O=u.current,v=(0,s.useCallback)(()=>l(!0),[]),{handleInboundMessage:T,requestPermissionOnOpen:m}=(0,b.default)({isOpen:h,enabled:a!==!1,options:typeof a=="object"?a:void 0,onActivate:v}),y=(0,s.useCallback)(f=>{f&&m(),l(f)},[m]),B=(0,d.default)({identityId:t,idempotencyKey:e,initialMessage:o,enabled:O,onInboundMessage:T});return(0,p.jsx)(n.Theme,{...I,children:(0,p.jsx)(n.Flex,{className:`fixed z-50 ${q[r]}`,children:(0,p.jsxs)(n.Popover.Root,{open:h,onOpenChange:y,children:[(0,p.jsx)(n.Popover.Trigger,{children:(0,p.jsx)(n.Button,{shape:"square",roundness:"full",variant:"fill",size:"large",children:(0,p.jsx)(C.MessageCircle,{})})}),(0,p.jsx)(n.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:(0,p.jsx)(P.InAppChat,{...B,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...A})})]})})})};var F=z;
1
+ "use strict";var B=Object.create;var i=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var L=Object.getPrototypeOf,S=Object.prototype.hasOwnProperty;var w=(t,e)=>{for(var o in e)i(t,o,{get:e[o],enumerable:!0})},c=(t,e,o,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of x(e))!S.call(t,r)&&r!==o&&i(t,r,{get:()=>e[r],enumerable:!(a=R(e,r))||a.enumerable});return t};var g=(t,e,o)=>(o=t!=null?B(L(t)):{},c(e||!t||!t.__esModule?i(o,"default",{value:t,enumerable:!0}):o,t)),M=t=>c(i({},"__esModule",{value:!0}),t);var F={};w(F,{default:()=>z});module.exports=M(F);var p=require("react/jsx-runtime"),s=require("react"),C=require("lucide-react"),n=require("../components"),P=require("./InAppChat.js"),d=g(require("../hooks/use-in-app-chat.js")),b=g(require("../hooks/use-in-app-chat-notifications.js"));const N={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},q=({identityId:t,conversationId:e,notifications:o=!0,position:a="bottom-right",theme:r,...I})=>{const[h,l]=(0,s.useState)(!1),u=(0,s.useRef)(!1);h&&(u.current=!0);const A=u.current,O=(0,s.useCallback)(()=>l(!0),[]),{handleInboundMessage:v,requestPermissionOnOpen:m}=(0,b.default)({isOpen:h,enabled:o!==!1,options:typeof o=="object"?o:void 0,onActivate:O}),T=(0,s.useCallback)(f=>{f&&m(),l(f)},[m]),y=(0,d.default)({identityId:t,conversationId:e,enabled:A,onInboundMessage:v});return(0,p.jsx)(n.Theme,{...r,children:(0,p.jsx)(n.Flex,{className:`fixed z-50 ${N[a]}`,children:(0,p.jsxs)(n.Popover.Root,{open:h,onOpenChange:T,children:[(0,p.jsx)(n.Popover.Trigger,{children:(0,p.jsx)(n.Button,{shape:"square",roundness:"full",variant:"fill",size:"large",children:(0,p.jsx)(C.MessageCircle,{})})}),(0,p.jsx)(n.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:(0,p.jsx)(P.InAppChat,{...y,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...I})})]})})})};var z=q;
2
2
  //# sourceMappingURL=InAppChatButton.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChatButton.tsx"],
4
- "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n idempotencyKey,\n initialMessage,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first\n // open the hook is idle, so no conversation is created on page load.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
- "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GA2EQ,IAAAI,EAAA,6BA3ERC,EAAqD,iBACrDC,EAA8B,wBAE9BC,EAA8D,yBAC9DC,EAAsD,0BACtDC,EAAyB,0CACzBC,EAAsC,wDAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,KAAI,YAAS,EAAK,EAMpCC,KAAe,UAAO,EAAK,EAC7BF,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,KAAO,eAAY,IAAMH,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,KAAI,EAAAC,SAA0B,CAClF,OAAAP,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKI,KAAmB,eACtBC,GAAsB,CACjBA,GAAUH,EAAwB,EACtCL,EAAUQ,CAAQ,CACpB,EACA,CAACH,CAAuB,CAC1B,EAEMI,KAAO,EAAAC,SAAa,CACxB,WAAAlB,EACA,eAAAC,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,SACE,OAAC,SAAO,GAAGP,EACT,mBAAC,QAAK,UAAW,cAAcP,EAAeM,CAAQ,CAAC,GACrD,oBAAC,UAAQ,KAAR,CAAa,KAAMG,EAAQ,aAAcQ,EACxC,oBAAC,UAAQ,QAAR,CACC,mBAAC,UAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,mBAAC,kBAAc,EACjB,EACF,KAKA,OAAC,UAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,mBAAC,aACE,GAAGE,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGX,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOjB,EAAQU",
6
- "names": ["InAppChatButton_exports", "__export", "InAppChatButton_default", "__toCommonJS", "import_jsx_runtime", "import_react", "import_lucide_react", "import_components", "import_InAppChat", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "initialMessage", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "useInAppChatNotifications", "handleOpenChange", "nextOpen", "chat", "useInAppChat"]
4
+ "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n conversationId,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first open\n // the hook is idle, so a page that never opens the launcher does no chat work\n // (no subscription, no history fetch). It never created a conversation either \u2014\n // the conversation is created by your backend and passed in as `conversationId`.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n conversationId,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so a launcher the visitor never opens costs nothing. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
+ "mappings": "0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GA2EQ,IAAAI,EAAA,6BA3ERC,EAAqD,iBACrDC,EAA8B,wBAE9BC,EAA8D,yBAC9DC,EAAsD,0BACtDC,EAAyB,0CACzBC,EAAsC,wDAYtC,MAAMC,EAAmD,CACvD,eAAgB,mBAChB,cAAe,kBACf,YAAa,gBACb,WAAY,cACd,EAEMC,EAAkB,CAAC,CACvB,WAAAC,EACA,eAAAC,EACA,cAAAC,EAAgB,GAChB,SAAAC,EAAW,eACX,MAAAC,EACA,GAAGC,CACL,IAA4B,CAC1B,KAAM,CAACC,EAAQC,CAAS,KAAI,YAAS,EAAK,EAQpCC,KAAe,UAAO,EAAK,EAC7BF,IAAQE,EAAa,QAAU,IACnC,MAAMC,EAAUD,EAAa,QAEvBE,KAAO,eAAY,IAAMH,EAAU,EAAI,EAAG,CAAC,CAAC,EAE5C,CAAE,qBAAAI,EAAsB,wBAAAC,CAAwB,KAAI,EAAAC,SAA0B,CAClF,OAAAP,EACA,QAASJ,IAAkB,GAC3B,QAAS,OAAOA,GAAkB,SAAWA,EAAgB,OAC7D,WAAYQ,CACd,CAAC,EAKKI,KAAmB,eACtBC,GAAsB,CACjBA,GAAUH,EAAwB,EACtCL,EAAUQ,CAAQ,CACpB,EACA,CAACH,CAAuB,CAC1B,EAEMI,KAAO,EAAAC,SAAa,CACxB,WAAAjB,EACA,eAAAC,EACA,QAAAQ,EACA,iBAAkBE,CACpB,CAAC,EAED,SACE,OAAC,SAAO,GAAGP,EACT,mBAAC,QAAK,UAAW,cAAcN,EAAeK,CAAQ,CAAC,GACrD,oBAAC,UAAQ,KAAR,CAAa,KAAMG,EAAQ,aAAcQ,EACxC,oBAAC,UAAQ,QAAR,CACC,mBAAC,UAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,mBAAC,kBAAc,EACjB,EACF,KAKA,OAAC,UAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,mBAAC,aACE,GAAGE,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGX,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOhB,EAAQU",
6
+ "names": ["InAppChatButton_exports", "__export", "InAppChatButton_default", "__toCommonJS", "import_jsx_runtime", "import_react", "import_lucide_react", "import_components", "import_InAppChat", "import_use_in_app_chat", "import_use_in_app_chat_notifications", "POSITION_CLASS", "InAppChatButton", "identityId", "conversationId", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "useInAppChatNotifications", "handleOpenChange", "nextOpen", "chat", "useInAppChat"]
7
7
  }
@@ -1,8 +1,7 @@
1
1
  import type { InAppChatMessageData } from '@dashx/browser';
2
2
  type UseInAppChatHookProps = {
3
3
  identityId: string;
4
- idempotencyKey: string;
5
- initialMessage?: string;
4
+ conversationId: string | null;
6
5
  enabled?: boolean;
7
6
  onInboundMessage?: (message: InAppChatMessageData) => void;
8
7
  };
@@ -16,7 +15,6 @@ type InAppChatMessage = {
16
15
  isPending?: boolean;
17
16
  };
18
17
  type UseInAppChatHookResponse = {
19
- conversationId: string | null;
20
18
  messages: InAppChatMessage[];
21
19
  isLoading: boolean;
22
20
  isConnected: boolean;
@@ -24,18 +22,22 @@ type UseInAppChatHookResponse = {
24
22
  sendMessage: (text: string) => boolean;
25
23
  };
26
24
  /**
27
- * Two-way InApp Chat for a visitor.
25
+ * Two-way InApp Chat within an EXISTING conversation.
26
+ *
27
+ * This hook participates; it never creates. Creating a conversation is a
28
+ * server-only operation — DashX rejects identity-token callers and requires an
29
+ * `accountUid` the browser has no authority to assert, and the conversation's
30
+ * metadata must be derived server-side. So the flow is: your backend creates the
31
+ * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.
28
32
  *
29
33
  * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
30
- * `identityToken` (and matching `identityUid`). The chat mutations require
31
- * identity-token auth — if the chat starts before an identity is resolved, they
32
- * are rejected and the hook surfaces an auth error. It does NOT auto-retry when
33
- * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
34
- * visitor token), so only render the chat once `identityToken` is available —
35
- * e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
36
- * this by starting lazily when the visitor opens it, by which point the provider
37
- * has applied the token.
34
+ * `identityToken` (and matching `identityUid`). Fetching history, sending, and
35
+ * subscribing all require identity-token auth — if they run before an identity is
36
+ * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry
37
+ * when a token arrives later (its inputs are `identityId`/`conversationId`, not the
38
+ * visitor token), so only render the chat once `identityToken` is available — e.g.
39
+ * `{identityToken && <InAppChat … />}`.
38
40
  */
39
- declare const useInAppChat: ({ identityId, idempotencyKey, initialMessage, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
41
+ declare const useInAppChat: ({ identityId, conversationId, enabled, onInboundMessage }: UseInAppChatHookProps) => UseInAppChatHookResponse;
40
42
  export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
41
43
  export default useInAppChat;
@@ -1,2 +1,2 @@
1
- import _ from"uuid-random";import{useCallback as k,useEffect as q,useRef as M,useState as I}from"react";import D from"./use-dashx-provider.js";import{useWebSocket as F}from"../providers/DashXProvider.js";const L="in_app_chat:conversation:",y=e=>({id:e.id,externalUid:e.externalUid??null,renderedContent:e.renderedContent,aiRole:e.aiRole??null,createdAt:e.createdAt,turnSeq:e.turnSeq}),$=(e,p)=>{const r=new Map,u=t=>t.externalUid||t.id;return[...e,...p].forEach(t=>{const n=r.get(u(t));(!n||n.isPending)&&r.set(u(t),t)}),[...r.values()].sort((t,n)=>t.createdAt!==n.createdAt?t.createdAt<n.createdAt?-1:1:(t.turnSeq??0)-(n.turnSeq??0))},X=({identityId:e,idempotencyKey:p,initialMessage:r,enabled:u=!0,onInboundMessage:t})=>{const n=D(),{isConnected:m,initializeWebSocket:b}=F(),[x,v]=I(null),[H,R]=I([]),[w,A]=I(!0),[P,l]=I(null),o=M(0),f=M(null),U=M(t);U.current=t;const i=k(a=>{R(s=>$(s,a))},[]);q(()=>{const a=o.current+=1,s=()=>a!==o.current;if(v(null),R([]),l(null),f.current=null,!u)return A(!1),()=>{o.current+=1};A(!0),b();let d;return(async()=>{try{const g=await n.startInAppChatConversation({identityId:e,clientIdempotencyKey:p,...r?{content:{text:r},clientMessageId:`${p.slice(0,122)}-intro`}:{}});if(s())return;const c=g.id;v(c),f.current=c;const h=async()=>{const C=await n.fetchInAppChatMessages({conversationId:c});s()||i(C.map(y))},S=n.subscribeToChannel(`${L}${c}`,C=>{s()||(i([y(C)]),U.current?.(C))},{onReconnectAck:()=>{s()||(l(null),h().catch(()=>{}))}});d=S.unsubscribe;try{await S.ready}catch{s()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(s())return;await h()}catch{s()||l("Failed to start chat")}finally{s()||A(!1)}})(),()=>{o.current+=1,d?.()}},[n,e,p,r,u,b,i]);const E=k(a=>{const s=f.current;if(!a.trim()||!s)return!1;const d=o.current,g=_(),c={id:g,externalUid:`in_app_chat:${g}`,renderedContent:{text:a},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return i([c]),(async()=>{try{const h=await n.sendInAppChatMessage({conversationId:s,identityId:e,content:{text:a},clientMessageId:g});if(d!==o.current)return;i([y(h)])}catch{d===o.current&&l("Failed to send message")}})(),!0},[n,e,i]);return{conversationId:x,messages:H,isLoading:w,isConnected:m,error:P,sendMessage:E}};var W=X;export{W as default};
1
+ import H from"uuid-random";import{useCallback as b,useEffect as x,useRef as R,useState as C}from"react";import P from"./use-dashx-provider.js";import{useWebSocket as w}from"../providers/DashXProvider.js";const E="in_app_chat:conversation:",f=t=>({id:t.id,externalUid:t.externalUid??null,renderedContent:t.renderedContent,aiRole:t.aiRole??null,createdAt:t.createdAt,turnSeq:t.turnSeq}),_=(t,s)=>{const r=new Map,u=e=>e.externalUid||e.id;return[...t,...s].forEach(e=>{const a=r.get(u(e));(!a||a.isPending)&&r.set(u(e),e)}),[...r.values()].sort((e,a)=>e.createdAt!==a.createdAt?e.createdAt<a.createdAt?-1:1:(e.turnSeq??0)-(a.turnSeq??0))},q=({identityId:t,conversationId:s,enabled:r=!0,onInboundMessage:u})=>{const e=P(),{isConnected:a,initializeWebSocket:M}=w(),[U,I]=C([]),[S,A]=C(!0),[k,l]=C(null),o=R(0),y=R(u);y.current=u;const p=b(i=>{I(n=>_(n,i))},[]);x(()=>{const i=o.current+=1,n=()=>i!==o.current;if(I([]),l(null),!r||!s)return A(!1),()=>{o.current+=1};A(!0),M();let c;return(async()=>{try{const d=async()=>{const h=await e.fetchInAppChatMessages({conversationId:s});n()||p(h.map(f))},g=e.subscribeToChannel(`${E}${s}`,h=>{n()||(p([f(h)]),y.current?.(h))},{onReconnectAck:()=>{n()||(l(null),d().catch(()=>{}))}});c=g.unsubscribe;try{await g.ready}catch{n()||l("Couldn\u2019t connect to live chat. Retrying\u2026");return}if(n())return;await d()}catch{n()||l("Failed to load chat")}finally{n()||A(!1)}})(),()=>{o.current+=1,c?.()}},[e,t,s,r,M,p]);const m=b(i=>{if(!i.trim()||!s||!r)return!1;const n=o.current,c=H(),d={id:c,externalUid:`in_app_chat:${c}`,renderedContent:{text:i},aiRole:"USER",createdAt:new Date().toISOString(),isPending:!0};return p([d]),(async()=>{try{const g=await e.sendInAppChatMessage({conversationId:s,identityId:t,content:{text:i},clientMessageId:c});if(n!==o.current)return;p([f(g)])}catch{n===o.current&&l("Failed to send message")}})(),!0},[e,t,s,r,p]);return{messages:U,isLoading:S,isConnected:a,error:k,sendMessage:m}};var $=q;export{$ as default};
2
2
  //# sourceMappingURL=use-in-app-chat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/hooks/use-in-app-chat.ts"],
4
- "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // Caller-supplied conversation key; the server uses it so repeat opens with\n // the same key resolve to the same conversation thread.\n idempotencyKey: string;\n // Optional automated first message sent when the conversation is first\n // created (e.g. \"Help with order #123\"). Sent via `startInAppChatConversation`\n // with a stable client message id, so it lands exactly once across reopens.\n initialMessage?: string;\n // When false, the hook is idle: no conversation is started, subscribed, or\n // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor\n // first opens the launcher, while keeping the hook mounted afterwards so its\n // subscription (and thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n conversationId: string | null;\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no conversation yet). Synchronous so the caller can clear the\n // composer immediately on `true`; callers keep the input populated on `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat for a visitor.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). The chat mutations require\n * identity-token auth \u2014 if the chat starts before an identity is resolved, they\n * are rejected and the hook surfaces an auth error. It does NOT auto-retry when\n * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014\n * e.g. `{identityToken && <InAppChat \u2026 />}`. `<InAppChatButton>` largely sidesteps\n * this by starting lazily when the visitor opens it, by which point the provider\n * has applied the token.\n */\nconst useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [conversationId, setConversationId] = useState<string | null>(null);\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/key change and on unmount so stale start/fetch/send\n // resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n const conversationIdRef = useRef<string | null>(null);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setConversationId(null);\n setMessages([]);\n setError(null);\n conversationIdRef.current = null;\n\n // Idle until enabled (e.g. before the launcher's first open): don't create a\n // conversation, subscribe, or fetch.\n if (!enabled) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const conversation = await dashX.startInAppChatConversation({\n identityId,\n clientIdempotencyKey: idempotencyKey,\n // Stable client message id \u2192 the automated message is inserted once,\n // even if the conversation is reopened (the server dedups repeat sends).\n // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is\n // truncated so the suffixed id stays within the 1-128 char limit.\n ...(initialMessage\n ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }\n : {}),\n });\n if (isStale()) return;\n\n const convId = conversation.id;\n setConversationId(convId);\n conversationIdRef.current = convId;\n\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId: convId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${convId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to start chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n const convId = conversationIdRef.current;\n // Not ready (conversation still starting, or start failed) \u2014 report back so\n // the caller can keep the typed text instead of clearing it on a no-op send.\n if (!text.trim() || !convId) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId: convId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, appendMessages],\n );\n\n return { conversationId, messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
- "mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAAsB,0BAC7B,OAAS,gBAAAC,MAAoB,gCAiD7B,MAAMC,EAAsB,4BAEtBC,EAAeC,IAAqD,CACxE,GAAIA,EAAQ,GAGZ,YAAaA,EAAQ,aAAe,KACpC,gBAAiBA,EAAQ,gBACzB,OAAQA,EAAQ,QAAU,KAC1B,UAAWA,EAAQ,UACnB,QAASA,EAAQ,OACnB,GAOMC,EAAgB,CACpBC,EACAC,IACuB,CACvB,MAAMC,EAAQ,IAAI,IACZC,EAASL,GAA8BA,EAAQ,aAAeA,EAAQ,GAE5E,OAAC,GAAGE,EAAU,GAAGC,CAAQ,EAAE,QAASH,GAAY,CAC9C,MAAMM,EAAiBF,EAAM,IAAIC,EAAML,CAAO,CAAC,GAC3C,CAACM,GAAkBA,EAAe,YACpCF,EAAM,IAAIC,EAAML,CAAO,EAAGA,CAAO,CAErC,CAAC,EAEM,CAAC,GAAGI,EAAM,OAAO,CAAC,EAAE,KAAK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AiB,CAAE,KAAAD,CAAK,EACxB,OAAQ,OACR,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,UAAW,EACb,EACA,OAAAZ,EAAe,CAACc,CAAU,CAAC,GAErB,SAAY,CAChB,GAAI,CACF,MAAMC,EAAgB,MAAM7B,EAAM,qBAAqB,CACrD,eAAgBoB,EAChB,WAAAzB,EACA,QAAS,CAAE,KAAA+B,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIX,IAAeL,EAAc,QAAS,OAE1CG,EAAe,CAAC9B,EAAY6C,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFb,IAAeL,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACV,EAAOL,EAAYmB,CAAc,CACpC,EAEA,MAAO,CAAE,eAAAX,EAAgB,SAAAE,EAAU,UAAAE,EAAW,YAAAN,EAAa,MAAAQ,EAAO,YAAAgB,CAAY,CAChF,EAIA,IAAOK,EAAQpC",
6
- "names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "idempotencyKey", "initialMessage", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "conversationId", "setConversationId", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "conversationIdRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "conversation", "convId", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
4
+ "sourcesContent": ["import uuid from 'uuid-random';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { InAppChatMessageData } from '@dashx/browser';\n\nimport useDashXProvider from './use-dashx-provider.js';\nimport { useWebSocket } from '../providers/DashXProvider.js';\n\ntype UseInAppChatHookProps = {\n // The workspace's chat-identity id (the receiving surface), created when the\n // chat integration is installed; pasted into config alongside the public key.\n identityId: string;\n // The conversation to participate in. This hook does NOT create conversations:\n // creating one is server-only (DashX rejects identity-token callers), so your\n // backend creates it and hands you the id. Pass `null` while you don't have one\n // yet \u2014 the hook stays idle rather than guessing.\n conversationId: string | null;\n // When false, the hook is idle: nothing is subscribed or fetched. Lets\n // `<InAppChatButton>` defer the subscription until the visitor first opens the\n // launcher, while keeping the hook mounted afterwards so its subscription (and\n // thus notifications) survive the panel being closed.\n enabled?: boolean;\n // Invoked once per LIVE inbound message (not for history load / reconnect\n // refetch). Drives browser notifications without having to diff backfilled\n // history against live events.\n onInboundMessage?: (message: InAppChatMessageData) => void;\n};\n\n// UI-level message. `aiRole` distinguishes the visitor from agent/AI replies and\n// drives alignment; it arrives lowercase ('user'/'assistant'), so the widget\n// compares it case-insensitively (see `isOutgoing`).\ntype InAppChatMessage = {\n id: string;\n externalUid: string | null;\n renderedContent: any;\n aiRole: string | null;\n createdAt: string;\n turnSeq?: number;\n isPending?: boolean;\n};\n\ntype UseInAppChatHookResponse = {\n messages: InAppChatMessage[];\n isLoading: boolean;\n isConnected: boolean;\n error: string | null;\n // Returns `true` if the message was optimistically queued, `false` if the chat\n // wasn't ready (no `conversationId`, or disabled). Synchronous so the caller can\n // clear the composer immediately on `true`; callers keep the input populated on\n // `false`.\n sendMessage: (text: string) => boolean;\n};\n\nconst CHAT_CHANNEL_PREFIX = 'in_app_chat:conversation:';\n\nconst toUiMessage = (message: InAppChatMessageData): InAppChatMessage => ({\n id: message.id,\n // `externalUid` / `aiRole` are nullable in the schema, so the SDK types them as\n // optional; normalize the absent case to null for the UI message shape.\n externalUid: message.externalUid ?? null,\n renderedContent: message.renderedContent,\n aiRole: message.aiRole ?? null,\n createdAt: message.createdAt,\n turnSeq: message.turnSeq,\n});\n\n// Dedup by externalUid (server message replaces the optimistic pending one)\n// then id; order by createdAt as the authoritative key. `turnSeq` isn't in the\n// fetched message fields, so it's absent from history (which already arrives\n// ordered, preserved by the stable sort); it only breaks same-createdAt ties\n// among realtime WS events, which carry it.\nconst mergeMessages = (\n existing: InAppChatMessage[],\n incoming: InAppChatMessage[],\n): InAppChatMessage[] => {\n const byKey = new Map<string, InAppChatMessage>();\n const keyOf = (message: InAppChatMessage) => message.externalUid || message.id;\n\n [...existing, ...incoming].forEach((message) => {\n const existingForKey = byKey.get(keyOf(message));\n if (!existingForKey || existingForKey.isPending) {\n byKey.set(keyOf(message), message);\n }\n });\n\n return [...byKey.values()].sort((a, b) => {\n if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? -1 : 1;\n return (a.turnSeq ?? 0) - (b.turnSeq ?? 0);\n });\n};\n\n/**\n * Two-way InApp Chat within an EXISTING conversation.\n *\n * This hook participates; it never creates. Creating a conversation is a\n * server-only operation \u2014 DashX rejects identity-token callers and requires an\n * `accountUid` the browser has no authority to assert, and the conversation's\n * metadata must be derived server-side. So the flow is: your backend creates the\n * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.\n *\n * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid\n * `identityToken` (and matching `identityUid`). Fetching history, sending, and\n * subscribing all require identity-token auth \u2014 if they run before an identity is\n * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry\n * when a token arrives later (its inputs are `identityId`/`conversationId`, not the\n * visitor token), so only render the chat once `identityToken` is available \u2014 e.g.\n * `{identityToken && <InAppChat \u2026 />}`.\n */\nconst useInAppChat = ({ identityId, conversationId, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {\n const dashX = useDashXProvider();\n const { isConnected, initializeWebSocket } = useWebSocket();\n\n const [messages, setMessages] = useState<InAppChatMessage[]>([]);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n // Bumped on every identity/conversation change and on unmount so stale\n // fetch/send resolutions are ignored (the classic React async race).\n const generationRef = useRef(0);\n\n // Latest live-message callback, kept in a ref so changing its identity doesn't\n // tear down and re-create the channel subscription.\n const onInboundMessageRef = useRef(onInboundMessage);\n onInboundMessageRef.current = onInboundMessage;\n\n const appendMessages = useCallback((incoming: InAppChatMessage[]) => {\n setMessages((prev) => mergeMessages(prev, incoming));\n }, []);\n\n useEffect(() => {\n const generation = (generationRef.current += 1);\n const isStale = () => generation !== generationRef.current;\n\n setMessages([]);\n setError(null);\n\n // Idle until enabled (e.g. before the launcher's first open) and until the\n // caller has a conversation to join: don't subscribe or fetch.\n if (!enabled || !conversationId) {\n setIsLoading(false);\n return () => { generationRef.current += 1; };\n }\n\n setIsLoading(true);\n\n // Ensure the WS exists (idempotent \u2014 returns early if already created).\n initializeWebSocket();\n\n let unsubscribe: (() => void) | undefined;\n\n (async () => {\n try {\n const refetchHistory = async () => {\n const history = await dashX.fetchInAppChatMessages({ conversationId });\n if (isStale()) return;\n appendMessages(history.map(toUiMessage));\n };\n\n // Subscribe BEFORE fetching history so a reply landing in the gap is\n // buffered, not dropped. `onReconnectAck` fires on reconnect re-acks and\n // on a first ack that arrives after a `ready` timeout \u2014 both mean we are\n // (now) subscribed, so clear any connection error and (re)load history.\n const subscription = dashX.subscribeToChannel(\n `${CHAT_CHANNEL_PREFIX}${conversationId}`,\n (event) => {\n if (isStale()) return;\n appendMessages([toUiMessage(event)]);\n // LIVE messages only \u2014 history load / reconnect refetch go through\n // `refetchHistory`, so notification consumers never fire for\n // backfilled messages.\n onInboundMessageRef.current?.(event);\n },\n {\n onReconnectAck: () => {\n if (isStale()) return;\n setError(null);\n refetchHistory().catch(() => {});\n },\n },\n );\n unsubscribe = subscription.unsubscribe;\n\n // Load history only once the subscription is acked \u2014 fetching before\n // that would show history while silently never receiving realtime\n // replies. On ack failure, surface an error and defer the fetch to\n // `onReconnectAck` (fires if/when the channel finally acks).\n try {\n await subscription.ready;\n } catch {\n if (!isStale()) setError('Couldn\u2019t connect to live chat. Retrying\u2026');\n return;\n }\n if (isStale()) return;\n await refetchHistory();\n } catch {\n if (!isStale()) setError('Failed to load chat');\n } finally {\n if (!isStale()) setIsLoading(false);\n }\n })();\n\n return () => {\n // Invalidate in-flight async and drop the old channel before the next\n // conversation binds.\n generationRef.current += 1;\n unsubscribe?.();\n };\n }, [dashX, identityId, conversationId, enabled, initializeWebSocket, appendMessages]);\n\n // Synchronous on purpose: it returns `true` the moment the message is optimistically\n // queued and runs the network send in the background. The caller clears the composer\n // on `true` immediately \u2014 if it instead awaited the round-trip, a fast second Enter\n // would re-send the still-present text as a new message (fresh clientMessageId, so the\n // backend won't dedupe it) and create a duplicate.\n const sendMessage = useCallback(\n (text: string): boolean => {\n // Not ready (no conversation supplied yet, or the hook is disabled) \u2014 report\n // back so the caller can keep the typed text instead of clearing it on a\n // no-op send.\n if (!text.trim() || !conversationId || !enabled) return false;\n\n // Pin the generation so a response that resolves after the identity/key\n // changed (or unmount) can't contaminate the new conversation's state.\n const generation = generationRef.current;\n const clientMessageId = uuid();\n const optimistic: InAppChatMessage = {\n id: clientMessageId,\n externalUid: `in_app_chat:${clientMessageId}`,\n renderedContent: { text },\n aiRole: 'USER',\n createdAt: new Date().toISOString(),\n isPending: true,\n };\n appendMessages([optimistic]);\n\n void (async () => {\n try {\n const serverMessage = await dashX.sendInAppChatMessage({\n conversationId,\n identityId,\n content: { text },\n clientMessageId,\n });\n if (generation !== generationRef.current) return;\n // Reconcile by externalUid (the WS echo reconciles too \u2014 both idempotent).\n appendMessages([toUiMessage(serverMessage)]);\n } catch {\n if (generation === generationRef.current) setError('Failed to send message');\n }\n })();\n\n // Queued (optimistically appended) \u2014 the background send reconciles/errors later.\n return true;\n },\n [dashX, identityId, conversationId, enabled, appendMessages],\n );\n\n return { messages, isLoading, isConnected, error, sendMessage };\n};\n\nexport type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };\n\nexport default useInAppChat;\n"],
5
+ "mappings": "AAAA,OAAOA,MAAU,cACjB,OAAS,eAAAC,EAAa,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QAGzD,OAAOC,MAA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MAAO,GAIxD,MAAMe,EAAaJ,EAAc,QAC3Ba,EAAkB7C,EAAK,EACvB8C,EAA+B,CACnC,GAAID,EACJ,YAAa,eAAeA,CAAe,GAC3C,gBAAiB,CAAE,KAAAD,CAAK,EACxB,OAAQ,OACR,UAAW,IAAI,KAAK,EAAE,YAAY,EAClC,UAAW,EACb,EACA,OAAAV,EAAe,CAACY,CAAU,CAAC,GAErB,SAAY,CAChB,GAAI,CACF,MAAMC,EAAgB,MAAMxB,EAAM,qBAAqB,CACrD,eAAAH,EACA,WAAAD,EACA,QAAS,CAAE,KAAAyB,CAAK,EAChB,gBAAAC,CACF,CAAC,EACD,GAAIT,IAAeJ,EAAc,QAAS,OAE1CE,EAAe,CAAC1B,EAAYuC,CAAa,CAAC,CAAC,CAC7C,MAAQ,CACFX,IAAeJ,EAAc,SAASD,EAAS,wBAAwB,CAC7E,CACF,GAAG,EAGI,EACT,EACA,CAACR,EAAOJ,EAAYC,EAAgBC,EAASa,CAAc,CAC7D,EAEA,MAAO,CAAE,SAAAR,EAAU,UAAAE,EAAW,YAAAJ,EAAa,MAAAM,EAAO,YAAAa,CAAY,CAChE,EAIA,IAAOK,EAAQ9B",
6
+ "names": ["uuid", "useCallback", "useEffect", "useRef", "useState", "useDashXProvider", "useWebSocket", "CHAT_CHANNEL_PREFIX", "toUiMessage", "message", "mergeMessages", "existing", "incoming", "byKey", "keyOf", "existingForKey", "a", "b", "useInAppChat", "identityId", "conversationId", "enabled", "onInboundMessage", "dashX", "isConnected", "initializeWebSocket", "messages", "setMessages", "isLoading", "setIsLoading", "error", "setError", "generationRef", "onInboundMessageRef", "appendMessages", "prev", "generation", "isStale", "unsubscribe", "refetchHistory", "history", "subscription", "event", "sendMessage", "text", "clientMessageId", "optimistic", "serverMessage", "use_in_app_chat_default"]
7
7
  }
@@ -10,7 +10,7 @@ declare const InAppChat: ({ messages, isLoading, error, sendMessage, withChatHea
10
10
  type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse> & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'> & {
11
11
  notifications?: boolean | InAppChatNotificationOptions;
12
12
  };
13
- declare const InAppChatWrapper: ({ identityId, idempotencyKey, initialMessage, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
13
+ declare const InAppChatWrapper: ({ identityId, conversationId, notifications, ...props }: InAppChatWrapperProps) => import("react/jsx-runtime").JSX.Element;
14
14
  export type { InAppChatProps, InAppChatWrapperProps };
15
15
  export { InAppChat };
16
16
  export default InAppChatWrapper;
@@ -1,2 +1,2 @@
1
- import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as b,Flex as s,Heading as T,Popover as S,Text as c,TextArea as k,Theme as H}from"../components";import{cn as x}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";import z from"../hooks/use-in-app-chat-notifications.js";const M=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},O=o=>o.aiRole?.toUpperCase()==="USER",y=({messages:o,isLoading:a,error:l,sendMessage:r,withChatHeader:u=!1,withPopoverClose:m=!1,borderless:d=!1,title:C="Chat"})=>{const[i,h]=w(""),{scrollAreaRef:A,scrollToBottom:g}=R();v(()=>{setTimeout(()=>g({smooth:!0}),0)},[o.length,g]);const f=()=>{i.trim()&&r(i)&&h("")},I=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),f())};return e(H,{asChild:!0,children:p(s,{direction:"column",className:x("h-full",!d&&"border border-gray-400/40"),children:[u&&p(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(T,{size:3,children:C}),m&&e(S.Close,{children:e(b,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(P,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:p(n.Root,{ref:A,className:"h-full grow p-6",children:[e(n.Viewport,{className:"h-full",children:p(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:x("max-w-[80%] rounded-lg py-2 px-3",O(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(c,{as:"p",size:2,children:M(t)})},t.externalUid||t.id)),a&&e(c,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),l&&e(c,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:l})]})}),e(n.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(n.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(n.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:p(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:i,onKeyDown:I,onChange:t=>h(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(b,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:f,isDisabled:!i.trim(),children:e(N,{size:20})})})]})})]})})},E=({identityId:o,idempotencyKey:a,initialMessage:l,notifications:r=!0,...u})=>{const m=z({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),d=U({identityId:o,idempotencyKey:a,initialMessage:l,onInboundMessage:m.handleInboundMessage});return e(y,{...d,...u})};var _=E;export{y as InAppChat,_ as default};
1
+ import{jsx as e,jsxs as p}from"react/jsx-runtime";import*as n from"@radix-ui/react-scroll-area";import{useEffect as v,useState as w}from"react";import{Send as N,X as P}from"lucide-react";import{Button as f,Flex as s,Heading as T,Popover as S,Text as d,TextArea as k,Theme as H}from"../components";import{cn as b}from"../utils/cn.js";import R from"../hooks/use-auto-scroll.js";import U from"../hooks/use-in-app-chat.js";import z from"../hooks/use-in-app-chat-notifications.js";const M=o=>{const a=o.renderedContent;return typeof a=="string"?a:a?.text??""},O=o=>o.aiRole?.toUpperCase()==="USER",x=({messages:o,isLoading:a,error:r,sendMessage:i,withChatHeader:u=!1,withPopoverClose:m=!1,borderless:y=!1,title:C="Chat"})=>{const[l,c]=w(""),{scrollAreaRef:A,scrollToBottom:h}=R();v(()=>{setTimeout(()=>h({smooth:!0}),0)},[o.length,h]);const g=()=>{l.trim()&&i(l)&&c("")},I=t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),g())};return e(H,{asChild:!0,children:p(s,{direction:"column",className:b("h-full",!y&&"border border-gray-400/40"),children:[u&&p(s,{align:"center",justify:"between",className:"border-b border-b-gray-400/40 px-6 py-4",children:[e(T,{size:3,children:C}),m&&e(S.Close,{children:e(f,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(P,{})})})]}),e(s,{direction:"column",className:"grow overflow-auto bg-gray-50",children:p(n.Root,{ref:A,className:"h-full grow p-6",children:[e(n.Viewport,{className:"h-full",children:p(s,{direction:"column",gap:3,children:[o.map(t=>e("div",{className:b("max-w-[80%] rounded-lg py-2 px-3",O(t)?"bg-accent-600 ml-auto items-end text-white":"bg-gray-200 mr-auto items-start text-gray-900"),children:e(d,{as:"p",size:2,children:M(t)})},t.externalUid||t.id)),a&&e(d,{as:"p",size:2,className:"mr-auto text-gray-500",children:"Loading\u2026"}),r&&e(d,{as:"p",size:2,className:"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3",children:r})]})}),e(n.Scrollbar,{orientation:"vertical",className:"w-1 bg-gray-200 opacity-50",children:e(n.Thumb,{className:"flex-1 rounded-2xl bg-gray-400"})}),e(n.Corner,{})]})}),e("div",{className:"shrink-0 grow-0 border-t border-t-gray-400/40",children:p(s,{gap:2,align:"end",className:"w-full",children:[e("div",{className:"w-full [&_textarea]:border-none! [&_textarea]:outline-none!",children:e(k,{"aria-label":"message",size:"extralarge",placeholder:"Type a message\u2026",value:l,onKeyDown:I,onChange:t=>c(t),roundness:"none",autogrow:!0})}),e("div",{className:"mr-[7px] mb-[7px]",children:e(f,{shape:"square",roundness:"full",variant:"fill",size:"medium",onPress:g,isDisabled:!l.trim(),children:e(N,{size:20})})})]})})]})})},E=({identityId:o,conversationId:a,notifications:r=!0,...i})=>{const u=z({isOpen:!0,enabled:r!==!1,options:{requestPermissionOn:"manual",...typeof r=="object"?r:void 0}}),m=U({identityId:o,conversationId:a,onInboundMessage:u.handleInboundMessage});return e(x,{...m,...i})};var _=E;export{x as InAppChat,_ as default};
2
2
  //# sourceMappingURL=InAppChat.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChat.tsx"],
4
- "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:border-none! [&_textarea]:outline-none!\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
- "mappings": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,QAAAC,EAAM,KAAAC,MAAS,eAGxB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,YAAAC,EAAU,SAAAC,MAAa,gBACtE,OAAS,MAAAC,MAAU,iBACnB,OAAOC,MAAmB,8BAC1B,OAAOC,MAIA,8BACP,OAAOC,MAEA,4CASP,MAAMC,EAAeC,GAAsC,CACzD,MAAMC,EAAUD,EAAQ,gBACxB,OAAI,OAAOC,GAAY,SAAiBA,EACjCA,GAAS,MAAQ,EAC1B,EAEMC,EAAcF,GAAuCA,EAAQ,QAAQ,YAAY,IAAM,OAEvFG,EAAY,CAAC,CACjB,SAAAC,EACA,UAAAC,EACA,MAAAC,EACA,YAAAC,EACA,eAAAC,EAAiB,GACjB,iBAAAC,EAAmB,GACnB,WAAAC,EAAa,GACb,MAAAC,EAAQ,MACV,IAAsB,CACpB,KAAM,CAACC,EAAYC,CAAa,EAAI5B,EAAS,EAAE,EACzC,CAAE,cAAA6B,EAAe,eAAAC,CAAe,EAAInB,EAAc,EAExDZ,EAAU,IAAM,CACd,WAAW,IAAM+B,EAAe,CAAE,OAAQ,EAAK,CAAC,EAAG,CAAC,CACtD,EAAG,CAACX,EAAS,OAAQW,CAAc,CAAC,EAEpC,MAAMC,EAAe,IAAM,CACpBJ,EAAW,KAAK,GAKjBL,EAAYK,CAAU,GAAGC,EAAc,EAAE,CAC/C,EAEMI,EAAiBC,GAA0C,CAC3DA,EAAE,MAAQ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F,EAAC,OAAI,UAAU,gDACb,SAAAC,EAACO,EAAA,CAAK,IAAK,EAAG,MAAM,MAAM,UAAU,SAClC,UAAAR,EAAC,OAAI,UAAU,8DACb,SAAAA,EAACY,EAAA,CACC,aAAW,UACX,KAAK,aACL,YAAY,uBACZ,MAAOmB,EACP,UAAWK,EACX,SAAWE,GAASN,EAAcM,CAAI,EACtC,UAAU,OACV,SAAQ,GACV,EACF,EACAtC,EAAC,OAAI,UAAU,oBACb,SAAAA,EAACO,EAAA,CACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAAS4B,EACT,WAAY,CAACJ,EAAW,KAAK,EAE7B,SAAA/B,EAACK,EAAA,CAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAaMkC,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,eAAAC,EAAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlI,MAAMC,EAAW5B,EAA0B,CACzC,OAAQ,GACR,QAAS0B,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKG,EAAO9B,EAAa,CACxB,WAAAwB,EACA,eAAAC,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,OAAO7C,EAACsB,EAAA,CAAW,GAAGwB,EAAO,GAAGF,EAAO,CACzC,EAMA,IAAOG,EAAQR",
6
- "names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "idempotencyKey", "initialMessage", "notifications", "props", "notifier", "chat", "InAppChat_default"]
4
+ "sourcesContent": ["import * as ScrollArea from '@radix-ui/react-scroll-area';\nimport React, { useEffect, useState } from 'react';\nimport { Send, X } from 'lucide-react';\nimport type { KeyboardEvent } from 'react';\n\nimport { Button, Flex, Heading, Popover, Text, TextArea, Theme } from '../components';\nimport { cn } from '../utils/cn.js';\nimport useAutoScroll from '../hooks/use-auto-scroll.js';\nimport useInAppChat, {\n type InAppChatMessage,\n type UseInAppChatHookProps,\n type UseInAppChatHookResponse,\n} from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications, {\n type InAppChatNotificationOptions,\n} from '../hooks/use-in-app-chat-notifications.js';\n\ntype InAppChatProps = UseInAppChatHookResponse & {\n withChatHeader?: boolean;\n withPopoverClose?: boolean;\n borderless?: boolean;\n title?: string;\n};\n\nconst messageText = (message: InAppChatMessage): string => {\n const content = message.renderedContent;\n if (typeof content === 'string') return content;\n return content?.text ?? '';\n};\n\nconst isOutgoing = (message: InAppChatMessage): boolean => message.aiRole?.toUpperCase() === 'USER';\n\nconst InAppChat = ({\n messages,\n isLoading,\n error,\n sendMessage,\n withChatHeader = false,\n withPopoverClose = false,\n borderless = false,\n title = 'Chat',\n}: InAppChatProps) => {\n const [inputValue, setInputValue] = useState('');\n const { scrollAreaRef, scrollToBottom } = useAutoScroll();\n\n useEffect(() => {\n setTimeout(() => scrollToBottom({ smooth: true }), 0);\n }, [messages.length, scrollToBottom]);\n\n const handleSubmit = () => {\n if (!inputValue.trim()) return;\n // `sendMessage` is synchronous: it returns true the instant the message is\n // optimistically queued (network send runs in the background). Clear the\n // composer right away on success so a fast second Enter can't re-send the same\n // text as a duplicate; on false (chat not ready) keep the visitor's text.\n if (sendMessage(inputValue)) setInputValue('');\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n handleSubmit();\n }\n };\n\n return (\n <Theme asChild>\n <Flex direction=\"column\" className={cn('h-full', !borderless && 'border border-gray-400/40')}>\n {withChatHeader && (\n <Flex align=\"center\" justify=\"between\" className=\"border-b border-b-gray-400/40 px-6 py-4\">\n <Heading size={3}>{title}</Heading>\n {withPopoverClose && (\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n )}\n </Flex>\n )}\n\n <Flex direction=\"column\" className=\"grow overflow-auto bg-gray-50\">\n <ScrollArea.Root ref={scrollAreaRef} className=\"h-full grow p-6\">\n <ScrollArea.Viewport className=\"h-full\">\n <Flex direction=\"column\" gap={3}>\n {messages.map((message) => (\n <div\n key={message.externalUid || message.id}\n className={cn(\n 'max-w-[80%] rounded-lg py-2 px-3',\n isOutgoing(message)\n ? 'bg-accent-600 ml-auto items-end text-white'\n : 'bg-gray-200 mr-auto items-start text-gray-900',\n )}\n >\n <Text as=\"p\" size={2}>{messageText(message)}</Text>\n </div>\n ))}\n\n {isLoading && (\n <Text as=\"p\" size={2} className=\"mr-auto text-gray-500\">\n Loading\u2026\n </Text>\n )}\n\n {error && (\n <Text\n as=\"p\"\n size={2}\n className=\"bg-negative-100 text-negative-900 mx-auto rounded-lg py-2 px-3\"\n >\n {error}\n </Text>\n )}\n </Flex>\n </ScrollArea.Viewport>\n <ScrollArea.Scrollbar orientation=\"vertical\" className=\"w-1 bg-gray-200 opacity-50\">\n <ScrollArea.Thumb className=\"flex-1 rounded-2xl bg-gray-400\" />\n </ScrollArea.Scrollbar>\n <ScrollArea.Corner />\n </ScrollArea.Root>\n </Flex>\n\n <div className=\"shrink-0 grow-0 border-t border-t-gray-400/40\">\n <Flex gap={2} align=\"end\" className=\"w-full\">\n <div className=\"w-full [&_textarea]:border-none! [&_textarea]:outline-none!\">\n <TextArea\n aria-label=\"message\"\n size=\"extralarge\"\n placeholder=\"Type a message\u2026\"\n value={inputValue}\n onKeyDown={handleKeyDown}\n onChange={(text) => setInputValue(text)}\n roundness=\"none\"\n autogrow\n />\n </div>\n <div className=\"mr-[7px] mb-[7px]\">\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant=\"fill\"\n size=\"medium\"\n onPress={handleSubmit}\n isDisabled={!inputValue.trim()}\n >\n <Send size={20} />\n </Button>\n </div>\n </Flex>\n </div>\n </Flex>\n </Theme>\n );\n};\n\n// `conversationId` is required (inherited from the hook's props): this widget\n// participates in a conversation your BACKEND created \u2014 it cannot create one, because\n// creating a chat is server-only in DashX. Pass `null` while you're still fetching the\n// id and the widget renders its empty/loading state instead of guessing.\ntype InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>\n & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>\n & {\n // Foreground browser notifications for incoming agent/AI messages while the\n // chat isn't focused. `false` disables; an object customizes title/icon/body.\n // Default: enabled but silent until permission is granted (this always-visible\n // surface never auto-prompts \u2014 call `Client.requestNotificationPermission()`\n // from your own UI, or use `<InAppChatButton>` which prompts on first open).\n notifications?: boolean | InAppChatNotificationOptions;\n };\n\nconst InAppChatWrapper = ({ identityId, conversationId, notifications = true, ...props }: InAppChatWrapperProps) => {\n // Always-visible surface: treat as \"open\" and gate notifications on tab\n // visibility/focus only. No launcher gesture exists here, so default to\n // 'manual' permission (auto-requesting would prompt on mount).\n const notifier = useInAppChatNotifications({\n isOpen: true,\n enabled: notifications !== false,\n options: {\n requestPermissionOn: 'manual',\n ...(typeof notifications === 'object' ? notifications : undefined),\n },\n });\n const chat = useInAppChat({\n identityId,\n conversationId,\n onInboundMessage: notifier.handleInboundMessage,\n });\n return <InAppChat {...chat} {...props} />;\n};\n\nexport type { InAppChatProps, InAppChatWrapperProps };\n\nexport { InAppChat };\n\nexport default InAppChatWrapper;\n"],
5
+ "mappings": "AAqEU,OACE,OAAAA,EADF,QAAAC,MAAA,oBArEV,UAAYC,MAAgB,8BAC5B,OAAgB,aAAAC,EAAW,YAAAC,MAAgB,QAC3C,OAAS,Q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,CACC,MAAM,SACN,UAAU,OACV,QAAQ,OACR,KAAK,SACL,QAAS4B,EACT,WAAY,CAACJ,EAAW,KAAK,EAE7B,SAAA/B,EAACK,EAAA,CAAK,KAAM,GAAI,EAClB,EACF,GACF,EACF,GACF,EACF,CAEJ,EAiBMkC,EAAmB,CAAC,CAAE,WAAAC,EAAY,eAAAC,EAAgB,cAAAC,EAAgB,GAAM,GAAGC,CAAM,IAA6B,CAIlH,MAAMC,EAAW3B,EAA0B,CACzC,OAAQ,GACR,QAASyB,IAAkB,GAC3B,QAAS,CACP,oBAAqB,SACrB,GAAI,OAAOA,GAAkB,SAAWA,EAAgB,MAC1D,CACF,CAAC,EACKG,EAAO7B,EAAa,CACxB,WAAAwB,EACA,eAAAC,EACA,iBAAkBG,EAAS,oBAC7B,CAAC,EACD,OAAO5C,EAACsB,EAAA,CAAW,GAAGuB,EAAO,GAAGF,EAAO,CACzC,EAMA,IAAOG,EAAQP",
6
+ "names": ["jsx", "jsxs", "ScrollArea", "useEffect", "useState", "Send", "X", "Button", "Flex", "Heading", "Popover", "Text", "TextArea", "Theme", "cn", "useAutoScroll", "useInAppChat", "useInAppChatNotifications", "messageText", "message", "content", "isOutgoing", "InAppChat", "messages", "isLoading", "error", "sendMessage", "withChatHeader", "withPopoverClose", "borderless", "title", "inputValue", "setInputValue", "scrollAreaRef", "scrollToBottom", "handleSubmit", "handleKeyDown", "e", "text", "InAppChatWrapper", "identityId", "conversationId", "notifications", "props", "notifier", "chat", "InAppChat_default"]
7
7
  }
@@ -7,6 +7,6 @@ type InAppChatButtonProps = InAppChatWrapperProps & {
7
7
  /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, …). */
8
8
  theme?: ThemeProps;
9
9
  };
10
- declare const InAppChatButton: ({ identityId, idempotencyKey, initialMessage, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
10
+ declare const InAppChatButton: ({ identityId, conversationId, notifications, position, theme, ...props }: InAppChatButtonProps) => import("react/jsx-runtime").JSX.Element;
11
11
  export type { InAppChatButtonProps };
12
12
  export default InAppChatButton;
@@ -1,2 +1,2 @@
1
- import{jsx as t,jsxs as w}from"react/jsx-runtime";import{useCallback as i,useRef as I,useState as A}from"react";import{MessageCircle as O}from"lucide-react";import{Button as v,Flex as T,Popover as p,Theme as y}from"../components";import{InAppChat as B}from"./InAppChat.js";import R from"../hooks/use-in-app-chat.js";import x from"../hooks/use-in-app-chat-notifications.js";const L={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},S=({identityId:h,idempotencyKey:l,initialMessage:u,notifications:e=!0,position:m="bottom-right",theme:f,...c})=>{const[o,n]=A(!1),r=I(!1);o&&(r.current=!0);const g=r.current,C=i(()=>n(!0),[]),{handleInboundMessage:P,requestPermissionOnOpen:s}=x({isOpen:o,enabled:e!==!1,options:typeof e=="object"?e:void 0,onActivate:C}),d=i(a=>{a&&s(),n(a)},[s]),b=R({identityId:h,idempotencyKey:l,initialMessage:u,enabled:g,onInboundMessage:P});return t(y,{...f,children:t(T,{className:`fixed z-50 ${L[m]}`,children:w(p.Root,{open:o,onOpenChange:d,children:[t(p.Trigger,{children:t(v,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(O,{})})}),t(p.Content,{spacing:"large",width:"350px",height:"450px",children:t(B,{...b,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...c})})]})})})};var H=S;export{H as default};
1
+ import{jsx as t,jsxs as S}from"react/jsx-runtime";import{useCallback as i,useRef as b,useState as I}from"react";import{MessageCircle as A}from"lucide-react";import{Button as O,Flex as v,Popover as p,Theme as T}from"../components";import{InAppChat as y}from"./InAppChat.js";import B from"../hooks/use-in-app-chat.js";import R from"../hooks/use-in-app-chat-notifications.js";const x={"bottom-right":"right-4 bottom-4","bottom-left":"left-4 bottom-4","top-right":"right-4 top-4","top-left":"left-4 top-4"},L=({identityId:h,conversationId:l,notifications:e=!0,position:u="bottom-right",theme:m,...f})=>{const[o,n]=I(!1),r=b(!1);o&&(r.current=!0);const c=r.current,g=i(()=>n(!0),[]),{handleInboundMessage:C,requestPermissionOnOpen:s}=R({isOpen:o,enabled:e!==!1,options:typeof e=="object"?e:void 0,onActivate:g}),P=i(a=>{a&&s(),n(a)},[s]),d=B({identityId:h,conversationId:l,enabled:c,onInboundMessage:C});return t(T,{...m,children:t(v,{className:`fixed z-50 ${x[u]}`,children:S(p.Root,{open:o,onOpenChange:P,children:[t(p.Trigger,{children:t(O,{shape:"square",roundness:"full",variant:"fill",size:"large",children:t(A,{})})}),t(p.Content,{spacing:"large",width:"350px",height:"450px",children:t(y,{...d,borderless:!0,withChatHeader:!0,withPopoverClose:!0,...f})})]})})})};var k=L;export{k as default};
2
2
  //# sourceMappingURL=InAppChatButton.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/widgets/InAppChatButton.tsx"],
4
- "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n idempotencyKey,\n initialMessage,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first\n // open the hook is idle, so no conversation is created on page load.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n idempotencyKey,\n initialMessage,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so no empty conversation is created on page load. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default InAppChatButton;\n"],
5
- "mappings": "AA2EQ,OAGM,OAAAA,EAHN,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AA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAN,EAACK,EAAA,EAAc,EACjB,EACF,EAKAL,EAACQ,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAR,EAACU,EAAA,CACE,GAAGqB,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGV,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOW,EAAQlB",
6
- "names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "POSITION_CLASS", "InAppChatButton", "identityId", "idempotencyKey", "initialMessage", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "handleOpenChange", "nextOpen", "chat", "InAppChatButton_default"]
4
+ "sourcesContent": ["import React, { useCallback, useRef, useState } from 'react';\nimport { MessageCircle } from 'lucide-react';\n\nimport { Button, Flex, Popover, Theme, type ThemeProps } from '../components';\nimport { InAppChat, type InAppChatWrapperProps } from './InAppChat.js';\nimport useInAppChat from '../hooks/use-in-app-chat.js';\nimport useInAppChatNotifications from '../hooks/use-in-app-chat-notifications.js';\n\ntype LauncherPosition = 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left';\n\ntype InAppChatButtonProps = InAppChatWrapperProps & {\n /** Where the floating launcher sits on screen. Defaults to `bottom-right`. */\n position?: LauncherPosition,\n /** Theme overrides for the launcher + chat surface (accent color, mode, roundness, \u2026). */\n theme?: ThemeProps,\n};\n\n// Full, non-interpolated class strings so Tailwind can detect them.\nconst POSITION_CLASS: Record<LauncherPosition, string> = {\n 'bottom-right': 'right-4 bottom-4',\n 'bottom-left': 'left-4 bottom-4',\n 'top-right': 'right-4 top-4',\n 'top-left': 'left-4 top-4',\n};\n\nconst InAppChatButton = ({\n identityId,\n conversationId,\n notifications = true,\n position = 'bottom-right',\n theme,\n ...props\n}: InAppChatButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n\n // Latch: once the launcher has been opened, keep the chat hook active so its\n // channel subscription persists while the panel is closed \u2014 that's what lets\n // us notify on replies that land while the panel is shut. Before the first open\n // the hook is idle, so a page that never opens the launcher does no chat work\n // (no subscription, no history fetch). It never created a conversation either \u2014\n // the conversation is created by your backend and passed in as `conversationId`.\n const hasOpenedRef = useRef(false);\n if (isOpen) hasOpenedRef.current = true;\n const enabled = hasOpenedRef.current;\n\n const open = useCallback(() => setIsOpen(true), []);\n\n const { handleInboundMessage, requestPermissionOnOpen } = useInAppChatNotifications({\n isOpen,\n enabled: notifications !== false,\n options: typeof notifications === 'object' ? notifications : undefined,\n onActivate: open,\n });\n\n // Request notification permission inside the open gesture (synchronously), so\n // the prompt runs within the browser's transient user activation \u2014 requesting\n // from an effect after the click unwinds is ignored on some browsers.\n const handleOpenChange = useCallback(\n (nextOpen: boolean) => {\n if (nextOpen) requestPermissionOnOpen();\n setIsOpen(nextOpen);\n },\n [requestPermissionOnOpen],\n );\n\n const chat = useInAppChat({\n identityId,\n conversationId,\n enabled,\n onInboundMessage: handleInboundMessage,\n });\n\n return (\n <Theme {...theme}>\n <Flex className={`fixed z-50 ${POSITION_CLASS[position]}`}>\n <Popover.Root open={isOpen} onOpenChange={handleOpenChange}>\n <Popover.Trigger>\n <Button shape=\"square\" roundness=\"full\" variant=\"fill\" size=\"large\">\n <MessageCircle />\n </Button>\n </Popover.Trigger>\n {/* The chat hook lives at the launcher level (above the popover) so its\n subscription survives the panel closing \u2014 required to notify on\n replies that arrive while the panel is shut. It activates lazily on\n first open, so a launcher the visitor never opens costs nothing. */}\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <InAppChat\n {...chat}\n borderless\n withChatHeader\n withPopoverClose\n {...props}\n />\n </Popover.Content>\n </Popover.Root>\n </Flex>\n </Theme>\n );\n};\n\nexport type { InAppChatButtonProps };\n\nexport default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AAQ,QAAR,CACC,SAAAR,EAACM,EAAA,CAAO,MAAM,SAAS,UAAU,OAAO,QAAQ,OAAO,KAAK,QAC1D,SAAAN,EAACK,EAAA,EAAc,EACjB,EACF,EAKAL,EAACQ,EAAQ,QAAR,CAAgB,QAAQ,QAAQ,MAAM,QAAQ,OAAO,QACpD,SAAAR,EAACU,EAAA,CACE,GAAGoB,EACJ,WAAU,GACV,eAAc,GACd,iBAAgB,GACf,GAAGV,EACN,EACF,GACF,EACF,EACF,CAEJ,EAIA,IAAOW,EAAQjB",
6
+ "names": ["jsx", "jsxs", "useCallback", "useRef", "useState", "MessageCircle", "Button", "Flex", "Popover", "Theme", "InAppChat", "useInAppChat", "useInAppChatNotifications", "POSITION_CLASS", "InAppChatButton", "identityId", "conversationId", "notifications", "position", "theme", "props", "isOpen", "setIsOpen", "hasOpenedRef", "enabled", "open", "handleInboundMessage", "requestPermissionOnOpen", "handleOpenChange", "nextOpen", "chat", "InAppChatButton_default"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dashx/react",
3
- "version": "0.3.6",
3
+ "version": "0.4.0",
4
4
  "license": "UNLICENSED",
5
5
  "type": "commonjs",
6
6
  "main": "./dist/cjs/index.js",
@@ -75,7 +75,7 @@
75
75
  "clean": "rm -rf .turbo node_modules dist tokens layout *.css"
76
76
  },
77
77
  "dependencies": {
78
- "@dashx/browser": "^0.8.5",
78
+ "@dashx/browser": "^0.10.0",
79
79
  "@radix-ui/colors": "^3.0.0",
80
80
  "@radix-ui/primitive": "^1.1.3",
81
81
  "@radix-ui/react-accessible-icon": "^1.1.8",
@@ -9,17 +9,15 @@ type UseInAppChatHookProps = {
9
9
  // The workspace's chat-identity id (the receiving surface), created when the
10
10
  // chat integration is installed; pasted into config alongside the public key.
11
11
  identityId: string;
12
- // Caller-supplied conversation key; the server uses it so repeat opens with
13
- // the same key resolve to the same conversation thread.
14
- idempotencyKey: string;
15
- // Optional automated first message sent when the conversation is first
16
- // created (e.g. "Help with order #123"). Sent via `startInAppChatConversation`
17
- // with a stable client message id, so it lands exactly once across reopens.
18
- initialMessage?: string;
19
- // When false, the hook is idle: no conversation is started, subscribed, or
20
- // fetched. Lets `<InAppChatButton>` defer the conversation until the visitor
21
- // first opens the launcher, while keeping the hook mounted afterwards so its
22
- // subscription (and thus notifications) survive the panel being closed.
12
+ // The conversation to participate in. This hook does NOT create conversations:
13
+ // creating one is server-only (DashX rejects identity-token callers), so your
14
+ // backend creates it and hands you the id. Pass `null` while you don't have one
15
+ // yet — the hook stays idle rather than guessing.
16
+ conversationId: string | null;
17
+ // When false, the hook is idle: nothing is subscribed or fetched. Lets
18
+ // `<InAppChatButton>` defer the subscription until the visitor first opens the
19
+ // launcher, while keeping the hook mounted afterwards so its subscription (and
20
+ // thus notifications) survive the panel being closed.
23
21
  enabled?: boolean;
24
22
  // Invoked once per LIVE inbound message (not for history load / reconnect
25
23
  // refetch). Drives browser notifications without having to diff backfilled
@@ -41,14 +39,14 @@ type InAppChatMessage = {
41
39
  };
42
40
 
43
41
  type UseInAppChatHookResponse = {
44
- conversationId: string | null;
45
42
  messages: InAppChatMessage[];
46
43
  isLoading: boolean;
47
44
  isConnected: boolean;
48
45
  error: string | null;
49
46
  // Returns `true` if the message was optimistically queued, `false` if the chat
50
- // wasn't ready (no conversation yet). Synchronous so the caller can clear the
51
- // composer immediately on `true`; callers keep the input populated on `false`.
47
+ // wasn't ready (no `conversationId`, or disabled). Synchronous so the caller can
48
+ // clear the composer immediately on `true`; callers keep the input populated on
49
+ // `false`.
52
50
  sendMessage: (text: string) => boolean;
53
51
  };
54
52
 
@@ -91,31 +89,33 @@ const mergeMessages = (
91
89
  };
92
90
 
93
91
  /**
94
- * Two-way InApp Chat for a visitor.
92
+ * Two-way InApp Chat within an EXISTING conversation.
93
+ *
94
+ * This hook participates; it never creates. Creating a conversation is a
95
+ * server-only operation — DashX rejects identity-token callers and requires an
96
+ * `accountUid` the browser has no authority to assert, and the conversation's
97
+ * metadata must be derived server-side. So the flow is: your backend creates the
98
+ * conversation (e.g. via `dashx-java`) and returns its id; you pass that id here.
95
99
  *
96
100
  * PREREQUISITE: the surrounding `<DashXProvider>` must already have a valid
97
- * `identityToken` (and matching `identityUid`). The chat mutations require
98
- * identity-token auth — if the chat starts before an identity is resolved, they
99
- * are rejected and the hook surfaces an auth error. It does NOT auto-retry when
100
- * a token arrives later (its inputs are `identityId`/`idempotencyKey`, not the
101
- * visitor token), so only render the chat once `identityToken` is available —
102
- * e.g. `{identityToken && <InAppChat … />}`. `<InAppChatButton>` largely sidesteps
103
- * this by starting lazily when the visitor opens it, by which point the provider
104
- * has applied the token.
101
+ * `identityToken` (and matching `identityUid`). Fetching history, sending, and
102
+ * subscribing all require identity-token auth — if they run before an identity is
103
+ * resolved they are rejected and the hook surfaces an error. It does NOT auto-retry
104
+ * when a token arrives later (its inputs are `identityId`/`conversationId`, not the
105
+ * visitor token), so only render the chat once `identityToken` is available — e.g.
106
+ * `{identityToken && <InAppChat … />}`.
105
107
  */
106
- const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
108
+ const useInAppChat = ({ identityId, conversationId, enabled = true, onInboundMessage }: UseInAppChatHookProps): UseInAppChatHookResponse => {
107
109
  const dashX = useDashXProvider();
108
110
  const { isConnected, initializeWebSocket } = useWebSocket();
109
111
 
110
- const [conversationId, setConversationId] = useState<string | null>(null);
111
112
  const [messages, setMessages] = useState<InAppChatMessage[]>([]);
112
113
  const [isLoading, setIsLoading] = useState(true);
113
114
  const [error, setError] = useState<string | null>(null);
114
115
 
115
- // Bumped on every identity/key change and on unmount so stale start/fetch/send
116
- // resolutions are ignored (the classic React async race).
116
+ // Bumped on every identity/conversation change and on unmount so stale
117
+ // fetch/send resolutions are ignored (the classic React async race).
117
118
  const generationRef = useRef(0);
118
- const conversationIdRef = useRef<string | null>(null);
119
119
 
120
120
  // Latest live-message callback, kept in a ref so changing its identity doesn't
121
121
  // tear down and re-create the channel subscription.
@@ -130,14 +130,12 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
130
130
  const generation = (generationRef.current += 1);
131
131
  const isStale = () => generation !== generationRef.current;
132
132
 
133
- setConversationId(null);
134
133
  setMessages([]);
135
134
  setError(null);
136
- conversationIdRef.current = null;
137
135
 
138
- // Idle until enabled (e.g. before the launcher's first open): don't create a
139
- // conversation, subscribe, or fetch.
140
- if (!enabled) {
136
+ // Idle until enabled (e.g. before the launcher's first open) and until the
137
+ // caller has a conversation to join: don't subscribe or fetch.
138
+ if (!enabled || !conversationId) {
141
139
  setIsLoading(false);
142
140
  return () => { generationRef.current += 1; };
143
141
  }
@@ -151,25 +149,8 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
151
149
 
152
150
  (async () => {
153
151
  try {
154
- const conversation = await dashX.startInAppChatConversation({
155
- identityId,
156
- clientIdempotencyKey: idempotencyKey,
157
- // Stable client message id → the automated message is inserted once,
158
- // even if the conversation is reopened (the server dedups repeat sends).
159
- // `-` separator (client ids allow only `[A-Za-z0-9._-]`); the key is
160
- // truncated so the suffixed id stays within the 1-128 char limit.
161
- ...(initialMessage
162
- ? { content: { text: initialMessage }, clientMessageId: `${idempotencyKey.slice(0, 122)}-intro` }
163
- : {}),
164
- });
165
- if (isStale()) return;
166
-
167
- const convId = conversation.id;
168
- setConversationId(convId);
169
- conversationIdRef.current = convId;
170
-
171
152
  const refetchHistory = async () => {
172
- const history = await dashX.fetchInAppChatMessages({ conversationId: convId });
153
+ const history = await dashX.fetchInAppChatMessages({ conversationId });
173
154
  if (isStale()) return;
174
155
  appendMessages(history.map(toUiMessage));
175
156
  };
@@ -179,7 +160,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
179
160
  // on a first ack that arrives after a `ready` timeout — both mean we are
180
161
  // (now) subscribed, so clear any connection error and (re)load history.
181
162
  const subscription = dashX.subscribeToChannel(
182
- `${CHAT_CHANNEL_PREFIX}${convId}`,
163
+ `${CHAT_CHANNEL_PREFIX}${conversationId}`,
183
164
  (event) => {
184
165
  if (isStale()) return;
185
166
  appendMessages([toUiMessage(event)]);
@@ -211,7 +192,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
211
192
  if (isStale()) return;
212
193
  await refetchHistory();
213
194
  } catch {
214
- if (!isStale()) setError('Failed to start chat');
195
+ if (!isStale()) setError('Failed to load chat');
215
196
  } finally {
216
197
  if (!isStale()) setIsLoading(false);
217
198
  }
@@ -223,7 +204,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
223
204
  generationRef.current += 1;
224
205
  unsubscribe?.();
225
206
  };
226
- }, [dashX, identityId, idempotencyKey, initialMessage, enabled, initializeWebSocket, appendMessages]);
207
+ }, [dashX, identityId, conversationId, enabled, initializeWebSocket, appendMessages]);
227
208
 
228
209
  // Synchronous on purpose: it returns `true` the moment the message is optimistically
229
210
  // queued and runs the network send in the background. The caller clears the composer
@@ -232,10 +213,10 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
232
213
  // backend won't dedupe it) and create a duplicate.
233
214
  const sendMessage = useCallback(
234
215
  (text: string): boolean => {
235
- const convId = conversationIdRef.current;
236
- // Not ready (conversation still starting, or start failed) — report back so
237
- // the caller can keep the typed text instead of clearing it on a no-op send.
238
- if (!text.trim() || !convId) return false;
216
+ // Not ready (no conversation supplied yet, or the hook is disabled) — report
217
+ // back so the caller can keep the typed text instead of clearing it on a
218
+ // no-op send.
219
+ if (!text.trim() || !conversationId || !enabled) return false;
239
220
 
240
221
  // Pin the generation so a response that resolves after the identity/key
241
222
  // changed (or unmount) can't contaminate the new conversation's state.
@@ -254,7 +235,7 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
254
235
  void (async () => {
255
236
  try {
256
237
  const serverMessage = await dashX.sendInAppChatMessage({
257
- conversationId: convId,
238
+ conversationId,
258
239
  identityId,
259
240
  content: { text },
260
241
  clientMessageId,
@@ -270,10 +251,10 @@ const useInAppChat = ({ identityId, idempotencyKey, initialMessage, enabled = tr
270
251
  // Queued (optimistically appended) — the background send reconciles/errors later.
271
252
  return true;
272
253
  },
273
- [dashX, identityId, appendMessages],
254
+ [dashX, identityId, conversationId, enabled, appendMessages],
274
255
  );
275
256
 
276
- return { conversationId, messages, isLoading, isConnected, error, sendMessage };
257
+ return { messages, isLoading, isConnected, error, sendMessage };
277
258
  };
278
259
 
279
260
  export type { UseInAppChatHookProps, UseInAppChatHookResponse, InAppChatMessage };
@@ -154,6 +154,10 @@ const InAppChat = ({
154
154
  );
155
155
  };
156
156
 
157
+ // `conversationId` is required (inherited from the hook's props): this widget
158
+ // participates in a conversation your BACKEND created — it cannot create one, because
159
+ // creating a chat is server-only in DashX. Pass `null` while you're still fetching the
160
+ // id and the widget renders its empty/loading state instead of guessing.
157
161
  type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse>
158
162
  & Omit<UseInAppChatHookProps, 'enabled' | 'onInboundMessage'>
159
163
  & {
@@ -165,7 +169,7 @@ type InAppChatWrapperProps = Omit<InAppChatProps, keyof UseInAppChatHookResponse
165
169
  notifications?: boolean | InAppChatNotificationOptions;
166
170
  };
167
171
 
168
- const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifications = true, ...props }: InAppChatWrapperProps) => {
172
+ const InAppChatWrapper = ({ identityId, conversationId, notifications = true, ...props }: InAppChatWrapperProps) => {
169
173
  // Always-visible surface: treat as "open" and gate notifications on tab
170
174
  // visibility/focus only. No launcher gesture exists here, so default to
171
175
  // 'manual' permission (auto-requesting would prompt on mount).
@@ -179,8 +183,7 @@ const InAppChatWrapper = ({ identityId, idempotencyKey, initialMessage, notifica
179
183
  });
180
184
  const chat = useInAppChat({
181
185
  identityId,
182
- idempotencyKey,
183
- initialMessage,
186
+ conversationId,
184
187
  onInboundMessage: notifier.handleInboundMessage,
185
188
  });
186
189
  return <InAppChat {...chat} {...props} />;
@@ -25,8 +25,7 @@ const POSITION_CLASS: Record<LauncherPosition, string> = {
25
25
 
26
26
  const InAppChatButton = ({
27
27
  identityId,
28
- idempotencyKey,
29
- initialMessage,
28
+ conversationId,
30
29
  notifications = true,
31
30
  position = 'bottom-right',
32
31
  theme,
@@ -36,8 +35,10 @@ const InAppChatButton = ({
36
35
 
37
36
  // Latch: once the launcher has been opened, keep the chat hook active so its
38
37
  // channel subscription persists while the panel is closed — that's what lets
39
- // us notify on replies that land while the panel is shut. Before the first
40
- // open the hook is idle, so no conversation is created on page load.
38
+ // us notify on replies that land while the panel is shut. Before the first open
39
+ // the hook is idle, so a page that never opens the launcher does no chat work
40
+ // (no subscription, no history fetch). It never created a conversation either —
41
+ // the conversation is created by your backend and passed in as `conversationId`.
41
42
  const hasOpenedRef = useRef(false);
42
43
  if (isOpen) hasOpenedRef.current = true;
43
44
  const enabled = hasOpenedRef.current;
@@ -64,8 +65,7 @@ const InAppChatButton = ({
64
65
 
65
66
  const chat = useInAppChat({
66
67
  identityId,
67
- idempotencyKey,
68
- initialMessage,
68
+ conversationId,
69
69
  enabled,
70
70
  onInboundMessage: handleInboundMessage,
71
71
  });
@@ -82,7 +82,7 @@ const InAppChatButton = ({
82
82
  {/* The chat hook lives at the launcher level (above the popover) so its
83
83
  subscription survives the panel closing — required to notify on
84
84
  replies that arrive while the panel is shut. It activates lazily on
85
- first open, so no empty conversation is created on page load. */}
85
+ first open, so a launcher the visitor never opens costs nothing. */}
86
86
  <Popover.Content spacing="large" width="350px" height="450px">
87
87
  <InAppChat
88
88
  {...chat}
@@ -1,2 +0,0 @@
1
- declare const NotificationBell: () => import("react/jsx-runtime").JSX.Element;
2
- export default NotificationBell;
@@ -1,2 +0,0 @@
1
- "use strict";var l=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var u=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var m=(a,r)=>{for(var n in r)l(a,n,{get:r[n],enumerable:!0})},T=(a,r,n,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of u(r))!c.call(a,o)&&o!==n&&l(a,o,{get:()=>r[o],enumerable:!(s=g(r,o))||s.enumerable});return a};var h=a=>T(l({},"__esModule",{value:!0}),a);var f={};m(f,{default:()=>x});module.exports=h(f);var t=require("react/jsx-runtime"),d=require("date-fns"),p=require("../hooks/index.js"),e=require("../components"),i=require("../icons/index.js");const v=()=>{let{markNotificationAsRead:a,markNotificationAsUnread:r,notifications:n,unreadNotificationsCount:s}=(0,p.useInApp)();return(0,t.jsx)(e.Theme,{children:(0,t.jsxs)(e.Popover.Root,{children:[(0,t.jsxs)(e.Tooltip.Root,{children:[(0,t.jsx)(e.Tooltip.Trigger,{children:(0,t.jsx)(e.Popover.Trigger,{children:(0,t.jsx)(e.Button,{shape:"square",roundness:"full",variant:s?"fill":"ghost",children:(0,t.jsx)(i.Inbox,{})})})}),(0,t.jsx)(e.Tooltip.Content,{content:"Notification"})]}),(0,t.jsxs)(e.Popover.Content,{spacing:"large",width:"350px",height:"450px",children:[(0,t.jsx)(e.Popover.Header,{asChild:!0,children:(0,t.jsxs)(e.Flex,{justify:"between",align:"center",children:[(0,t.jsx)(e.Heading,{size:3,children:"Notifications"}),(0,t.jsx)(e.Popover.Close,{children:(0,t.jsx)(e.Button,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:(0,t.jsx)(i.X,{})})})]})}),(0,t.jsx)(e.Popover.Body,{children:(0,t.jsxs)(e.Flex,{direction:"column",gap:1,children:[n.length===0&&(0,t.jsx)(e.Flex,{justify:"center",align:"center",children:(0,t.jsx)(e.Text,{variant:"tertiary",size:2,children:"No notifications yet."})}),n.map(o=>(0,t.jsx)(e.Card,{children:(0,t.jsxs)(e.Flex,{align:"center",gap:4,justify:"between",children:[(0,t.jsxs)(e.Flex,{direction:"column",gap:1,children:[(0,t.jsx)(e.Text,{as:"p",variant:"secondary",weight:"semibold",size:2,children:o.renderedContent.body}),(0,t.jsx)(e.Text,{size:1,variant:"tertiary",children:(0,d.intlFormatDistance)(o.sentAt,new Date)})]}),(0,t.jsxs)(e.Tooltip.Root,{children:[(0,t.jsx)(e.Tooltip.Trigger,{children:(0,t.jsx)(e.Button,{shape:"square",variant:"ghost",roundness:"full",mode:o.readAt?"subtle":"distinct",onPress:()=>{o.readAt?r(o.id):a(o.id)},children:o.readAt?(0,t.jsx)(i.MailOpen,{}):(0,t.jsx)(i.Mail,{})})}),(0,t.jsx)(e.Tooltip.Content,{content:o.readAt?"Mark as unread":"Mark as read"})]})]})},o.id))]})}),(0,t.jsx)(e.Popover.Footer,{asChild:!0,children:(0,t.jsx)(e.Text,{as:"p",align:"center",color:"accent",variant:"tertiary",size:1,children:"Powered by DashX"})})]})]})})};var x=v;
2
- //# sourceMappingURL=NotificationBell.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/widgets/NotificationBell.tsx"],
4
- "sourcesContent": ["import { intlFormatDistance } from 'date-fns';\n\nimport { useInApp } from '../hooks/index.js';\nimport { Button, Card, Flex, Heading, Popover, Text, Theme, Tooltip } from '../components';\nimport { Inbox, Mail, MailOpen, X } from '../icons/index.js';\n\nconst NotificationBell = () => {\n let {\n markNotificationAsRead,\n markNotificationAsUnread,\n notifications,\n unreadNotificationsCount,\n } = useInApp();\n\n return (\n <Theme>\n <Popover.Root>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Popover.Trigger>\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant={unreadNotificationsCount ? 'fill' : 'ghost'}\n >\n <Inbox />\n </Button>\n </Popover.Trigger>\n </Tooltip.Trigger>\n <Tooltip.Content content=\"Notification\" />\n </Tooltip.Root>\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <Popover.Header asChild>\n <Flex justify=\"between\" align=\"center\">\n <Heading size={3}>Notifications</Heading>\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n </Flex>\n </Popover.Header>\n <Popover.Body>\n <Flex direction=\"column\" gap={1}>\n {notifications.length === 0 && (\n <Flex justify=\"center\" align=\"center\">\n <Text variant=\"tertiary\" size={2}>\n No notifications yet.\n </Text>\n </Flex>\n )}\n {notifications.map((notification) => (\n <Card key={notification.id}>\n <Flex align=\"center\" gap={4} justify=\"between\">\n <Flex direction=\"column\" gap={1}>\n <Text as=\"p\" variant=\"secondary\" weight=\"semibold\" size={2}>\n {notification.renderedContent.body}\n </Text>\n <Text size={1} variant=\"tertiary\">\n {intlFormatDistance(notification.sentAt, new Date())}\n </Text>\n </Flex>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Button\n shape=\"square\"\n variant=\"ghost\"\n roundness=\"full\"\n mode={notification.readAt ? 'subtle' : 'distinct'}\n onPress={() => {\n if (notification.readAt) {\n markNotificationAsUnread(notification.id);\n } else {\n markNotificationAsRead(notification.id);\n }\n }}\n >\n {notification.readAt ? <MailOpen /> : <Mail />}\n </Button>\n </Tooltip.Trigger>\n <Tooltip.Content\n content={notification.readAt ? 'Mark as unread' : 'Mark as read'}\n />\n </Tooltip.Root>\n </Flex>\n </Card>\n ))}\n </Flex>\n </Popover.Body>\n <Popover.Footer asChild>\n <Text as=\"p\" align=\"center\" color=\"accent\" variant=\"tertiary\" size={1}>\n Powered by DashX\n </Text>\n </Popover.Footer>\n </Popover.Content>\n </Popover.Root>\n </Theme>\n );\n};\n\nexport default NotificationBell;\n"],
5
- "mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,aAAAE,IAAA,eAAAC,EAAAH,GAiBQ,IAAAI,EAAA,6BAjBRC,EAAmC,oBAEnCC,EAAyB,6BACzBC,EAA2E,yBAC3EC,EAAyC,6BAEzC,MAAMC,EAAmB,IAAM,CAC7B,GAAI,CACF,uBAAAC,EACA,yBAAAC,EACA,cAAAC,EACA,yBAAAC,CACF,KAAI,YAAS,EAEb,SACE,OAAC,SACC,oBAAC,U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EAAuBI,EAAa,EAAE,CAE1C,EAEC,SAAAA,EAAa,UAAS,OAAC,aAAS,KAAK,OAAC,SAAK,EAC9C,EACF,KACA,OAAC,UAAQ,QAAR,CACC,QAASA,EAAa,OAAS,iBAAmB,eACpD,GACF,GACF,GAhCSA,EAAa,EAiCxB,CACD,GACH,EACF,KACA,OAAC,UAAQ,OAAR,CAAe,QAAO,GACrB,mBAAC,QAAK,GAAG,IAAI,MAAM,SAAS,MAAM,SAAS,QAAQ,WAAW,KAAM,EAAG,4BAEvE,EACF,GACF,GACF,EACF,CAEJ,EAEA,IAAOZ,EAAQO",
6
- "names": ["NotificationBell_exports", "__export", "NotificationBell_default", "__toCommonJS", "import_jsx_runtime", "import_date_fns", "import_hooks", "import_components", "import_icons", "NotificationBell", "markNotificationAsRead", "markNotificationAsUnread", "notifications", "unreadNotificationsCount", "notification"]
7
- }
@@ -1,2 +0,0 @@
1
- declare const NotificationBell: () => import("react/jsx-runtime").JSX.Element;
2
- export default NotificationBell;
@@ -1,2 +0,0 @@
1
- import{jsx as e,jsxs as o}from"react/jsx-runtime";import{intlFormatDistance as u}from"date-fns";import{useInApp as c}from"../hooks/index.js";import{Button as s,Card as m,Flex as i,Heading as T,Popover as r,Text as n,Theme as h,Tooltip as a}from"../components";import{Inbox as v,Mail as x,MailOpen as f,X as y}from"../icons/index.js";const C=()=>{let{markNotificationAsRead:d,markNotificationAsUnread:p,notifications:l,unreadNotificationsCount:g}=c();return e(h,{children:o(r.Root,{children:[o(a.Root,{children:[e(a.Trigger,{children:e(r.Trigger,{children:e(s,{shape:"square",roundness:"full",variant:g?"fill":"ghost",children:e(v,{})})})}),e(a.Content,{content:"Notification"})]}),o(r.Content,{spacing:"large",width:"350px",height:"450px",children:[e(r.Header,{asChild:!0,children:o(i,{justify:"between",align:"center",children:[e(T,{size:3,children:"Notifications"}),e(r.Close,{children:e(s,{shape:"square",roundness:"full",variant:"ghost",mode:"subtle",inset:"right",children:e(y,{})})})]})}),e(r.Body,{children:o(i,{direction:"column",gap:1,children:[l.length===0&&e(i,{justify:"center",align:"center",children:e(n,{variant:"tertiary",size:2,children:"No notifications yet."})}),l.map(t=>e(m,{children:o(i,{align:"center",gap:4,justify:"between",children:[o(i,{direction:"column",gap:1,children:[e(n,{as:"p",variant:"secondary",weight:"semibold",size:2,children:t.renderedContent.body}),e(n,{size:1,variant:"tertiary",children:u(t.sentAt,new Date)})]}),o(a.Root,{children:[e(a.Trigger,{children:e(s,{shape:"square",variant:"ghost",roundness:"full",mode:t.readAt?"subtle":"distinct",onPress:()=>{t.readAt?p(t.id):d(t.id)},children:t.readAt?e(f,{}):e(x,{})})}),e(a.Content,{content:t.readAt?"Mark as unread":"Mark as read"})]})]})},t.id))]})}),e(r.Footer,{asChild:!0,children:e(n,{as:"p",align:"center",color:"accent",variant:"tertiary",size:1,children:"Powered by DashX"})})]})]})})};var B=C;export{B as default};
2
- //# sourceMappingURL=NotificationBell.js.map
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../src/widgets/NotificationBell.tsx"],
4
- "sourcesContent": ["import { intlFormatDistance } from 'date-fns';\n\nimport { useInApp } from '../hooks/index.js';\nimport { Button, Card, Flex, Heading, Popover, Text, Theme, Tooltip } from '../components';\nimport { Inbox, Mail, MailOpen, X } from '../icons/index.js';\n\nconst NotificationBell = () => {\n let {\n markNotificationAsRead,\n markNotificationAsUnread,\n notifications,\n unreadNotificationsCount,\n } = useInApp();\n\n return (\n <Theme>\n <Popover.Root>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Popover.Trigger>\n <Button\n shape=\"square\"\n roundness=\"full\"\n variant={unreadNotificationsCount ? 'fill' : 'ghost'}\n >\n <Inbox />\n </Button>\n </Popover.Trigger>\n </Tooltip.Trigger>\n <Tooltip.Content content=\"Notification\" />\n </Tooltip.Root>\n <Popover.Content spacing=\"large\" width=\"350px\" height=\"450px\">\n <Popover.Header asChild>\n <Flex justify=\"between\" align=\"center\">\n <Heading size={3}>Notifications</Heading>\n <Popover.Close>\n <Button shape=\"square\" roundness=\"full\" variant=\"ghost\" mode=\"subtle\" inset=\"right\">\n <X />\n </Button>\n </Popover.Close>\n </Flex>\n </Popover.Header>\n <Popover.Body>\n <Flex direction=\"column\" gap={1}>\n {notifications.length === 0 && (\n <Flex justify=\"center\" align=\"center\">\n <Text variant=\"tertiary\" size={2}>\n No notifications yet.\n </Text>\n </Flex>\n )}\n {notifications.map((notification) => (\n <Card key={notification.id}>\n <Flex align=\"center\" gap={4} justify=\"between\">\n <Flex direction=\"column\" gap={1}>\n <Text as=\"p\" variant=\"secondary\" weight=\"semibold\" size={2}>\n {notification.renderedContent.body}\n </Text>\n <Text size={1} variant=\"tertiary\">\n {intlFormatDistance(notification.sentAt, new Date())}\n </Text>\n </Flex>\n <Tooltip.Root>\n <Tooltip.Trigger>\n <Button\n shape=\"square\"\n variant=\"ghost\"\n roundness=\"full\"\n mode={notification.readAt ? 'subtle' : 'distinct'}\n onPress={() => {\n if (notification.readAt) {\n markNotificationAsUnread(notification.id);\n } else {\n markNotificationAsRead(notification.id);\n }\n }}\n >\n {notification.readAt ? <MailOpen /> : <Mail />}\n </Button>\n </Tooltip.Trigger>\n <Tooltip.Content\n content={notification.readAt ? 'Mark as unread' : 'Mark as read'}\n />\n </Tooltip.Root>\n </Flex>\n </Card>\n ))}\n </Flex>\n </Popover.Body>\n <Popover.Footer asChild>\n <Text as=\"p\" align=\"center\" color=\"accent\" variant=\"tertiary\" size={1}>\n Powered by DashX\n </Text>\n </Popover.Footer>\n </Popover.Content>\n </Popover.Root>\n </Theme>\n );\n};\n\nexport default NotificationBell;\n"],
5
- "mappings": "AAiBQ,OAQQ,OAAAA,EARR,QAAAC,MAAA,oBAjBR,OAAS,sBAAAC,MAA0B,WAEnC,OAAS,YAAAC,MAAgB,oBACzB,OAAS,UAAAC,EAAQ,QAAAC,EAAM,QAAAC,EAAM,WAAAC,EAAS,WAAAC,EAAS,QAAAC,EAAM,SAAAC,EAAO,WAAAC,M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AAA,CAAK,UAAU,SAAS,IAAK,EAC5B,UAAAN,EAACS,EAAA,CAAK,GAAG,IAAI,QAAQ,YAAY,OAAO,WAAW,KAAM,EACtD,SAAAY,EAAa,gBAAgB,KAChC,EACArB,EAACS,EAAA,CAAK,KAAM,EAAG,QAAQ,WACpB,SAAAP,EAAmBmB,EAAa,OAAQ,IAAI,IAAM,EACrD,GACF,EACApB,EAACU,EAAQ,KAAR,CACC,UAAAX,EAACW,EAAQ,QAAR,CACC,SAAAX,EAACI,EAAA,CACC,MAAM,SACN,QAAQ,QACR,UAAU,OACV,KAAMiB,EAAa,OAAS,SAAW,WACvC,QAAS,IAAM,CACTA,EAAa,OACfH,EAAyBG,EAAa,EAAE,EAExCJ,EAAuBI,EAAa,EAAE,CAE1C,EAEC,SAAAA,EAAa,OAASrB,EAACc,EAAA,EAAS,EAAKd,EAACa,EAAA,EAAK,EAC9C,EACF,EACAb,EAACW,EAAQ,QAAR,CACC,QAASU,EAAa,OAAS,iBAAmB,eACpD,GACF,GACF,GAhCSA,EAAa,EAiCxB,CACD,GACH,EACF,EACArB,EAACQ,EAAQ,OAAR,CAAe,QAAO,GACrB,SAAAR,EAACS,EAAA,CAAK,GAAG,IAAI,MAAM,SAAS,MAAM,SAAS,QAAQ,WAAW,KAAM,EAAG,4BAEvE,EACF,GACF,GACF,EACF,CAEJ,EAEA,IAAOa,EAAQN",
6
- "names": ["jsx", "jsxs", "intlFormatDistance", "useInApp", "Button", "Card", "Flex", "Heading", "Popover", "Text", "Theme", "Tooltip", "Inbox", "Mail", "MailOpen", "X", "NotificationBell", "markNotificationAsRead", "markNotificationAsUnread", "notifications", "unreadNotificationsCount", "notification", "NotificationBell_default"]
7
- }