@gemina/elements 0.1.1 → 0.2.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/README.md +24 -0
- package/dist/chat.cjs +182 -16
- package/dist/chat.cjs.map +1 -1
- package/dist/chat.js +1 -1
- package/dist/{chunk-PR3OAE6B.js → chunk-2UMJ235A.js} +183 -17
- package/dist/chunk-2UMJ235A.js.map +1 -0
- package/dist/index.cjs +182 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chat.d.cts +0 -45
- package/dist/chat.d.ts +0 -45
- package/dist/chunk-PR3OAE6B.js.map +0 -1
- package/dist/index.d.cts +0 -8
- package/dist/index.d.ts +0 -8
- package/dist/token-manager.d.cts +0 -99
- package/dist/token-manager.d.ts +0 -99
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/token-manager.ts","../src/chat.tsx","../src/version.ts"],"sourcesContent":["// Token management (no React required — also available as\n// `@gemina/elements/token-manager`).\nexport { GeminaTokenManager } from './token-manager';\nexport type { FetchTokenResult, GeminaTokenManagerOptions } from './token-manager';\n\n// Chat UI (React — also available as `@gemina/elements/chat`).\nexport { GeminaChat } from './chat';\nexport type { GeminaChatProps, GeminaChatTheme, GeminaChatDirection } from './chat';\n\nexport { VERSION } from './version';\n","/**\n * GeminaTokenManager — in-memory holder for short-lived Gemina session\n * tokens, per the Document Intelligence token spec (PRD §6.11.1).\n *\n * Security model (the five footguns this file designs out):\n *\n * 1. **The API key never enters the browser.** The constructor throws if it\n * is handed a raw string instead of a `fetchToken` callback, and\n * `getToken()` rejects if the callback ever resolves with an\n * API-key-shaped string (32 alphanumerics, no dots).\n * 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,\n * cookies, or IndexedDB anywhere in this package — the token lives only\n * in memory, inside state that is not an own property of the instance.\n * 3. **The browser never asserts its own scope.** This manager carries no\n * scope parameters at all; scope is signed into the token server-side.\n * 4. **No refresh token is held in the browser.** Renewal always goes back\n * through the tenant's own authenticated backend via `fetchToken`.\n * 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*\n * what the tenant backend minted; it has no code path to\n * `POST /v1/sessions/token`.\n *\n * Storage choice: internal state (including the token) lives in a\n * module-scoped `WeakMap` keyed by the instance rather than in an ordinary\n * class field. An ordinary field — even a `#private` one via devtools — is\n * trivially discoverable by enumerating the instance; the WeakMap keeps the\n * token out of `Object.keys`, `JSON.stringify`, spread copies, and casual\n * inspection, and it is unreachable without a reference to both the WeakMap\n * (module-private) and the instance. This is hardening against accidental\n * exposure/serialization, not encryption: code running in the same realm\n * with a debugger can still read process memory. The upgrade path for\n * stronger isolation is a Web Worker (see PRD §6.11.1).\n *\n * SSR-safe: this module touches no `window`/`document` at import time and\n * starts no timers — refresh happens lazily inside `getToken()`, so an idle\n * manager consumes nothing and never keeps a Node process alive.\n */\n\n/** What `fetchToken` must resolve with (mirror of the mint response). */\nexport interface FetchTokenResult {\n /** The raw session token (a JWT). Pass it WITHOUT a \"Bearer \" prefix. */\n token: string;\n /** Token lifetime in seconds, as returned by the mint endpoint. */\n expiresIn: number;\n}\n\n/** Constructor options for {@link GeminaTokenManager}. */\nexport interface GeminaTokenManagerOptions {\n /**\n * Callback that obtains a fresh session token from the TENANT'S OWN\n * backend (which in turn calls Gemina's `POST /v1/sessions/token` with\n * the API key, server-side). It must resolve with\n * `{ token, expiresIn }`. It must NEVER return a Gemina API key.\n */\n fetchToken: () => Promise<FetchTokenResult>;\n /**\n * How many seconds before the token's expiry `getToken()` starts\n * refreshing. Default 60 (the PRD's `exp − 60s` refresh point).\n */\n refreshSkewSeconds?: number;\n}\n\n/** Gemina API keys are exactly 32 alphanumerics with no prefix. */\nconst API_KEY_SHAPE = /^[A-Za-z0-9]{32}$/;\n\nconst API_KEY_ERROR =\n 'GeminaTokenManager received an API-key-shaped credential (32 alphanumeric ' +\n 'characters). Gemina API keys are master keys and must NEVER enter the ' +\n 'browser: mint a short-lived session token on YOUR backend via ' +\n 'POST /v1/sessions/token (sessions.mintRetrievalToken in @gemina/sdk) and ' +\n 'return { token, expiresIn } from fetchToken instead.';\n\ninterface TokenState {\n fetchToken: () => Promise<FetchTokenResult>;\n refreshSkewMs: number;\n /** The cached raw token, or null when absent/invalidated. */\n token: string | null;\n /** Epoch ms after which the cached token is considered expired. */\n expiresAtMs: number;\n /** Shared in-flight refresh, so concurrent callers never stampede. */\n inFlight: Promise<string> | null;\n /** Bumped by invalidate(); stale refreshes must not repopulate the cache. */\n epoch: number;\n}\n\n// Module-private state store — see the header comment for why the token is\n// deliberately NOT an own property of the instance.\nconst STATES = new WeakMap<GeminaTokenManager, TokenState>();\n\nfunction getState(manager: GeminaTokenManager): TokenState {\n const state = STATES.get(manager);\n if (state === undefined) {\n throw new Error(\n 'GeminaTokenManager state missing — was the instance constructed normally? ' +\n '(Object.create/deserialization is not supported.)',\n );\n }\n return state;\n}\n\n/**\n * Validate what `fetchToken` resolved with and return the raw token.\n * Rejects API-key-shaped strings and anything that is not JWT-shaped.\n */\nfunction validateFetchedToken(result: FetchTokenResult): string {\n if (result === null || typeof result !== 'object') {\n throw new Error(\n 'GeminaTokenManager: fetchToken must resolve with { token, expiresIn } ' +\n `(got ${result === null ? 'null' : typeof result}).`,\n );\n }\n const { token, expiresIn } = result;\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved without a token string. ' +\n 'Return { token, expiresIn } from the mint response.',\n );\n }\n if (API_KEY_SHAPE.test(token)) {\n throw new Error(API_KEY_ERROR);\n }\n // Session tokens are JWTs: exactly three non-empty dot-separated segments.\n const segments = token.split('.');\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0)) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with a value that is not a ' +\n 'session token. Gemina session tokens are JWTs (three dot-separated ' +\n 'segments); return the `token` field from POST /v1/sessions/token.',\n );\n }\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with an invalid expiresIn ' +\n `(${String(expiresIn)}). Return the mint response's expiresIn (seconds > 0).`,\n );\n }\n return token;\n}\n\n/**\n * Holds a short-lived Gemina session token in memory and keeps it fresh.\n *\n * ```ts\n * const tokenManager = new GeminaTokenManager({\n * // YOUR backend endpoint — it holds the API key and mints the token.\n * fetchToken: async () => {\n * const res = await fetch(\"/api/gemina-session\", { method: \"POST\" });\n * if (!res.ok) throw new Error(\"Failed to mint Gemina session token\");\n * return res.json(); // { token, expiresIn }\n * },\n * });\n * ```\n *\n * - `getToken()` fetches lazily on first use, then auto-refreshes when the\n * cached token is within `refreshSkewSeconds` of expiry. Concurrent\n * callers share a single in-flight fetch.\n * - `invalidate()` drops the cache so the next `getToken()` refetches\n * (use after a 401).\n * - No timers run while idle; nothing is ever written to storage.\n */\nexport class GeminaTokenManager {\n constructor(options: GeminaTokenManagerOptions) {\n if (typeof options === 'string') {\n // Someone did `new GeminaTokenManager(\"<api key or token>\")`.\n throw new Error(\n API_KEY_SHAPE.test(options)\n ? API_KEY_ERROR\n : 'GeminaTokenManager takes { fetchToken } — a callback that asks ' +\n 'YOUR backend for a fresh session token — not a raw string. ' +\n 'Never pass a Gemina API key to browser code.',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new Error(\n 'GeminaTokenManager requires an options object: new GeminaTokenManager({ fetchToken }).',\n );\n }\n const { fetchToken, refreshSkewSeconds = 60 } = options;\n if (typeof fetchToken === 'string') {\n throw new Error(\n (API_KEY_SHAPE.test(fetchToken) ? `${API_KEY_ERROR} ` : '') +\n 'GeminaTokenManager: fetchToken must be a function returning ' +\n 'Promise<{ token, expiresIn }>, not a string.',\n );\n }\n if (typeof fetchToken !== 'function') {\n throw new Error(\n 'GeminaTokenManager: fetchToken is required and must be a function ' +\n 'returning Promise<{ token, expiresIn }>.',\n );\n }\n if (\n typeof refreshSkewSeconds !== 'number' ||\n !Number.isFinite(refreshSkewSeconds) ||\n refreshSkewSeconds < 0\n ) {\n throw new Error(\n `GeminaTokenManager: refreshSkewSeconds must be a non-negative number (got ${String(\n refreshSkewSeconds,\n )}).`,\n );\n }\n\n STATES.set(this, {\n fetchToken,\n refreshSkewMs: refreshSkewSeconds * 1000,\n token: null,\n expiresAtMs: 0,\n inFlight: null,\n epoch: 0,\n });\n }\n\n /**\n * Return a valid session token, fetching or refreshing as needed.\n *\n * A cached token is reused until `now >= expiry - refreshSkewSeconds`\n * (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).\n * All concurrent callers during a refresh share ONE in-flight fetch.\n * A failed fetch is not cached — the next call retries.\n */\n getToken(): Promise<string> {\n const state = getState(this);\n\n if (state.token !== null && Date.now() < state.expiresAtMs - state.refreshSkewMs) {\n return Promise.resolve(state.token);\n }\n\n if (state.inFlight !== null) {\n return state.inFlight;\n }\n\n const epoch = state.epoch;\n const fetchStartedAtMs = Date.now();\n // Start the user callback immediately (getToken() should fire the mint\n // request right away), but convert a synchronous throw into a rejection\n // so the in-flight bookkeeping below stays consistent.\n let fetched: Promise<FetchTokenResult>;\n try {\n fetched = Promise.resolve(state.fetchToken());\n } catch (error) {\n fetched = Promise.reject(error);\n }\n const inFlight: Promise<string> = fetched\n .then((result) => {\n const token = validateFetchedToken(result);\n if (state.epoch === epoch) {\n state.token = token;\n state.expiresAtMs = fetchStartedAtMs + result.expiresIn * 1000;\n }\n // If invalidate() ran mid-flight, still hand this (already-minted)\n // token to the callers who asked before the invalidation — but do\n // not cache it; the next getToken() fetches fresh.\n return token;\n })\n .finally(() => {\n if (state.inFlight === inFlight) {\n state.inFlight = null;\n }\n });\n\n state.inFlight = inFlight;\n return inFlight;\n }\n\n /**\n * Drop the cached token (and detach any in-flight refresh) so the next\n * `getToken()` fetches a fresh one. Call this when the API answers 401,\n * then retry the request once with a new `getToken()`.\n */\n invalidate(): void {\n const state = getState(this);\n state.token = null;\n state.expiresAtMs = 0;\n state.inFlight = null;\n state.epoch += 1;\n }\n}\n","/**\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 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 /** 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/**\n * Extract an HTTP status from a thrown value by shape rather than\n * `instanceof ResponseError` — robust against duplicated `@gemina/sdk`\n * copies in a bundle (class identity is not shared across copies).\n */\nfunction httpStatus(error: unknown): number | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (\n response !== null &&\n typeof response === 'object' &&\n typeof (response as { status?: unknown }).status === 'number'\n ) {\n return (response as { status: number }).status;\n }\n }\n return undefined;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Document Intelligence isn't enabled on this plan.\";\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\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-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__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__typing {\n align-self: flex-start;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\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 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\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 return client.chat.chatQuery({ chatQueryInDTO: { message, endUserId } });\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 const result = await queryWithRetry(text);\n if (!mountedRef.current) {\n return;\n }\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 const status = httpStatus(error);\n if (status === 401) {\n appendMessage({ role: 'error', text: SESSION_EXPIRED_TEXT });\n } else if (status === 429) {\n appendMessage({ role: 'error', text: RATE_LIMIT_TEXT });\n } else if (status === 402 || status === 403) {\n appendMessage({ role: 'error', text: PLAN_GATE_TEXT });\n } else {\n appendMessage({ role: 'error', text: GENERIC_ERROR_TEXT, retryText: text });\n }\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\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 <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.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 && <div className=\"gemina-chat__typing\">Thinking…</div>}\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","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.1.1';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8DA,IAAM,gBAAgB;AAEtB,IAAM,gBACJ;AAqBF,IAAM,SAAS,oBAAI,QAAwC;AAE3D,SAAS,SAAS,SAAyC;AACzD,QAAM,QAAQ,OAAO,IAAI,OAAO;AAChC,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAMA,SAAS,qBAAqB,QAAkC;AAC9D,MAAI,WAAW,QAAQ,OAAO,WAAW,UAAU;AACjD,UAAM,IAAI;AAAA,MACR,8EACU,WAAW,OAAO,SAAS,OAAO,MAAM;AAAA,IACpD;AAAA,EACF;AACA,QAAM,EAAE,OAAO,UAAU,IAAI;AAC7B,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACnD,UAAM,IAAI;AAAA,MAC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,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/token-manager.ts","../src/chat.tsx","../src/version.ts"],"sourcesContent":["// Token management (no React required — also available as\n// `@gemina/elements/token-manager`).\nexport { GeminaTokenManager } from './token-manager';\nexport type { FetchTokenResult, GeminaTokenManagerOptions } from './token-manager';\n\n// Chat UI (React — also available as `@gemina/elements/chat`).\nexport { GeminaChat } from './chat';\nexport type { GeminaChatProps, GeminaChatTheme, GeminaChatDirection } from './chat';\n\nexport { VERSION } from './version';\n","/**\n * GeminaTokenManager — in-memory holder for short-lived Gemina session\n * tokens, per the Document Intelligence token spec (PRD §6.11.1).\n *\n * Security model (the five footguns this file designs out):\n *\n * 1. **The API key never enters the browser.** The constructor throws if it\n * is handed a raw string instead of a `fetchToken` callback, and\n * `getToken()` rejects if the callback ever resolves with an\n * API-key-shaped string (32 alphanumerics, no dots).\n * 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,\n * cookies, or IndexedDB anywhere in this package — the token lives only\n * in memory, inside state that is not an own property of the instance.\n * 3. **The browser never asserts its own scope.** This manager carries no\n * scope parameters at all; scope is signed into the token server-side.\n * 4. **No refresh token is held in the browser.** Renewal always goes back\n * through the tenant's own authenticated backend via `fetchToken`.\n * 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*\n * what the tenant backend minted; it has no code path to\n * `POST /v1/sessions/token`.\n *\n * Storage choice: internal state (including the token) lives in a\n * module-scoped `WeakMap` keyed by the instance rather than in an ordinary\n * class field. An ordinary field — even a `#private` one via devtools — is\n * trivially discoverable by enumerating the instance; the WeakMap keeps the\n * token out of `Object.keys`, `JSON.stringify`, spread copies, and casual\n * inspection, and it is unreachable without a reference to both the WeakMap\n * (module-private) and the instance. This is hardening against accidental\n * exposure/serialization, not encryption: code running in the same realm\n * with a debugger can still read process memory. The upgrade path for\n * stronger isolation is a Web Worker (see PRD §6.11.1).\n *\n * SSR-safe: this module touches no `window`/`document` at import time and\n * starts no timers — refresh happens lazily inside `getToken()`, so an idle\n * manager consumes nothing and never keeps a Node process alive.\n */\n\n/** What `fetchToken` must resolve with (mirror of the mint response). */\nexport interface FetchTokenResult {\n /** The raw session token (a JWT). Pass it WITHOUT a \"Bearer \" prefix. */\n token: string;\n /** Token lifetime in seconds, as returned by the mint endpoint. */\n expiresIn: number;\n}\n\n/** Constructor options for {@link GeminaTokenManager}. */\nexport interface GeminaTokenManagerOptions {\n /**\n * Callback that obtains a fresh session token from the TENANT'S OWN\n * backend (which in turn calls Gemina's `POST /v1/sessions/token` with\n * the API key, server-side). It must resolve with\n * `{ token, expiresIn }`. It must NEVER return a Gemina API key.\n */\n fetchToken: () => Promise<FetchTokenResult>;\n /**\n * How many seconds before the token's expiry `getToken()` starts\n * refreshing. Default 60 (the PRD's `exp − 60s` refresh point).\n */\n refreshSkewSeconds?: number;\n}\n\n/** Gemina API keys are exactly 32 alphanumerics with no prefix. */\nconst API_KEY_SHAPE = /^[A-Za-z0-9]{32}$/;\n\nconst API_KEY_ERROR =\n 'GeminaTokenManager received an API-key-shaped credential (32 alphanumeric ' +\n 'characters). Gemina API keys are master keys and must NEVER enter the ' +\n 'browser: mint a short-lived session token on YOUR backend via ' +\n 'POST /v1/sessions/token (sessions.mintRetrievalToken in @gemina/sdk) and ' +\n 'return { token, expiresIn } from fetchToken instead.';\n\ninterface TokenState {\n fetchToken: () => Promise<FetchTokenResult>;\n refreshSkewMs: number;\n /** The cached raw token, or null when absent/invalidated. */\n token: string | null;\n /** Epoch ms after which the cached token is considered expired. */\n expiresAtMs: number;\n /** Shared in-flight refresh, so concurrent callers never stampede. */\n inFlight: Promise<string> | null;\n /** Bumped by invalidate(); stale refreshes must not repopulate the cache. */\n epoch: number;\n}\n\n// Module-private state store — see the header comment for why the token is\n// deliberately NOT an own property of the instance.\nconst STATES = new WeakMap<GeminaTokenManager, TokenState>();\n\nfunction getState(manager: GeminaTokenManager): TokenState {\n const state = STATES.get(manager);\n if (state === undefined) {\n throw new Error(\n 'GeminaTokenManager state missing — was the instance constructed normally? ' +\n '(Object.create/deserialization is not supported.)',\n );\n }\n return state;\n}\n\n/**\n * Validate what `fetchToken` resolved with and return the raw token.\n * Rejects API-key-shaped strings and anything that is not JWT-shaped.\n */\nfunction validateFetchedToken(result: FetchTokenResult): string {\n if (result === null || typeof result !== 'object') {\n throw new Error(\n 'GeminaTokenManager: fetchToken must resolve with { token, expiresIn } ' +\n `(got ${result === null ? 'null' : typeof result}).`,\n );\n }\n const { token, expiresIn } = result;\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved without a token string. ' +\n 'Return { token, expiresIn } from the mint response.',\n );\n }\n if (API_KEY_SHAPE.test(token)) {\n throw new Error(API_KEY_ERROR);\n }\n // Session tokens are JWTs: exactly three non-empty dot-separated segments.\n const segments = token.split('.');\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0)) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with a value that is not a ' +\n 'session token. Gemina session tokens are JWTs (three dot-separated ' +\n 'segments); return the `token` field from POST /v1/sessions/token.',\n );\n }\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with an invalid expiresIn ' +\n `(${String(expiresIn)}). Return the mint response's expiresIn (seconds > 0).`,\n );\n }\n return token;\n}\n\n/**\n * Holds a short-lived Gemina session token in memory and keeps it fresh.\n *\n * ```ts\n * const tokenManager = new GeminaTokenManager({\n * // YOUR backend endpoint — it holds the API key and mints the token.\n * fetchToken: async () => {\n * const res = await fetch(\"/api/gemina-session\", { method: \"POST\" });\n * if (!res.ok) throw new Error(\"Failed to mint Gemina session token\");\n * return res.json(); // { token, expiresIn }\n * },\n * });\n * ```\n *\n * - `getToken()` fetches lazily on first use, then auto-refreshes when the\n * cached token is within `refreshSkewSeconds` of expiry. Concurrent\n * callers share a single in-flight fetch.\n * - `invalidate()` drops the cache so the next `getToken()` refetches\n * (use after a 401).\n * - No timers run while idle; nothing is ever written to storage.\n */\nexport class GeminaTokenManager {\n constructor(options: GeminaTokenManagerOptions) {\n if (typeof options === 'string') {\n // Someone did `new GeminaTokenManager(\"<api key or token>\")`.\n throw new Error(\n API_KEY_SHAPE.test(options)\n ? API_KEY_ERROR\n : 'GeminaTokenManager takes { fetchToken } — a callback that asks ' +\n 'YOUR backend for a fresh session token — not a raw string. ' +\n 'Never pass a Gemina API key to browser code.',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new Error(\n 'GeminaTokenManager requires an options object: new GeminaTokenManager({ fetchToken }).',\n );\n }\n const { fetchToken, refreshSkewSeconds = 60 } = options;\n if (typeof fetchToken === 'string') {\n throw new Error(\n (API_KEY_SHAPE.test(fetchToken) ? `${API_KEY_ERROR} ` : '') +\n 'GeminaTokenManager: fetchToken must be a function returning ' +\n 'Promise<{ token, expiresIn }>, not a string.',\n );\n }\n if (typeof fetchToken !== 'function') {\n throw new Error(\n 'GeminaTokenManager: fetchToken is required and must be a function ' +\n 'returning Promise<{ token, expiresIn }>.',\n );\n }\n if (\n typeof refreshSkewSeconds !== 'number' ||\n !Number.isFinite(refreshSkewSeconds) ||\n refreshSkewSeconds < 0\n ) {\n throw new Error(\n `GeminaTokenManager: refreshSkewSeconds must be a non-negative number (got ${String(\n refreshSkewSeconds,\n )}).`,\n );\n }\n\n STATES.set(this, {\n fetchToken,\n refreshSkewMs: refreshSkewSeconds * 1000,\n token: null,\n expiresAtMs: 0,\n inFlight: null,\n epoch: 0,\n });\n }\n\n /**\n * Return a valid session token, fetching or refreshing as needed.\n *\n * A cached token is reused until `now >= expiry - refreshSkewSeconds`\n * (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).\n * All concurrent callers during a refresh share ONE in-flight fetch.\n * A failed fetch is not cached — the next call retries.\n */\n getToken(): Promise<string> {\n const state = getState(this);\n\n if (state.token !== null && Date.now() < state.expiresAtMs - state.refreshSkewMs) {\n return Promise.resolve(state.token);\n }\n\n if (state.inFlight !== null) {\n return state.inFlight;\n }\n\n const epoch = state.epoch;\n const fetchStartedAtMs = Date.now();\n // Start the user callback immediately (getToken() should fire the mint\n // request right away), but convert a synchronous throw into a rejection\n // so the in-flight bookkeeping below stays consistent.\n let fetched: Promise<FetchTokenResult>;\n try {\n fetched = Promise.resolve(state.fetchToken());\n } catch (error) {\n fetched = Promise.reject(error);\n }\n const inFlight: Promise<string> = fetched\n .then((result) => {\n const token = validateFetchedToken(result);\n if (state.epoch === epoch) {\n state.token = token;\n state.expiresAtMs = fetchStartedAtMs + result.expiresIn * 1000;\n }\n // If invalidate() ran mid-flight, still hand this (already-minted)\n // token to the callers who asked before the invalidation — but do\n // not cache it; the next getToken() fetches fresh.\n return token;\n })\n .finally(() => {\n if (state.inFlight === inFlight) {\n state.inFlight = null;\n }\n });\n\n state.inFlight = inFlight;\n return inFlight;\n }\n\n /**\n * Drop the cached token (and detach any in-flight refresh) so the next\n * `getToken()` fetches a fresh one. Call this when the API answers 401,\n * then retry the request once with a new `getToken()`.\n */\n invalidate(): void {\n const state = getState(this);\n state.token = null;\n state.expiresAtMs = 0;\n state.inFlight = null;\n state.epoch += 1;\n }\n}\n","/**\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 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 /** 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/**\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 */\ninterface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nfunction 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`. */\nfunction httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\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 fetch body can be read once, so we clone defensively;\n * if that fails (non-JSON, empty, or already consumed) the status still stands.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const response = getResponseLike(error);\n const info: ChatErrorInfo = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n retryAfterSeconds: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n const rawRetryAfter = response.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\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\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-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 justify-content: flex-end;\n align-items: center;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__newchat {\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__typing {\n align-self: flex-start;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\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 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 {messages.length > 0 && (\n <div className=\"gemina-chat__header\">\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\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.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 && <div className=\"gemina-chat__typing\">Thinking…</div>}\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","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.2.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8DA,IAAM,gBAAgB;AAEtB,IAAM,gBACJ;AAqBF,IAAM,SAAS,oBAAI,QAAwC;AAE3D,SAAS,SAAS,SAAyC;AACzD,QAAM,QAAQ,OAAO,IAAI,OAAO;AAChC,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAMA,SAAS,qBAAqB,QAAkC;AAC9D,MAAI,WAAW,QAAQ,OAAO,WAAW,UAAU;AACjD,UAAM,IAAI;AAAA,MACR,8EACU,WAAW,OAAO,SAAS,OAAO,MAAM;AAAA,IACpD;AAAA,EACF;AACA,QAAM,EAAE,OAAO,UAAU,IAAI;AAC7B,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACnD,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,MAAI,cAAc,KAAK,KAAK,GAAG;AAC7B,UAAM,IAAI,MAAM,aAAa;AAAA,EAC/B;AAEA,QAAM,WAAW,MAAM,MAAM,GAAG;AAChC,MAAI,SAAS,WAAW,KAAK,SAAS,KAAK,CAAC,YAAY,QAAQ,WAAW,CAAC,GAAG;AAC7E,UAAM,IAAI;AAAA,MACR;AAAA,IAGF;AAAA,EACF;AACA,MAAI,OAAO,cAAc,YAAY,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,GAAG;AAClF,UAAM,IAAI;AAAA,MACR,sEACM,OAAO,SAAS,CAAC;AAAA,IACzB;AAAA,EACF;AACA,SAAO;AACT;AAuBO,IAAM,qBAAN,MAAyB;AAAA,EAC9B,YAAY,SAAoC;AAC9C,QAAI,OAAO,YAA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AAAA,oBAAC;AAAA;AAAA,sBACC,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,QAAQ,4CAAC,SAAI,WAAU,uBAAsB,4BAAS;AAAA;AAAA;AAAA,IACzD;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":[]}
|
package/dist/index.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gemina/elements",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Embeddable browser UI for Gemina Document Intelligence — a drop-in React chat component plus a security-hardened session-token manager. The API key never enters the browser.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
package/dist/chat.d.cts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import * as React from 'react';
|
|
2
|
-
import { GeminaTokenManager } from './token-manager.cjs';
|
|
3
|
-
|
|
4
|
-
/** Visual theme. `"auto"` follows `prefers-color-scheme`. */
|
|
5
|
-
type GeminaChatTheme = 'light' | 'dark' | 'auto';
|
|
6
|
-
/**
|
|
7
|
-
* Text direction. `"auto"` flips the widget to RTL when the user's latest
|
|
8
|
-
* message contains Hebrew, and lets each bubble resolve its own direction.
|
|
9
|
-
*/
|
|
10
|
-
type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';
|
|
11
|
-
interface GeminaChatProps {
|
|
12
|
-
/** Token source. Required — see {@link GeminaTokenManager}. */
|
|
13
|
-
tokenManager: GeminaTokenManager;
|
|
14
|
-
/** Gemina API base URL (default `https://api.gemina.co`). */
|
|
15
|
-
baseUrl?: string;
|
|
16
|
-
/**
|
|
17
|
-
* Optional end-user id forwarded with each query. On the session-token
|
|
18
|
-
* path the token's SIGNED scope always wins server-side — this is a
|
|
19
|
-
* hint, not a security control.
|
|
20
|
-
*/
|
|
21
|
-
endUserId?: string;
|
|
22
|
-
/** Visual theme (default `"auto"`). */
|
|
23
|
-
theme?: GeminaChatTheme;
|
|
24
|
-
/** Text direction (default `"auto"`). */
|
|
25
|
-
dir?: GeminaChatDirection;
|
|
26
|
-
/** Input placeholder text. */
|
|
27
|
-
placeholder?: string;
|
|
28
|
-
/** Called with the cited `documentId` when a citation chip is clicked. */
|
|
29
|
-
onCitationClick?: (documentId: string) => void;
|
|
30
|
-
/** Extra class name(s) for the root element (e.g. to override CSS vars). */
|
|
31
|
-
className?: string;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Embeddable Gemina Document Intelligence chat.
|
|
35
|
-
*
|
|
36
|
-
* ```tsx
|
|
37
|
-
* <GeminaChat
|
|
38
|
-
* tokenManager={tokenManager}
|
|
39
|
-
* onCitationClick={(documentId) => openDocument(documentId)}
|
|
40
|
-
* />
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
declare function GeminaChat(props: GeminaChatProps): React.JSX.Element;
|
|
44
|
-
|
|
45
|
-
export { GeminaChat, type GeminaChatDirection, type GeminaChatProps, type GeminaChatTheme };
|
package/dist/chat.d.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import * as React from 'react';
|
|
2
|
-
import { GeminaTokenManager } from './token-manager.js';
|
|
3
|
-
|
|
4
|
-
/** Visual theme. `"auto"` follows `prefers-color-scheme`. */
|
|
5
|
-
type GeminaChatTheme = 'light' | 'dark' | 'auto';
|
|
6
|
-
/**
|
|
7
|
-
* Text direction. `"auto"` flips the widget to RTL when the user's latest
|
|
8
|
-
* message contains Hebrew, and lets each bubble resolve its own direction.
|
|
9
|
-
*/
|
|
10
|
-
type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';
|
|
11
|
-
interface GeminaChatProps {
|
|
12
|
-
/** Token source. Required — see {@link GeminaTokenManager}. */
|
|
13
|
-
tokenManager: GeminaTokenManager;
|
|
14
|
-
/** Gemina API base URL (default `https://api.gemina.co`). */
|
|
15
|
-
baseUrl?: string;
|
|
16
|
-
/**
|
|
17
|
-
* Optional end-user id forwarded with each query. On the session-token
|
|
18
|
-
* path the token's SIGNED scope always wins server-side — this is a
|
|
19
|
-
* hint, not a security control.
|
|
20
|
-
*/
|
|
21
|
-
endUserId?: string;
|
|
22
|
-
/** Visual theme (default `"auto"`). */
|
|
23
|
-
theme?: GeminaChatTheme;
|
|
24
|
-
/** Text direction (default `"auto"`). */
|
|
25
|
-
dir?: GeminaChatDirection;
|
|
26
|
-
/** Input placeholder text. */
|
|
27
|
-
placeholder?: string;
|
|
28
|
-
/** Called with the cited `documentId` when a citation chip is clicked. */
|
|
29
|
-
onCitationClick?: (documentId: string) => void;
|
|
30
|
-
/** Extra class name(s) for the root element (e.g. to override CSS vars). */
|
|
31
|
-
className?: string;
|
|
32
|
-
}
|
|
33
|
-
/**
|
|
34
|
-
* Embeddable Gemina Document Intelligence chat.
|
|
35
|
-
*
|
|
36
|
-
* ```tsx
|
|
37
|
-
* <GeminaChat
|
|
38
|
-
* tokenManager={tokenManager}
|
|
39
|
-
* onCitationClick={(documentId) => openDocument(documentId)}
|
|
40
|
-
* />
|
|
41
|
-
* ```
|
|
42
|
-
*/
|
|
43
|
-
declare function GeminaChat(props: GeminaChatProps): React.JSX.Element;
|
|
44
|
-
|
|
45
|
-
export { GeminaChat, type GeminaChatDirection, type GeminaChatProps, type GeminaChatTheme };
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/chat.tsx","../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 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 /** 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/**\n * Extract an HTTP status from a thrown value by shape rather than\n * `instanceof ResponseError` — robust against duplicated `@gemina/sdk`\n * copies in a bundle (class identity is not shared across copies).\n */\nfunction httpStatus(error: unknown): number | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (\n response !== null &&\n typeof response === 'object' &&\n typeof (response as { status?: unknown }).status === 'number'\n ) {\n return (response as { status: number }).status;\n }\n }\n return undefined;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Document Intelligence isn't enabled on this plan.\";\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\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-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__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__typing {\n align-self: flex-start;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\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 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\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 return client.chat.chatQuery({ chatQueryInDTO: { message, endUserId } });\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 const result = await queryWithRetry(text);\n if (!mountedRef.current) {\n return;\n }\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 const status = httpStatus(error);\n if (status === 401) {\n appendMessage({ role: 'error', text: SESSION_EXPIRED_TEXT });\n } else if (status === 429) {\n appendMessage({ role: 'error', text: RATE_LIMIT_TEXT });\n } else if (status === 402 || status === 403) {\n appendMessage({ role: 'error', text: PLAN_GATE_TEXT });\n } else {\n appendMessage({ role: 'error', text: GENERIC_ERROR_TEXT, retryText: text });\n }\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\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 <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.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 && <div className=\"gemina-chat__typing\">Thinking…</div>}\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","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.1.1';\n"],"mappings":";AAYA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,oBAAoB;;;ACbtB,IAAM,UAAU;;;AD6fT,cAYA,YAZA;AA7ad,IAAM,YAAY;AAOlB,SAAS,WAAW,OAAoC;AACtD,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,cAAc,OAAO;AACtE,UAAM,WAAY,MAAiC;AACnD,QACE,aAAa,QACb,OAAO,aAAa,YACpB,OAAQ,SAAkC,WAAW,UACrD;AACA,aAAQ,SAAgC;AAAA,IAC1C;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAM,uBAAuB;AAC7B,IAAM,kBAAkB;AACxB,IAAM,iBAAiB;AACv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AA,wBACL,WAAU;AAAA,wBACV,OAAO,iBAAiB,UAAU;AAAA,wBAClC,SAAS,MAAM,kBAAkB,UAAU;AAAA,wBAE1C;AAAA;AAAA,sBANI,GAAG,UAAU,IAAI,KAAK;AAAA,oBAO7B,CACD,GACH;AAAA;AAAA;AAAA,gBA1BG,QAAQ;AAAA,cA4Bf;AAAA,YAEJ;AACA,mBACE;AAAA,cAAC;AAAA;AAAA,gBAEC,MAAK;AAAA,gBACL,WAAU;AAAA,gBAET;AAAA,0BAAQ;AAAA,kBACR,QAAQ,cAAc,UACrB;AAAA,oBAAC;AAAA;AAAA,sBACC,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,QAAQ,oBAAC,SAAI,WAAU,uBAAsB,4BAAS;AAAA;AAAA;AAAA,IACzD;AAAA,IACA,qBAAC,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":[]}
|
package/dist/index.d.cts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
export { FetchTokenResult, GeminaTokenManager, GeminaTokenManagerOptions } from './token-manager.cjs';
|
|
2
|
-
export { GeminaChat, GeminaChatDirection, GeminaChatProps, GeminaChatTheme } from './chat.cjs';
|
|
3
|
-
import 'react';
|
|
4
|
-
|
|
5
|
-
/** Package version. Keep in sync with package.json. */
|
|
6
|
-
declare const VERSION = "0.1.1";
|
|
7
|
-
|
|
8
|
-
export { VERSION };
|
package/dist/index.d.ts
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
export { FetchTokenResult, GeminaTokenManager, GeminaTokenManagerOptions } from './token-manager.js';
|
|
2
|
-
export { GeminaChat, GeminaChatDirection, GeminaChatProps, GeminaChatTheme } from './chat.js';
|
|
3
|
-
import 'react';
|
|
4
|
-
|
|
5
|
-
/** Package version. Keep in sync with package.json. */
|
|
6
|
-
declare const VERSION = "0.1.1";
|
|
7
|
-
|
|
8
|
-
export { VERSION };
|
package/dist/token-manager.d.cts
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* GeminaTokenManager — in-memory holder for short-lived Gemina session
|
|
3
|
-
* tokens, per the Document Intelligence token spec (PRD §6.11.1).
|
|
4
|
-
*
|
|
5
|
-
* Security model (the five footguns this file designs out):
|
|
6
|
-
*
|
|
7
|
-
* 1. **The API key never enters the browser.** The constructor throws if it
|
|
8
|
-
* is handed a raw string instead of a `fetchToken` callback, and
|
|
9
|
-
* `getToken()` rejects if the callback ever resolves with an
|
|
10
|
-
* API-key-shaped string (32 alphanumerics, no dots).
|
|
11
|
-
* 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,
|
|
12
|
-
* cookies, or IndexedDB anywhere in this package — the token lives only
|
|
13
|
-
* in memory, inside state that is not an own property of the instance.
|
|
14
|
-
* 3. **The browser never asserts its own scope.** This manager carries no
|
|
15
|
-
* scope parameters at all; scope is signed into the token server-side.
|
|
16
|
-
* 4. **No refresh token is held in the browser.** Renewal always goes back
|
|
17
|
-
* through the tenant's own authenticated backend via `fetchToken`.
|
|
18
|
-
* 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*
|
|
19
|
-
* what the tenant backend minted; it has no code path to
|
|
20
|
-
* `POST /v1/sessions/token`.
|
|
21
|
-
*
|
|
22
|
-
* Storage choice: internal state (including the token) lives in a
|
|
23
|
-
* module-scoped `WeakMap` keyed by the instance rather than in an ordinary
|
|
24
|
-
* class field. An ordinary field — even a `#private` one via devtools — is
|
|
25
|
-
* trivially discoverable by enumerating the instance; the WeakMap keeps the
|
|
26
|
-
* token out of `Object.keys`, `JSON.stringify`, spread copies, and casual
|
|
27
|
-
* inspection, and it is unreachable without a reference to both the WeakMap
|
|
28
|
-
* (module-private) and the instance. This is hardening against accidental
|
|
29
|
-
* exposure/serialization, not encryption: code running in the same realm
|
|
30
|
-
* with a debugger can still read process memory. The upgrade path for
|
|
31
|
-
* stronger isolation is a Web Worker (see PRD §6.11.1).
|
|
32
|
-
*
|
|
33
|
-
* SSR-safe: this module touches no `window`/`document` at import time and
|
|
34
|
-
* starts no timers — refresh happens lazily inside `getToken()`, so an idle
|
|
35
|
-
* manager consumes nothing and never keeps a Node process alive.
|
|
36
|
-
*/
|
|
37
|
-
/** What `fetchToken` must resolve with (mirror of the mint response). */
|
|
38
|
-
interface FetchTokenResult {
|
|
39
|
-
/** The raw session token (a JWT). Pass it WITHOUT a "Bearer " prefix. */
|
|
40
|
-
token: string;
|
|
41
|
-
/** Token lifetime in seconds, as returned by the mint endpoint. */
|
|
42
|
-
expiresIn: number;
|
|
43
|
-
}
|
|
44
|
-
/** Constructor options for {@link GeminaTokenManager}. */
|
|
45
|
-
interface GeminaTokenManagerOptions {
|
|
46
|
-
/**
|
|
47
|
-
* Callback that obtains a fresh session token from the TENANT'S OWN
|
|
48
|
-
* backend (which in turn calls Gemina's `POST /v1/sessions/token` with
|
|
49
|
-
* the API key, server-side). It must resolve with
|
|
50
|
-
* `{ token, expiresIn }`. It must NEVER return a Gemina API key.
|
|
51
|
-
*/
|
|
52
|
-
fetchToken: () => Promise<FetchTokenResult>;
|
|
53
|
-
/**
|
|
54
|
-
* How many seconds before the token's expiry `getToken()` starts
|
|
55
|
-
* refreshing. Default 60 (the PRD's `exp − 60s` refresh point).
|
|
56
|
-
*/
|
|
57
|
-
refreshSkewSeconds?: number;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Holds a short-lived Gemina session token in memory and keeps it fresh.
|
|
61
|
-
*
|
|
62
|
-
* ```ts
|
|
63
|
-
* const tokenManager = new GeminaTokenManager({
|
|
64
|
-
* // YOUR backend endpoint — it holds the API key and mints the token.
|
|
65
|
-
* fetchToken: async () => {
|
|
66
|
-
* const res = await fetch("/api/gemina-session", { method: "POST" });
|
|
67
|
-
* if (!res.ok) throw new Error("Failed to mint Gemina session token");
|
|
68
|
-
* return res.json(); // { token, expiresIn }
|
|
69
|
-
* },
|
|
70
|
-
* });
|
|
71
|
-
* ```
|
|
72
|
-
*
|
|
73
|
-
* - `getToken()` fetches lazily on first use, then auto-refreshes when the
|
|
74
|
-
* cached token is within `refreshSkewSeconds` of expiry. Concurrent
|
|
75
|
-
* callers share a single in-flight fetch.
|
|
76
|
-
* - `invalidate()` drops the cache so the next `getToken()` refetches
|
|
77
|
-
* (use after a 401).
|
|
78
|
-
* - No timers run while idle; nothing is ever written to storage.
|
|
79
|
-
*/
|
|
80
|
-
declare class GeminaTokenManager {
|
|
81
|
-
constructor(options: GeminaTokenManagerOptions);
|
|
82
|
-
/**
|
|
83
|
-
* Return a valid session token, fetching or refreshing as needed.
|
|
84
|
-
*
|
|
85
|
-
* A cached token is reused until `now >= expiry - refreshSkewSeconds`
|
|
86
|
-
* (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).
|
|
87
|
-
* All concurrent callers during a refresh share ONE in-flight fetch.
|
|
88
|
-
* A failed fetch is not cached — the next call retries.
|
|
89
|
-
*/
|
|
90
|
-
getToken(): Promise<string>;
|
|
91
|
-
/**
|
|
92
|
-
* Drop the cached token (and detach any in-flight refresh) so the next
|
|
93
|
-
* `getToken()` fetches a fresh one. Call this when the API answers 401,
|
|
94
|
-
* then retry the request once with a new `getToken()`.
|
|
95
|
-
*/
|
|
96
|
-
invalidate(): void;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export { type FetchTokenResult, GeminaTokenManager, type GeminaTokenManagerOptions };
|
package/dist/token-manager.d.ts
DELETED
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* GeminaTokenManager — in-memory holder for short-lived Gemina session
|
|
3
|
-
* tokens, per the Document Intelligence token spec (PRD §6.11.1).
|
|
4
|
-
*
|
|
5
|
-
* Security model (the five footguns this file designs out):
|
|
6
|
-
*
|
|
7
|
-
* 1. **The API key never enters the browser.** The constructor throws if it
|
|
8
|
-
* is handed a raw string instead of a `fetchToken` callback, and
|
|
9
|
-
* `getToken()` rejects if the callback ever resolves with an
|
|
10
|
-
* API-key-shaped string (32 alphanumerics, no dots).
|
|
11
|
-
* 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,
|
|
12
|
-
* cookies, or IndexedDB anywhere in this package — the token lives only
|
|
13
|
-
* in memory, inside state that is not an own property of the instance.
|
|
14
|
-
* 3. **The browser never asserts its own scope.** This manager carries no
|
|
15
|
-
* scope parameters at all; scope is signed into the token server-side.
|
|
16
|
-
* 4. **No refresh token is held in the browser.** Renewal always goes back
|
|
17
|
-
* through the tenant's own authenticated backend via `fetchToken`.
|
|
18
|
-
* 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*
|
|
19
|
-
* what the tenant backend minted; it has no code path to
|
|
20
|
-
* `POST /v1/sessions/token`.
|
|
21
|
-
*
|
|
22
|
-
* Storage choice: internal state (including the token) lives in a
|
|
23
|
-
* module-scoped `WeakMap` keyed by the instance rather than in an ordinary
|
|
24
|
-
* class field. An ordinary field — even a `#private` one via devtools — is
|
|
25
|
-
* trivially discoverable by enumerating the instance; the WeakMap keeps the
|
|
26
|
-
* token out of `Object.keys`, `JSON.stringify`, spread copies, and casual
|
|
27
|
-
* inspection, and it is unreachable without a reference to both the WeakMap
|
|
28
|
-
* (module-private) and the instance. This is hardening against accidental
|
|
29
|
-
* exposure/serialization, not encryption: code running in the same realm
|
|
30
|
-
* with a debugger can still read process memory. The upgrade path for
|
|
31
|
-
* stronger isolation is a Web Worker (see PRD §6.11.1).
|
|
32
|
-
*
|
|
33
|
-
* SSR-safe: this module touches no `window`/`document` at import time and
|
|
34
|
-
* starts no timers — refresh happens lazily inside `getToken()`, so an idle
|
|
35
|
-
* manager consumes nothing and never keeps a Node process alive.
|
|
36
|
-
*/
|
|
37
|
-
/** What `fetchToken` must resolve with (mirror of the mint response). */
|
|
38
|
-
interface FetchTokenResult {
|
|
39
|
-
/** The raw session token (a JWT). Pass it WITHOUT a "Bearer " prefix. */
|
|
40
|
-
token: string;
|
|
41
|
-
/** Token lifetime in seconds, as returned by the mint endpoint. */
|
|
42
|
-
expiresIn: number;
|
|
43
|
-
}
|
|
44
|
-
/** Constructor options for {@link GeminaTokenManager}. */
|
|
45
|
-
interface GeminaTokenManagerOptions {
|
|
46
|
-
/**
|
|
47
|
-
* Callback that obtains a fresh session token from the TENANT'S OWN
|
|
48
|
-
* backend (which in turn calls Gemina's `POST /v1/sessions/token` with
|
|
49
|
-
* the API key, server-side). It must resolve with
|
|
50
|
-
* `{ token, expiresIn }`. It must NEVER return a Gemina API key.
|
|
51
|
-
*/
|
|
52
|
-
fetchToken: () => Promise<FetchTokenResult>;
|
|
53
|
-
/**
|
|
54
|
-
* How many seconds before the token's expiry `getToken()` starts
|
|
55
|
-
* refreshing. Default 60 (the PRD's `exp − 60s` refresh point).
|
|
56
|
-
*/
|
|
57
|
-
refreshSkewSeconds?: number;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Holds a short-lived Gemina session token in memory and keeps it fresh.
|
|
61
|
-
*
|
|
62
|
-
* ```ts
|
|
63
|
-
* const tokenManager = new GeminaTokenManager({
|
|
64
|
-
* // YOUR backend endpoint — it holds the API key and mints the token.
|
|
65
|
-
* fetchToken: async () => {
|
|
66
|
-
* const res = await fetch("/api/gemina-session", { method: "POST" });
|
|
67
|
-
* if (!res.ok) throw new Error("Failed to mint Gemina session token");
|
|
68
|
-
* return res.json(); // { token, expiresIn }
|
|
69
|
-
* },
|
|
70
|
-
* });
|
|
71
|
-
* ```
|
|
72
|
-
*
|
|
73
|
-
* - `getToken()` fetches lazily on first use, then auto-refreshes when the
|
|
74
|
-
* cached token is within `refreshSkewSeconds` of expiry. Concurrent
|
|
75
|
-
* callers share a single in-flight fetch.
|
|
76
|
-
* - `invalidate()` drops the cache so the next `getToken()` refetches
|
|
77
|
-
* (use after a 401).
|
|
78
|
-
* - No timers run while idle; nothing is ever written to storage.
|
|
79
|
-
*/
|
|
80
|
-
declare class GeminaTokenManager {
|
|
81
|
-
constructor(options: GeminaTokenManagerOptions);
|
|
82
|
-
/**
|
|
83
|
-
* Return a valid session token, fetching or refreshing as needed.
|
|
84
|
-
*
|
|
85
|
-
* A cached token is reused until `now >= expiry - refreshSkewSeconds`
|
|
86
|
-
* (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).
|
|
87
|
-
* All concurrent callers during a refresh share ONE in-flight fetch.
|
|
88
|
-
* A failed fetch is not cached — the next call retries.
|
|
89
|
-
*/
|
|
90
|
-
getToken(): Promise<string>;
|
|
91
|
-
/**
|
|
92
|
-
* Drop the cached token (and detach any in-flight refresh) so the next
|
|
93
|
-
* `getToken()` fetches a fresh one. Call this when the API answers 401,
|
|
94
|
-
* then retry the request once with a new `getToken()`.
|
|
95
|
-
*/
|
|
96
|
-
invalidate(): void;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export { type FetchTokenResult, GeminaTokenManager, type GeminaTokenManagerOptions };
|