@gemina/elements 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/chat.cjs CHANGED
@@ -73,7 +73,7 @@ async function readErrorEnvelope(error) {
73
73
  }
74
74
 
75
75
  // src/version.ts
76
- var VERSION = "0.8.0";
76
+ var VERSION = "0.9.0";
77
77
 
78
78
  // src/chat.tsx
79
79
  var import_jsx_runtime = require("react/jsx-runtime");
package/dist/chat.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/chat.tsx","../src/internal/response-like.ts","../src/version.ts"],"sourcesContent":["/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport { getResponseLike, httpStatus, readErrorEnvelope } from './internal/response-like';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables\n * (including `--gemina-chat-header-bg` for the header bar).\n */\n title?: string;\n /**\n * Plain text shown centered in the empty conversation area until the\n * first message. Use it to set expectations about what the assistant\n * can and can't see (e.g. \"Answers come from your indexed document\n * data\"). Newlines split it into separately spaced paragraphs — no\n * markup, so the string stays safe and portable.\n */\n intro?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The envelope parsing (with its defensive clone/json\n * dance) lives in `readErrorEnvelope`; only the `Retry-After` header handling\n * is chat-specific.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const envelope = await readErrorEnvelope(error);\n const info: ChatErrorInfo = { ...envelope, retryAfterSeconds: undefined };\n\n const rawRetryAfter = getResponseLike(error)?.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-header-bg: transparent;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n align-items: center;\n /* Guaranteed minimum separation. The pushing itself is the button's\n auto margin below — NOT a margin on the title, whose dir=\"auto\" can\n resolve opposite to the widget (English title in an RTL chat) and\n collapse an inline-aware margin to the wrong side. */\n gap: 12px;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n background: var(--gemina-chat-header-bg);\n}\n.gemina-chat__title {\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n margin-inline-start: auto;\n flex-shrink: 0;\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__intro {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin: auto;\n max-width: 46ch;\n padding: 16px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-chat-muted);\n}\n.gemina-chat__intro-line { margin: 0; }\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n intro,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.length === 0 && intro !== undefined && (\n <div className=\"gemina-chat__intro\" dir={bubbleDir}>\n {intro\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line, index) => (\n <p key={index} className=\"gemina-chat__intro-line\">\n {line}\n </p>\n ))}\n </div>\n )}\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/**\n * Shared transport-error helpers for the widgets (chat + verification).\n *\n * Extracted verbatim from chat.tsx so both components read thrown SDK errors\n * the same way. Pure and dependency-free: no React, no DOM.\n */\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\nexport interface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nexport function getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nexport function httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/** What the standard backend error envelope reliably carries. */\nexport interface ErrorEnvelope {\n status: number | undefined;\n /** Stable backend `errors[0].error_code`. */\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status and\n * the stable `errors[0].error_code` / `description` are reliable across\n * environments — production strips `errors[0].detail`, so we never touch it.\n * The fetch body can be read once, so we clone defensively; if that fails\n * (non-JSON, empty, or already consumed) the status still stands.\n */\nexport async function readErrorEnvelope(error: unknown): Promise<ErrorEnvelope> {\n const response = getResponseLike(error);\n const info: ErrorEnvelope = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.8.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,mBAAyD;AAEzD,iBAA6B;;;ACOtB,SAAS,gBAAgB,OAA0C;AACxE,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,cAAc,OAAO;AACtE,UAAM,WAAY,MAAiC;AACnD,QAAI,aAAa,QAAQ,OAAO,aAAa,UAAU;AACrD,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,WAAW,OAAoC;AAC7D,QAAM,SAAS,gBAAgB,KAAK,GAAG;AACvC,SAAO,OAA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,MAAK;AAAA,sBACL,WAAU;AAAA,sBACV,SAAS,MAAM,aAAa,OAAO;AAAA,sBACpC;AAAA;AAAA,kBAED;AAAA;AAAA;AAAA,cAZG,QAAQ;AAAA,YAcf;AAAA,UAEJ,CAAC;AAAA,UACA;AAAA;AAAA,UAGC,6CAAC,SAAI,WAAU,uBAAsB;AAAA;AAAA,YAEnC,6CAAC,UAAK,WAAU,4BAA2B,eAAY,QACrD;AAAA,0DAAC,UAAK;AAAA,cACN,4CAAC,UAAK;AAAA,cACN,4CAAC,UAAK;AAAA,eACR;AAAA,aACF;AAAA;AAAA;AAAA,IAEJ;AAAA,IACA,6CAAC,UAAK,WAAU,yBAAwB,UAAU,cAChD;AAAA;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,cAAW;AAAA,UACX,MAAM;AAAA,UACN,OAAO;AAAA,UACP;AAAA,UACA,KAAK;AAAA,UACL,UAAU,CAAC,UAAU,SAAS,MAAM,OAAO,KAAK;AAAA,UAChD,WAAW;AAAA;AAAA,MACb;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,cAAW;AAAA,UACX,UAAU,QAAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/chat.tsx","../src/internal/response-like.ts","../src/version.ts"],"sourcesContent":["/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport { getResponseLike, httpStatus, readErrorEnvelope } from './internal/response-like';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables\n * (including `--gemina-chat-header-bg` for the header bar).\n */\n title?: string;\n /**\n * Plain text shown centered in the empty conversation area until the\n * first message. Use it to set expectations about what the assistant\n * can and can't see (e.g. \"Answers come from your indexed document\n * data\"). Newlines split it into separately spaced paragraphs — no\n * markup, so the string stays safe and portable.\n */\n intro?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The envelope parsing (with its defensive clone/json\n * dance) lives in `readErrorEnvelope`; only the `Retry-After` header handling\n * is chat-specific.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const envelope = await readErrorEnvelope(error);\n const info: ChatErrorInfo = { ...envelope, retryAfterSeconds: undefined };\n\n const rawRetryAfter = getResponseLike(error)?.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-header-bg: transparent;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n align-items: center;\n /* Guaranteed minimum separation. The pushing itself is the button's\n auto margin below — NOT a margin on the title, whose dir=\"auto\" can\n resolve opposite to the widget (English title in an RTL chat) and\n collapse an inline-aware margin to the wrong side. */\n gap: 12px;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n background: var(--gemina-chat-header-bg);\n}\n.gemina-chat__title {\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n margin-inline-start: auto;\n flex-shrink: 0;\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__intro {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin: auto;\n max-width: 46ch;\n padding: 16px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-chat-muted);\n}\n.gemina-chat__intro-line { margin: 0; }\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n intro,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.length === 0 && intro !== undefined && (\n <div className=\"gemina-chat__intro\" dir={bubbleDir}>\n {intro\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line, index) => (\n <p key={index} className=\"gemina-chat__intro-line\">\n {line}\n </p>\n ))}\n </div>\n )}\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/**\n * Shared transport-error helpers for the widgets (chat + verification).\n *\n * Extracted verbatim from chat.tsx so both components read thrown SDK errors\n * the same way. Pure and dependency-free: no React, no DOM.\n */\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\nexport interface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nexport function getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nexport function httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/** What the standard backend error envelope reliably carries. */\nexport interface ErrorEnvelope {\n status: number | undefined;\n /** Stable backend `errors[0].error_code`. */\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status and\n * the stable `errors[0].error_code` / `description` are reliable across\n * environments — production strips `errors[0].detail`, so we never touch it.\n * The fetch body can be read once, so we clone defensively; if that fails\n * (non-JSON, empty, or already consumed) the status still stands.\n */\nexport async function readErrorEnvelope(error: unknown): Promise<ErrorEnvelope> {\n const response = getResponseLike(error);\n const info: ErrorEnvelope = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.9.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,mBAAyD;AAEzD,iBAA6B;;;ACOtB,SAAS,gBAAgB,OAA0C;AACxE,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,cAAc,OAAO;AACtE,UAAM,WAAY,MAAiC;AACnD,QAAI,aAAa,QAAQ,OAAO,aAAa,UAAU;AACrD,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAGO,SAAS,WAAW,OAAoC;AAC7D,QAAM,SAAS,gBAAgB,KAAK,GAAG;AACvC,SAAO,OAAO,WAAW,WAAW,SAAS;AAC/C;AAkBA,eAAsB,kBAAkB,OAAwC;AAC9E,QAAM,WAAW,gBAAgB,KAAK;AACtC,QAAM,OAAsB;AAAA,IAC1B,QAAQ,OAAO,UAAU,WAAW,WAAW,SAAS,SAAS;AAAA,IACjE,WAAW;AAAA,IACX,aAAa;AAAA,EACf;AACA,MAAI,aAAa,QAAW;AAC1B,WAAO;AAAA,EACT;AAEA,MAAI;AACJ,MAAI;AACF,UAAM,SAAS,OAAO,SAAS,UAAU,aAAa,SAAS,MAAM,IAAI;AACzE,WAAO,OAAO,OAAO,SAAS,aAAa,MAAM,OAAO,KAAK,IAAI;AAAA,EACnE,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,SAAS,QAAQ,OAAO,SAAS,UAAU;AAC7C,UAAM,SAAU,KAA8B;AAC9C,QACE,MAAM,QAAQ,MAAM,KACpB,OAAO,SAAS,KAChB,OAAO,CAAC,MAAM,QACd,OAAO,OAAO,CAAC,MAAM,UACrB;AACA,YAAM,QAAQ,OAAO,CAAC;AACtB,UAAI,OAAO,MAAM,eAAe,UAAU;AACxC,aAAK,YAAY,MAAM;AAAA,MACzB;AACA,UAAI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UAAU,QAAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
package/dist/chat.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  GeminaChat
3
- } from "./chunk-3SZSUO7E.js";
4
- import "./chunk-724KJLIY.js";
3
+ } from "./chunk-DU6BUHR5.js";
4
+ import "./chunk-S4KBJRIP.js";
5
5
  export {
6
6
  GeminaChat
7
7
  };
@@ -3,7 +3,7 @@ import {
3
3
  getResponseLike,
4
4
  httpStatus,
5
5
  readErrorEnvelope
6
- } from "./chunk-724KJLIY.js";
6
+ } from "./chunk-S4KBJRIP.js";
7
7
 
8
8
  // src/chat.tsx
9
9
  import { useCallback, useEffect, useRef, useState } from "react";
@@ -656,4 +656,4 @@ function GeminaChat(props) {
656
656
  export {
657
657
  GeminaChat
658
658
  };
659
- //# sourceMappingURL=chunk-3SZSUO7E.js.map
659
+ //# sourceMappingURL=chunk-DU6BUHR5.js.map