@gemina/elements 0.5.4 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +137 -11
- package/dist/chat.cjs +27 -21
- package/dist/chat.cjs.map +1 -1
- package/dist/chat.js +2 -1
- package/dist/chunk-CDGDP2C3.js +2680 -0
- package/dist/chunk-CDGDP2C3.js.map +1 -0
- package/dist/chunk-MQMT7SEJ.js +56 -0
- package/dist/chunk-MQMT7SEJ.js.map +1 -0
- package/dist/{chunk-I6CB46UZ.js → chunk-PB3PXDYZ.js} +11 -50
- package/dist/chunk-PB3PXDYZ.js.map +1 -0
- package/dist/index.cjs +2709 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +8 -2
- package/dist/verification.cjs +2757 -0
- package/dist/verification.cjs.map +1 -0
- package/dist/verification.d.cts +68 -0
- package/dist/verification.d.ts +68 -0
- package/dist/verification.js +8 -0
- package/dist/verification.js.map +1 -0
- package/package.json +8 -3
- package/dist/chunk-I6CB46UZ.js.map +0 -1
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 /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables\n * (including `--gemina-chat-header-bg` for the header bar).\n */\n title?: string;\n /**\n * Plain text shown centered in the empty conversation area until the\n * first message. Use it to set expectations about what the assistant\n * can and can't see (e.g. \"Answers come from your indexed document\n * data\"). Newlines split it into separately spaced paragraphs — no\n * markup, so the string stays safe and portable.\n */\n intro?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/**\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-header-bg: transparent;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n align-items: center;\n /* Guaranteed minimum separation. The pushing itself is the button's\n auto margin below — NOT a margin on the title, whose dir=\"auto\" can\n resolve opposite to the widget (English title in an RTL chat) and\n collapse an inline-aware margin to the wrong side. */\n gap: 12px;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n background: var(--gemina-chat-header-bg);\n}\n.gemina-chat__title {\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n margin-inline-start: auto;\n flex-shrink: 0;\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__intro {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin: auto;\n max-width: 46ch;\n padding: 16px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-chat-muted);\n}\n.gemina-chat__intro-line { margin: 0; }\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n intro,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.length === 0 && intro !== undefined && (\n <div className=\"gemina-chat__intro\" dir={bubbleDir}>\n {intro\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line, index) => (\n <p key={index} className=\"gemina-chat__intro-line\">\n {line}\n </p>\n ))}\n </div>\n )}\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\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,KAAK;AAAA,UAChD,WAAW;AAAA;AAAA,MACb;AAAA,MACA;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,WAAU;AAAA,UACV,cAAW;AAAA,UACX,UAAU,QAAQ,MAAM,KAAK,EAAE,WAAW;AAAA,UAC3C;AAAA;AAAA,MAED;AAAA,OACF;AAAA,KACF;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/token-manager.ts","../src/chat.tsx","../src/internal/response-like.ts","../src/version.ts","../src/verification/index.tsx","../src/verification/classify.ts","../src/verification/pointer.ts","../src/verification/bindings.ts","../src/verification/form.tsx","../src/verification/viewer.tsx","../src/verification/viewer-math.ts","../src/verification/styles.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\n// Verification UI (React — also available as `@gemina/elements/verification`).\nexport { GeminaVerification } from './verification/index';\nexport type {\n GeminaVerificationProps,\n GeminaVerificationTheme,\n GeminaVerificationDirection,\n VerificationErrorReason,\n VerificationErrorDetail,\n VerificationCompletion,\n} from './verification/index';\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 { getResponseLike, httpStatus, readErrorEnvelope } from './internal/response-like';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables\n * (including `--gemina-chat-header-bg` for the header bar).\n */\n title?: string;\n /**\n * Plain text shown centered in the empty conversation area until the\n * first message. Use it to set expectations about what the assistant\n * can and can't see (e.g. \"Answers come from your indexed document\n * data\"). Newlines split it into separately spaced paragraphs — no\n * markup, so the string stays safe and portable.\n */\n intro?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The envelope parsing (with its defensive clone/json\n * dance) lives in `readErrorEnvelope`; only the `Retry-After` header handling\n * is chat-specific.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const envelope = await readErrorEnvelope(error);\n const info: ChatErrorInfo = { ...envelope, retryAfterSeconds: undefined };\n\n const rawRetryAfter = getResponseLike(error)?.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-header-bg: transparent;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n align-items: center;\n /* Guaranteed minimum separation. The pushing itself is the button's\n auto margin below — NOT a margin on the title, whose dir=\"auto\" can\n resolve opposite to the widget (English title in an RTL chat) and\n collapse an inline-aware margin to the wrong side. */\n gap: 12px;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n background: var(--gemina-chat-header-bg);\n}\n.gemina-chat__title {\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n margin-inline-start: auto;\n flex-shrink: 0;\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__intro {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin: auto;\n max-width: 46ch;\n padding: 16px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-chat-muted);\n}\n.gemina-chat__intro-line { margin: 0; }\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n intro,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.length === 0 && intro !== undefined && (\n <div className=\"gemina-chat__intro\" dir={bubbleDir}>\n {intro\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line, index) => (\n <p key={index} className=\"gemina-chat__intro-line\">\n {line}\n </p>\n ))}\n </div>\n )}\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/**\n * Shared transport-error helpers for the widgets (chat + verification).\n *\n * Extracted verbatim from chat.tsx so both components read thrown SDK errors\n * the same way. Pure and dependency-free: no React, no DOM.\n */\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\nexport interface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nexport function getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nexport function httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/** What the standard backend error envelope reliably carries. */\nexport interface ErrorEnvelope {\n status: number | undefined;\n /** Stable backend `errors[0].error_code`. */\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status and\n * the stable `errors[0].error_code` / `description` are reliable across\n * environments — production strips `errors[0].detail`, so we never touch it.\n * The fetch body can be read once, so we clone defensively; if that fails\n * (non-JSON, empty, or already consumed) the status still stands.\n */\nexport async function readErrorEnvelope(error: unknown): Promise<ErrorEnvelope> {\n const response = getResponseLike(error);\n const info: ErrorEnvelope = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.7.0';\n","/**\n * <GeminaVerification> — drop-in human verification UI for one extraction.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager} (chat parity):\n * the component asks it for a short-lived session token and calls\n * `GET /v1/documents/extractions/{id}` through `@gemina/sdk`. It never sees —\n * and cannot accept — a Gemina API key.\n *\n * This module owns the fetch + state machine + edge states (Task 14):\n * loading → unavailable | review — the layout/flash/RTL layer (Task 15):\n * the stacked-below-860px root observer, eye-click → viewer flash wiring,\n * chat-parity Hebrew direction autodetect, and the silent expired-image-URL\n * refresh — the edit state + progress footer (Task 16): the immutable\n * edits map with delete-on-revert dirty tracking, and the\n * \"N confirmed · M corrected\" line fed by composeSubmission — and the submit\n * flow (Task 17): the confirm-final dialog, the PUT with 401\n * invalidate-retry-once, the 409 silent-refetch landing, submit-error with\n * edits preserved, and the exactly-once onComplete.\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ExtractionPrimaryViewOutDTO } from '@gemina/sdk';\nimport { httpStatus, readErrorEnvelope } from '../internal/response-like';\nimport {\n buildBindings,\n composeSubmission,\n indexBindingsByFieldPointer,\n toInputString,\n} from './bindings';\nimport type { FieldBinding } from './bindings';\nimport { classifyData, ROW_META_KEY } from './classify';\nimport { VerificationForm } from './form';\nimport { ensureVerificationStylesInjected } from './styles';\nimport type {\n GeminaVerificationProps,\n VerificationErrorDetail,\n VerificationErrorReason,\n} from './types';\nimport { VerificationViewer } from './viewer';\nimport type { RelativeRect } from './viewer';\n\nexport type {\n GeminaVerificationProps,\n GeminaVerificationTheme,\n GeminaVerificationDirection,\n VerificationErrorReason,\n VerificationErrorDetail,\n VerificationCompletion,\n} from './types';\n\n/**\n * The component's complete phase model. `review`, `confirming`, `submitting`,\n * and `submit-error` form the REVIEW FAMILY: all four render the same review\n * content (form, edits, aria-live progress — kept mounted so edits stay\n * visible through the whole submit sequence); confirming/submitting add the\n * overlay on top, submit-error the inline error banner. The read-only flag\n * lives in separate `alreadyValidated` state, not in the variants, so the\n * family shares it without every variant re-carrying it.\n */\ntype Phase =\n | { name: 'loading' }\n | { name: 'unavailable'; reason: VerificationErrorReason; message: string; canRetry: boolean }\n | { name: 'review' }\n | { name: 'confirming' } // confirm dialog open over review\n | { name: 'submitting' } // PUT in flight; dialog stays, buttons disabled\n | { name: 'submit-error'; message: string }\n | { name: 'done'; confirmed: number; corrected: number };\n\n/** The four phases that render the review content. */\ntype ReviewFamilyPhase = Extract<\n Phase,\n { name: 'review' | 'confirming' | 'submitting' | 'submit-error' }\n>;\n\n/** Hebrew Unicode block (U+0590–U+05FF) — chat.tsx's exact detector. */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/** Below this root width the two panes stack (one column, sticky viewer). */\nconst STACKED_BREAKPOINT = 860; // px\n\n/** At most one silent image-URL refresh per window — the refetch-loop brake. */\nconst IMAGE_REFRESH_THROTTLE_MS = 60_000;\n\nconst LOADING_TEXT = 'Loading extraction…';\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\n// The SUBMIT-side 401 copy must NOT suggest reloading: the reviewer's edits\n// live only in component state, and a reload would destroy them — while a\n// fresh sign-in in another tab plus Retry preserves and submits them.\nconst SUBMIT_SESSION_EXPIRED_TEXT =\n 'Session expired — sign in again in another tab, then press Retry. Your corrections are still here.';\nconst NOT_AVAILABLE_TEXT = 'This extraction is not available.';\nconst LOAD_FAILED_TEXT = \"Couldn't load the extraction.\";\nconst PURGED_TEXT = 'Document no longer available (retention policy).';\nconst NOT_COMPLETED_TEXT = 'This extraction did not complete, so there is nothing to verify.';\nconst VERIFICATION_UNAVAILABLE_TEXT = \"Verification isn't available for this extraction.\";\n// Deliberately does NOT imply the shown data is the corrected data — the\n// primary view returns the ORIGINAL extraction, not the validated values.\nconst ALREADY_VALIDATED_TEXT = 'Already verified — showing the original extraction.';\nconst CONFIRM_TEXT =\n 'Submit verification? This is final — feedback can be submitted only once and cannot be changed.';\nconst SUBMITTING_TEXT = 'Submitting…';\nconst SUBMIT_FAILED_TEXT = 'Submission failed — your corrections are still here.';\nconst DONE_TITLE_TEXT = 'Feedback submitted';\n\n/** What a successful load pins for the review phase (values + schema together,\n * so the derived memos see one consistent snapshot). */\ninterface LoadedData {\n values: unknown;\n schema: string[];\n}\n\n/** The empty edits map — the initial state AND every load's reset value.\n * One shared instance (SectionShared contract: `edits` is compared by\n * reference, so \"no edits\" must always be the same object). */\nconst NO_EDITS: ReadonlyMap<string, string> = new Map();\n\n/**\n * Unavailable reasons that are FAILURES (a thrown fetch: 401/404/network/5xx)\n * announce assertively as role=\"alert\". The meta-derived landings (purged,\n * not-completed, verification-unavailable) are calm facts about the extraction\n * — the load succeeded, there is just nothing to verify — and announce\n * politely as role=\"status\".\n */\nconst ALERT_REASONS: ReadonlySet<VerificationErrorReason> = new Set([\n 'session-expired',\n 'not-available',\n 'load-failed',\n]);\n\n/**\n * Embeddable Gemina extraction-verification UI.\n *\n * ```tsx\n * <GeminaVerification\n * extractionId={extractionId}\n * tokenManager={tokenManager}\n * onComplete={(result) => console.log(result.summary)}\n * />\n * ```\n */\nexport function GeminaVerification(props: GeminaVerificationProps): React.JSX.Element {\n const {\n extractionId,\n tokenManager,\n baseUrl,\n theme = 'auto',\n dir = 'auto',\n onComplete,\n onError,\n className,\n } = props;\n\n const [phase, setPhase] = useState<Phase>({ name: 'loading' });\n // Lifted OUT of the review phase variant (Task 17 restructure): the whole\n // review family reads it (read-only form, banner, hidden progress line)\n // while confirming/submitting/submit-error carry no flags of their own.\n // In every load path read-only ⇔ already-validated, so ONE flag serves both.\n const [alreadyValidated, setAlreadyValidated] = useState(false);\n const [loaded, setLoaded] = useState<LoadedData | null>(null);\n // Dirty fields only: raw schema key → current input string, VERBATIM (no\n // trim/normalize — that is the composer's job at submit). Replaced\n // immutably on every change; delete-on-revert keeps composeSubmission's\n // confirmed/corrected counts honest (see its edits-map contract).\n const [edits, setEdits] = useState<ReadonlyMap<string, string>>(NO_EDITS);\n // Held separately from `loaded`: the expiry refresh swaps an expired URL in\n // place without disturbing the (memo-feeding) values/schema snapshot.\n const [imageUrl, setImageUrl] = useState<string | null>(null);\n // The rects currently flashing on the viewer (null = no flash in flight).\n const [flashRects, setFlashRects] = useState<RelativeRect[] | null>(null);\n // One-column layout, driven by the ROOT's own width (see the observer below).\n const [stacked, setStacked] = useState(false);\n\n const rootRef = useRef<HTMLDivElement | null>(null);\n const mountedRef = useRef(false);\n // Monotonic load id: a load that lost the race (prop change re-ran the\n // effect, or Retry started a newer attempt) must not write its result.\n const loadSeqRef = useRef(0);\n // Timestamp of the last expiry-triggered refetch (the 60s throttle).\n const lastImageRefreshRef = useRef(0);\n // Latest onError without threading its identity through the load callback.\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n const onCompleteRef = useRef(onComplete);\n onCompleteRef.current = onComplete;\n // onComplete fires EXACTLY once per loaded extraction; load() resets it.\n const completedRef = useRef(false);\n // Re-entry latch for doSubmit (the disabled Confirm button is the UI guard;\n // this is the belt for a re-dispatch racing the disabling re-render).\n const submitInFlightRef = useRef(false);\n // Set by Cancel: focus returns to the Submit button, but only from the\n // effect AFTER the review re-render — while the handler runs the phase is\n // still `confirming`, so the footer button is still disabled and unfocusable.\n const restoreFocusRef = useRef(false);\n const submitButtonRef = useRef<HTMLButtonElement | null>(null);\n const confirmButtonRef = useRef<HTMLButtonElement | null>(null);\n const cancelButtonRef = useRef<HTMLButtonElement | null>(null);\n // Focus landings for the phases that unmount the dialog under the keyboard\n // user: the submit-error Retry button, and the done state (tabIndex -1).\n const retrySubmitButtonRef = useRef<HTMLButtonElement | null>(null);\n const doneStateRef = useRef<HTMLDivElement | null>(null);\n\n /**\n * Enter a terminal unavailable state and notify the host. onError fires\n * once per terminal-state ENTRY (see the prop's JSDoc): each resolved load\n * attempt calls this at most once, and a Retry that fails again re-enters —\n * and therefore re-fires.\n */\n const enterUnavailable = useCallback(\n (\n reason: VerificationErrorReason,\n message: string,\n canRetry: boolean,\n detail?: VerificationErrorDetail,\n ) => {\n setPhase({ name: 'unavailable', reason, message, canRetry });\n onErrorRef.current?.(reason, detail);\n },\n [],\n );\n\n const fetchOnce = useCallback(async () => {\n const token = await tokenManager.getToken();\n return GeminaClient.withSessionToken(token, baseUrl).documents.getDocumentExtraction({\n documentExtractionId: extractionId,\n });\n }, [tokenManager, baseUrl, extractionId]);\n\n /** The chat widget's mandated 401 pattern: invalidate + retry exactly once. */\n const fetchWithRetry = useCallback(async () => {\n try {\n return await fetchOnce();\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n tokenManager.invalidate();\n return await fetchOnce();\n }\n }, [fetchOnce, tokenManager]);\n\n const load = useCallback(async () => {\n const seq = ++loadSeqRef.current;\n /** Guard on EVERY async setState: unmount AND stale-load protection. */\n const live = () => mountedRef.current && loadSeqRef.current === seq;\n\n setPhase({ name: 'loading' });\n // Per-extraction onComplete semantics: a new load (extractionId change,\n // Retry, the 409 refetch) re-arms the exactly-once guard.\n completedRef.current = false;\n // A stale flash must not survive into the next review: the viewer\n // unmounts during loading, and a REMOUNTED viewer handed old non-null\n // flashRects would phantom-flash the new document once it sizes up.\n setFlashRects(null);\n // A new load must not inherit the previous extraction's expiry-refresh\n // throttle window (the viewer is unmounted until review re-enters, so\n // nothing can race this reset).\n lastImageRefreshRef.current = 0;\n let view: ExtractionPrimaryViewOutDTO;\n try {\n view = await fetchWithRetry();\n } catch (error) {\n // Reading the error body is async (fetch), so re-check liveness after.\n const detail = await readErrorEnvelope(error);\n if (!live()) {\n return;\n }\n if (detail.status === 401) {\n // Only reachable after the invalidate-retry-once path failed again.\n enterUnavailable('session-expired', SESSION_EXPIRED_TEXT, false, detail);\n } else if (detail.status === 404) {\n enterUnavailable('not-available', NOT_AVAILABLE_TEXT, false, detail);\n } else {\n // Everything else — 5xx, network failures, and a tokenManager whose\n // fetchToken rejected (no HTTP status at all) — is retryable: the\n // server or the tenant's token backend may recover.\n enterUnavailable('load-failed', LOAD_FAILED_TEXT, true, detail);\n }\n return;\n }\n if (!live()) {\n return;\n }\n\n const enterReview = (validated: boolean) => {\n const schema = view.meta.validationFeedback?.validationSchema;\n setLoaded({\n values: view.values,\n schema: Array.isArray(schema) ? schema : [],\n });\n // Fresh extraction data → clean editing slate, batched with setLoaded so\n // new bindings never pair with old edits for even one commit. Covers the\n // extractionId change, Retry, AND the Task-17 409-refetch (all of which\n // route through load()).\n setEdits(NO_EDITS);\n const url = view.document.imageUrl;\n setImageUrl(typeof url === 'string' && url.length > 0 ? url : null);\n setAlreadyValidated(validated);\n setPhase({ name: 'review' });\n };\n\n // Result mapping — EXACT order: purge before status, validated before\n // schema (an already-validated extraction with a null schema must land in\n // review-readOnly, not verification-unavailable).\n if (view.meta.purgedAt != null) {\n enterUnavailable('purged', PURGED_TEXT, false);\n } else if (view.meta.processingStatus !== 'success') {\n enterUnavailable('not-completed', NOT_COMPLETED_TEXT, false);\n } else if (view.meta.validated === true) {\n enterReview(true);\n } else if (\n !Array.isArray(view.meta.validationFeedback?.validationSchema) ||\n view.meta.validationFeedback.validationSchema.length === 0\n ) {\n enterUnavailable('verification-unavailable', VERIFICATION_UNAVAILABLE_TEXT, false);\n } else {\n enterReview(false);\n }\n }, [fetchWithRetry, enterUnavailable]);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureVerificationStylesInjected();\n void load();\n return () => {\n mountedRef.current = false;\n };\n }, [load]);\n\n // Stacked layout: the ROOT observes its OWN width — not the window, because\n // the host may embed the widget in a narrow column of a wide page — and\n // flips to one column below the breakpoint. useEffect (not layout effect)\n // keeps server rendering warning-free; the first client frame corrects.\n // SSR/test-safe: no ResizeObserver → a one-shot measure; a width of 0\n // (unmeasured or hidden host) never forces a layout flip.\n useEffect(() => {\n const el = rootRef.current;\n if (el === null) {\n return;\n }\n const apply = (width: number) => setStacked(width > 0 && width < STACKED_BREAKPOINT);\n if (typeof ResizeObserver === 'undefined') {\n apply(el.getBoundingClientRect().width);\n return;\n }\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0];\n if (!entry) {\n return;\n }\n // Border-box width: the element's OUTER width — the same box the\n // no-ResizeObserver fallback's getBoundingClientRect measures, so the\n // 860px breakpoint means one thing on both paths. contentRect is the\n // pre-borderBoxSize fallback (Safari < 15.4), off by padding + border.\n const width = entry.borderBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;\n apply(width);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n\n // --- Derived review data — computed ONCE per load (form stability contract:\n // `classified`/`bindingIndex` are compared by reference in the row memo). ---\n // classifyData is total (null/garbage values → empty buckets) — no guard.\n const classified = useMemo(() => classifyData(loaded?.values), [loaded]);\n const bindings = useMemo(() => buildBindings(loaded?.schema ?? [], loaded?.values), [loaded]);\n const bindingIndex = useMemo(() => indexBindingsByFieldPointer(bindings), [bindings]);\n // Bindings whose fieldPointer matches no classified leaf — the \"model\n // missed the whole field\" case, rendered as the form's Not-detected section.\n const unmatched = useMemo(() => {\n const rendered = new Set<string>();\n for (const field of classified.headers) {\n rendered.add(field.pointer);\n }\n for (const list of classified.simpleLists) {\n for (const item of list.items) {\n rendered.add(item.pointer);\n }\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) {\n rendered.add(cell.pointer);\n }\n }\n }\n for (const table of classified.tables) {\n for (const row of table.rows) {\n for (const [key, cell] of Object.entries(row)) {\n // _rowMeta is synthetic (its pointer is the ROW pointer) — it never\n // corresponds to a binding, so it must not mask one.\n if (key !== ROW_META_KEY) {\n rendered.add(cell.pointer);\n }\n }\n }\n }\n return bindings.filter((binding) => !rendered.has(binding.fieldPointer));\n }, [classified, bindings]);\n // Every detection region the extraction carries, feeding the viewer's\n // overlay toggle. Memoized on the classified snapshot (stability contract):\n // the viewer sees ONE stable array per load. undefined when there is\n // genuinely nothing to overlay — the viewer's hasRects check treats\n // undefined and empty alike (toggle disabled); undefined states the intent.\n const overlayRects = useMemo(() => {\n const rects: RelativeRect[] = [];\n for (const field of classified.headers) {\n if (field.coordinates) {\n rects.push(field.coordinates);\n }\n }\n for (const list of classified.simpleLists) {\n for (const item of list.items) {\n if (item.coordinates) {\n rects.push(item.coordinates);\n }\n }\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) {\n if (cell.coordinates) {\n rects.push(cell.coordinates);\n }\n }\n }\n }\n for (const table of classified.tables) {\n for (const row of table.rows) {\n for (const [key, cell] of Object.entries(row)) {\n // _rowMeta is synthetic (coordinates null by construction) — skip\n // it so a future row-level coordinate never renders a stray box.\n if (key !== ROW_META_KEY && cell.coordinates) {\n rects.push(cell.coordinates);\n }\n }\n }\n }\n return rects.length > 0 ? rects : undefined;\n }, [classified]);\n\n // dir=\"auto\" (chat parity): Hebrew anywhere in the bound DISPLAY values —\n // toInputString over binding.extracted, the same strings the inputs prefill,\n // never the raw JSON payload — flips the whole widget to RTL. Computed once\n // per load: `bindings` is memoized on the loaded snapshot.\n const hasHebrewContent = useMemo(\n () => bindings.some((binding) => HEBREW_RE.test(toInputString(binding.extracted))),\n [bindings],\n );\n const effectiveDir: 'ltr' | 'rtl' = dir === 'auto' ? (hasHebrewContent ? 'rtl' : 'ltr') : dir;\n\n // Revert detection needs the binding behind a raw key. Read through a ref\n // so handleEdit stays permanently stable (SectionShared contract: the\n // table-row memo compares onEdit by reference; a per-load identity would\n // silently re-render every row once per load).\n const bindingsByRawKey = useMemo(() => {\n const map = new Map<string, FieldBinding>();\n for (const binding of bindings) {\n map.set(binding.key.raw, binding);\n }\n return map;\n }, [bindings]);\n const bindingsByRawKeyRef = useRef(bindingsByRawKey);\n bindingsByRawKeyRef.current = bindingsByRawKey;\n\n // The edit tracker. The value is stored VERBATIM — never trimmed or\n // normalized (IME safety: the input must echo exactly what the user is\n // composing; composeSubmission trims at submit time). Dirty-tracking\n // contract (Task 4): the entry is DELETED when the value returns to the\n // binding's initial input string, so composeSubmission's counts stay honest.\n // Every change builds a NEW Map (SectionShared: the row-memo comparator\n // short-circuits on reference equality, so in-place mutation renders nothing);\n // no-op updates return `prev` unchanged to keep that same short-circuit.\n const handleEdit = useCallback((rawKey: string, value: string) => {\n const binding = bindingsByRawKeyRef.current.get(rawKey);\n // Pristine = the input shows exactly what an untouched input would show:\n // toInputString of the binding's DISPLAY value (FieldInput's prefill) —\n // including '' for a never-extracted fill-in.\n const pristine = binding !== undefined && value === toInputString(binding.extracted);\n setEdits((prev) => {\n if (pristine) {\n if (!prev.has(rawKey)) {\n return prev;\n }\n const next = new Map(prev);\n next.delete(rawKey);\n return next;\n }\n if (prev.get(rawKey) === value) {\n return prev;\n }\n const next = new Map(prev);\n next.set(rawKey, value);\n return next;\n });\n }, []);\n\n // Progress counts — composeSubmission IS the source of truth (the same call\n // Task 17 submits), so the line can never disagree with what would be sent.\n const submission = useMemo(() => composeSubmission(bindings, edits), [bindings, edits]);\n\n // Flash wiring (form → viewer). STABLE callback — the table-row memo\n // compares onFlash by reference, so rows never re-render on unrelated\n // flashes — that stores a FRESH array per eye-click: TableRow memoizes its\n // row rects, so without the copy a second click on the same row would hand\n // the viewer's flash effect an identical reference and never restart.\n const handleFlash = useCallback((rects: Array<{ points: [number, number][] }>) => {\n setFlashRects(rects.map((rect) => ({ points: rect.points })));\n }, []);\n\n // The viewer announces the fade finished: drop our reference so the next\n // click is a fresh transition. NEVER gate anything beyond this cleanup on\n // onFlashComplete — it may never fire (the image may never load).\n const handleFlashComplete = useCallback(() => {\n setFlashRects(null);\n }, []);\n\n /**\n * Silent expired-image-URL refresh. Swaps ONLY `imageUrl` — deliberately\n * NOT `loaded` (values/meta): replacing the loaded snapshot would re-create\n * the memoized classified/bindings objects and shift the dirty-tracking\n * baseline mid-edit, yanking the form out from under the reviewer. (The\n * plan's \"and refreshed values/meta\" parenthetical is superseded by review.)\n * Throttled to one refetch per 60s so a signed URL that keeps dying (e.g. a\n * document purged mid-review) cannot refetch-loop; the viewer's own\n * has-loaded gate already stops the loop for URLs that never load at all.\n *\n * INVARIANT: any future refetch that writes state must bump loadSeqRef or\n * route through load() — a refetch that writes without owning the sequence\n * can be overtaken by a newer load and clobber its state.\n */\n const handleImageExpired = useCallback(() => {\n const now = Date.now();\n if (now - lastImageRefreshRef.current < IMAGE_REFRESH_THROTTLE_MS) {\n return;\n }\n lastImageRefreshRef.current = now;\n const seq = loadSeqRef.current;\n fetchWithRetry()\n .then((view) => {\n // A newer load owns the state now (or we unmounted) — drop it.\n if (!mountedRef.current || loadSeqRef.current !== seq) {\n return;\n }\n const url = view.document.imageUrl;\n if (typeof url === 'string' && url.length > 0) {\n setImageUrl(url);\n }\n })\n // Swallowed by design: the refresh is best-effort background work — the\n // review (and any pending edits) must stay put on failure. The reviewer\n // keeps a broken image until the next throttle window; phase/loaded/\n // edits are never touched from here.\n .catch(() => {});\n }, [fetchWithRetry]);\n\n const handleRetry = useCallback(() => {\n void load();\n }, [load]);\n\n /**\n * The PUT. Reuses the `submission` memo — the SAME pure composeSubmission\n * result the progress line displays — so what the reviewer was just shown\n * (\"N confirmed · M corrected\") is by construction what goes on the wire.\n * 401 handling mirrors the GET: invalidate + retry exactly once. Outcomes:\n * success → done (+ exactly-once onComplete); 409 → SILENT refetch through\n * load() (the seq-guard invariant), landing in the already-validated\n * read-only review with no onError; 401 after the retry → submit-error with\n * the session-expired copy; anything else → submit-error with the server's\n * description when present. Edits are NEVER cleared on failure — the\n * submit-error review keeps the form (and the corrections) mounted.\n */\n const doSubmit = useCallback(async () => {\n if (submitInFlightRef.current) {\n return;\n }\n submitInFlightRef.current = true;\n const seq = loadSeqRef.current;\n /** Same liveness rule as load(): a newer load owns the state now. */\n const live = () => mountedRef.current && loadSeqRef.current === seq;\n setPhase({ name: 'submitting' });\n const body = submission;\n const submitOnce = async () => {\n const token = await tokenManager.getToken();\n return GeminaClient.withSessionToken(token, baseUrl).documents.validateDocumentExtraction({\n targetDocumentExtractionId: extractionId,\n extractionValidationInDTO: { data: body.data },\n });\n };\n try {\n let result: Awaited<ReturnType<typeof submitOnce>>;\n try {\n try {\n result = await submitOnce();\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n tokenManager.invalidate();\n result = await submitOnce();\n }\n } catch (error) {\n const detail = await readErrorEnvelope(error);\n if (!live()) {\n return;\n }\n if (detail.status === 409) {\n // Someone verified concurrently. Refetch and land in the\n // already-validated read-only banner state — deliberately NO\n // onError (the extraction IS verified; that is a success shape),\n // and the brief loading flash is accepted.\n void load();\n return;\n }\n if (detail.status === 401) {\n // Only after the one mandated retry. Edits are kept: a fresh\n // sign-in elsewhere + Retry can still succeed — hence the\n // submit-specific copy (never \"reload the page\").\n setPhase({ name: 'submit-error', message: SUBMIT_SESSION_EXPIRED_TEXT });\n onErrorRef.current?.('session-expired', detail);\n return;\n }\n setPhase({\n name: 'submit-error',\n message: detail.description ?? SUBMIT_FAILED_TEXT,\n });\n onErrorRef.current?.('submit-failed', detail);\n return;\n }\n if (!live()) {\n return;\n }\n setPhase({ name: 'done', confirmed: body.confirmed, corrected: body.corrected });\n if (!completedRef.current) {\n completedRef.current = true;\n // The generated client resolves ExtractionValidationResultOutDTO;\n // its `.data` is the ComparisonSummaryModel the host is promised.\n onCompleteRef.current?.({ correctedValues: body.byLabel, summary: result.data });\n }\n } finally {\n submitInFlightRef.current = false;\n }\n }, [submission, tokenManager, baseUrl, extractionId, load]);\n\n const handleSubmitClick = useCallback(() => {\n setPhase({ name: 'confirming' });\n }, []);\n\n const handleConfirm = useCallback(() => {\n void doSubmit();\n }, [doSubmit]);\n\n const handleCancelConfirm = useCallback(() => {\n restoreFocusRef.current = true;\n setPhase({ name: 'review' });\n }, []);\n\n /** Retry goes STRAIGHT back to submitting — confirm-final is never re-asked. */\n const handleRetrySubmit = useCallback(() => {\n void doSubmit();\n }, [doSubmit]);\n\n const handleConfirmKeyDown = useCallback(\n (event: React.KeyboardEvent) => {\n // Keys only act while the QUESTION is open. During `submitting` the\n // in-flight PUT cannot be aborted (Escape is ignored) and both dialog\n // buttons are disabled — nothing inside is focusable, so there is\n // nothing to trap either; the phase resolves to done/submit-error in\n // one round-trip and the phase-entry effect re-anchors focus there.\n if (phase.name !== 'confirming') {\n return;\n }\n if (event.key === 'Escape') {\n event.stopPropagation();\n handleCancelConfirm();\n return;\n }\n // Minimal focus trap: the dialog has exactly two tabbables (Cancel and\n // Confirm), so Tab/Shift+Tab wrap between them instead of escaping into\n // the scrimmed background the overlay only covers visually.\n if (event.key === 'Tab') {\n const cancel = cancelButtonRef.current;\n const confirm = confirmButtonRef.current;\n if (cancel === null || confirm === null) {\n return;\n }\n const active = document.activeElement;\n if (event.shiftKey && active === cancel) {\n event.preventDefault();\n confirm.focus();\n } else if (!event.shiftKey && active === confirm) {\n event.preventDefault();\n cancel.focus();\n } else if (active !== cancel && active !== confirm) {\n // Belt only: focus INSIDE the overlay subtree but on neither button\n // (no such element exists today). This is NOT scrim-click recovery —\n // a blur to <body> would put keydowns outside this subtree handler\n // entirely; the scrim's mousedown preventDefault is what keeps that\n // blur from ever happening.\n event.preventDefault();\n confirm.focus();\n }\n }\n },\n [phase.name, handleCancelConfirm],\n );\n\n // Phase-entry focus anchoring. Entering `confirming` moves focus to the\n // final-action button (Enter submits, Escape cancels); a Cancel hands it\n // back to the Submit button — from here, AFTER the review re-render\n // re-enabled it. The two phases that unmount the dialog under the keyboard\n // user get their own landings (without them focus drops to <body>):\n // submit-error → the inline Retry button; done → the state container\n // (tabIndex -1, no ring — a non-interactive announcement landing).\n useEffect(() => {\n if (phase.name === 'confirming') {\n confirmButtonRef.current?.focus();\n } else if (phase.name === 'review' && restoreFocusRef.current) {\n restoreFocusRef.current = false;\n submitButtonRef.current?.focus();\n } else if (phase.name === 'submit-error') {\n retrySubmitButtonRef.current?.focus();\n } else if (phase.name === 'done') {\n doneStateRef.current?.focus();\n }\n }, [phase.name]);\n\n const rootClassName = [\n 'gemina-verification',\n `gemina-verification--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-verification--rtl' : '',\n stacked ? 'gemina-verification--stacked' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n // One id per instance for the dialog's label (multiple widgets may coexist).\n const dialogTextId = useId();\n\n /**\n * The review family: review | confirming | submitting | submit-error all\n * render THIS content, so the form (edits included!) and the aria-live\n * progress region stay mounted through the whole submit sequence. Only the\n * decorations differ per member: confirming/submitting put the overlay up\n * (same dialog shell — the copy flips to \"Submitting…\" and both buttons\n * disable, which is the double-click guard), submit-error adds the inline\n * error banner. The form is never readOnly-flipped mid-flight — that would\n * visually discard the reviewer's edits.\n */\n const renderReview = (reviewPhase: ReviewFamilyPhase): React.JSX.Element => {\n const overlayUp = reviewPhase.name === 'confirming' || reviewPhase.name === 'submitting';\n return (\n <>\n {alreadyValidated && (\n <div className=\"gemina-verification__banner\">{ALREADY_VALIDATED_TEXT}</div>\n )}\n <div className=\"gemina-verification__panes\">\n {imageUrl !== null && (\n <VerificationViewer\n src={imageUrl}\n relativeRects={overlayRects}\n flashRects={flashRects}\n onFlashComplete={handleFlashComplete}\n onImageExpired={handleImageExpired}\n />\n )}\n <VerificationForm\n classified={classified}\n unmatched={unmatched}\n bindingIndex={bindingIndex}\n edits={edits}\n onEdit={handleEdit}\n readOnly={alreadyValidated}\n onFlash={handleFlash}\n />\n </div>\n {reviewPhase.name === 'submit-error' && (\n <div\n className=\"gemina-verification__banner gemina-verification__banner--error gemina-verification__submit-error\"\n role=\"alert\"\n >\n <span>{reviewPhase.message}</span>\n <button\n type=\"button\"\n ref={retrySubmitButtonRef}\n className=\"gemina-verification__retry\"\n onClick={handleRetrySubmit}\n >\n Retry\n </button>\n </div>\n )}\n <div className=\"gemina-verification__footer\">\n {/* aria-live: a reviewer deep in a long form hears the count move\n as they confirm/correct without tabbing back to the footer.\n Hidden when read-only — the already-verified landing would\n otherwise show \"0 corrected\" noise about the ORIGINAL payload —\n while the disabled Submit stays for discoverability. */}\n {!alreadyValidated && (\n <div className=\"gemina-verification__progress\" aria-live=\"polite\">\n {`${submission.confirmed} confirmed · ${submission.corrected} corrected`}\n </div>\n )}\n <button\n type=\"button\"\n ref={submitButtonRef}\n className=\"gemina-verification__submit\"\n disabled={alreadyValidated || reviewPhase.name !== 'review'}\n onClick={handleSubmitClick}\n >\n Submit feedback\n </button>\n </div>\n {overlayUp && (\n <div\n className=\"gemina-verification__confirm\"\n onKeyDown={handleConfirmKeyDown}\n // A press anywhere NON-interactive — the scrim AND the dialog's\n // own interior (the confirm text, padding, actions row) — must not\n // blur the dialog: preventDefault on mousedown suppresses the\n // browser's focus-move default, so activeElement stays on a dialog\n // button and the subtree keydown handler above stays in the focus\n // path (focus on <body> would put Escape/Tab out of its reach).\n // Only presses on a button keep their default. Trade-off, accepted:\n // the dialog copy (one sentence) can't be text-selected by mouse.\n onMouseDown={(event) => {\n if (!(event.target as Element).closest('button')) {\n event.preventDefault();\n }\n }}\n >\n <div\n className=\"gemina-verification__confirm-dialog\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={dialogTextId}\n >\n <p id={dialogTextId} className=\"gemina-verification__confirm-text\">\n {reviewPhase.name === 'submitting' ? SUBMITTING_TEXT : CONFIRM_TEXT}\n </p>\n <div className=\"gemina-verification__confirm-actions\">\n <button\n type=\"button\"\n ref={cancelButtonRef}\n className=\"gemina-verification__confirm-cancel\"\n onClick={handleCancelConfirm}\n disabled={reviewPhase.name === 'submitting'}\n >\n Cancel\n </button>\n <button\n type=\"button\"\n ref={confirmButtonRef}\n className=\"gemina-verification__submit\"\n onClick={handleConfirm}\n disabled={reviewPhase.name === 'submitting'}\n >\n Confirm submission\n </button>\n </div>\n </div>\n </div>\n )}\n </>\n );\n };\n\n // EXHAUSTIVE by construction: the explicit return type makes a phase\n // variant without a case a compile error (the function could fall through\n // returning undefined) — a forgotten renderer can never ship as a blank\n // widget. No default clause, ever.\n const content = ((): React.JSX.Element => {\n switch (phase.name) {\n case 'loading':\n return (\n <div className=\"gemina-verification__state\" role=\"status\">\n {LOADING_TEXT}\n </div>\n );\n case 'unavailable':\n return (\n <div\n className=\"gemina-verification__state\"\n role={ALERT_REASONS.has(phase.reason) ? 'alert' : 'status'}\n >\n <div>{phase.message}</div>\n {phase.canRetry && (\n <button type=\"button\" className=\"gemina-verification__retry\" onClick={handleRetry}>\n Retry\n </button>\n )}\n </div>\n );\n case 'review':\n case 'confirming':\n case 'submitting':\n case 'submit-error':\n return renderReview(phase);\n case 'done':\n return (\n <div\n ref={doneStateRef}\n // Programmatic focus landing only — see the phase-entry focus\n // effect. Not tab-reachable; the stylesheet suppresses the ring.\n tabIndex={-1}\n className=\"gemina-verification__state gemina-verification__state--done\"\n role=\"status\"\n >\n <span className=\"gemina-verification__done-check\" aria-hidden=\"true\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\">\n <path\n d=\"M4 10.5l4 4 8-9\"\n stroke=\"currentColor\"\n strokeWidth=\"2.4\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n </span>\n <div className=\"gemina-verification__done-title\">{DONE_TITLE_TEXT}</div>\n <div className=\"gemina-verification__progress\">\n {`${phase.confirmed} confirmed · ${phase.corrected} corrected`}\n </div>\n </div>\n );\n }\n })();\n\n return (\n <div ref={rootRef} className={rootClassName} dir={effectiveDir}>\n {content}\n </div>\n );\n}\n","/**\n * Shape classifier for arbitrary extraction payloads.\n *\n * Near-verbatim port of the console's battle-tested classifier\n * (gemina-console `src/pages/extractions/components/FormView/utils.ts`).\n * It buckets a payload into headers / simpleLists / tables / entities /\n * fallback. The heuristics are intentionally unchanged — they are proven\n * against every extraction type.\n *\n * ONE structural addition over the console: every emitted leaf carries the\n * JSON pointer at which it lives in the ORIGINAL payload, so bindings can\n * match fields to server-generated schema keys. Pointers point at the\n * value-object WRAPPER (e.g. `/supplier_name`, not `/supplier_name/value`);\n * `/value` normalization happens at binding time. When the payload wraps its\n * fields in a root `{ data: ... }` object, inner pointers keep the `/data`\n * prefix because server pointers resolve against the payload root.\n *\n * Pointer segments are RFC-6901 escaped (`~` → `~0` first, then `/` → `~1`)\n * so emitted pointers round-trip through `resolvePointer`.\n *\n * Pure and dependency-free: no React, no DOM, no antd.\n */\n\n/**\n * Common acronyms that should stay uppercase\n */\nconst ACRONYMS = new Set(['ID', 'VAT', 'OCR', 'PDF', 'URL', 'API', 'HTML', 'CSS', 'JSON', 'XML', 'UUID']);\n\n/**\n * Convert camelCase or snake_case to Title Case with acronym handling\n * Examples:\n * supplierName -> \"Supplier Name\"\n * vat_amount -> \"VAT Amount\"\n * ocr_text -> \"OCR Text\"\n * businessNumber -> \"Business Number\"\n */\nexport function formatLabel(key: string): string {\n // First, split by underscores and camelCase\n const words = key\n // Insert space before uppercase letters (camelCase)\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n // Replace underscores with spaces\n .replace(/_/g, ' ')\n // Split into words\n .split(' ')\n .filter(Boolean);\n\n return words\n .map((word) => {\n const upper = word.toUpperCase();\n if (ACRONYMS.has(upper)) {\n return upper;\n }\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();\n })\n .join(' ');\n}\n\n/**\n * Format a value for display based on its type.\n *\n * DISPLAY ONLY — never feed this into inputs or submissions; the raw\n * `value` on each classified leaf is the source of truth.\n */\nexport function formatValue(value: unknown, fieldName?: string): string {\n if (value === null || value === undefined) {\n return '-';\n }\n\n if (typeof value === 'boolean') {\n return value ? 'Yes' : 'No';\n }\n\n if (typeof value === 'number') {\n // Check if it looks like a percentage (field name contains rate/percent)\n if (fieldName && /rate|percent/i.test(fieldName)) {\n return `${value}%`;\n }\n // Don't format identifier fields with thousand separators\n if (fieldName && /number|num|id|code|phone|fax|postal|zip/i.test(fieldName)) {\n return String(value);\n }\n // Format numbers with thousand separators\n return value.toLocaleString();\n }\n\n if (typeof value === 'string') {\n // Try to detect and format ISO dates\n if (/^\\d{4}-\\d{2}-\\d{2}(T|$)/.test(value)) {\n try {\n const date = new Date(value);\n if (!isNaN(date.getTime())) {\n return date.toLocaleDateString();\n }\n } catch {\n // Fall through to return original\n }\n }\n return value;\n }\n\n return String(value);\n}\n\n/**\n * Check if a value is a \"value object\" with { value, coordinates?, confidence? }\n */\nexport function isValueObject(obj: unknown): obj is { value: unknown; coordinates?: unknown; confidence?: string; confidence_reasons?: string[] } {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return false;\n }\n return 'value' in obj;\n}\n\n/**\n * Check if an array contains only primitives\n */\nexport function isPrimitiveArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n return arr.every((item) => item === null || typeof item !== 'object');\n}\n\n/**\n * Check if an array is a \"simple value array\" (Type C)\n * Array of { value, coordinates? } objects\n */\nexport function isSimpleValueArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n return arr.every((item) => isValueObject(item) && Object.keys(item as object).every(k => ['value', 'coordinates', 'confidence', 'confidence_reasons'].includes(k)));\n}\n\n/**\n * Check if an array is a \"table array\" (Type A)\n * Array of flat objects with many fields\n */\nexport function isTableArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n const first = arr[0];\n if (!first || typeof first !== 'object' || Array.isArray(first)) return false;\n\n // Count non-metadata fields\n const metaFields = new Set(['confidence', 'confidence_reasons', 'coordinates']);\n const keys = Object.keys(first as object).filter(k => !metaFields.has(k));\n\n // If objects have >3 non-meta fields and those values are primitives or value objects, it's a table\n if (keys.length > 3) {\n const firstObj = first as Record<string, unknown>;\n // Only check the non-metadata field values\n const nonMetaValues = keys.map(k => firstObj[k]);\n const allSimple = nonMetaValues.every(v =>\n v === null ||\n typeof v !== 'object' ||\n isValueObject(v)\n );\n return allSimple;\n }\n return false;\n}\n\n/**\n * Check if an array is an \"entity array\" (Type B)\n * Array of objects that aren't tables - includes both wrapped value objects\n * and plain object arrays with few fields\n */\nexport function isEntityArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n if (isPrimitiveArray(arr)) return false;\n if (isSimpleValueArray(arr)) return false;\n if (isTableArray(arr)) return false;\n\n const first = arr[0];\n if (!first || typeof first !== 'object' || Array.isArray(first)) return false;\n\n // Any array of objects that isn't a table or simple value array is an entity array\n // This includes objects with nested value wrappers OR plain objects with few fields\n return true;\n}\n\n/**\n * Extract the actual value from a field (handles value objects)\n */\nexport function extractValue(field: unknown): unknown {\n if (isValueObject(field)) {\n return field.value;\n }\n return field;\n}\n\n/**\n * Extract coordinates from a field if present\n */\nexport function extractCoordinates(field: unknown): { points: [number, number][] } | null {\n if (isValueObject(field) && field.coordinates) {\n const coords = field.coordinates as { relative?: [number, number][] };\n if (coords.relative) {\n return { points: coords.relative };\n }\n }\n return null;\n}\n\n/**\n * Extract confidence from a field if present\n */\nexport function extractConfidence(field: unknown): { level: string; reasons: string[] } | null {\n if (isValueObject(field) && field.confidence) {\n return {\n level: field.confidence,\n reasons: field.confidence_reasons || [],\n };\n }\n return null;\n}\n\n/**\n * Escape one JSON-pointer segment per RFC 6901 (`~` before `/`, mirroring the\n * resolver's unescape order of `~1` before `~0`).\n */\nfunction escapeSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * One classified leaf field. `pointer` locates the field's value-object\n * wrapper (or raw value) in the ORIGINAL payload.\n */\nexport interface ClassifiedField {\n key: string; // display label source (formatLabel applied at render)\n pointer: string; // pointer to this field in the ORIGINAL payload\n value: unknown; // unwrapped raw value\n coordinates: { points: [number, number][] } | null;\n confidence: { level: string; reasons: string[] } | null;\n}\n\n/**\n * Key under which a table row's synthetic row-level confidence cell is\n * stored. Not a real payload field — it never binds to a server schema key.\n */\nexport const ROW_META_KEY = '_rowMeta';\n\n/** A cell inside a table row or entity card (no own display key). */\nexport interface ClassifiedCell {\n pointer: string;\n value: unknown;\n coordinates: { points: [number, number][] } | null;\n confidence: { level: string; reasons: string[] } | null;\n}\n\n/**\n * Classify all fields in a data object\n */\nexport interface ClassifiedData {\n headers: ClassifiedField[];\n simpleLists: Array<{\n key: string;\n pointer: string;\n items: ClassifiedCell[];\n }>;\n entities: Array<{\n key: string;\n pointer: string;\n items: Array<Record<string, ClassifiedCell>>;\n }>;\n tables: Array<{\n key: string;\n pointer: string;\n columns: string[];\n rows: Array<Record<string, ClassifiedCell>>;\n overallConfidence: { level: string; reasons: string[] } | null;\n }>;\n fallback: Array<{\n key: string;\n data: unknown;\n }>;\n}\n\nexport function classifyData(data: unknown): ClassifiedData {\n const result: ClassifiedData = {\n headers: [],\n simpleLists: [],\n entities: [],\n tables: [],\n fallback: [],\n };\n\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n return result;\n }\n\n // Handle wrapped data (some extractions wrap in { data: ... })\n let rootData = data as Record<string, unknown>;\n let basePointer = '';\n if ('data' in rootData && typeof rootData.data === 'object' && rootData.data !== null && !Array.isArray(rootData.data)) {\n // Process top-level non-data fields first (like total_lines, overall_confidence)\n for (const [key, value] of Object.entries(rootData)) {\n if (key === 'data') continue;\n processField(key, value, result, rootData, '');\n }\n rootData = rootData.data as Record<string, unknown>;\n // Inner fields live under the wrapper in the original payload — server\n // pointers resolve against the payload root, so keep the /data prefix.\n basePointer = '/data';\n }\n\n for (const [key, value] of Object.entries(rootData)) {\n processField(key, value, result, rootData, basePointer);\n }\n\n return result;\n}\n\nfunction processField(\n key: string,\n value: unknown,\n result: ClassifiedData,\n parentObj: Record<string, unknown> | undefined,\n basePointer: string,\n): void {\n // Skip metadata fields at root level\n // overall_confidence and confidence_reasons are handled by table headers\n if (['confidence', 'confidence_reasons', 'coordinates', 'overall_confidence'].includes(key)) {\n return;\n }\n\n const pointer = `${basePointer}/${escapeSegment(key)}`;\n\n // Primitive or null\n if (value === null || typeof value !== 'object') {\n result.headers.push({\n key,\n pointer,\n value,\n coordinates: null,\n confidence: null,\n });\n return;\n }\n\n // Value object (has 'value' property)\n if (isValueObject(value)) {\n result.headers.push({\n key,\n pointer,\n value: extractValue(value),\n coordinates: extractCoordinates(value),\n confidence: extractConfidence(value),\n });\n return;\n }\n\n // Array\n if (Array.isArray(value)) {\n if (value.length === 0) {\n result.headers.push({\n key,\n pointer,\n value: null,\n coordinates: null,\n confidence: null,\n });\n return;\n }\n\n // Array of primitives - display as simple list\n if (isPrimitiveArray(value)) {\n result.simpleLists.push({\n key,\n pointer,\n items: value.map((item, index) => ({\n pointer: `${pointer}/${index}`,\n value: item,\n coordinates: null,\n confidence: null,\n })),\n });\n return;\n }\n\n // Simple value array (Type C) - array of { value, coordinates? }\n if (isSimpleValueArray(value)) {\n result.simpleLists.push({\n key,\n pointer,\n items: value.map((item, index) => ({\n pointer: `${pointer}/${index}`,\n value: extractValue(item),\n coordinates: extractCoordinates(item),\n confidence: extractConfidence(item),\n })),\n });\n return;\n }\n\n // Table array (Type A) - array of flat objects with many fields\n if (isTableArray(value)) {\n const first = value[0] as Record<string, unknown>;\n const metaFields = new Set(['confidence', 'confidence_reasons', 'coordinates']);\n const columns = Object.keys(first).filter(k => !metaFields.has(k));\n\n // Look for table-level overall confidence from sibling fields\n // Check patterns: {key}_confidence, or overall_confidence at root\n let overallConfidence: { level: string; reasons: string[] } | null = null;\n if (parentObj) {\n // First check for specific key pattern (e.g., line_items_confidence)\n const confidenceKey = `${key}_confidence`;\n const reasonsKey = `${key}_confidence_reasons`;\n if (parentObj[confidenceKey]) {\n overallConfidence = {\n level: parentObj[confidenceKey] as string,\n reasons: (parentObj[reasonsKey] as string[]) || [],\n };\n }\n // Also check for overall_confidence at root level\n else if (parentObj['overall_confidence']) {\n overallConfidence = {\n level: parentObj['overall_confidence'] as string,\n reasons: (parentObj['confidence_reasons'] as string[]) || [],\n };\n }\n }\n\n result.tables.push({\n key,\n pointer,\n columns,\n overallConfidence,\n rows: value.map((row, rowIndex) => {\n const rowPointer = `${pointer}/${rowIndex}`;\n const rowData: Record<string, ClassifiedCell> = {};\n // isTableArray samples only the first element; a null/non-object row\n // later in the array must not crash — its cells emit with undefined.\n const rowObj = (row ?? {}) as Record<string, unknown>;\n\n for (const col of columns) {\n const cell = rowObj[col];\n rowData[col] = {\n pointer: `${rowPointer}/${escapeSegment(col)}`,\n value: extractValue(cell),\n coordinates: extractCoordinates(cell),\n confidence: extractConfidence(cell),\n };\n }\n\n // Also extract row-level confidence if present\n if (rowObj.confidence || rowObj.confidence_reasons) {\n // _rowMeta is synthetic (no real field behind it); its pointer is\n // the ROW pointer, and it never binds to a server schema key.\n rowData[ROW_META_KEY] = {\n pointer: rowPointer,\n value: null,\n coordinates: null,\n confidence: {\n level: rowObj.confidence as string || '',\n reasons: (rowObj.confidence_reasons as string[]) || [],\n },\n };\n }\n\n return rowData;\n }),\n });\n return;\n }\n\n // Entity array (Type B) - array of objects (cards)\n if (isEntityArray(value)) {\n result.entities.push({\n key,\n pointer,\n items: value.map((item, index) => {\n const entity: Record<string, ClassifiedCell> = {};\n\n // isEntityArray samples only the first element; a null/non-object\n // item later in the array emits an empty entity so indices (and\n // therefore sibling pointers) stay aligned with the payload.\n if (item === null || typeof item !== 'object' || Array.isArray(item)) {\n return entity;\n }\n\n for (const [fieldKey, fieldValue] of Object.entries(item as Record<string, unknown>)) {\n // Skip metadata fields\n if (['confidence', 'confidence_reasons', 'coordinates'].includes(fieldKey)) {\n continue;\n }\n entity[fieldKey] = {\n pointer: `${pointer}/${index}/${escapeSegment(fieldKey)}`,\n value: extractValue(fieldValue),\n coordinates: extractCoordinates(fieldValue),\n confidence: extractConfidence(fieldValue),\n };\n }\n\n return entity;\n }),\n });\n return;\n }\n\n // Fallback for unrecognized arrays\n result.fallback.push({ key, data: value });\n return;\n }\n\n // Nested object without 'value' property - try to recurse into it\n const nestedObj = value as Record<string, unknown>;\n const nestedKeys = Object.keys(nestedObj).filter(k => !['confidence', 'confidence_reasons', 'coordinates'].includes(k));\n\n // If the nested object has fields, process them recursively with prefixed keys\n if (nestedKeys.length > 0 && nestedKeys.length <= 10) {\n // Small nested objects get flattened into headers with grouped key names\n for (const nestedKey of nestedKeys) {\n const nestedValue = nestedObj[nestedKey];\n const combinedKey = `${key}.${nestedKey}`;\n const nestedPointer = `${pointer}/${escapeSegment(nestedKey)}`;\n\n // Process primitives and value objects as headers\n if (nestedValue === null || typeof nestedValue !== 'object') {\n result.headers.push({\n key: combinedKey,\n pointer: nestedPointer,\n value: nestedValue,\n coordinates: null,\n confidence: null,\n });\n } else if (isValueObject(nestedValue)) {\n result.headers.push({\n key: combinedKey,\n pointer: nestedPointer,\n value: extractValue(nestedValue),\n coordinates: extractCoordinates(nestedValue),\n confidence: extractConfidence(nestedValue),\n });\n } else {\n // Complex nested values go to fallback\n result.fallback.push({ key: combinedKey, data: nestedValue });\n }\n }\n return;\n }\n\n // Large or empty nested objects go to fallback\n result.fallback.push({ key, data: value });\n}\n","/**\n * Server-generated submission keys and JSON-pointer resolution.\n *\n * Mirrors the backend exactly (gemina-api-v2 `data_validator.py` /\n * `validator/utils.py`) so that what the component resolves client-side is\n * what the server will resolve when it scores the submission:\n * - key regex `^label:([^|]+)\\|ptr:(/.*)$`\n * - `~1` unescaped before `~0`\n * - list segments must be all digits\n * - unresolvable paths are a sentinel, distinct from a stored `null`.\n *\n * Known divergences from the backend (all client-stricter; unreachable via\n * server-generated keys):\n * - Python's `$` in the key regex also matches before a trailing newline;\n * JS `$` (no `m` flag) matches only at end-of-string.\n * - The backend's `pointer.lstrip(\"/\")` collapses multiple leading slashes\n * (`//a` resolves `doc[\"a\"]`); here that is NOT_FOUND (RFC-6901-correct).\n * - Python's `isdigit()` accepts non-ASCII unicode digits as list indices;\n * `/^\\d+$/` here is ASCII-only.\n */\n\nexport interface SchemaKey {\n /** The raw key — submitted verbatim as a property name in the feedback body. */\n raw: string;\n /** Human-meaningful label; the only key format the host app ever sees. */\n label: string;\n /** JSON pointer into the extraction values payload. */\n pointer: string;\n}\n\nconst KEY_RE = /^label:([^|]+)\\|ptr:(\\/.*)$/;\n\n/** Parse one schema key, or null for a malformed entry (the backend skips those quietly too). */\nexport function parseSchemaKey(raw: string): SchemaKey | null {\n const match = KEY_RE.exec(raw);\n if (match === null) {\n return null;\n }\n return { raw, label: match[1] as string, pointer: match[2] as string };\n}\n\n/** \"Path did not resolve\" — deliberately distinct from a stored null value. */\nexport const NOT_FOUND: unique symbol = Symbol('gemina-verification-not-found');\nexport type NotFound = typeof NOT_FOUND;\n\n/** Resolve a JSON pointer against a document, backend-compatible (see module docs). */\nexport function resolvePointer(doc: unknown, pointer: string): unknown | NotFound {\n if (pointer === '') {\n return doc;\n }\n if (!pointer.startsWith('/')) {\n return NOT_FOUND;\n }\n let current: unknown = doc;\n for (const rawSegment of pointer.slice(1).split('/')) {\n const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~');\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) {\n return NOT_FOUND;\n }\n const index = Number(segment);\n if (index >= current.length) {\n return NOT_FOUND;\n }\n current = current[index];\n } else if (current !== null && typeof current === 'object') {\n if (!Object.prototype.hasOwnProperty.call(current, segment)) {\n return NOT_FOUND;\n }\n current = (current as Record<string, unknown>)[segment];\n } else {\n return NOT_FOUND;\n }\n }\n return current;\n}\n","import { isValueObject } from './classify';\nimport { NOT_FOUND, parseSchemaKey } from './pointer';\nimport type { NotFound, SchemaKey } from './pointer';\n\n/** One server-mandated submission slot, bound to whatever was extracted there. */\nexport interface FieldBinding {\n key: SchemaKey;\n /**\n * The RAW resolved node — never unwrapped — or NOT_FOUND. This is what an\n * untouched binding submits verbatim: the server resolves the same pointer\n * against the same model tree (casing aside), so wrapper objects compare\n * dict-vs-dict and score correct. Note: dict-valued submissions additionally\n * require INNER-key casing identity with the server's scoring dict — which\n * holds for custom_template's uncamelized dicts, the only reachable case.\n */\n serverValue: unknown | NotFound;\n /** DISPLAY value: serverValue unwrapped via isValueObject, else serverValue. */\n extracted: unknown | NotFound;\n /**\n * The actually-RESOLVED pointer (payload casing — camel in prod) minus a\n * trailing `/value` segment; the pointer the classifier reports for this\n * field. For NOT_FOUND bindings: best-effort camelized schema pointer.\n */\n fieldPointer: string;\n /**\n * False when serverValue is a container (object/array, including value-object\n * wrappers): the server's `coerce_like` does nothing for containers, so a\n * string edit could never score correct. True for NOT_FOUND (fill-in), null,\n * and primitives.\n */\n editable: boolean;\n}\n\nfunction unescapeSegment(raw: string): string {\n return raw.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nfunction escapeSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/** `vendor_name` → `vendorName`; plain lower single words are identical under both. */\nfunction snakeToCamel(segment: string): string {\n return segment.replace(/_([a-zA-Z0-9])/g, (_, ch: string) => ch.toUpperCase());\n}\n\n/** Best-effort camelization of a whole pointer (used when resolution fails). */\nfunction camelizePointer(pointer: string): string {\n if (!pointer.startsWith('/')) {\n return pointer;\n }\n return '/' + pointer\n .slice(1)\n .split('/')\n .map((raw) => escapeSegment(snakeToCamel(unescapeSegment(raw))))\n .join('/');\n}\n\ninterface Resolution {\n node: unknown | NotFound;\n /** The pointer as actually matched in the payload (camel in prod). */\n resolvedPointer: string;\n}\n\n/**\n * Resolve a schema pointer against the view payload, casing-aware (review C1):\n * schema pointers are snake_case while the prod payload is camelCase, so each\n * object-key segment tries exact first, then snake→camel. The server scores\n * against its own snake dict, so the mismatch is client-only; structurally the\n * walk mirrors `resolvePointer` (backend parity — no fallbacks, no unwrapping).\n */\nfunction resolveCasingAware(doc: unknown, pointer: string): Resolution {\n const missing: Resolution = { node: NOT_FOUND, resolvedPointer: camelizePointer(pointer) };\n if (pointer === '') {\n return { node: doc, resolvedPointer: '' };\n }\n if (!pointer.startsWith('/')) {\n return missing;\n }\n let current: unknown = doc;\n const matched: string[] = [];\n for (const rawSegment of pointer.slice(1).split('/')) {\n const segment = unescapeSegment(rawSegment);\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) {\n return missing;\n }\n const index = Number(segment);\n if (index >= current.length) {\n return missing;\n }\n current = current[index];\n matched.push(rawSegment);\n } else if (current !== null && typeof current === 'object') {\n let key: string;\n if (Object.prototype.hasOwnProperty.call(current, segment)) {\n key = segment;\n } else {\n const camel = snakeToCamel(segment);\n if (camel === segment || !Object.prototype.hasOwnProperty.call(current, camel)) {\n return missing;\n }\n key = camel;\n }\n current = (current as Record<string, unknown>)[key];\n matched.push(escapeSegment(key));\n } else {\n return missing;\n }\n }\n return { node: current, resolvedPointer: '/' + matched.join('/') };\n}\n\n/** A schema pointer `P/value` and a classifier pointer `P` are the same field. */\nfunction stripValueSuffix(pointer: string): string {\n return pointer.endsWith('/value') ? pointer.slice(0, -'/value'.length) : pointer;\n}\n\n/** Parse + resolve every schema key. Malformed entries are skipped (backend parity). */\nexport function buildBindings(validationSchema: string[], values: unknown): FieldBinding[] {\n const bindings: FieldBinding[] = [];\n for (const raw of validationSchema) {\n const key = parseSchemaKey(raw);\n if (key === null) {\n continue;\n }\n const { node: serverValue, resolvedPointer } = resolveCasingAware(values, key.pointer);\n const extracted = serverValue !== NOT_FOUND && isValueObject(serverValue)\n ? serverValue.value\n : serverValue;\n const editable = serverValue === NOT_FOUND\n || serverValue === null\n || typeof serverValue !== 'object';\n bindings.push({\n key,\n serverValue,\n extracted,\n fieldPointer: stripValueSuffix(resolvedPointer),\n editable,\n });\n }\n return bindings;\n}\n\n/**\n * Index bindings by the pointer the CLASSIFIER reports for a field. The\n * classifier walks the same payload the bindings resolved against, so its\n * pointers carry the payload's casing — which is exactly what `fieldPointer`\n * recorded during resolution.\n */\nexport function indexBindingsByFieldPointer(bindings: FieldBinding[]): Map<string, FieldBinding> {\n const map = new Map<string, FieldBinding>();\n for (const binding of bindings) {\n map.set(binding.fieldPointer, binding);\n }\n return map;\n}\n\n/**\n * What an editable input is prefilled with. RAW value stringification only —\n * display formatting (`formatValue`) must never round-trip into a submission\n * (a locale-formatted \"1,500\" or date would score as a correction).\n */\nexport function toInputString(extracted: unknown | NotFound): string {\n if (extracted === NOT_FOUND || extracted === null || extracted === undefined) {\n return '';\n }\n if (typeof extracted === 'object') {\n return JSON.stringify(extracted);\n }\n return String(extracted);\n}\n\nexport interface SubmissionResult {\n /** Body for `ExtractionValidationInDTO.data` — raw schema keys, ALL asserted fields. */\n data: Record<string, unknown>;\n /** The same entries keyed by human label — handed to `onComplete`. */\n byLabel: Record<string, unknown>;\n confirmed: number;\n corrected: number;\n}\n\n/**\n * Compose the one-shot feedback body.\n *\n * `edits` holds ONLY dirty keys (raw schema key → current input string; the\n * UI removes an entry when the input returns to its initial string). The\n * counts trust that contract: a caller that fails to delete-on-revert\n * relabels a confirmation as a correction in `confirmed`/`corrected`; the\n * server-side scoring itself survives, since the unchanged string coerces\n * back to a value equal to the extracted one.\n *\n * Rules (verified against the backend DataValidator):\n * - untouched + resolved (even resolved-null): submit `serverValue` verbatim\n * — the raw node, wrappers included — the server resolves the same node\n * and compares equal → scored a confirmation;\n * - untouched + never extracted: OMIT — the user asserted nothing, and\n * submitting null would force a false \"missing\";\n * - dirty, non-empty: submit the trimmed string (only scalar-valued bindings\n * are editable, and for scalar targets the server's `coerce_like` adopts\n * the extracted value's type before comparing; containers are never\n * editable — see `FieldBinding.editable`);\n * - dirty, cleared: the user asserts the field is absent/wrong → null;\n * unless nothing was extracted either, in which case there is nothing\n * to assert → OMIT.\n */\nexport function composeSubmission(\n bindings: FieldBinding[],\n edits: ReadonlyMap<string, string>,\n): SubmissionResult {\n const data: Record<string, unknown> = {};\n const byLabel: Record<string, unknown> = {};\n let confirmed = 0;\n let corrected = 0;\n\n for (const binding of bindings) {\n const edit = edits.get(binding.key.raw);\n if (edit !== undefined) {\n const trimmed = edit.trim();\n if (trimmed === '' && binding.serverValue === NOT_FOUND) {\n continue;\n }\n const value = trimmed === '' ? null : trimmed;\n data[binding.key.raw] = value;\n byLabel[binding.key.label] = value;\n corrected += 1;\n } else {\n if (binding.serverValue === NOT_FOUND) {\n continue;\n }\n data[binding.key.raw] = binding.serverValue;\n byLabel[binding.key.label] = binding.serverValue;\n confirmed += 1;\n }\n }\n return { data, byLabel, confirmed, corrected };\n}\n","/**\n * Verification form — field primitives (Task 12).\n *\n * Port of the console's `FieldValue.tsx` through the house-style\n * transformation table: antd `<Tooltip>` becomes a native `title` attribute\n * paired with an aria-label, `@ant-design/icons` becomes the hand-drawn\n * `IconEye`, SCSS-module classes become the Task 6 `.gemina-verification__*`\n * contract classes, and NO inline colors — every visual state is a class\n * driven by the theme tokens.\n *\n * Accessibility contract (load-bearing, not decorative):\n * - The confidence dot is a color-only signal, so it always carries\n * `role=\"img\"` + a text `aria-label` and a `title` tooltip listing the\n * formatted reasons (WCAG 1.4.1 / 1.4.11).\n * - The dirty state pairs the `--dirty` border color with a visible \"edited\"\n * text badge, linked to the input via `aria-describedby`. When a missed\n * field is filled in, `--missed`'s error border wins the CSS cascade — the\n * badge is then the ONLY visible dirty channel, which is why it is a word\n * and not another color.\n *\n * Editing contract: dirtiness is exactly `edit !== undefined`. The PARENT\n * owns revert detection (it deletes the edits entry when the value returns to\n * the initial string) — nothing here compares against the initial value.\n *\n * Layout contract: FieldInput renders a FRAGMENT (input + \"edited\" badge) and\n * expects a flex-row container — `__dd`, `__cell`, and the simple-list items\n * provide it.\n *\n * Shape sections (Task 13): VerificationForm renders the classifier's buckets\n * in the CONSOLE's section order (FormView/index.tsx): Details (headers +\n * simple lists), entity cards, tables, fallback — then the SDK-only\n * \"Not detected\" section for bindings that matched no rendered field.\n */\nimport React from 'react';\nimport type { FieldBinding } from './bindings';\nimport { toInputString } from './bindings';\nimport type { ClassifiedCell, ClassifiedData, ClassifiedField } from './classify';\nimport { ROW_META_KEY, formatLabel, formatValue } from './classify';\nimport { NOT_FOUND } from './pointer';\nimport { IconEye } from './viewer';\n\n/** Colored dot + native tooltip. Absent (or blank-level) confidence renders nothing. */\nexport function ConfidenceDot(props: {\n confidence: { level: string; reasons: string[] } | null;\n}): React.JSX.Element | null {\n const { confidence } = props;\n if (!confidence?.level) {\n return null;\n }\n\n let variant: 'high' | 'medium' | 'low' | 'unknown';\n let label: string;\n switch (confidence.level.toLowerCase()) {\n case 'high':\n variant = 'high';\n label = 'High confidence';\n break;\n case 'medium':\n variant = 'medium';\n label = 'Medium confidence';\n break;\n case 'low':\n variant = 'low';\n label = 'Low confidence';\n break;\n default:\n variant = 'unknown';\n label = `${confidence.level} confidence`;\n }\n\n const reasons = confidence.reasons.map(formatLabel);\n const title = [label, ...reasons].join('\\n');\n // The title tooltip is hover-only; the reasons must also reach AT (and the\n // keyboard), so the accessible NAME carries them: \"Low confidence: Blurry\n // Region, Low OCR Quality\". One string, no extra DOM.\n const ariaLabel = reasons.length > 0 ? `${label}: ${reasons.join(', ')}` : label;\n return (\n <span\n className={`gemina-verification__dot gemina-verification__dot--${variant}`}\n role=\"img\"\n aria-label={ariaLabel}\n title={title}\n />\n );\n}\n\n/** Eye button that flashes the field's rects on the document. */\nexport function EyeButton(props: {\n coordinates: { points: [number, number][] } | null;\n onFlash: () => void;\n}): React.JSX.Element | null {\n const { coordinates, onFlash } = props;\n if (!coordinates) {\n return null;\n }\n return (\n <button\n type=\"button\"\n className=\"gemina-verification__eye\"\n title=\"Show on document\"\n aria-label=\"Show on document\"\n onClick={(event) => {\n // Rows use click-to-flash (Task 13); the field eye must not double-fire it.\n event.stopPropagation();\n onFlash();\n }}\n >\n <IconEye />\n </button>\n );\n}\n\n/** One editable field: input prefilled with the RAW value, dirty + missed states. */\nexport function FieldInput(props: {\n binding: FieldBinding;\n /** Current value if dirty, else undefined (input falls back to initial). */\n edit: string | undefined;\n /** Parent deletes the edits entry when value returns to the initial string. */\n onEdit: (rawKey: string, value: string) => void;\n readOnly: boolean;\n /** formatLabel(label) — the visible label lives in the surrounding layout. */\n ariaLabel: string;\n}): React.JSX.Element {\n const { binding, edit, onEdit, readOnly, ariaLabel } = props;\n const editedBadgeId = React.useId();\n\n // Container serverValues (value-object wrappers, arrays, objects) can never\n // score correct from a string edit — the server's coerce_like only adopts\n // types for scalar targets — so they render read-only (C1/C2 amendment).\n // NOTE: this branch deliberately DISCARDS `edit` and shows the extracted\n // value — correct for the 409 already-validated path. Task 17: keep\n // submit-in-progress as disabled buttons, NOT a readOnly flip, or the\n // user's pending edits would visually vanish mid-submit.\n if (readOnly || !binding.editable) {\n const display = binding.extracted === NOT_FOUND ? null : binding.extracted;\n return <span>{formatValue(display, binding.key.label)}</span>;\n }\n\n const dirty = edit !== undefined;\n const missed = binding.serverValue === NOT_FOUND;\n const className = [\n 'gemina-verification__input',\n dirty ? 'gemina-verification__input--dirty' : '',\n missed ? 'gemina-verification__input--missed' : '',\n ]\n .filter(Boolean)\n .join(' ');\n\n return (\n <>\n <input\n type=\"text\"\n className={className}\n // Per-input bidi: a Latin value inside an RTL (Hebrew) document — or\n // vice versa — must lay out by its own content, not the widget's dir.\n dir=\"auto\"\n // RAW value only — a display-formatted \"1,500\" round-tripped into the\n // submission would score as a correction (see toInputString).\n value={dirty ? edit : toInputString(binding.extracted)}\n onChange={(event) => onEdit(binding.key.raw, event.target.value)}\n placeholder={missed ? 'Not detected — fill in if present' : undefined}\n aria-label={ariaLabel}\n aria-describedby={dirty ? editedBadgeId : undefined}\n autoComplete=\"off\"\n />\n {dirty ? (\n <span className=\"gemina-verification__edited\" id={editedBadgeId}>\n edited\n </span>\n ) : null}\n </>\n );\n}\n\n// --- Shape sections (Task 13) ------------------------------------------------\n\ninterface FlashRect {\n points: [number, number][];\n}\n\n/** State + callbacks every section threads down to its fields.\n *\n * STABILITY CONTRACT (callers, i.e. Task 14): `onEdit`, `onFlash`, and\n * `bindingIndex` MUST be referentially stable across renders (useCallback /\n * useMemo) — the table-row memo compares them by reference, so an unstable\n * handler silently degrades every row bail-out to a full re-render. `edits`\n * MUST be replaced immutably on every change, never mutated in place: the\n * comparator short-circuits on `prevEdits === nextEdits`, so an in-place\n * mutation renders no update at all. */\ninterface SectionShared {\n bindingIndex: Map<string, FieldBinding>;\n edits: ReadonlyMap<string, string>;\n onEdit: (rawKey: string, value: string) => void;\n readOnly: boolean;\n onFlash: (rects: FlashRect[]) => void;\n}\n\n/** Props for the whole form pane.\n *\n * The SectionShared stability contract applies (see above), and `classified`\n * must be the memoized product of one `classifyData` call — a fresh object\n * per render defeats both the row memo and the fallback-section memo. */\nexport interface VerificationFormProps extends SectionShared {\n classified: ClassifiedData;\n /** Bindings whose pointer matched NO rendered field — the \"model missed the\n * whole field\" case; rendered as an extra \"Not detected\" section of empty inputs. */\n unmatched: FieldBinding[];\n}\n\n/** True when the click started on an interactive element — row click-to-flash\n * must never hijack typing, button presses, or link follows. */\nfunction isInteractiveTarget(target: EventTarget | null): boolean {\n return target instanceof Element && target.closest('input, button, a, select, textarea') !== null;\n}\n\n/** One label/value pair inside a description list (headers + entity cards). */\nfunction FieldPair(props: {\n label: string;\n ariaLabel: string;\n cell: ClassifiedCell | ClassifiedField;\n shared: SectionShared;\n}): React.JSX.Element {\n const { label, ariaLabel, cell, shared } = props;\n const binding = shared.bindingIndex.get(cell.pointer);\n return (\n <>\n <dt className=\"gemina-verification__dt\">\n <ConfidenceDot confidence={cell.confidence} />\n <span>{label}</span>\n </dt>\n <dd className=\"gemina-verification__dd\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={ariaLabel}\n />\n ) : (\n <span>{formatValue(cell.value, label)}</span>\n )}\n <EyeButton\n coordinates={cell.coordinates}\n onFlash={() => {\n if (cell.coordinates) {\n shared.onFlash([cell.coordinates]);\n }\n }}\n />\n </dd>\n </>\n );\n}\n\n/** \"Details\": header fields + simple lists in one description-list section. */\nfunction HeaderSection(props: {\n headers: ClassifiedField[];\n simpleLists: ClassifiedData['simpleLists'];\n shared: SectionShared;\n}): React.JSX.Element | null {\n const { headers, simpleLists, shared } = props;\n if (headers.length === 0 && simpleLists.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Details\">\n <div className=\"gemina-verification__section-header\">Details</div>\n <dl className=\"gemina-verification__dl\">\n {headers.map((field) => (\n <FieldPair\n key={field.pointer}\n label={formatLabel(field.key)}\n ariaLabel={formatLabel(field.key)}\n cell={field}\n shared={shared}\n />\n ))}\n {simpleLists.map((list) => (\n <React.Fragment key={list.pointer}>\n <dt className=\"gemina-verification__dt\">\n <span>{formatLabel(list.key)}</span>\n </dt>\n <dd className=\"gemina-verification__dd\">\n <ul className=\"gemina-verification__list\">\n {list.items.map((item, index) => {\n const binding = shared.bindingIndex.get(item.pointer);\n return (\n <li key={item.pointer} className=\"gemina-verification__cell\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={`${formatLabel(list.key)} item ${index + 1}`}\n />\n ) : (\n <span>{formatValue(item.value)}</span>\n )}\n <ConfidenceDot confidence={item.confidence} />\n <EyeButton\n coordinates={item.coordinates}\n onFlash={() => {\n if (item.coordinates) {\n shared.onFlash([item.coordinates]);\n }\n }}\n />\n </li>\n );\n })}\n </ul>\n </dd>\n </React.Fragment>\n ))}\n </dl>\n </section>\n );\n}\n\n/** Entity bucket: one card per item, headers singularized console-style. */\nfunction EntitySection(props: {\n entity: ClassifiedData['entities'][number];\n shared: SectionShared;\n}): React.JSX.Element {\n const { entity, shared } = props;\n const label = formatLabel(entity.key);\n // The console's naive strip-trailing-s, ported verbatim (\"Suppliers\" →\n // \"Supplier\"; yes, \"Parties\" → \"Partie\" — console parity over grammar).\n const singular = label.replace(/s$/, '');\n return (\n <section className=\"gemina-verification__section\" aria-label={label}>\n <div className=\"gemina-verification__section-header\">\n {label} ({entity.items.length})\n </div>\n <div className=\"gemina-verification__section-body\">\n {entity.items.map((item, itemIndex) => (\n <div key={itemIndex} className=\"gemina-verification__card\">\n <div className=\"gemina-verification__card-header\">\n {singular} {itemIndex + 1}\n </div>\n <dl className=\"gemina-verification__dl\">\n {Object.entries(item).map(([fieldKey, cell]) => (\n <FieldPair\n key={fieldKey}\n label={formatLabel(fieldKey)}\n // Card context: two \"Supplier\" cards both announcing a bare\n // \"Name\" would be ambiguous to a screen reader.\n ariaLabel={`${singular} ${itemIndex + 1} — ${formatLabel(fieldKey)}`}\n cell={cell}\n shared={shared}\n />\n ))}\n </dl>\n </div>\n ))}\n </div>\n </section>\n );\n}\n\ninterface TableRowViewProps {\n row: Record<string, ClassifiedCell>;\n rowIndex: number;\n columns: string[];\n /** formatLabel(tableKey), precomputed once per table. */\n tableLabel: string;\n hasCoords: boolean;\n hasRowConfidence: boolean;\n shared: SectionShared;\n}\n\nfunction TableRowView(props: TableRowViewProps): React.JSX.Element {\n const { row, rowIndex, columns, tableLabel, hasCoords, hasRowConfidence, shared } = props;\n const { bindingIndex, edits, onEdit, readOnly, onFlash } = shared;\n\n const rects = React.useMemo(() => {\n const collected: FlashRect[] = [];\n for (const [key, cell] of Object.entries(row)) {\n if (key !== ROW_META_KEY && cell.coordinates) {\n collected.push(cell.coordinates);\n }\n }\n return collected;\n }, [row]);\n\n const handleRowClick = React.useCallback(\n (event: React.MouseEvent<HTMLTableRowElement>) => {\n if (isInteractiveTarget(event.target)) {\n return;\n }\n if (rects.length > 0) {\n onFlash(rects);\n }\n },\n [rects, onFlash],\n );\n\n const firstRect = rects.length > 0 ? rects[0]! : null;\n return (\n <tr onClick={handleRowClick}>\n {hasCoords ? (\n <td>\n {/* EyeButton's coordinates prop is only the render gate here — the\n click flashes ALL the row's rects, console DataTable style. */}\n <EyeButton coordinates={firstRect} onFlash={() => onFlash(rects)} />\n </td>\n ) : null}\n {hasRowConfidence ? (\n <td>\n <ConfidenceDot confidence={row[ROW_META_KEY]?.confidence ?? null} />\n </td>\n ) : null}\n {columns.map((column) => {\n const cell = row[column];\n const binding = cell === undefined ? undefined : bindingIndex.get(cell.pointer);\n return (\n <td key={column}>\n <div className=\"gemina-verification__cell\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n edit={edits.get(binding.key.raw)}\n onEdit={onEdit}\n readOnly={readOnly}\n ariaLabel={`${tableLabel} row ${rowIndex + 1} — ${formatLabel(column)}`}\n />\n ) : (\n <span>{cell === undefined ? '-' : formatValue(cell.value, column)}</span>\n )}\n <ConfidenceDot confidence={cell?.confidence ?? null} />\n </div>\n </td>\n );\n })}\n </tr>\n );\n}\n\n/** Bail out unless THIS row's data or its slice of the edits changed. The\n * comparator inspects only edits for bindings on this row's cells, so one\n * keystroke re-renders one row. Callbacks are compared by reference: the\n * parent must pass referentially stable `onEdit`/`onFlash` (and a stable\n * `classified`/`bindingIndex`) or the memoization degrades to plain renders. */\nfunction areRowPropsEqual(prev: TableRowViewProps, next: TableRowViewProps): boolean {\n if (\n prev.row !== next.row\n || prev.rowIndex !== next.rowIndex\n || prev.columns !== next.columns\n || prev.tableLabel !== next.tableLabel\n || prev.hasCoords !== next.hasCoords\n || prev.hasRowConfidence !== next.hasRowConfidence\n || prev.shared.bindingIndex !== next.shared.bindingIndex\n || prev.shared.onEdit !== next.shared.onEdit\n || prev.shared.onFlash !== next.shared.onFlash\n || prev.shared.readOnly !== next.shared.readOnly\n ) {\n return false;\n }\n if (prev.shared.edits === next.shared.edits) {\n return true;\n }\n for (const column of next.columns) {\n const cell = next.row[column];\n const binding = cell === undefined ? undefined : next.shared.bindingIndex.get(cell.pointer);\n if (\n binding !== undefined\n && prev.shared.edits.get(binding.key.raw) !== next.shared.edits.get(binding.key.raw)\n ) {\n return false;\n }\n }\n return true;\n}\n\nconst TableRow = React.memo(TableRowView, areRowPropsEqual);\n\n/** Table bucket: the console DataTable's column model without antd. */\nfunction TableSection(props: {\n table: ClassifiedData['tables'][number];\n shared: SectionShared;\n}): React.JSX.Element {\n const { table, shared } = props;\n const label = formatLabel(table.key);\n // Full-row scans — memoized so keystroke re-renders don't re-walk every cell.\n const hasCoords = React.useMemo(\n () =>\n table.rows.some((row) =>\n Object.entries(row).some(([key, cell]) => key !== ROW_META_KEY && cell.coordinates !== null),\n ),\n [table],\n );\n const hasRowConfidence = React.useMemo(\n () => table.rows.some((row) => Boolean(row[ROW_META_KEY]?.confidence?.level)),\n [table],\n );\n return (\n <section className=\"gemina-verification__section\" aria-label={label}>\n <div className=\"gemina-verification__section-header\">\n <span>\n {label} ({table.rows.length} rows)\n </span>\n <ConfidenceDot confidence={table.overallConfidence} />\n </div>\n <div className=\"gemina-verification__table-wrap\">\n <table className=\"gemina-verification__table\">\n <thead>\n <tr>\n {hasCoords ? <th aria-label=\"Show row on document\" /> : null}\n {hasRowConfidence ? <th aria-label=\"Row confidence\" /> : null}\n {table.columns.map((column) => (\n <th key={column}>{formatLabel(column)}</th>\n ))}\n </tr>\n </thead>\n <tbody>\n {table.rows.map((row, rowIndex) => (\n <TableRow\n key={rowIndex}\n row={row}\n rowIndex={rowIndex}\n columns={table.columns}\n tableLabel={label}\n hasCoords={hasCoords}\n hasRowConfidence={hasRowConfidence}\n shared={shared}\n />\n ))}\n </tbody>\n </table>\n </div>\n </section>\n );\n}\n\n/** Unclassifiable blobs: native <details> + pretty-printed JSON (no viewer dep).\n * Memoized: fallback is exactly where large unclassifiable payloads land, and\n * without the memo every parent render (i.e., every keystroke) would re-run\n * JSON.stringify over all of them. `classified.fallback` is referentially\n * stable (the parent memoizes classifyData), so the memo is a complete fix. */\nconst FallbackSection = React.memo(function FallbackSection(\n props: { fallback: ClassifiedData['fallback'] },\n): React.JSX.Element | null {\n const { fallback } = props;\n if (fallback.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Additional Data\">\n <div className=\"gemina-verification__section-header\">Additional Data</div>\n <div className=\"gemina-verification__section-body\">\n {fallback.map((item) => (\n <details key={item.key} className=\"gemina-verification__fallback\">\n <summary>{formatLabel(item.key)}</summary>\n <pre>{JSON.stringify(item.data, null, 2)}</pre>\n </details>\n ))}\n </div>\n </section>\n );\n});\n\n/** Bindings the model missed entirely: a section of empty fill-in inputs. */\nfunction UnmatchedSection(props: {\n unmatched: FieldBinding[];\n shared: SectionShared;\n}): React.JSX.Element | null {\n const { unmatched, shared } = props;\n if (unmatched.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Not detected\">\n <div className=\"gemina-verification__section-header\">Not detected</div>\n <dl className=\"gemina-verification__dl\">\n {unmatched.map((binding) => (\n <React.Fragment key={binding.key.raw}>\n {/* Schema labels are already human text — formatLabel is for raw\n payload keys only (it would mangle \"PO Number\" → \"Po Number\"). */}\n <dt className=\"gemina-verification__dt\">\n <span>{binding.key.label}</span>\n </dt>\n <dd className=\"gemina-verification__dd\">\n <FieldInput\n binding={binding}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={binding.key.label}\n />\n </dd>\n </React.Fragment>\n ))}\n </dl>\n </section>\n );\n}\n\n/** The whole form pane: every classified bucket in console order, then the\n * unmatched \"Not detected\" section. Empty buckets render nothing. */\nexport function VerificationForm(props: VerificationFormProps): React.JSX.Element {\n const { classified, unmatched, bindingIndex, edits, onEdit, readOnly, onFlash } = props;\n const shared: SectionShared = { bindingIndex, edits, onEdit, readOnly, onFlash };\n return (\n // A real, labeled <form> (role \"form\" landmark): AT users can jump\n // straight to the editable fields. Submission is owned by the root's\n // footer button, never by the form element itself — preventDefault stops\n // implicit submission (Enter in a payload with exactly one input would\n // otherwise navigate).\n <form\n className=\"gemina-verification__form\"\n aria-label=\"Extraction fields\"\n onSubmit={(event) => event.preventDefault()}\n >\n <HeaderSection headers={classified.headers} simpleLists={classified.simpleLists} shared={shared} />\n {classified.entities.map((entity) => (\n <EntitySection key={entity.pointer} entity={entity} shared={shared} />\n ))}\n {classified.tables.map((table) => (\n <TableSection key={table.pointer} table={table} shared={shared} />\n ))}\n <FallbackSection fallback={classified.fallback} />\n <UnmatchedSection unmatched={unmatched} shared={shared} />\n </form>\n );\n}\n","/**\n * Internal document viewer for <GeminaVerification> — image canvas with a\n * zoom/rotate toolbar. Port of the console's ZoomableImageViewer skeleton\n * (gemina-console/src/components/viewers/ZoomableImageViewer.tsx): same\n * state/refs/effects shape, with the gesture/travel transform math delegated\n * to `viewer-math.ts` (the magnifier's presentation math stays local, exactly\n * as inline as the console's) and all styling on the Task 6\n * `.gemina-verification__*` classes. Tasks 8+9 add wheel zoom, mouse pan, the\n * double-click fit/100% toggle, and touch pan + pinch zoom; Task 10 adds\n * coordinate overlays, the flash-zoom travel animation, and the image-expiry\n * hook; Task 11 adds the magnifier loupe.\n *\n * Coordinate spaces: the console's zoomAtPoint takes clientX/Y and subtracts\n * the canvas rect INSIDE itself; the elements zoomAtPoint (viewer-math.ts) is\n * container-relative, so every DOM call site converts via\n * `zoomAtClientPoint` (Task 7 review carry-forward — a verbatim port anchors\n * wrong in any scrolled/offset layout).\n *\n * SSR-safe: no `window`/`document` access at import time; `ResizeObserver`\n * is only touched inside an effect (with a one-shot measure fallback).\n */\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport {\n centeredTranslation,\n clampScale,\n easeOutCubic,\n fitScaleFor,\n flashZoomTarget,\n zoomAtPoint,\n} from './viewer-math';\nimport type { Size, Transform } from './viewer-math';\n\n/** Axis-aligned detection region in relative image coordinates (0–1). */\nexport interface RelativeRect {\n points: [number, number][];\n}\n\nexport interface VerificationViewerProps {\n src: string;\n alt?: string;\n relativeRects?: RelativeRect[];\n flashRects?: RelativeRect[] | null;\n onFlashComplete?: () => void;\n /** Fired when the <img> errors AFTER at least one successful load (URL expiry). */\n onImageExpired?: () => void;\n}\n\n// --- Icons ------------------------------------------------------------------\n// One hand-drawn family: 16×16 grid, 1.5px stroke, round caps/joins, painted\n// with currentColor so the toolbar's normal/active colors flow through. The\n// only fills are the two dots of the 1:1 colon. Each icon stays ≤ 6 segments.\n\nfunction IconBase({ children }: { children: React.ReactNode }): React.JSX.Element {\n return (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n {children}\n </svg>\n );\n}\n\n/** Shared magnifying-glass body (lens + handle) for the zoom/magnifier trio. */\nfunction GlassBody(): React.JSX.Element {\n return (\n <>\n <circle cx=\"6.75\" cy=\"6.75\" r=\"4.25\" />\n <line x1=\"9.9\" y1=\"9.9\" x2=\"13.5\" y2=\"13.5\" />\n </>\n );\n}\n\nexport function IconZoomIn(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n <line x1=\"4.9\" y1=\"6.75\" x2=\"8.6\" y2=\"6.75\" />\n <line x1=\"6.75\" y1=\"4.9\" x2=\"6.75\" y2=\"8.6\" />\n </IconBase>\n );\n}\n\nexport function IconZoomOut(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n <line x1=\"4.9\" y1=\"6.75\" x2=\"8.6\" y2=\"6.75\" />\n </IconBase>\n );\n}\n\nexport function IconMagnifier(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n </IconBase>\n );\n}\n\n/** \"1:1\" drawn as numeral strokes — actual pixel size. */\nexport function IconActualSize(): React.JSX.Element {\n return (\n <IconBase>\n <polyline points=\"2.8 6.2 4 5 4 11\" />\n <polyline points=\"10.8 6.2 12 5 12 11\" />\n <circle cx=\"8\" cy=\"6.75\" r=\"0.8\" fill=\"currentColor\" stroke=\"none\" />\n <circle cx=\"8\" cy=\"9.25\" r=\"0.8\" fill=\"currentColor\" stroke=\"none\" />\n </IconBase>\n );\n}\n\n/** Two arrows collapsing inward — fit to screen. */\nexport function IconFit(): React.JSX.Element {\n return (\n <IconBase>\n <line x1=\"13.8\" y1=\"2.2\" x2=\"9.6\" y2=\"6.4\" />\n <polyline points=\"9.6 3.9 9.6 6.4 12.1 6.4\" />\n <line x1=\"2.2\" y1=\"13.8\" x2=\"6.4\" y2=\"9.6\" />\n <polyline points=\"6.4 12.1 6.4 9.6 3.9 9.6\" />\n </IconBase>\n );\n}\n\n/** Clockwise circular arrow. */\nexport function IconRotate(): React.JSX.Element {\n return (\n <IconBase>\n <path d=\"M11.83 4.79A5 5 0 1 1 8 3\" />\n <polyline points=\"6 1.7 8 3 6 4.3\" />\n </IconBase>\n );\n}\n\n/** Dashed square — detection overlay regions. */\nexport function IconOverlay(): React.JSX.Element {\n return (\n <IconBase>\n <rect x=\"2.75\" y=\"2.75\" width=\"10.5\" height=\"10.5\" rx=\"1.5\" strokeDasharray=\"3 2.2\" />\n </IconBase>\n );\n}\n\n/** Eye — used by the form's field-peek buttons (Task 12+). */\nexport function IconEye(): React.JSX.Element {\n return (\n <IconBase>\n <path d=\"M1.5 8s2.4-4.5 6.5-4.5S14.5 8 14.5 8s-2.4 4.5-6.5 4.5S1.5 8 1.5 8z\" />\n <circle cx=\"8\" cy=\"8\" r=\"2.1\" />\n </IconBase>\n );\n}\n\n// --- Toolbar ----------------------------------------------------------------\n\ninterface ToolbarButtonProps {\n label: string;\n onClick: () => void;\n disabled?: boolean;\n /** aria-pressed toggle button (overlay toggle). */\n pressed?: boolean;\n /** role=\"switch\" + aria-checked (magnifier). */\n checked?: boolean;\n children: React.ReactNode;\n}\n\nfunction ToolbarButton({\n label,\n onClick,\n disabled,\n pressed,\n checked,\n children,\n}: ToolbarButtonProps): React.JSX.Element {\n const active = (pressed ?? checked) === true;\n return (\n <button\n type=\"button\"\n className={\n active\n ? 'gemina-verification__toolbar-btn gemina-verification__toolbar-btn--active'\n : 'gemina-verification__toolbar-btn'\n }\n title={label}\n aria-label={label}\n role={checked === undefined ? undefined : 'switch'}\n aria-checked={checked}\n aria-pressed={pressed}\n disabled={disabled}\n onClick={onClick}\n >\n {children}\n </button>\n );\n}\n\n// --- Viewer -----------------------------------------------------------------\n\nconst ZOOM_STEP = 1.2;\nconst IDENTITY: Transform = { scale: 1, tx: 0, ty: 0 };\n\n// Console flash constants (ZoomableImageViewer ~56-57): the rect fades over\n// 1500ms while the transform travels for its first 350ms.\nconst FLASH_DURATION = 1500; // ms\nconst ZOOM_ANIMATION_DURATION = 350; // ms - smooth but fast travel animation\n/** Reduced motion: no travel, no fade — jump to the target and hold the rect\n * at full opacity for a beat long enough to register, then complete. */\nconst REDUCED_MOTION_FLASH_MS = 800;\n\n/** Console's minimum visible rect size, as a ratio of the natural dimension\n * (~750): hairline detection boxes stay clickable-eye-visible. */\nconst MIN_SIZE_RATIO = 0.008;\n\n// Console magnifier constants (ZoomableImageViewer ~59-60).\nconst MAG_RADIUS = 150; // px — loupe radius (console: 140-160px)\nconst MAG_ZOOM = 2.5; // magnification applied on top of the current scale\n\n/** Rect geometry in image pixel space — the overlays render INSIDE the\n * transform layer, so left/top/width/height are natural-size pixels and the\n * layer's scale/rotate carries them (console ~742-756). Returns null for\n * degenerate rects (a single point, or no points at all). */\nfunction rectGeometry(\n rect: RelativeRect,\n natural: Size,\n): { left: number; top: number; width: number; height: number } | null {\n const xs = rect.points.map((point) => point[0]);\n const ys = rect.points.map((point) => point[1]);\n const minX = Math.min(...xs);\n const minY = Math.min(...ys);\n const rawWidthRatio = Math.max(0, Math.max(...xs) - minX);\n const rawHeightRatio = Math.max(0, Math.max(...ys) - minY);\n if (rawWidthRatio <= 0 && rawHeightRatio <= 0) return null;\n return {\n left: minX * natural.w,\n top: minY * natural.h,\n width: Math.max(rawWidthRatio, MIN_SIZE_RATIO) * natural.w,\n height: Math.max(rawHeightRatio, MIN_SIZE_RATIO) * natural.h,\n };\n}\n\nexport function VerificationViewer(props: VerificationViewerProps): React.JSX.Element {\n const { src, alt, relativeRects, flashRects, onFlashComplete, onImageExpired } = props;\n\n const canvasRef = useRef<HTMLDivElement | null>(null);\n const imgRef = useRef<HTMLImageElement | null>(null);\n\n const [natural, setNatural] = useState<Size | null>(null);\n const [container, setContainer] = useState<Size>({ w: 0, h: 0 });\n const [transform, setTransform] = useState<Transform>(IDENTITY);\n const [rotation, setRotation] = useState(0); // degrees, multiples of 90\n\n const [showRects, setShowRects] = useState(false);\n const [magnifierOn, setMagnifierOn] = useState(false);\n\n // Loupe pointer state (console ~37-38): showMag flips on canvas\n // mousemove/mouseleave, mousePos is container-relative. Both track on EVERY\n // move regardless of the switch — console parity — so toggling the switch\n // with the pointer resting over the canvas (keyboard toggle) shows the\n // loupe at the right spot. The per-move re-render is the console's own\n // accepted cost; the loupe subtree is tiny.\n const [showMag, setShowMag] = useState(false);\n const [mousePos, setMousePos] = useState<{ x: number; y: number }>({ x: 0, y: 0 });\n\n const [isPanning, setIsPanning] = useState(false);\n const panStart = useRef<{ x: number; y: number; tx: number; ty: number } | null>(null);\n\n // Flash animation state (console ~43-57).\n const [flashOpacity, setFlashOpacity] = useState(0);\n const [activeFlashRects, setActiveFlashRects] = useState<RelativeRect[] | null>(null);\n const travelRafRef = useRef<number | null>(null);\n const fadeRafRef = useRef<number | null>(null);\n const reducedFlashTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Render-synced mirror of the transform (console's scaleRef/txRef/tyRef):\n // the travel animation reads its from-values here instead of closing over\n // state inside the rAF loop (review carry-forward).\n const transformRef = useRef(transform);\n transformRef.current = transform;\n\n // Latest-value ref so an inline onFlashComplete prop cannot restart the\n // flash effect on every parent render.\n const onFlashCompleteRef = useRef(onFlashComplete);\n onFlashCompleteRef.current = onFlashComplete;\n\n // True once the CURRENT src has loaded successfully — the expiry gate.\n const hasLoadedRef = useRef(false);\n\n // Measure the canvas (console lines ~124-133), with a one-shot fallback for\n // environments without ResizeObserver. contentRect on purpose (unlike the\n // root's stacked observer, which reads border-box): the fit/zoom math needs\n // the CONTENT area the image is positioned within.\n useLayoutEffect(() => {\n const el = canvasRef.current;\n if (!el) return;\n if (typeof ResizeObserver === 'undefined') {\n const rect = el.getBoundingClientRect();\n setContainer({ w: rect.width, h: rect.height });\n return;\n }\n const ro = new ResizeObserver((entries) => {\n const cr = entries[0]?.contentRect;\n if (cr) setContainer({ w: cr.width, h: cr.height });\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n // Natural image size (console ~136-139), with an identity-preserving setter\n // (review carry-forward): a re-minted URL for the SAME image (the\n // onImageExpired flow) reports identical dimensions, and returning the prev\n // object keeps the fit effect from re-running and resetting the user's\n // zoom/pan mid-review.\n const handleImgLoad = useCallback(() => {\n const img = imgRef.current;\n if (!img) return;\n hasLoadedRef.current = true;\n const w = img.naturalWidth;\n const h = img.naturalHeight;\n setNatural((prev) => (prev && prev.w === w && prev.h === h ? prev : { w, h }));\n }, []);\n\n // Expiry hook — replaces the console's fallbackSrc error handler (~374-378).\n // The loaded flag resets on every src change: a NEW src that fails before it\n // ever loads is a broken URL, not an expired one, and firing onImageExpired\n // there would re-mint forever in a loop. It also disarms when it fires, so\n // one load reports at most one expiry (the re-minted load re-arms it).\n useEffect(() => {\n hasLoadedRef.current = false;\n }, [src]);\n\n const handleImgError = useCallback(() => {\n if (!hasLoadedRef.current) return;\n hasLoadedRef.current = false;\n onImageExpired?.();\n }, [onImageExpired]);\n\n /** The console's `fitScale` memo, including its degenerate-size guard. */\n const currentFitScale = useCallback((): number => {\n if (!natural || !container.w || !container.h) return 1;\n return fitScaleFor(natural, container, rotation);\n }, [natural, container, rotation]);\n\n // Fit + center on first load, and re-fit on container/rotation changes\n // (console ~186-196).\n useEffect(() => {\n if (!natural || !container.w || !container.h) return;\n const fit = fitScaleFor(natural, container, rotation);\n const { tx, ty } = centeredTranslation(natural, container, fit, rotation);\n setTransform((prev) =>\n Math.abs(prev.scale - fit) < 0.0001 && prev.tx === tx && prev.ty === ty\n ? prev\n : { scale: fit, tx, ty },\n );\n }, [natural, container, rotation]);\n\n // DELIBERATE IMPROVEMENT over the console (reviewer-endorsed): the console\n // never cancels the flash travel on user input, so its rAF loop keeps\n // stomping wheel/drag transforms for the rest of its 350ms window. Here any\n // canvas gesture (wheel, mousedown, touchstart, dblclick) AND any toolbar\n // zoom (zoom in/out, fit, 100%) stops the travel — the user just took the\n // wheel. Only the transform drive stops: the flash rect keeps fading, and\n // the fade loop still fires onFlashComplete.\n const cancelFlashTravel = useCallback(() => {\n if (travelRafRef.current !== null) {\n cancelAnimationFrame(travelRafRef.current);\n travelRafRef.current = null;\n }\n }, []);\n\n // Toolbar handlers (console ~251-278). zoomAtPoint returns the SAME object\n // on clamped no-ops, so the updater form bails out of re-rendering.\n const zoomBy = useCallback(\n (factor: number) => {\n const node = canvasRef.current;\n if (!node || !natural) return;\n cancelFlashTravel();\n const rect = node.getBoundingClientRect();\n const fit = currentFitScale();\n setTransform((prev) =>\n zoomAtPoint(prev, factor, rect.width / 2, rect.height / 2, rotation, fit),\n );\n },\n [natural, rotation, currentFitScale, cancelFlashTravel],\n );\n\n const handleZoomIn = useCallback(() => zoomBy(ZOOM_STEP), [zoomBy]);\n const handleZoomOut = useCallback(() => zoomBy(1 / ZOOM_STEP), [zoomBy]);\n\n /** Client -> container-relative conversion lives HERE, at the call sites\n * (wheel, double-click; pinch joins in Task 9) — viewer-math's zoomAtPoint\n * is container-relative by contract. */\n const zoomAtClientPoint = useCallback(\n (factor: number, clientX: number, clientY: number) => {\n const node = canvasRef.current;\n if (!node || !natural) return;\n const rect = node.getBoundingClientRect();\n const fit = currentFitScale();\n setTransform((prev) =>\n zoomAtPoint(prev, factor, clientX - rect.left, clientY - rect.top, rotation, fit),\n );\n },\n [natural, rotation, currentFitScale],\n );\n\n // Wheel zoom (console ~232-249): React's onWheel is passive, so attach a\n // NON-PASSIVE native listener — preventDefault must keep the page from\n // scrolling under the zoom.\n const handleWheel = useCallback(\n (event: WheelEvent) => {\n event.preventDefault();\n event.stopPropagation();\n cancelFlashTravel();\n const factor = event.deltaY > 0 ? 0.92 : 1.08; // console's wheel constants\n zoomAtClientPoint(factor, event.clientX, event.clientY);\n },\n [zoomAtClientPoint, cancelFlashTravel],\n );\n\n useEffect(() => {\n const node = canvasRef.current;\n if (!node) return;\n const listener = (event: WheelEvent) => handleWheel(event);\n node.addEventListener('wheel', listener, { passive: false });\n return () => node.removeEventListener('wheel', listener);\n }, [handleWheel]);\n\n // Beyond fit there is something to pan; at fit the drag is inert and the\n // cursor honestly says zoom-in (console ~296-322 policy). Shared by the\n // mousedown gate and the cursor state below.\n const atFitScale = transform.scale <= currentFitScale() + 0.001;\n\n // Mouse pan. Deliberate deviation from the console: move/up listen on\n // `document` while panning so the drag survives leaving the canvas instead\n // of dropping at the edge.\n const handleMouseDown = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n // Any press grabs the canvas — stop the flash travel before the gates.\n cancelFlashTravel();\n // Primary button only: with document-level listeners a right-click's\n // context menu would swallow the mouseup and leave the pan stuck.\n // (Tap-synthesized compat mouse events report button 0 and pass — fine;\n // Task 9's touch handlers own that path.)\n if (e.button !== 0) return;\n if (atFitScale) return;\n e.preventDefault(); // document-level drag: don't start selections outside the widget\n panStart.current = { x: e.clientX, y: e.clientY, tx: transform.tx, ty: transform.ty };\n setIsPanning(true);\n },\n [atFitScale, transform.tx, transform.ty, cancelFlashTravel],\n );\n\n useEffect(() => {\n if (!isPanning) return;\n const onMove = (e: MouseEvent) => {\n const start = panStart.current;\n if (!start) return;\n const dx = e.clientX - start.x;\n const dy = e.clientY - start.y;\n setTransform((prev) => ({ scale: prev.scale, tx: start.tx + dx, ty: start.ty + dy }));\n };\n const onUp = () => {\n panStart.current = null;\n setIsPanning(false);\n };\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onUp);\n // Cleanup runs on mouseup (isPanning flips false) AND on unmount mid-pan.\n return () => {\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('mouseup', onUp);\n };\n }, [isPanning]);\n\n // Touch: one-finger pan (only beyond fit — the mousedown gate's twin) and\n // two-finger pinch zoom. Verbatim console port (~324-369) except the pinch\n // factor routes through zoomAtClientPoint — client → container conversion\n // plus the shared fit-floor clamp — instead of any local math.\n // `touch-action: none` on __canvas (styles.ts) hands these gestures to us,\n // so React's passive onTouch* handlers suffice; no preventDefault needed.\n // Gesture state lives in a ref: nothing re-renders per touch-move except\n // the transform update itself, and isPanning/data-cursor stay mouse-only\n // (a touch screen shows no cursor).\n const touchState = useRef<\n | { mode: 'pan'; x: number; y: number; tx: number; ty: number }\n | { mode: 'pinch'; dist: number }\n | null\n >(null);\n\n const handleTouchStart = useCallback(\n (e: React.TouchEvent<HTMLDivElement>) => {\n // A finger on the canvas grabs it — stop the flash travel.\n cancelFlashTravel();\n // Length checks don't narrow TouchList indexing under\n // noUncheckedIndexedAccess, so a/b/their truthiness carry the guard.\n const a = e.touches[0];\n const b = e.touches[1];\n if (e.touches.length === 2 && a && b) {\n // Only the start distance seeds a pinch — no midpoint is stored,\n // because every move re-anchors at the CURRENT midpoint (console\n // policy). A second finger landing mid-pan arrives here too, so 1→2\n // hands the gesture off to pinch automatically.\n touchState.current = {\n mode: 'pinch',\n dist: Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY),\n };\n } else if (e.touches.length === 1 && a && !atFitScale) {\n touchState.current = { mode: 'pan', x: a.clientX, y: a.clientY, tx: transform.tx, ty: transform.ty };\n } else {\n touchState.current = null;\n }\n },\n [atFitScale, transform.tx, transform.ty, cancelFlashTravel],\n );\n\n const handleTouchMove = useCallback(\n (e: React.TouchEvent<HTMLDivElement>) => {\n const state = touchState.current;\n if (!state) return;\n if (state.mode === 'pinch' && e.touches.length === 2) {\n const a = e.touches[0];\n const b = e.touches[1];\n if (!a || !b) return;\n const dist = Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY);\n if (state.dist > 0) {\n // Per-move ratio, re-seeded below: each factor is relative to the\n // LAST move, and the updater-form zoomAtPoint composes it onto the\n // accumulated transform, so React batching can't double-apply a\n // step. Two-finger travel without spread is factor 1 — zoomAtPoint's\n // same-object bail-out makes it a no-op (console policy: a pinch\n // never pans; the image only shifts through the moving anchor while\n // the scale is changing).\n zoomAtClientPoint(dist / state.dist, (a.clientX + b.clientX) / 2, (a.clientY + b.clientY) / 2);\n }\n state.dist = dist;\n } else if (state.mode === 'pan' && e.touches.length === 1) {\n // START-RELATIVE deltas (the established pan pattern) — never\n // accumulated per event, so a dropped move can't skew the drag.\n const t = e.touches[0];\n if (!t) return;\n setTransform((prev) => ({\n scale: prev.scale,\n tx: state.tx + (t.clientX - state.x),\n ty: state.ty + (t.clientY - state.y),\n }));\n }\n },\n [zoomAtClientPoint],\n );\n\n // 2→1 deliberately leaves an INERT pinch until every finger lifts\n // (console-faithful): the remaining finger matches neither move branch, so\n // nothing jumps; the next touchstart begins a fresh gesture.\n const handleTouchEnd = useCallback((e: React.TouchEvent<HTMLDivElement>) => {\n if (e.touches.length === 0) touchState.current = null;\n }, []);\n\n // Loupe pointer tracking (console ~305-308, ~695-703), container-relative\n // like every other pointer path (Task 7 carry-forward). Show on any canvas\n // mousemove, hide only on mouseleave — console policy verbatim. On a touch\n // device a tap synthesizes compat mousemoves that PARK the loupe at the tap\n // point while the switch is on; the console does nothing about that either\n // (its loupe is a desktop pattern), and the parked loupe clears on the next\n // compat mouseleave. Pan is untouched: it lives on document-level listeners.\n const handleCanvasMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {\n const rect = canvasRef.current?.getBoundingClientRect();\n if (!rect) return;\n setShowMag(true);\n setMousePos({ x: e.clientX - rect.left, y: e.clientY - rect.top });\n }, []);\n\n const handleCanvasMouseLeave = useCallback(() => {\n setShowMag(false);\n }, []);\n\n // Double-click toggle (console ~281-294): near fit -> 100% anchored at the\n // click point; otherwise back to centered fit.\n const handleDoubleClick = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n cancelFlashTravel();\n if (!natural) return;\n const fit = currentFitScale();\n const nearFit = Math.abs(transform.scale - fit) < 0.001;\n if (nearFit) {\n const target = clampScale(1, fit);\n zoomAtClientPoint(target / transform.scale, e.clientX, e.clientY);\n } else {\n setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });\n }\n },\n [natural, container, rotation, transform.scale, currentFitScale, zoomAtClientPoint, cancelFlashTravel],\n );\n\n const handleFit = useCallback(() => {\n if (!natural) return;\n cancelFlashTravel();\n const fit = currentFitScale();\n setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });\n }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);\n\n const handleActualSize = useCallback(() => {\n if (!natural) return;\n cancelFlashTravel();\n const target = clampScale(1, currentFitScale());\n setTransform({ scale: target, ...centeredTranslation(natural, container, target, rotation) });\n }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);\n\n // Deliberately does NOT cancelFlashTravel: `rotation` is a dep of the flash\n // effect, so a rotate mid-travel re-runs it — cleanup cancels both loops,\n // then the effect recomputes flashZoomTarget for the NEW rotation and\n // restarts travel (and fade, from full opacity) from the current transform.\n // The rect therefore lands rotation-correct instead of coasting toward a\n // stale pre-rotation target (pinned by the rotate-mid-travel test).\n const handleRotate = useCallback(() => {\n setRotation((r) => (r + 90) % 360);\n }, []);\n\n // Overlay toggle only means something while rects exist (console ~450-456).\n const hasRects = relativeRects !== undefined && relativeRects.length > 0;\n useEffect(() => {\n if (!hasRects) setShowRects(false);\n }, [hasRects]);\n\n // Flash animation + zoom-to-rect travel (console ~458-581). Two parallel\n // drives: the transform travels to flashZoomTarget over 350ms (easeOutCubic,\n // from-values read off transformRef), while the flash rect fades 1 - p²\n // over 1500ms. The FADE loop owns completion: it clears the rects and fires\n // onFlashComplete — so a gesture-canceled travel never swallows the\n // callback. Cleanup cancels BOTH loops, which covers unmount mid-flash and\n // makes a re-trigger (rapid eye-clicks re-running this effect) a clean\n // restart; the console leaked its fade loop here and only canceled the\n // travel — fixed deliberately.\n useEffect(() => {\n if (!flashRects || flashRects.length === 0 || !natural || !container.w || !container.h) {\n // A parent nulling flashRects mid-flash declares the flash over: clear\n // the display (cleanup already canceled both loops) WITHOUT firing\n // onFlashComplete — the parent initiated this, echoing back would loop.\n // (The console coasted here on its leaked fade loop to clear the rect;\n // with the leak fixed, the clear must be explicit.) The prev-identity\n // bail keeps the common null→null path render-free.\n setActiveFlashRects((prev) => (prev === null ? prev : null));\n setFlashOpacity(0);\n return;\n }\n\n const fit = fitScaleFor(natural, container, rotation);\n const target = flashZoomTarget(flashRects, natural, container, rotation, fit);\n\n setActiveFlashRects(flashRects);\n setFlashOpacity(1);\n\n const prefersReduced =\n typeof window !== 'undefined' &&\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n if (prefersReduced) {\n // No travel, no fade: jump to the target and hold the rect long enough\n // to register, then complete. (The stylesheet's reduced-motion block is\n // the CSS backstop; this is the JS half.)\n setTransform(target);\n reducedFlashTimeoutRef.current = setTimeout(() => {\n reducedFlashTimeoutRef.current = null;\n setActiveFlashRects(null);\n setFlashOpacity(0);\n onFlashCompleteRef.current?.();\n }, REDUCED_MOTION_FLASH_MS);\n return () => {\n if (reducedFlashTimeoutRef.current !== null) {\n clearTimeout(reducedFlashTimeoutRef.current);\n reducedFlashTimeoutRef.current = null;\n }\n };\n }\n\n // Travel: capture the from-values ONCE from the render-synced ref (review\n // carry-forward — no state reads inside the rAF loop).\n const from = transformRef.current;\n const zoomStartTime = Date.now();\n const animateZoom = () => {\n const progress = Math.min((Date.now() - zoomStartTime) / ZOOM_ANIMATION_DURATION, 1);\n const eased = easeOutCubic(progress);\n setTransform({\n scale: from.scale + (target.scale - from.scale) * eased,\n tx: from.tx + (target.tx - from.tx) * eased,\n ty: from.ty + (target.ty - from.ty) * eased,\n });\n travelRafRef.current = progress < 1 ? requestAnimationFrame(animateZoom) : null;\n };\n travelRafRef.current = requestAnimationFrame(animateZoom);\n\n // Flash fade, in parallel: 1 - p² over the 1500ms window, then complete.\n const flashStartTime = Date.now();\n const animateFlash = () => {\n const progress = Math.min((Date.now() - flashStartTime) / FLASH_DURATION, 1);\n setFlashOpacity(1 - progress * progress);\n if (progress < 1) {\n fadeRafRef.current = requestAnimationFrame(animateFlash);\n } else {\n fadeRafRef.current = null;\n setActiveFlashRects(null);\n setFlashOpacity(0);\n onFlashCompleteRef.current?.();\n }\n };\n fadeRafRef.current = requestAnimationFrame(animateFlash);\n\n return () => {\n cancelFlashTravel();\n if (fadeRafRef.current !== null) {\n cancelAnimationFrame(fadeRafRef.current);\n fadeRafRef.current = null;\n }\n };\n // container is identity-replaced per resize; depend on its values (like\n // the console) so a same-size measurement can't restart a live flash.\n }, [flashRects, natural, container.w, container.h, rotation, cancelFlashTravel]);\n\n // Cursor is the promise of what a drag will do (console ~371-372): zoom-in\n // while the whole page fits (drag is inert; wheel/double-click zooms), grab\n // once zoomed beyond fit, grabbing mid-pan. CSS maps data-cursor to cursors.\n const cursorMode = atFitScale ? 'zoom-in' : isPanning ? 'grabbing' : 'grab';\n\n // Magnifier loupe (console ~380-431), rotation-aware: invert the current\n // transform to find the image point under the pointer, clamp it inside the\n // image, then re-project it at scale × MAG_ZOOM so that point lands at the\n // loupe's center. The inverse map mirrors zoomAtPoint's — inline here just\n // as it is in the console (presentation math, not gesture math). NOT\n // ported: the console's opacity-0 placeholder div for switch-on/pointer-away\n // (~432-448) — nothing visible ever animated on it, pure dead weight. The\n // inner img is bare (no onLoad/onError): wiring the expiry handler here\n // would double-fire onImageExpired for one dying URL.\n let magnifier: React.ReactNode = null;\n if (magnifierOn && showMag && natural && transform.scale > 0) {\n const rad = (rotation * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n const dx = mousePos.x - transform.tx;\n const dy = mousePos.y - transform.ty;\n const cxRaw = (cosA * dx + sinA * dy) / transform.scale;\n const cyRaw = (-sinA * dx + cosA * dy) / transform.scale;\n const clampedX = Math.max(0, Math.min(cxRaw, natural.w));\n const clampedY = Math.max(0, Math.min(cyRaw, natural.h));\n const zoomScale = transform.scale * MAG_ZOOM;\n const px = clampedX * zoomScale;\n const py = clampedY * zoomScale;\n const rotatedX = px * cosA - py * sinA;\n const rotatedY = px * sinA + py * cosA;\n const translateX = MAG_RADIUS - rotatedX;\n const translateY = MAG_RADIUS - rotatedY;\n magnifier = (\n <div\n className=\"gemina-verification__magnifier\"\n style={{\n width: MAG_RADIUS * 2,\n height: MAG_RADIUS * 2,\n top: mousePos.y - MAG_RADIUS,\n left: mousePos.x - MAG_RADIUS,\n }}\n >\n <img\n src={src}\n alt=\"\"\n draggable={false}\n style={{\n position: 'absolute',\n width: natural.w,\n height: natural.h,\n transformOrigin: '0 0',\n transform: `translate(${translateX}px, ${translateY}px) rotate(${rotation}deg) scale(${zoomScale})`,\n }}\n />\n </div>\n );\n }\n\n return (\n <div className=\"gemina-verification__viewer\">\n <div className=\"gemina-verification__toolbar\">\n <ToolbarButton label=\"Zoom out\" onClick={handleZoomOut}>\n <IconZoomOut />\n </ToolbarButton>\n <ToolbarButton label=\"Zoom in\" onClick={handleZoomIn}>\n <IconZoomIn />\n </ToolbarButton>\n <ToolbarButton label=\"Actual size (100%)\" onClick={handleActualSize}>\n <IconActualSize />\n </ToolbarButton>\n <ToolbarButton label=\"Fit to screen\" onClick={handleFit}>\n <IconFit />\n </ToolbarButton>\n <ToolbarButton label=\"Rotate 90 degrees\" onClick={handleRotate}>\n <IconRotate />\n </ToolbarButton>\n <ToolbarButton\n label=\"Toggle detection overlays\"\n pressed={showRects}\n disabled={!hasRects}\n onClick={() => setShowRects((prev) => !prev)}\n >\n <IconOverlay />\n </ToolbarButton>\n <ToolbarButton\n label=\"Magnifier\"\n checked={magnifierOn}\n onClick={() => setMagnifierOn((prev) => !prev)}\n >\n <IconMagnifier />\n </ToolbarButton>\n </div>\n\n <div\n ref={canvasRef}\n className=\"gemina-verification__canvas\"\n data-cursor={cursorMode}\n // One composite picture to AT: the inner <img>, overlay boxes, flash\n // and loupe are all facets of \"the document image\" — announcing each\n // separately would be noise, so the canvas is the labeled image and\n // everything inside is presentational. The host's `alt` prop names\n // THIS label (the inner img's alt is unread by AT here but kept for\n // non-AT contexts: broken-image text, save/copy affordances).\n role=\"img\"\n aria-label={alt ?? 'Document image'}\n onDoubleClick={handleDoubleClick}\n onMouseDown={handleMouseDown}\n onMouseMove={handleCanvasMouseMove}\n onMouseLeave={handleCanvasMouseLeave}\n onTouchStart={handleTouchStart}\n onTouchMove={handleTouchMove}\n onTouchEnd={handleTouchEnd}\n // The browser cancelling a gesture (edge swipe, notification shade)\n // must reset it exactly like a full lift — a stale touchState would\n // make the NEXT touch continue a dead pan/pinch.\n onTouchCancel={handleTouchEnd}\n >\n {/* Canvas geometry (not layout) — inline by design; CSS owns appearance. */}\n <div\n style={{\n position: 'absolute',\n left: transform.tx,\n top: transform.ty,\n transform: `rotate(${rotation}deg) scale(${transform.scale})`,\n transformOrigin: 'top left',\n willChange: 'transform,left,top',\n }}\n >\n <img\n ref={imgRef}\n src={src}\n alt={alt ?? 'Document'}\n draggable={false}\n onLoad={handleImgLoad}\n onError={handleImgError}\n />\n {/* Detection overlays (toggle-controlled, console ~742-792). Index\n keys are stable here: rect arrays are replaced wholesale and the\n boxes are stateless leaves. Geometry inline; appearance in CSS.\n aria-hidden per rect (badge included): the canvas is one labeled\n image to AT — the \"#N\" chips are visual decoration on it. */}\n {showRects &&\n natural &&\n relativeRects?.map((rect, idx) => {\n const geometry = rectGeometry(rect, natural);\n if (!geometry) return null;\n return (\n <div\n key={`rect-${idx}`}\n className=\"gemina-verification__rect\"\n style={geometry}\n aria-hidden=\"true\"\n >\n <span className=\"gemina-verification__rect-badge\">#{idx + 1}</span>\n </div>\n );\n })}\n {/* Flash overlay (temporary, independent of the toggle). Element-level\n opacity is equivalent to the console's per-channel alpha fade\n modulo overlapping-layer compositing — see the __flash-rect\n comment in styles.ts. aria-hidden: purely decorative highlight. */}\n {activeFlashRects &&\n natural &&\n activeFlashRects.map((rect, idx) => {\n const geometry = rectGeometry(rect, natural);\n if (!geometry) return null;\n return (\n <div\n key={`flash-rect-${idx}`}\n className=\"gemina-verification__flash-rect\"\n style={{ ...geometry, opacity: flashOpacity }}\n aria-hidden=\"true\"\n />\n );\n })}\n </div>\n {magnifier}\n </div>\n </div>\n );\n}\n","/**\n * Pure zoom/rotation math for the verification document viewer.\n *\n * Direct ports from the console's viewer\n * (gemina-console/src/components/viewers/ZoomableImageViewer.tsx):\n * fit scale (lines ~142-149), rotated bounding box (~152-172), centered\n * translation (~174-183), scale clamp + zoom-at-point (~198-230), flash-zoom\n * target (~459-509, math portion), easeOutCubic (~523). Bodies must stay\n * behavior-identical so the elements viewer renders pixel-identically to the\n * console's. No DOM, no React.\n */\n\nexport interface Size {\n w: number;\n h: number;\n}\n\nexport interface Transform {\n scale: number;\n tx: number;\n ty: number;\n}\n\n/** Scale that fits a (possibly rotated) natural size into a container.\n * rotationDeg is expected in multiples of 90; other angles fall back to the\n * unrotated box (matching the console). */\nexport function fitScaleFor(natural: Size, container: Size, rotationDeg: number): number {\n const rot = ((rotationDeg % 180) + 180) % 180;\n const w = rot === 90 ? natural.h : natural.w;\n const h = rot === 90 ? natural.w : natural.h;\n const s = Math.min(container.w / w, container.h / h);\n // The console's memo also early-returns 1 when the container has no size;\n // a zero container makes s = 0 here, so this guard yields the same 1.\n return isFinite(s) && s > 0 ? s : 1;\n}\n\n/** Rotated bounding box extents; minX/minY compensate rotation offsets.\n * rotationDeg is expected in multiples of 90; other angles fall back to the\n * unrotated box (matching the console). zoomAtPoint/flashZoomTarget use real\n * trig and work at any angle. */\nexport function rotatedBox(\n natural: Size,\n scale: number,\n rotationDeg: number,\n): { W: number; H: number; minX: number; minY: number } {\n const w0 = natural.w;\n const h0 = natural.h;\n const s = scale;\n const rot = ((rotationDeg % 360) + 360) % 360;\n switch (rot) {\n case 0:\n return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };\n case 90:\n return { W: h0 * s, H: w0 * s, minX: -h0 * s, minY: 0 };\n case 180:\n return { W: w0 * s, H: h0 * s, minX: -w0 * s, minY: -h0 * s };\n case 270:\n return { W: h0 * s, H: w0 * s, minX: 0, minY: -w0 * s };\n default:\n return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };\n }\n}\n\n/** Translation that centers the rotated image. */\nexport function centeredTranslation(\n natural: Size,\n container: Size,\n scale: number,\n rotationDeg: number,\n): { tx: number; ty: number } {\n const { W, H, minX, minY } = rotatedBox(natural, scale, rotationDeg);\n const nx = (container.w - W) / 2 - minX;\n const ny = (container.h - H) / 2 - minY;\n return { tx: nx, ty: ny };\n}\n\nexport function clampScale(s: number, fitScale: number, max = 8): number {\n return Math.max(fitScale, Math.min(max, s));\n}\n\n/** New transform after zooming by `factor` anchored at container point (px,py). */\nexport function zoomAtPoint(\n current: Transform,\n factor: number,\n px: number,\n py: number,\n rotationDeg: number,\n fitScale: number,\n): Transform {\n const { scale, tx, ty } = current;\n const newScale = clampScale(scale * factor, fitScale);\n if (newScale === scale) return current;\n\n const rad = (rotationDeg * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n\n const dx = px - tx;\n const dy = py - ty;\n const cx = (cosA * dx + sinA * dy) / scale;\n const cy = (-sinA * dx + cosA * dy) / scale;\n\n const ntx = px - (cosA * (newScale * cx) - sinA * (newScale * cy));\n const nty = py - (sinA * (newScale * cx) + cosA * (newScale * cy));\n\n return { scale: newScale, tx: ntx, ty: nty };\n}\n\n/** Target transform for the flash-zoom travel: center the rects' bbox at a\n * comfortable size (100px target, scale clamped to [fitScale, 1.8]). */\nexport function flashZoomTarget(\n rects: Array<{ points: [number, number][] }>,\n natural: Size,\n container: Size,\n rotationDeg: number,\n fitScale: number,\n): Transform {\n // Calculate bounding box of all flash rects (in relative coords 0-1)\n let minX = 1,\n minY = 1,\n maxX = 0,\n maxY = 0;\n for (const rect of rects) {\n for (const [px, py] of rect.points) {\n minX = Math.min(minX, px);\n minY = Math.min(minY, py);\n maxX = Math.max(maxX, px);\n maxY = Math.max(maxY, py);\n }\n }\n\n // Calculate center of the bounding box in image pixel coordinates\n const centerX = ((minX + maxX) / 2) * natural.w;\n const centerY = ((minY + maxY) / 2) * natural.h;\n const bboxWidth = (maxX - minX) * natural.w;\n const bboxHeight = (maxY - minY) * natural.h;\n\n // Calculate target zoom level from a FIXED baseline (not current zoom)\n // Goal: make the field a comfortable, consistent size on screen\n const rad = (rotationDeg * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n\n // Target: make the bbox render at approximately this size\n const TARGET_RENDERED_SIZE = 100; // pixels - comfortable reading size\n\n // Calculate scale needed to render bbox at target size\n // Use the larger dimension to determine scale (so it fits nicely)\n const largerDimension = Math.max(bboxWidth, bboxHeight);\n const scaleForTargetSize = largerDimension > 0 ? TARGET_RENDERED_SIZE / largerDimension : 1;\n\n // Clamp: at least fitScale (don't zoom out), at most 1.8x (reasonable max)\n const targetScale = Math.max(fitScale, Math.min(scaleForTargetSize, 1.8));\n\n // Calculate target position to center on the field\n const newScreenX = cosA * centerX * targetScale - sinA * centerY * targetScale;\n const newScreenY = sinA * centerX * targetScale + cosA * centerY * targetScale;\n const targetTx = container.w / 2 - newScreenX;\n const targetTy = container.h / 2 - newScreenY;\n\n return { scale: targetScale, tx: targetTx, ty: targetTy };\n}\n\n// Ease out cubic for smooth deceleration\nexport const easeOutCubic = (t: number): number => 1 - Math.pow(1 - t, 3);\n","import { VERSION } from '../version';\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-verification and\n// driven by CSS custom properties so host apps can re-theme without touching\n// the DOM. The palette and rhythm deliberately match the chat widget\n// (chat.tsx) so both widgets read as one product when embedded side by side.\n//\n// Design intent: a focused reviewing tool. Document viewer on one pane, form\n// on the other; quiet neutral surfaces everywhere; the confidence dots are the\n// only saturated color in the form, and the overlay blue is reserved for the\n// document canvas. Values are set in tabular numerals so amounts line up with\n// the scanned document the reviewer is comparing them against.\n//\n// Layout uses logical properties exclusively (margin-inline-*, padding-inline,\n// border-block-*) so RTL works for free. Physical left/top appear only inside\n// the viewer canvas, where later tasks position geometry inline from JS —\n// that is geometry, not layout.\n\nconst DARK_VARS = `\n --gemina-verification-bg: #101418;\n --gemina-verification-fg: #e6e9ee;\n --gemina-verification-border: #2a323c;\n --gemina-verification-accent: #4c8dff;\n --gemina-verification-accent-fg: #ffffff;\n --gemina-verification-surface: #1c232b;\n --gemina-verification-muted: #98a2b3;\n --gemina-verification-error: #f97066;\n --gemina-verification-input-bg: #12171d;\n --gemina-verification-input-border: #2a323c;\n --gemina-verification-dirty: #f7b27a;\n`;\n\nconst VERIFICATION_CSS = `\n.gemina-verification {\n --gemina-verification-bg: #ffffff;\n --gemina-verification-fg: #1a1d21;\n --gemina-verification-border: #d9dce1;\n --gemina-verification-accent: #2f6fed;\n --gemina-verification-accent-fg: #ffffff;\n --gemina-verification-surface: #f2f4f7;\n --gemina-verification-muted: #667085;\n --gemina-verification-error: #b42318;\n --gemina-verification-input-bg: #ffffff;\n --gemina-verification-input-border: #d0d5e2;\n --gemina-verification-dirty: #b54708;\n --gemina-verification-confidence-high: #52c41a;\n --gemina-verification-confidence-medium: #faad14;\n --gemina-verification-confidence-low: #ff4d4f;\n --gemina-verification-confidence-unknown: #d9d9d9;\n --gemina-verification-overlay-rgb: 24, 144, 255;\n --gemina-verification-radius: 10px;\n --gemina-verification-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n position: relative; /* anchors __confirm; never overflow:hidden here — it would break the stacked sticky viewer */\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 16px;\n background: var(--gemina-verification-bg);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n font-family: var(--gemina-verification-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-verification *, .gemina-verification *::before, .gemina-verification *::after { box-sizing: border-box; }\n.gemina-verification--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-verification--auto { ${DARK_VARS} }\n}\n.gemina-verification--rtl { direction: rtl; }\n\n/* --- Two-pane layout ------------------------------------------------------ */\n.gemina-verification__panes {\n display: grid;\n grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);\n gap: 16px;\n}\n.gemina-verification--stacked .gemina-verification__panes {\n /* Flex column, NOT a one-column grid: a sticky GRID item is confined to its\n own grid area — whose auto row is exactly its own height, leaving zero\n travel — while a sticky FLEX child's containing block is the whole panes\n box, so the viewer genuinely floats over the form as it scrolls. The gap\n carries over from the base rule. */\n display: flex;\n flex-direction: column;\n}\n.gemina-verification--stacked .gemina-verification__viewer {\n position: sticky;\n top: 0; /* block axis, not inline — RTL-safe */\n z-index: 2;\n /* Cap AND height in one declaration: the canvas is absolutely-positioned\n geometry with no intrinsic height (it contributes only its min-height),\n so a max-block-size alone would never bind — the explicit block-size is\n what the canvas fills. 48vh keeps the majority of a short viewport for\n the form the reviewer is working through; 420px stops a tall narrow\n window from devoting a huge sticky band to the document. The dvh line\n wins where supported (mobile browser chrome shrinks the visual viewport). */\n flex: 0 0 auto;\n block-size: min(48vh, 420px);\n block-size: min(48dvh, 420px);\n}\n.gemina-verification--stacked .gemina-verification__canvas {\n /* The stacked cap owns the height; the side-by-side 280px floor would\n overflow it on short viewports (48vh of a 568px screen is ~273px). */\n min-height: 120px;\n}\n\n/* --- Document viewer ------------------------------------------------------ */\n.gemina-verification__viewer {\n display: flex;\n flex-direction: column;\n min-width: 0;\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n overflow: hidden;\n}\n.gemina-verification__toolbar {\n display: flex;\n /* Narrow roots (~<330px) can't fit all 7 buttons on one line: wrap to a\n second row instead of clipping past the canvas edge. The gap shorthand\n below already provides the 6px row-gap between wrapped rows. */\n flex-wrap: wrap;\n align-items: center;\n gap: 6px;\n flex: 0 0 auto;\n padding: 8px 10px;\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__toolbar-btn {\n font: inherit;\n font-size: 12px;\n padding: 4px 10px;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n border: 1px solid var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-fg);\n cursor: pointer;\n transition: border-color 120ms ease, background-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__toolbar-btn svg { display: block; } /* no inline-baseline slack under the icons */\n.gemina-verification__toolbar-btn:hover:not(:disabled) { border-color: var(--gemina-verification-accent); }\n.gemina-verification__toolbar-btn:disabled { opacity: 0.5; cursor: default; }\n.gemina-verification__toolbar-btn--active {\n background: var(--gemina-verification-accent);\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n.gemina-verification__canvas {\n position: relative;\n flex: 1;\n min-height: 280px;\n overflow: hidden;\n background: var(--gemina-verification-surface);\n touch-action: none;\n cursor: zoom-in; /* initial truth: at fit a drag is inert, wheel/dblclick zooms */\n user-select: none;\n -webkit-user-select: none;\n}\n/* Cursor is the promise of what a drag will do, so it follows viewer state\n (data-cursor), never :active — a bare :active rule would claim \"grabbing\"\n at fit scale where pan never engages. */\n.gemina-verification__canvas[data-cursor='zoom-in'] { cursor: zoom-in; }\n.gemina-verification__canvas[data-cursor='grab'] { cursor: grab; }\n.gemina-verification__canvas[data-cursor='grabbing'] { cursor: grabbing; }\n/* The document image is geometry, not layout: a block box at natural size,\n positioned purely by the JS transform layer above it. */\n.gemina-verification__canvas img {\n display: block;\n max-width: unset;\n max-height: unset;\n}\n/* Overlay geometry (left/top/width/height) is set inline by the viewer from\n transform math; CSS owns only the appearance. */\n.gemina-verification__rect {\n position: absolute;\n z-index: 2;\n pointer-events: none;\n border: 2px solid rgba(var(--gemina-verification-overlay-rgb), 0.85);\n background: rgba(var(--gemina-verification-overlay-rgb), 0.16);\n border-radius: 2px;\n}\n/* Numbered \"#1\" chip on each overlay rect. Physical left/top: the badge lives\n in image coordinate space inside the transform layer (geometry, not layout),\n so it scales and rotates with the document exactly like the console's.\n Explicit line-height pins the chip height across host font stacks. */\n.gemina-verification__rect-badge {\n position: absolute;\n top: -18px;\n left: 0;\n font-size: 11px;\n font-weight: 600;\n line-height: 16px;\n color: rgb(var(--gemina-verification-overlay-rgb));\n background: rgba(255, 255, 255, 0.92); /* floats over the document, not the theme surface */\n padding: 0 6px;\n border-radius: 12px;\n box-shadow: 0 1px 4px rgba(0, 0, 0, 0.16);\n pointer-events: none;\n}\n.gemina-verification__flash-rect {\n /* Fade is driven by JS via element-level opacity (rAF travel animation);\n no CSS animation here so the two never fight. Element-level opacity is\n equivalent to the console's per-channel fade — border (1·o), background\n (0.25·o), glow (0.6·o / 0.3·o) — modulo overlapping-layer compositing:\n per-channel alphas blend border-over-background where they overlap,\n element opacity flattens the group first. Indistinguishable in practice. */\n position: absolute;\n z-index: 3;\n pointer-events: none;\n border: 5px solid rgba(var(--gemina-verification-overlay-rgb), 1);\n background: rgba(var(--gemina-verification-overlay-rgb), 0.25);\n box-shadow: 0 0 20px rgba(var(--gemina-verification-overlay-rgb), 0.6),\n inset 0 0 10px rgba(var(--gemina-verification-overlay-rgb), 0.3);\n border-radius: 2px;\n}\n.gemina-verification__magnifier {\n position: absolute;\n z-index: 4;\n pointer-events: none;\n overflow: hidden;\n border-radius: 50%;\n border: 2px solid rgba(255, 255, 255, 0.85);\n box-shadow: 0 2px 12px rgba(0, 0, 0, 0.35);\n background: var(--gemina-verification-surface);\n}\n\n/* --- Form pane ------------------------------------------------------------ */\n/* A real <form> element (labeled AT landmark) — margin reset guards against\n host/UA form margins. */\n.gemina-verification__form {\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-width: 0;\n margin: 0;\n}\n.gemina-verification__section {\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n overflow: hidden;\n}\n.gemina-verification__section-header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 12px;\n background: var(--gemina-verification-surface);\n border-block-end: 1px solid var(--gemina-verification-border);\n font-size: 13px;\n font-weight: 600;\n}\n.gemina-verification__dl {\n display: grid;\n grid-template-columns: minmax(0, 2fr) minmax(0, 3fr);\n column-gap: 12px;\n margin: 0;\n padding: 8px 12px;\n}\n.gemina-verification__dt {\n display: flex;\n align-items: center;\n gap: 6px;\n padding-block: 5px;\n min-width: 0;\n font-size: 12px;\n color: var(--gemina-verification-muted);\n overflow-wrap: break-word;\n}\n.gemina-verification__dd {\n display: flex;\n align-items: center;\n gap: 6px;\n margin: 0; /* resets the UA's margin-inline-start on <dd> */\n padding-block: 5px;\n min-width: 0;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n overflow-wrap: break-word;\n}\n.gemina-verification__input {\n width: 100%;\n font: inherit;\n font-size: 13px;\n color: var(--gemina-verification-fg);\n background: var(--gemina-verification-input-bg);\n border: 1px solid var(--gemina-verification-input-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n padding: 5px 8px;\n}\n.gemina-verification__input--dirty { border-color: var(--gemina-verification-dirty); }\n.gemina-verification__input--missed {\n border-color: var(--gemina-verification-error);\n box-shadow: 0 0 0 1px var(--gemina-verification-error);\n}\n/* Non-color dirty channel: the word itself is the signal (WCAG 1.4.1) — it\n stays legible when --missed's error border overrides the dirty border. */\n.gemina-verification__edited {\n flex: 0 0 auto;\n font-size: 10px;\n font-weight: 600;\n letter-spacing: 0.06em;\n text-transform: uppercase;\n color: var(--gemina-verification-dirty);\n}\n.gemina-verification__dot {\n display: inline-block;\n flex: 0 0 auto;\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: var(--gemina-verification-confidence-unknown);\n}\n.gemina-verification__dot--high { background: var(--gemina-verification-confidence-high); }\n.gemina-verification__dot--medium { background: var(--gemina-verification-confidence-medium); }\n.gemina-verification__dot--low { background: var(--gemina-verification-confidence-low); }\n.gemina-verification__dot--unknown { background: var(--gemina-verification-confidence-unknown); }\n.gemina-verification__eye {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex: 0 0 auto;\n width: 24px;\n height: 24px;\n padding: 0;\n border: 0;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n transition: background-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__eye:hover {\n color: var(--gemina-verification-accent);\n background: var(--gemina-verification-surface);\n}\n\n/* --- Tables and cards ----------------------------------------------------- */\n/* Section content that is not flush with the section frame (cards, fallback\n details) sits inside this padded body. */\n.gemina-verification__section-body { padding: 8px 12px; }\n/* Flex row for FieldInput's fragment (input + \"edited\" badge) inside <td>s\n and list items — the fragment has no container of its own. */\n.gemina-verification__cell {\n display: flex;\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n/* Simple-list items stack inside a __dd; each item row is a __cell. */\n.gemina-verification__list {\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1 1 auto;\n min-width: 0;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.gemina-verification__table-wrap { overflow-x: auto; }\n.gemina-verification__table {\n width: 100%;\n border-collapse: collapse;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n}\n.gemina-verification__table th {\n text-align: start;\n padding: 6px 10px;\n font-size: 12px;\n font-weight: 600;\n color: var(--gemina-verification-muted);\n background: var(--gemina-verification-surface);\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__table td {\n padding: 6px 10px;\n vertical-align: top;\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__table tr:last-child td { border-block-end: 0; }\n/* Wide tables lean on __table-wrap's scroll; the clamp keeps a cell input\n usable instead of letting the table squeeze it to nothing. */\n.gemina-verification__table .gemina-verification__input { min-width: 6ch; }\n.gemina-verification__card {\n display: flex;\n flex-direction: column;\n gap: 6px;\n padding: 10px 12px;\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n}\n.gemina-verification__card + .gemina-verification__card { margin-block-start: 8px; }\n.gemina-verification__card-header {\n font-size: 12px;\n font-weight: 600;\n color: var(--gemina-verification-muted);\n}\n/* The card already pads; its inner description list must not double it. */\n.gemina-verification__card .gemina-verification__dl { padding: 0; }\n/* Fallback blobs are a native <details>: summary is the toggle, the JSON\n lives in a <pre> so only the code is monospace/pre-wrapped. */\n.gemina-verification__fallback {\n margin: 0;\n padding: 8px 12px;\n font-size: 12px;\n background: var(--gemina-verification-surface);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n}\n.gemina-verification__fallback + .gemina-verification__fallback { margin-block-start: 8px; }\n.gemina-verification__fallback summary {\n cursor: pointer;\n font-weight: 600;\n user-select: none;\n}\n.gemina-verification__fallback pre {\n margin: 0;\n margin-block-start: 8px;\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n white-space: pre-wrap;\n overflow-wrap: break-word;\n overflow-x: auto;\n}\n\n/* --- Messaging, progress, actions ----------------------------------------- */\n.gemina-verification__banner {\n padding: 10px 12px;\n font-size: 13px;\n background: var(--gemina-verification-surface);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n}\n.gemina-verification__banner--error {\n background: transparent;\n border-color: var(--gemina-verification-error);\n color: var(--gemina-verification-error);\n}\n.gemina-verification__progress {\n font-size: 12px;\n color: var(--gemina-verification-muted);\n font-variant-numeric: tabular-nums;\n /* The counts copy (\"N confirmed · M corrected\") is untranslated English\n chrome; under dir=\"rtl\" the RTL paragraph direction reorders its\n leading-number run (\"confirmed · 0 corrected 7\"). plaintext makes the\n line take its base direction from its own first strong character, so\n the English copy lays out LTR inside the RTL widget. The done-state\n recap reuses this same class, so it is covered too. */\n unicode-bidi: plaintext;\n}\n.gemina-verification__footer {\n display: flex;\n align-items: center;\n gap: 10px;\n padding-block-start: 12px;\n border-block-start: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__footer .gemina-verification__submit { margin-inline-start: auto; }\n.gemina-verification__submit {\n font: inherit;\n border: none;\n border-radius: var(--gemina-verification-radius);\n background: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-verification__submit:disabled { opacity: 0.5; cursor: default; }\n.gemina-verification__retry {\n font: inherit;\n font-size: 12px;\n padding: 2px 10px;\n border-radius: var(--gemina-verification-radius);\n border: 1px solid var(--gemina-verification-error);\n background: transparent;\n color: var(--gemina-verification-error);\n cursor: pointer;\n}\n.gemina-verification__state {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 8px;\n min-height: 220px;\n padding: 24px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-verification-muted);\n}\n/* Submit-error banner: message + inline Retry on one line. */\n.gemina-verification__submit-error {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n}\n/* Done: the one saturated moment outside the form — a single accent check. */\n.gemina-verification__state--done { color: var(--gemina-verification-fg); }\n/* Programmatic focus landing (tabIndex -1), not an interactive control: no\n ring — the accent check IS the visual landing; focus moves here purely so\n keyboard/AT users don't drop to <body> when the dialog unmounts. */\n.gemina-verification__state--done:focus,\n.gemina-verification__state--done:focus-visible { outline: none; }\n.gemina-verification__done-check {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n.gemina-verification__done-title {\n font-size: 14px;\n font-weight: 600;\n}\n.gemina-verification__state--done .gemina-verification__progress { font-size: 13px; }\n\n/* --- Confirm dialog ------------------------------------------------------- */\n.gemina-verification__confirm {\n position: absolute;\n inset: 0;\n z-index: 10;\n display: flex;\n /* flex-start + a sticky dialog: the scrim spans the whole component, but the\n dialog slides with the page so it is in view even when the user is\n scrolled deep into a long stacked form. Sticky (not fixed) so it survives\n transformed-ancestor hosts where fixed re-anchors. */\n align-items: flex-start;\n justify-content: center;\n padding: 16px;\n background: rgba(16, 20, 24, 0.45);\n border-radius: var(--gemina-verification-radius);\n}\n.gemina-verification__confirm-dialog {\n position: sticky;\n top: 20vh; /* block axis — RTL-safe */\n display: flex;\n flex-direction: column;\n gap: 12px;\n width: 100%;\n max-width: 380px;\n padding: 16px;\n background: var(--gemina-verification-bg);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n box-shadow: 0 12px 32px rgba(16, 20, 24, 0.24);\n}\n.gemina-verification__confirm-text {\n margin: 0;\n font-size: 13px;\n}\n.gemina-verification__confirm-actions {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n}\n/* Quiet counterpart to __submit: same geometry, bordered, no fill — the\n accent stays on the final action. */\n.gemina-verification__confirm-cancel {\n font: inherit;\n padding: 8px 16px;\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n background: transparent;\n color: var(--gemina-verification-fg);\n cursor: pointer;\n transition: border-color 120ms ease;\n}\n.gemina-verification__confirm-cancel:hover:not(:disabled) {\n border-color: var(--gemina-verification-accent);\n}\n.gemina-verification__confirm-cancel:disabled { opacity: 0.5; cursor: default; }\n\n/* --- Focus ---------------------------------------------------------------- */\n.gemina-verification__input:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: -1px;\n}\n.gemina-verification__toolbar-btn:focus-visible,\n.gemina-verification__eye:focus-visible,\n.gemina-verification__submit:focus-visible,\n.gemina-verification__retry:focus-visible,\n.gemina-verification__confirm-cancel:focus-visible,\n.gemina-verification__fallback summary:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: 1px;\n}\n\n/* --- Reduced motion -------------------------------------------------------- */\n/* The viewer also checks this in JS before animating; the CSS block is the\n backstop that stills the canvas (flash, travel, micro-transitions). */\n@media (prefers-reduced-motion: reduce) {\n .gemina-verification__flash-rect,\n .gemina-verification__rect,\n .gemina-verification__canvas,\n .gemina-verification__canvas * {\n animation: none;\n transition: none;\n }\n}\n`;\n\nconst STYLE_ATTR = 'data-gemina-verification';\n\n/**\n * Inject the verification stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled). Safe to call during SSR: it no-ops\n * when there is no document, and importing this module never touches it.\n */\nexport function ensureVerificationStylesInjected(): 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 = VERIFICATION_CSS;\n document.head.appendChild(style);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;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,K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AA,kBACF,QAAO;AAAA,kBACP,aAAY;AAAA,kBACZ,eAAc;AAAA,kBACd,gBAAe;AAAA;AAAA,cACjB,GACF,GACF;AAAA,cACA,6CAAC,SAAI,WAAU,mCAAmC,2BAAgB;AAAA,cAClE,6CAAC,SAAI,WAAU,iCACZ,aAAG,MAAM,SAAS,mBAAgB,MAAM,SAAS,cACpD;AAAA;AAAA;AAAA,QACF;AAAA,IAEN;AAAA,EACF,GAAG;AAEH,SACE,6CAAC,SAAI,KAAK,SAAS,WAAW,eAAe,KAAK,cAC/C,mBACH;AAEJ;","names":["import_react","import_sdk","escapeSegment","import_react","import_react","import_jsx_runtime","import_jsx_runtime","React","FallbackSection","DARK_VARS","STYLE_ATTR","import_jsx_runtime","HEBREW_RE","SESSION_EXPIRED_TEXT","next"]}
|