@exige/web-scanner-sdk 0.2.27 → 0.2.29
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 +4 -4
- package/dist/assets/document-worker.js +1 -1
- package/dist/assets/document-worker.js.map +1 -1
- package/dist/assets/zxing-wasm.LICENSE +21 -0
- package/dist/assets/zxing-wasm.NOTICE +4 -0
- package/dist/assets/zxing_reader.wasm +0 -0
- package/dist/assets-manifest.json +2 -1
- package/dist/driver-license-CKMrW8dP.js +2876 -0
- package/dist/driver-license-CKMrW8dP.js.map +1 -0
- package/dist/index.d.ts +7 -1
- package/dist/react/context.d.ts +1 -1
- package/dist/react/types.d.ts +28 -2
- package/dist/react.d.ts +1 -1
- package/dist/react.js +435 -342
- package/dist/react.js.map +1 -1
- package/dist/scanner-sdk.js +17 -924
- package/dist/scanner-sdk.js.map +1 -1
- package/dist/sdk/aamva.d.ts +58 -0
- package/dist/sdk/barcode.d.ts +12 -0
- package/dist/sdk/camera.d.ts +8 -1
- package/dist/sdk/driver-license.d.ts +63 -0
- package/dist/sdk/finder.d.ts +21 -1
- package/dist/sdk/ort-runtime.d.ts +2 -1
- package/dist/sdk/scan.d.ts +5 -0
- package/dist/sdk/zxing-runtime.d.ts +22 -0
- package/package.json +4 -2
- package/dist/finder-BlN89ZeT.js +0 -1484
- package/dist/finder-BlN89ZeT.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"finder-BlN89ZeT.js","names":[],"sources":["../src/sdk/errors.ts","../src/sdk/license-codec.ts","../src/sdk/license-public-key.ts","../src/sdk/license-runtime.ts","../src/sdk/license.ts","../src/sdk/model-download.ts","../src/sdk/ort-runtime.ts","../src/sdk/image.ts","../src/sdk/scan.ts","../src/sdk/camera.ts","../src/sdk/lighting.ts","../src/sdk/finder.ts"],"sourcesContent":["/**\n * Operational failure from the scanner runtime.\n *\n * Scan quality stays a returned status (`success`, `no-document`,\n * `low-confidence`, or `low-quality`). Redaction match quality stays\n * `success`, `partial`, or `unmatched`. Neither of those outcomes uses this error.\n * A bad image does not throw.\n */\nexport type ScannerErrorCode =\n | 'secure-context'\n | 'worker'\n | 'model-http'\n | 'language'\n | 'canvas'\n\nexport class ScannerError extends Error {\n readonly code: ScannerErrorCode\n\n constructor(code: ScannerErrorCode, message: string) {\n super(message)\n this.name = 'ScannerError'\n this.code = code\n }\n}\n\nexport function canvasUnavailable(): ScannerError {\n return new ScannerError('canvas', 'Canvas 2D is unavailable in this browser.')\n}\n","export function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '')\n}\n\nexport function base64UrlToBytes(value: string): Uint8Array {\n const normalized = value.replaceAll('-', '+').replaceAll('_', '/')\n const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)\n const binary = atob(padded)\n const bytes = new Uint8Array(binary.length)\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index)\n }\n return bytes\n}\n","/**\n * Raw Ed25519 public key: 32 bytes, base64url, no padding.\n *\n * The license portal signs with `LICENSE_SIGNING_PRIVATE_KEY`.\n * Generate a pair with `npm run generate-keypair --prefix license-portal`,\n * then replace this constant with the printed public key and rebuild the\n * library. Never commit the private key.\n */\nexport const LICENSE_PUBLIC_KEY_BASE64 = 'uFpA_UXGk-1AjjG31cFP6cqXOQX0w2TnuR7Bl-msZ6I'\n","import { base64UrlToBytes } from './license-codec'\nimport { LICENSE_PUBLIC_KEY_BASE64 } from './license-public-key'\n\n/** Public key embedded in the published package. Tests replace this module. */\nexport function embeddedLicensePublicKey(): Uint8Array {\n return base64UrlToBytes(LICENSE_PUBLIC_KEY_BASE64)\n}\n","import { base64UrlToBytes } from './license-codec'\nimport { embeddedLicensePublicKey } from './license-runtime'\n\n/**\n * Hosts that may use the SDK before a paid license exists.\n * Add a production hostname here when it should run without a signed key.\n *\n * An entry is either an exact hostname or a single `*.suffix` pattern.\n * `*.exige.io` matches `exige.io` and any host that ends with `.exige.io`.\n * It does not match `exige.io.evil.com`. `*.localhost` is the only\n * single-label suffix; `app.localhost` is allowed. Ngrok tunnel suffixes\n * are allowed. Nothing here allows `*.vercel.app`. Paid license `domains`\n * stay exact hostnames.\n */\nexport const DEV_LICENSE_HOSTS = [\n 'localhost',\n '127.0.0.1',\n 'exige-scanner-sdk.vercel.app',\n '*.localhost',\n '*.exige.io',\n '*.ngrok.io',\n '*.ngrok.app',\n '*.ngrok.dev',\n '*.ngrok-free.app',\n '*.ngrok-free.dev',\n] as const\n\nexport const LICENSE_FEATURES = ['scan', 'ocr', 'redaction', 'vehicles', 'torch'] as const\n\nexport type LicenseFeature = (typeof LICENSE_FEATURES)[number]\n\nexport type LicenseErrorCode =\n | 'missing'\n | 'malformed'\n | 'invalid-signature'\n | 'expired'\n | 'domain'\n | 'feature'\n\nexport interface LicenseFeatures {\n scan: boolean\n ocr: boolean\n redaction: boolean\n /**\n * Kept so existing signed keys still verify.\n * No camera, finder, scan, OCR, or redaction entry point asserts this flag.\n */\n vehicles: boolean\n torch: boolean\n}\n\nexport interface LicenseClaims {\n customerId: string\n /** Exact hostnames. `localhost` and `127.0.0.1` are included only when listed. */\n domains: string[]\n /** Unix expiry in seconds. The key is valid while `now < exp`. */\n exp: number\n features: LicenseFeatures\n}\n\n/**\n * Compact signed payload: `base64url(json).base64url(ed25519 signature)`.\n * The signature covers the raw JSON bytes. Public APIs do not accept a\n * caller-supplied public key or hostname.\n */\nexport interface LicenseVerification {\n publicKey: Uint8Array\n /** Injected only for Node tests. Browsers use `location.hostname`. */\n hostname: string\n /** Unix time in seconds. */\n now: number\n}\n\nexport class LicenseError extends Error {\n readonly code: LicenseErrorCode\n\n constructor(code: LicenseErrorCode, message: string) {\n super(message)\n this.name = 'LicenseError'\n this.code = code\n }\n}\n\nlet activeToken: string | undefined\nlet activeClaims: LicenseClaims | undefined\n\nexport function normalizeHostname(value: string): string {\n return value.trim().toLowerCase().replace(/\\.$/u, '')\n}\n\n/**\n * Canonical JSON signed by the license portal. Key order is part of the\n * signature bytes. Keep this in lockstep with `license-portal/lib/license-token.ts`.\n */\nexport function canonicalLicensePayload(claims: LicenseClaims): string {\n const domains = [...new Set(claims.domains.map(normalizeHostname).filter(Boolean))].sort()\n const features = {\n ocr: claims.features.ocr === true,\n redaction: claims.features.redaction === true,\n scan: claims.features.scan === true,\n torch: claims.features.torch === true,\n vehicles: claims.features.vehicles === true,\n }\n return JSON.stringify({\n customerId: claims.customerId,\n domains,\n exp: claims.exp,\n features,\n })\n}\n\nfunction readBrowserHostname(): string | undefined {\n const host = (globalThis as { location?: { hostname?: string } }).location?.hostname\n if (typeof host !== 'string') return undefined\n const normalized = normalizeHostname(host)\n return normalized || undefined\n}\n\nfunction unixNow(): number {\n return Math.floor(Date.now() / 1000)\n}\n\nfunction matchesDevLicenseEntry(hostname: string, entry: string): boolean {\n const pattern = normalizeHostname(entry)\n if (pattern.startsWith('*.')) {\n const suffix = pattern.slice(2)\n const allowSingleLabel = suffix === 'localhost'\n if ((!suffix.includes('.') && !allowSingleLabel) || suffix.startsWith('.') || suffix.includes('*')) {\n return false\n }\n return hostname === suffix || hostname.endsWith(`.${suffix}`)\n }\n return hostname === pattern\n}\n\nfunction isDevLicenseHost(hostname: string): boolean {\n const host = normalizeHostname(hostname)\n if (!host || host.includes('*')) return false\n return DEV_LICENSE_HOSTS.some((entry) => matchesDevLicenseEntry(host, entry))\n}\n\n/** All features, only for the host that matched `DEV_LICENSE_HOSTS`. */\nfunction developmentLicense(hostname: string): LicenseClaims {\n return {\n customerId: 'dev',\n domains: [hostname],\n exp: 4_102_444_800,\n features: {\n scan: true,\n ocr: true,\n redaction: true,\n vehicles: true,\n torch: true,\n },\n }\n}\n\nfunction copyClaims(claims: LicenseClaims): LicenseClaims {\n return {\n customerId: claims.customerId,\n domains: [...claims.domains],\n exp: claims.exp,\n features: { ...claims.features },\n }\n}\n\nfunction malformed(message = 'This license key is not a signed payload.'): LicenseError {\n return new LicenseError('malformed', message)\n}\n\nfunction parseClaims(payload: unknown): LicenseClaims {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw malformed()\n const record = payload as Record<string, unknown>\n if (typeof record.customerId !== 'string' || record.customerId.trim() === '' || record.customerId.length > 200) {\n throw malformed('This license key is missing a customer id.')\n }\n if (!Array.isArray(record.domains) || record.domains.some((domain) => typeof domain !== 'string')) {\n throw malformed('This license key is missing a domain list.')\n }\n if (typeof record.exp !== 'number' || !Number.isSafeInteger(record.exp) || record.exp <= 0) {\n throw malformed('This license key is missing a Unix expiry.')\n }\n if (!record.features || typeof record.features !== 'object' || Array.isArray(record.features)) {\n throw malformed('This license key is missing feature flags.')\n }\n const flags = record.features as Record<string, unknown>\n const domains = [...new Set(record.domains.map((domain) => normalizeHostname(domain)).filter(Boolean))].sort()\n return {\n customerId: record.customerId.trim(),\n domains,\n exp: record.exp,\n features: {\n scan: flags.scan === true,\n ocr: flags.ocr === true,\n redaction: flags.redaction === true,\n vehicles: flags.vehicles === true,\n torch: flags.torch === true,\n },\n }\n}\n\n/**\n * Verifies a compact license. Hostname and public key are explicit so Node\n * tests can inject them. Published entry points call `assertLicense`, which\n * always uses the embedded public key and `location.hostname`.\n */\nexport async function verifyLicenseToken(\n licenseKey: string,\n verification: LicenseVerification,\n): Promise<LicenseClaims> {\n const parts = licenseKey.trim().split('.')\n if (parts.length !== 2 || !parts[0] || !parts[1]) throw malformed()\n let payloadBytes: Uint8Array\n let signature: Uint8Array\n try {\n payloadBytes = base64UrlToBytes(parts[0])\n signature = base64UrlToBytes(parts[1])\n } catch {\n throw malformed()\n }\n let key: CryptoKey\n let valid = false\n try {\n key = await crypto.subtle.importKey(\n 'raw',\n verification.publicKey as BufferSource,\n { name: 'Ed25519' },\n false,\n ['verify'],\n )\n valid = await crypto.subtle.verify('Ed25519', key, signature as BufferSource, payloadBytes as BufferSource)\n } catch {\n valid = false\n }\n if (!valid) {\n throw new LicenseError('invalid-signature', 'This license key signature does not match the SDK public key.')\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(new TextDecoder().decode(payloadBytes))\n } catch {\n throw malformed()\n }\n const claims = parseClaims(parsed)\n if (claims.exp <= verification.now) {\n throw new LicenseError('expired', 'This license key has expired.')\n }\n const hostname = normalizeHostname(verification.hostname)\n if (!hostname || !claims.domains.includes(hostname)) {\n throw new LicenseError('domain', `This license key is not valid for ${hostname || 'this host'}.`)\n }\n return claims\n}\n\n/**\n * Verifies `licenseKey` for the current page and keeps it for later calls.\n *\n * @throws {LicenseError} LicenseError when the key is missing, malformed, badly signed,\n * expired, or not issued for `location.hostname`.\n */\nexport async function setLicenseKey(licenseKey: string): Promise<LicenseClaims> {\n const hostname = readBrowserHostname()\n if (!hostname) {\n throw new LicenseError('domain', 'The license check requires a browser hostname.')\n }\n const claims = await verifyLicenseToken(licenseKey, {\n publicKey: embeddedLicensePublicKey(),\n hostname,\n now: unixNow(),\n })\n activeToken = licenseKey.trim()\n activeClaims = claims\n return copyClaims(claims)\n}\n\n/**\n * Feature flags from the key most recently accepted by `setLicenseKey`.\n * Returns null when no key is loaded, the key is expired, or this hostname\n * is not on the key. Enforcement still re-checks the signature in `assertLicense`.\n */\nexport function getLicense(): LicenseClaims | null {\n const hostname = readBrowserHostname()\n if (activeClaims && hostname && activeClaims.domains.includes(hostname) && activeClaims.exp > unixNow()) {\n return copyClaims(activeClaims)\n }\n if (!activeToken && hostname && isDevLicenseHost(hostname)) return copyClaims(developmentLicense(hostname))\n return null\n}\n\n/**\n * Fail-closed gate used by the public camera, finder, scan, OCR, and\n * redaction entry points.\n *\n * @throws {LicenseError} LicenseError before those APIs do any work, when the key is\n * missing, invalid, or missing `feature`.\n */\nexport async function assertLicense(feature: LicenseFeature): Promise<LicenseClaims> {\n const hostname = readBrowserHostname()\n if (!hostname) {\n throw new LicenseError('domain', 'The license check requires a browser hostname.')\n }\n if (!activeToken) {\n if (isDevLicenseHost(hostname)) return copyClaims(developmentLicense(hostname))\n throw new LicenseError(\n 'missing',\n 'A license key is required. Call setLicenseKey() before using the scanner SDK.',\n )\n }\n const claims = await verifyLicenseToken(activeToken, {\n publicKey: embeddedLicensePublicKey(),\n hostname,\n now: unixNow(),\n })\n activeClaims = claims\n if (!claims.features[feature]) {\n throw new LicenseError('feature', `This license key does not include the ${feature} feature.`)\n }\n return copyClaims(claims)\n}\n\n/** Drops the in-memory key. Not part of the published package entry. */\nexport function clearLicenseForTests(): void {\n activeToken = undefined\n activeClaims = undefined\n}\n","import { ScannerError } from './errors'\n\nexport interface ModelDownloadProgress {\n loaded: number\n /** Byte length from Content-Length. Null when that header is absent. */\n total: number | null\n done?: boolean\n}\n\nexport interface ModelDownloadSnapshot {\n downloading: boolean\n loaded: number\n /** Sum of Content-Length values when every active transfer has one. */\n total: number | null\n}\n\nconst STORE = Symbol.for('exige.web-scanner-sdk.model-downloads')\n\ninterface ModelDownloadStore {\n active: Map<string, { loaded: number; total: number | null }>\n listeners: Set<(snapshot: ModelDownloadSnapshot) => void>\n cache: Map<string, ArrayBuffer>\n inflight: Map<string, Promise<ArrayBuffer>>\n}\n\n/** One store across the package entry and the React entry. */\nfunction store(): ModelDownloadStore {\n const scope = globalThis as typeof globalThis & { [STORE]?: ModelDownloadStore }\n if (!scope[STORE]) {\n scope[STORE] = {\n active: new Map(),\n listeners: new Set(),\n cache: new Map(),\n inflight: new Map(),\n }\n }\n return scope[STORE]\n}\n\nconst active = store().active\nconst listeners = store().listeners\nconst cache = store().cache\nconst inflight = store().inflight\n\nfunction contentLength(response: Response) {\n const parsed = Number(response.headers.get('content-length'))\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null\n}\n\nexport function modelDownloadSnapshot(): ModelDownloadSnapshot {\n if (active.size === 0) return { downloading: false, loaded: 0, total: null }\n let loaded = 0\n let total = 0\n let known = true\n for (const item of active.values()) {\n loaded += item.loaded\n if (item.total == null) known = false\n else total += item.total\n }\n return { downloading: true, loaded, total: known ? total : null }\n}\n\nfunction emit() {\n const snapshot = modelDownloadSnapshot()\n for (const listener of listeners) listener(snapshot)\n}\n\n/** Subscribing does not fetch. The document worker and `downloadModelBytes` report into the same snapshot. */\nexport function subscribeModelDownloads(listener: (snapshot: ModelDownloadSnapshot) => void) {\n listener(modelDownloadSnapshot())\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n}\n\n/** Progress reported from another realm, such as the document worker. */\nexport function reportModelDownload(url: string, progress: ModelDownloadProgress) {\n if (progress.done) active.delete(url)\n else active.set(url, { loaded: progress.loaded, total: progress.total })\n emit()\n}\n\nexport async function readResponseBytes(\n response: Response,\n onProgress?: (progress: ModelDownloadProgress) => void,\n) {\n const total = contentLength(response)\n if (!response.body) {\n const bytes = await response.arrayBuffer()\n onProgress?.({ loaded: bytes.byteLength, total: total ?? bytes.byteLength })\n return bytes\n }\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let loaded = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (!value?.byteLength) continue\n chunks.push(value)\n loaded += value.byteLength\n onProgress?.({ loaded, total })\n }\n const bytes = new Uint8Array(loaded)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n if (loaded === 0) onProgress?.({ loaded: 0, total })\n return bytes.buffer\n}\n\n/**\n * Fetch a model file and report loaded/total while the body transfers.\n * A second call for the same URL reuses the cached bytes and does not fetch.\n */\nexport async function downloadModelBytes(url: string, init?: { cache?: RequestCache }) {\n const cached = cache.get(url)\n if (cached) return cached.slice(0)\n const existing = inflight.get(url)\n if (existing) return existing.then((bytes) => bytes.slice(0))\n const request = (async () => {\n reportModelDownload(url, { loaded: 0, total: null })\n const response = await fetch(url, { cache: init?.cache })\n if (!response.ok) {\n throw new ScannerError('model-http', `Model request failed with HTTP ${response.status}.`)\n }\n return readResponseBytes(response, (progress) => reportModelDownload(url, progress))\n })()\n inflight.set(url, request)\n try {\n const bytes = await request\n cache.set(url, bytes)\n return bytes.slice(0)\n } finally {\n inflight.delete(url)\n if (active.has(url)) {\n active.delete(url)\n emit()\n }\n }\n}\n","/**\n * ONNX Runtime Web 1.30 extern-wasm JSEP build. Document finding uses WASM.\n * Literal `new URL` calls are what Webpack and Turbopack copy.\n */\nexport const packagedOrtWasmFile = new URL(\n './runtime/ort-wasm-simd-threaded.jsep.wasm',\n import.meta.url,\n)\nexport const packagedOrtWasmGlue = new URL(\n './runtime/ort-wasm-simd-threaded.jsep.mjs',\n import.meta.url,\n)\n\nexport type {\n OrtLoadSource,\n OrtImporter,\n OrtModule,\n OrtWasmPaths,\n PackagedOrtWasmPaths,\n} from './ort-cdn'\nexport {\n LAST_RESORT_ORT_CDN_BASE,\n ORT_JS_FILENAME,\n ORT_WASM_FILENAME,\n ORT_WASM_MJS_FILENAME,\n PINNED_ONNXRUNTIME_WEB_VERSION,\n PREFERRED_ORT_CDN_BASE,\n SIBLING_ORT_MODULE,\n expandOrtWasmPaths,\n importOrtSpecifier,\n joinOrtCdnUrl,\n loadOrtJsFromPinnedCdn,\n loadOrtRuntime,\n pinnedOrtJsUrls,\n pinnedOrtWasmPaths,\n probeHttpUrl,\n probeOrtWasmPaths,\n resolveUsableOrtWasmPaths,\n siblingOrtUrl,\n} from './ort-cdn'\n\nimport { type OrtWasmPaths, type PackagedOrtWasmPaths } from './ort-cdn'\n\nexport function packagedOrtWasmPaths(): PackagedOrtWasmPaths {\n return {\n wasm: packagedOrtWasmFile.href,\n mjs: packagedOrtWasmGlue.href,\n }\n}\n\n/** Uses the packaged wasm pair when the override is missing or blank. */\nexport function resolveOrtWasmPaths(value?: OrtWasmPaths): OrtWasmPaths {\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (trimmed) return trimmed\n return packagedOrtWasmPaths()\n }\n if (value?.wasm.trim() && value.mjs.trim()) {\n return { wasm: value.wasm.trim(), mjs: value.mjs.trim() }\n }\n return packagedOrtWasmPaths()\n}\n","import { canvasUnavailable } from './errors'\nimport type { ImageSource } from './types'\n\nexport interface CanvasSourceOptions {\n cloneCanvas?: boolean\n maxDimension?: number\n}\n\nfunction scaledSize(width: number, height: number, maxDimension?: number) {\n const scale = maxDimension ? Math.min(1, maxDimension / Math.max(width, height)) : 1\n return {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n}\n\nasync function blobToImage(blob: Blob) {\n const url = URL.createObjectURL(blob)\n try {\n const image = new Image()\n image.src = url\n await image.decode()\n return image\n } finally {\n URL.revokeObjectURL(url)\n }\n}\n\nexport async function sourceToCanvas(\n source: ImageSource,\n options: CanvasSourceOptions = {},\n): Promise<HTMLCanvasElement> {\n if (source instanceof HTMLCanvasElement && options.cloneCanvas === false && !options.maxDimension) {\n return source\n }\n const canvas = document.createElement('canvas')\n const context = canvas.getContext('2d', { willReadFrequently: true })\n if (!context) throw canvasUnavailable()\n\n if (source instanceof Blob) {\n if ('createImageBitmap' in window) {\n try {\n const bitmap = await createImageBitmap(source)\n const size = scaledSize(bitmap.width, bitmap.height, options.maxDimension)\n canvas.width = size.width\n canvas.height = size.height\n context.drawImage(bitmap, 0, 0, size.width, size.height)\n bitmap.close()\n return canvas\n } catch {\n // Fall through to HTMLImageElement decoding for iOS/WebKit formats.\n }\n }\n source = await blobToImage(source)\n }\n\n const width = source instanceof HTMLImageElement ? source.naturalWidth : source.width\n const height = source instanceof HTMLImageElement ? source.naturalHeight : source.height\n if (!width || !height) throw new Error('The image has no readable dimensions.')\n const size = scaledSize(width, height, options.maxDimension)\n canvas.width = size.width\n canvas.height = size.height\n context.drawImage(source, 0, 0, size.width, size.height)\n return canvas\n}\n\nexport function canvasToBlob(\n canvas: HTMLCanvasElement,\n type = 'image/png',\n quality = 0.92,\n): Promise<Blob> {\n return new Promise((resolve, reject) =>\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error('Could not encode the image.'))),\n type,\n quality,\n ),\n )\n}\n\nexport function clampBox(\n box: { x: number; y: number; width: number; height: number },\n width: number,\n height: number,\n) {\n const x = Math.max(0, Math.min(width, box.x))\n const y = Math.max(0, Math.min(height, box.y))\n return {\n x,\n y,\n width: Math.max(0, Math.min(width - x, box.width)),\n height: Math.max(0, Math.min(height - y, box.height)),\n }\n}\n","import { canvasUnavailable, ScannerError } from './errors'\nimport { assertLicense } from './license'\nimport { reportModelDownload } from './model-download'\nimport { resolveOrtWasmPaths, type OrtWasmPaths } from './ort-runtime'\nimport { sourceToCanvas } from './image'\nimport type {\n DocumentCorners,\n DocumentDetectionResult,\n DocumentModelStatus,\n DocumentQuad,\n ImageSource,\n Point,\n ScanResult,\n} from './types'\n\nexport interface ScanOptions {\n minDimension?: number\n minConfidence?: number\n maxAnalysisDimension?: number\n maxOutputDimension?: number\n useWorker?: boolean\n /**\n * DocAligner checkpoint URL. Omit this. The default is the Exige CDN\n * DocAligner model (`DEFAULT_DOCUMENT_MODEL_URL`).\n */\n modelUrl?: string\n /** Heatmap threshold used before largest-component corner centroids. */\n heatmapThreshold?: number\n /** Reuse model bytes through the browser HTTP cache. */\n cacheModel?: boolean\n /**\n * ONNX Runtime wasm override. Omit this. The default is the packaged\n * `ort-wasm-simd-threaded.jsep.wasm` and `.mjs` files.\n * A string is a directory that contains both files. An object sets each URL.\n */\n ortWasmPaths?: OrtWasmPaths\n}\n\nexport const DEFAULT_DOCUMENT_MODEL_URL =\n 'https://exige-scanner-sdk.vercel.app/models/docaligner-lcnet100-f4117b78.onnx'\nexport const TALL_PAGE_ASPECT = 1.6\nexport const TALL_PAGE_ANALYSIS_DIMENSION = 1280\n/** Matches `STILL_MAX_EDGE`. Mobile no longer crushes crops to 2048. */\nexport const DEFAULT_OUTPUT_DIMENSION = 4096\n\nexport function analysisDimensionForSource(\n width: number,\n height: number,\n requested?: number,\n) {\n if (requested) return requested\n const longEdge = Math.max(width, height)\n const shortEdge = Math.max(1, Math.min(width, height))\n const aspect = longEdge / shortEdge\n const base = isMobileClassDevice() ? 560 : 900\n if (aspect >= TALL_PAGE_ASPECT) {\n return Math.min(longEdge, Math.max(base, TALL_PAGE_ANALYSIS_DIMENSION))\n }\n return base\n}\n\nexport function resolveDocumentModelUrl(modelUrl?: string) {\n return modelUrl?.trim() || DEFAULT_DOCUMENT_MODEL_URL\n}\n\ninterface WorkerAnalysis {\n sharpness: number\n candidate?: { corners: DocumentCorners; confidence: number }\n detector?: 'ml'\n modelStatus?: DocumentModelStatus\n modelProvider?: 'webgpu' | 'wasm'\n modelError?: string\n modelNote?: string\n inferenceMs?: number\n}\n\nconst MIN_DOCUMENT_SHARPNESS = 3\n\nlet analysisWorker: Worker | undefined\nlet analysisRequestId = 0\nconst analysisRequests = new Map<number, {\n resolve: (analysis: WorkerAnalysis) => void\n reject: (error: Error) => void\n}>()\n\nfunction distance(a: Point, b: Point) {\n return Math.hypot(a.x - b.x, a.y - b.y)\n}\n\nfunction toQuad(corners: DocumentCorners): DocumentQuad {\n return {\n ...corners,\n edges: {\n top: { start: corners.topLeft, end: corners.topRight },\n right: { start: corners.topRight, end: corners.bottomRight },\n bottom: { start: corners.bottomRight, end: corners.bottomLeft },\n left: { start: corners.bottomLeft, end: corners.topLeft },\n },\n }\n}\n\nfunction scaleCorners(corners: DocumentCorners, scale: number): DocumentCorners {\n const resize = (point: Point) => ({ x: point.x / scale, y: point.y / scale })\n return {\n topLeft: resize(corners.topLeft),\n topRight: resize(corners.topRight),\n bottomRight: resize(corners.bottomRight),\n bottomLeft: resize(corners.bottomLeft),\n }\n}\n\nfunction isMobileClassDevice() {\n if (typeof navigator === 'undefined') return false\n return navigator.maxTouchPoints > 0 || navigator.hardwareConcurrency <= 4 ||\n (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches)\n}\n\nfunction analyzeInWorker(\n pixels: Uint8ClampedArray,\n width: number,\n height: number,\n options: ScanOptions,\n): Promise<WorkerAnalysis> {\n return new Promise((resolve, reject) => {\n if (!analysisWorker) {\n analysisWorker = new Worker(new URL('./document-worker.ts', import.meta.url), { type: 'module' })\n analysisWorker.onmessage = (event: MessageEvent<{\n id: number\n result?: WorkerAnalysis\n error?: string\n errorCode?: ScannerError['code']\n download?: { url: string; loaded: number; total: number | null; done?: boolean }\n }>) => {\n if (event.data.download?.url) {\n reportModelDownload(event.data.download.url, event.data.download)\n return\n }\n const pending = analysisRequests.get(event.data.id)\n if (!pending) return\n analysisRequests.delete(event.data.id)\n if (event.data.error) {\n pending.reject(event.data.errorCode\n ? new ScannerError(event.data.errorCode, event.data.error)\n : new Error(event.data.error))\n }\n else if (event.data.result) pending.resolve(event.data.result)\n else pending.reject(new Error('The document worker returned no result.'))\n }\n analysisWorker.onerror = () => {\n const error = new ScannerError('worker', 'The document worker could not start.')\n for (const pending of analysisRequests.values()) pending.reject(error)\n analysisRequests.clear()\n analysisWorker?.terminate()\n analysisWorker = undefined\n }\n }\n const id = ++analysisRequestId\n analysisRequests.set(id, { resolve, reject })\n const transferable = pixels.slice().buffer\n analysisWorker.postMessage({\n id,\n pixels: transferable,\n width,\n height,\n modelUrl: resolveDocumentModelUrl(options.modelUrl),\n heatmapThreshold: options.heatmapThreshold,\n cacheModel: options.cacheModel,\n ortWasmPaths: resolveOrtWasmPaths(options.ortWasmPaths),\n }, [transferable])\n })\n}\n\nasync function analyzeCanvas(\n canvas: HTMLCanvasElement,\n options: ScanOptions,\n): Promise<DocumentDetectionResult> {\n const { width, height } = canvas\n const minDimension = options.minDimension ?? 360\n if (Math.min(width, height) < minDimension) {\n return {\n status: 'low-quality',\n confidence: 0,\n message: `Use an image at least ${minDimension}px on its shortest side.`,\n sourceWidth: width,\n sourceHeight: height,\n }\n }\n\n const analysisDimension = analysisDimensionForSource(\n width,\n height,\n options.maxAnalysisDimension,\n )\n const scale = Math.min(1, analysisDimension / Math.max(width, height))\n const sample = document.createElement('canvas')\n sample.width = Math.max(1, Math.round(width * scale))\n sample.height = Math.max(1, Math.round(height * scale))\n const context = sample.getContext('2d', { willReadFrequently: true })\n if (!context) throw canvasUnavailable()\n context.drawImage(canvas, 0, 0, sample.width, sample.height)\n const pixels = context.getImageData(0, 0, sample.width, sample.height).data\n let analysis: WorkerAnalysis\n if (options.useWorker !== false && typeof Worker !== 'undefined') {\n try {\n analysis = await analyzeInWorker(\n pixels,\n sample.width,\n sample.height,\n options,\n )\n } catch (error) {\n if (\n error instanceof ScannerError &&\n (error.code === 'worker' || error.code === 'model-http')\n ) {\n throw error\n }\n const message = error instanceof Error ? error.message : 'Document worker failed.'\n analysis = {\n sharpness: 20,\n detector: 'ml',\n modelStatus: 'failed',\n modelError: message,\n }\n }\n } else {\n analysis = {\n sharpness: 20,\n detector: 'ml',\n modelStatus: 'failed',\n modelError: 'ML detection requires a Web Worker.',\n }\n }\n const {\n sharpness,\n candidate,\n detector,\n modelStatus,\n modelProvider,\n modelError,\n modelNote,\n inferenceMs,\n } = analysis\n const detectorMetadata = {\n detector,\n modelStatus,\n modelProvider,\n modelError,\n modelNote,\n inferenceMs,\n }\n if (sharpness < MIN_DOCUMENT_SHARPNESS) {\n return {\n status: 'low-quality',\n confidence: Math.min(0.3, sharpness / 18),\n message: 'The image is too soft or dark to resolve four document edges.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n }\n\n if (!candidate) {\n return {\n status: 'no-document',\n confidence: 0,\n message: 'No document corners found. Place all four edges on a contrasting surface.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n }\n\n const corners = scaleCorners(candidate.corners, scale)\n const quad = toQuad(corners)\n const minimumConfidence = options.minConfidence ?? 0.58\n if (candidate.confidence < minimumConfidence) {\n return {\n status: 'low-confidence',\n quad,\n corners,\n confidence: candidate.confidence,\n message: 'Four possible corners were found, but the geometry is not reliable enough to crop.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n }\n return {\n status: 'success',\n quad,\n corners,\n confidence: candidate.confidence,\n message: 'Four document edges detected.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n}\n\nexport function perspectiveOutputSize(corners: DocumentCorners, maxDimension: number) {\n const naturalWidth = Math.max(\n 1,\n Math.round(Math.max(\n distance(corners.topLeft, corners.topRight),\n distance(corners.bottomLeft, corners.bottomRight),\n )),\n )\n const naturalHeight = Math.max(\n 1,\n Math.round(Math.max(\n distance(corners.topLeft, corners.bottomLeft),\n distance(corners.topRight, corners.bottomRight),\n )),\n )\n const outputScale = Math.min(1, maxDimension / Math.max(naturalWidth, naturalHeight))\n return {\n width: Math.max(1, Math.round(naturalWidth * outputScale)),\n height: Math.max(1, Math.round(naturalHeight * outputScale)),\n }\n}\n\nexport function sampleBilinear(\n pixels: Uint8ClampedArray,\n width: number,\n height: number,\n x: number,\n y: number,\n) {\n const clampedX = Math.max(0, Math.min(width - 1, x))\n const clampedY = Math.max(0, Math.min(height - 1, y))\n const x0 = Math.floor(clampedX)\n const y0 = Math.floor(clampedY)\n const x1 = Math.min(width - 1, x0 + 1)\n const y1 = Math.min(height - 1, y0 + 1)\n const tx = clampedX - x0\n const ty = clampedY - y0\n const row0 = y0 * width\n const row1 = y1 * width\n const sample = (channel: number) => {\n const top = pixels[(row0 + x0) * 4 + channel] * (1 - tx) +\n pixels[(row0 + x1) * 4 + channel] * tx\n const bottom = pixels[(row1 + x0) * 4 + channel] * (1 - tx) +\n pixels[(row1 + x1) * 4 + channel] * tx\n return Math.round(top * (1 - ty) + bottom * ty)\n }\n return [sample(0), sample(1), sample(2), 255]\n}\n\nfunction perspectiveWarp(source: HTMLCanvasElement, corners: DocumentCorners, maxDimension: number) {\n const { width, height } = perspectiveOutputSize(corners, maxDimension)\n const sourceContext = source.getContext('2d', { willReadFrequently: true })\n if (!sourceContext) throw canvasUnavailable()\n const sourcePixels = sourceContext.getImageData(0, 0, source.width, source.height)\n const output = document.createElement('canvas')\n output.width = width\n output.height = height\n const outputContext = output.getContext('2d')\n if (!outputContext) throw canvasUnavailable()\n const outputPixels = outputContext.createImageData(width, height)\n const { topLeft: tl, topRight: tr, bottomRight: br, bottomLeft: bl } = corners\n const dx1 = tr.x - br.x\n const dx2 = bl.x - br.x\n const dy1 = tr.y - br.y\n const dy2 = bl.y - br.y\n const sx = tl.x - tr.x + br.x - bl.x\n const sy = tl.y - tr.y + br.y - bl.y\n const denominator = dx1 * dy2 - dx2 * dy1\n const projectiveX = Math.abs(denominator) < 0.0001 ? 0 : (sx * dy2 - dx2 * sy) / denominator\n const projectiveY = Math.abs(denominator) < 0.0001 ? 0 : (dx1 * sy - sx * dy1) / denominator\n const a = tr.x - tl.x + projectiveX * tr.x\n const b = bl.x - tl.x + projectiveY * bl.x\n const d = tr.y - tl.y + projectiveX * tr.y\n const e = bl.y - tl.y + projectiveY * bl.y\n\n for (let y = 0; y < height; y += 1) {\n const v = y / Math.max(1, height - 1)\n for (let x = 0; x < width; x += 1) {\n const u = x / Math.max(1, width - 1)\n const divisor = projectiveX * u + projectiveY * v + 1\n const sourceX = (a * u + b * v + tl.x) / divisor\n const sourceY = (d * u + e * v + tl.y) / divisor\n const [red, green, blue, alpha] = sampleBilinear(\n sourcePixels.data,\n source.width,\n source.height,\n sourceX,\n sourceY,\n )\n const outputOffset = (y * width + x) * 4\n outputPixels.data[outputOffset] = red\n outputPixels.data[outputOffset + 1] = green\n outputPixels.data[outputOffset + 2] = blue\n outputPixels.data[outputOffset + 3] = alpha\n }\n }\n outputContext.putImageData(outputPixels, 0, 0)\n return output\n}\n\n/**\n * Finds document corners. Returns `success`, `no-document`, `low-confidence`,\n * or `low-quality`. A bad image is one of those statuses and does not throw.\n * Inference or geometry failure is `modelStatus: 'failed'`, not a throw.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed. Detection does not start.\n * @throws {ScannerError} ScannerError `canvas` when canvas 2D is unavailable.\n * `worker` when the document worker cannot start.\n * `model-http` when the DocAligner file returns a failed HTTP response.\n */\nexport async function detectDocument(\n source: ImageSource,\n options: ScanOptions = {},\n): Promise<DocumentDetectionResult> {\n await assertLicense('scan')\n return analyzeCanvas(await sourceToCanvas(source, { cloneCanvas: false }), options)\n}\n\n/**\n * Perspective-crops `corners` onto a new canvas.\n * Resolves with `status: 'success'`. It does not score image quality.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed.\n * @throws {ScannerError} ScannerError `canvas` when canvas 2D is unavailable.\n */\nexport async function cropDocument(\n source: ImageSource,\n corners: DocumentCorners,\n options: Pick<ScanOptions, 'maxOutputDimension'> = {},\n): Promise<ScanResult> {\n await assertLicense('scan')\n const canvas = await sourceToCanvas(source, { cloneCanvas: false })\n const maxOutputDimension = options.maxOutputDimension ?? DEFAULT_OUTPUT_DIMENSION\n return {\n status: 'success',\n corners,\n quad: toQuad(corners),\n confidence: 1,\n message: 'Captured with the document edges shown in the finder.',\n sourceWidth: canvas.width,\n sourceHeight: canvas.height,\n canvas: perspectiveWarp(canvas, corners, maxOutputDimension),\n }\n}\n\n/**\n * Detects a document and perspective-crops it.\n * Returns `success`, `no-document`, `low-confidence`, or `low-quality`.\n * A bad image is one of those statuses and does not throw.\n * Inference or geometry failure is `modelStatus: 'failed'`, not a throw.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed. Detection does not start.\n * @throws {ScannerError} ScannerError `canvas` when canvas 2D is unavailable.\n * `worker` when the document worker cannot start.\n * `model-http` when the DocAligner file returns a failed HTTP response.\n */\nexport async function scanDocument(\n source: ImageSource,\n options: ScanOptions = {},\n): Promise<ScanResult> {\n await assertLicense('scan')\n const canvas = await sourceToCanvas(source, { cloneCanvas: false })\n const detection = await analyzeCanvas(canvas, options)\n if (detection.status !== 'success' || !detection.corners) return detection\n const maxOutputDimension = options.maxOutputDimension ?? DEFAULT_OUTPUT_DIMENSION\n return {\n ...detection,\n canvas: perspectiveWarp(canvas, detection.corners, maxOutputDimension),\n message: 'Four document edges detected and perspective-corrected.',\n }\n}\n\n/** User-visible copy when a system-camera still has no cropable document. */\nexport function systemCameraFindMessage(result: Pick<DocumentDetectionResult, 'status' | 'message' | 'modelStatus' | 'modelError'>) {\n if (result.status === 'success') return result.message\n if (result.status === 'low-quality') {\n return result.message.includes('shortest side')\n ? `${result.message} Take another photo.`\n : 'That photo is too soft or dark to find a document. Take another photo in better light.'\n }\n if (result.status === 'low-confidence') {\n return 'The page edges were not clear enough to crop. Take another photo with the whole page in frame.'\n }\n const modelFail = result.modelStatus === 'failed' && result.modelError\n ? ` (${result.modelError})`\n : ''\n return `No document was found in that photo. Take another photo with the whole page in frame.${modelFail}`\n}\n\n/**\n * Runs DocAligner on a system-camera JPEG and crops the most prominent\n * document (the single largest-component quad the model returns). A miss\n * is a status plus a retry-oriented message. It does not throw.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed.\n */\nexport async function scanSystemCameraStill(\n source: ImageSource,\n options: ScanOptions = {},\n): Promise<ScanResult> {\n const result = await scanDocument(source, options)\n if (result.status === 'success') return result\n return {\n ...result,\n message: systemCameraFindMessage(result),\n }\n}\n","import { canvasUnavailable, ScannerError } from './errors'\nimport { assertLicense } from './license'\n\nexport interface CameraOptions {\n facingMode?: 'environment' | 'user'\n idealWidth?: number\n idealHeight?: number\n /** Host opt-in. The SDK does not apply an Android-only width cap. */\n maxWidth?: number\n /** Host opt-in. The SDK does not apply an Android-only 1920 height cap. */\n maxHeight?: number\n maxFrameRate?: number\n /** Rear-camera torch policy. Defaults to `alwaysOff`. */\n torch?: TorchMode\n}\n\nexport type TorchMode =\n | 'defaultOn'\n | 'defaultOff'\n | 'alwaysOn'\n | 'alwaysOff'\n | 'auto'\n\nexport interface TorchStatus {\n mode: TorchMode\n supported: boolean\n on: boolean\n /** Whether the camera UI should show a torch control. */\n visible: boolean\n /** Whether an end user can change the control with `setTorch()`. */\n mutable: boolean\n /** True when luminance hysteresis, rather than an end user, owns the state. */\n automatic: boolean\n}\n\nexport interface CameraSession {\n stream: MediaStream\n readonly torchMode: TorchMode\n readonly torchSupported: boolean\n readonly torchOn: boolean\n capture: (maxDimension?: number) => HTMLCanvasElement\n /**\n * Full-resolution still. Outside WebKit this is `ImageCapture.takePhoto()`\n * at the camera's max native still (one axis only — both maxima ask Chrome\n * for a square and it scales). Map finder corners onto it with\n * `mapDocumentCornersToFrame`. A still longer than `STILL_MAX_EDGE` (4096)\n * is scaled down with high-quality smoothing so a 12MP+ JPEG does not\n * exhaust mobile memory. WebKit still copies the live preview, because\n * `takePhoto()` returns a black JPEG there.\n */\n capturePhoto: () => Promise<CameraPhoto>\n getSettings: () => MediaTrackSettings\n getDiagnostics: () => CameraDiagnostics\n getTorchStatus: () => TorchStatus\n /**\n * Changes torch state only for `defaultOn` and `defaultOff`.\n * Returns false, without throwing, for unsupported or immutable modes.\n */\n setTorch: (enabled: boolean) => Promise<boolean>\n stop: () => void\n}\n\nexport type CapturePath = 'video-frame' | 'live-mirror' | 'image-capture' | 'system-camera'\n\n/**\n * How `ScannerProvider` captures.\n *\n * - `auto` (default): Android opens the system Camera app as soon as\n * `open` becomes true from a user gesture. iOS and desktop stay on\n * the live finder overlay.\n * - `live`: always use the live preview + finder, including on Android.\n * - `system-camera`: always use `pickNativeCameraStill()`, including on iOS.\n */\nexport type CaptureMode = 'auto' | 'live' | 'system-camera'\n\nexport interface CameraPhoto {\n /** Still pixels. Long edge is at most `STILL_MAX_EDGE` (4096). */\n frame: HTMLCanvasElement\n method: CapturePath\n settings: MediaTrackSettings\n fallbackReason?:\n | 'video-frame-empty'\n | 'image-capture-empty'\n | 'image-capture-failed'\n | 'image-capture-aspect'\n | 'image-capture-preview-size'\n luminance: number\n diagnostics: CameraDiagnostics\n}\n\nexport interface CameraDiagnostics {\n videoWidth: number\n videoHeight: number\n readyState: number\n paused: boolean\n connected: boolean\n rendered: boolean\n trackReadyState: MediaStreamTrackState | 'missing'\n trackEnabled: boolean\n trackMuted: boolean\n liveLuminance: number\n mirrorLuminance: number\n mirrorAgeMs: number\n /**\n * Whether the browser exposes `ImageCapture`. Stills use `takePhoto()`\n * outside WebKit. WebKit exposes the constructor and returns a black JPEG.\n */\n hasImageCapture: boolean\n torchMode: TorchMode\n torchSupported: boolean\n torchOn: boolean\n torch: TorchStatus\n engine: BrowserEngine\n}\n\nexport interface CaptureDiagnosticsReport {\n capturedAt?: string\n error?: string\n captureMethod?: CapturePath\n luminance?: number\n fallbackReason?: CameraPhoto['fallbackReason']\n shutter?: CameraDiagnostics\n live?: CameraDiagnostics\n finder?: {\n state?: string\n confidence?: number\n stableFrames?: number\n requiredStableFrames?: number\n detector?: string\n modelStatus?: string\n modelError?: string\n modelProvider?: string\n modelNote?: string\n inferenceMs?: number\n sourceWidth?: number\n sourceHeight?: number\n }\n}\n\nfunction formatDiagnosticsBlock(label: string, diagnostics: CameraDiagnostics) {\n const { engine } = diagnostics\n return [\n `${label}:`,\n ` engine: ${engine.engine}/${engine.browser}${engine.iosWebKit ? ' ios-webkit' : ''}`,\n ` ua: ${engine.userAgent}`,\n ` video: ${diagnostics.videoWidth}x${diagnostics.videoHeight} readyState=${diagnostics.readyState}${diagnostics.paused ? ' paused' : ''}${diagnostics.rendered ? '' : ' hidden'}${diagnostics.connected ? '' : ' disconnected'}`,\n ` track: ${diagnostics.trackReadyState}${diagnostics.trackEnabled ? '' : ' disabled'}${diagnostics.trackMuted ? ' muted' : ''}`,\n ` liveLuma: ${diagnostics.liveLuminance.toFixed(1)}`,\n ` mirrorLuma: ${diagnostics.mirrorLuminance.toFixed(1)}`,\n ` mirrorAgeMs: ${Number.isFinite(diagnostics.mirrorAgeMs) ? Math.round(diagnostics.mirrorAgeMs) : 'none'}`,\n ` hasImageCapture: ${diagnostics.hasImageCapture}${diagnostics.engine.iosWebKit ? ' (skipped on webkit)' : ' (still capture)'}`,\n ` torch: ${diagnostics.torch.mode} supported=${diagnostics.torch.supported} on=${diagnostics.torch.on}`,\n ].join('\\n')\n}\n\n/** Plain-text dump safe to paste into chat or a ticket. */\nexport function formatCaptureDiagnosticsReport(report: CaptureDiagnosticsReport) {\n const lines = [\n 'Exige scanner capture report',\n `time: ${report.capturedAt ?? new Date().toISOString()}`,\n ]\n if (report.error) lines.push(`error: ${report.error}`)\n if (report.captureMethod) lines.push(`method: ${report.captureMethod}`)\n if (report.luminance !== undefined) lines.push(`luminance: ${report.luminance.toFixed(1)}`)\n if (report.fallbackReason) lines.push(`fallback: ${report.fallbackReason}`)\n if (report.shutter) lines.push(formatDiagnosticsBlock('shutter', report.shutter))\n if (report.live) lines.push(formatDiagnosticsBlock('live', report.live))\n if (report.finder) {\n const finder = report.finder\n lines.push(\n [\n 'finder:',\n ` state: ${finder.state ?? 'unknown'}`,\n ` confidence: ${finder.confidence === undefined ? '—' : finder.confidence.toFixed(3)}`,\n ` stable: ${finder.stableFrames ?? '—'}/${finder.requiredStableFrames ?? '—'}`,\n ` detector: ${finder.detector ?? '—'} ${finder.modelStatus ?? ''}`.trim(),\n ` modelError: ${finder.modelError ?? '—'}`,\n ` provider: ${finder.modelProvider ?? '—'}`,\n ` note: ${finder.modelNote ?? '—'}`,\n ` inferenceMs: ${finder.inferenceMs === undefined ? '—' : Math.round(finder.inferenceMs)}`,\n ` source: ${finder.sourceWidth ?? '—'}x${finder.sourceHeight ?? '—'}`,\n ].join('\\n'),\n )\n }\n return `${lines.join('\\n')}\\n`\n}\n\nexport interface BrowserEngine {\n /** Engine actually executing, not the vendor shell around it. */\n engine: 'webkit' | 'blink' | 'gecko' | 'unknown'\n /** Vendor shell, which on iOS is only a wrapper around WebKit. */\n browser: string\n iosWebKit: boolean\n userAgent: string\n}\n\n/**\n * Identifies the rendering engine by capability plus the vendor shell by name.\n * Every iOS browser is WebKit, so behavior must never be gated on Safari alone.\n */\nexport function detectBrowserEngine(\n userAgent = typeof navigator === 'undefined' ? '' : navigator.userAgent,\n maxTouchPoints = typeof navigator === 'undefined' ? 0 : navigator.maxTouchPoints,\n): BrowserEngine {\n const browser = /CriOS|Chrome/i.test(userAgent)\n ? 'chrome'\n : /EdgiOS|Edg/i.test(userAgent)\n ? 'edge'\n : /FxiOS|Firefox/i.test(userAgent)\n ? 'firefox'\n : /Safari/i.test(userAgent)\n ? 'safari'\n : 'unknown'\n const iosDevice = /iPhone|iPad|iPod/i.test(userAgent) ||\n (/Macintosh/i.test(userAgent) && maxTouchPoints > 1)\n const iosShell = /CriOS|EdgiOS|FxiOS|OPiOS|Mercury/i.test(userAgent)\n const iosWebKit = iosDevice || iosShell\n const engine = iosWebKit || (/AppleWebKit/i.test(userAgent) && !/Chrome|Chromium|Edg/i.test(userAgent))\n ? 'webkit'\n : /Chrome|Chromium|Edg/i.test(userAgent)\n ? 'blink'\n : /Gecko\\//i.test(userAgent)\n ? 'gecko'\n : 'unknown'\n return { engine, browser, iosWebKit, userAgent }\n}\n\n/** Mean luminance below this is treated as an empty/black frame. */\n\n/** Android browser, not an iOS shell that happens to mention Android. */\nexport function isAndroidBrowser(engine: BrowserEngine) {\n return /Android/i.test(engine.userAgent) && !engine.iosWebKit\n}\n\n/**\n * Android `auto` uses the system Camera app. Chrome `takePhoto()` cannot\n * match Camera-app quality, and there is no live document guide on that path.\n * Hosts opt out with `live` and force the picker with `system-camera`.\n */\nexport function shouldUseSystemCameraCapture(\n mode: CaptureMode = 'auto',\n engine: BrowserEngine = detectBrowserEngine(),\n) {\n if (mode === 'system-camera') return true\n if (mode === 'live') return false\n return isAndroidBrowser(engine)\n}\n\n/** WebKit's ImageCapture.takePhoto() resolves with a black JPEG. Other engines can use it for a sharp still. */\nexport function shouldUseImageCapture(engine: BrowserEngine, hasImageCapture: boolean) {\n return hasImageCapture && !engine.iosWebKit\n}\n\nexport interface PhotoSizeRange {\n min?: number\n max?: number\n step?: number\n}\n\n/** Snap a requested still edge onto the camera's min/max/step grid. */\nexport function snapPhotoDimension(preferred: number, range?: PhotoSizeRange) {\n if (!preferred || !Number.isFinite(preferred)) return undefined\n const max = range?.max\n if (!max || !Number.isFinite(max)) return Math.round(preferred)\n const min = range?.min && Number.isFinite(range.min) ? range.min : 1\n const step = range?.step && range.step > 0 ? range.step : 1\n const clamped = Math.min(max, Math.max(min, preferred))\n const snapped = min + Math.round((clamped - min) / step) * step\n return Math.round(Math.min(max, Math.max(min, snapped)))\n}\n\n/**\n * Largest still the camera reports. Requests only one axis.\n *\n * Chrome's photo sample sets `imageWidth` alone and lets the UA pick a\n * native pair. Passing both `imageWidth.max` and `imageHeight.max` repeats\n * the 0.2.14 square trap: phones that advertise the same max on both axes\n * (portrait + landscape stills) get a max×max square, and Chrome scales\n * the sensor image into a large soft JPEG.\n */\nexport function maxPhotoSettings(capabilities?: {\n imageWidth?: PhotoSizeRange\n imageHeight?: PhotoSizeRange\n}) {\n const imageWidth = snapPhotoDimension(\n capabilities?.imageWidth?.max ?? 0,\n capabilities?.imageWidth,\n )\n const imageHeight = snapPhotoDimension(\n capabilities?.imageHeight?.max ?? 0,\n capabilities?.imageHeight,\n )\n if (imageWidth && imageHeight) {\n return imageWidth >= imageHeight\n ? { imageWidth }\n : { imageHeight }\n }\n if (imageWidth) return { imageWidth }\n if (imageHeight) return { imageHeight }\n return undefined\n}\n\n/**\n * True when the still has meaningfully more pixels than the live preview.\n * A same-size `takePhoto()` JPEG is often a recompress of the video frame\n * and looks softer than copying the `<video>` pixels.\n */\nexport function stillBeatsPreview(\n still: { width: number; height: number },\n preview: { width: number; height: number },\n) {\n if (!still.width || !still.height || !preview.width || !preview.height) return false\n return still.width * still.height > preview.width * preview.height * 1.15\n}\n\n/**\n * Whether a still and the preview share an aspect ratio. Capture still uses\n * a visible `takePhoto()` still when this is false; finder corners are mapped\n * onto that full-res still with `mapDocumentCornersToFrame`.\n */\nexport function stillMatchesPreview(\n still: { width: number; height: number },\n preview: { width: number; height: number },\n) {\n if (!still.width || !still.height || !preview.width || !preview.height) return false\n const ratio = (still.width / still.height) / (preview.width / preview.height)\n return ratio > 0.97 && ratio < 1.03\n}\nexport const NEAR_BLACK_LUMINANCE = 10\n\nexport interface AutoTorchOptions {\n /** Luminance at or below which dark samples accumulate. */\n turnOnLuminance?: number\n /** Luminance at or above which bright samples accumulate. */\n turnOffLuminance?: number\n /** Consecutive dark samples required before enabling the torch. */\n darkSamples?: number\n /** Consecutive bright samples required before disabling the torch. */\n brightSamples?: number\n}\n\n/**\n * Stateful automatic torch policy. The wide threshold gap and consecutive\n * sample counts prevent exposure changes and hand movement from flickering the\n * LED. `update()` returns a new requested state only when the state changes.\n */\nexport class AutoTorchController {\n private on = false\n private darkCount = 0\n private brightCount = 0\n private readonly turnOnLuminance: number\n private readonly turnOffLuminance: number\n private readonly darkSamples: number\n private readonly brightSamples: number\n\n constructor(options: AutoTorchOptions = {}) {\n this.turnOnLuminance = options.turnOnLuminance ?? 62\n this.turnOffLuminance = options.turnOffLuminance ?? 155\n this.darkSamples = options.darkSamples ?? 3\n this.brightSamples = options.brightSamples ?? 8\n }\n\n update(luminance: number) {\n if (!Number.isFinite(luminance) || luminance <= NEAR_BLACK_LUMINANCE) {\n this.darkCount = 0\n this.brightCount = 0\n return undefined\n }\n if (!this.on) {\n this.brightCount = 0\n this.darkCount = luminance <= this.turnOnLuminance ? this.darkCount + 1 : 0\n if (this.darkCount < this.darkSamples) return undefined\n this.darkCount = 0\n this.on = true\n return true\n }\n this.darkCount = 0\n this.brightCount = luminance >= this.turnOffLuminance ? this.brightCount + 1 : 0\n if (this.brightCount < this.brightSamples) return undefined\n this.brightCount = 0\n this.on = false\n return false\n }\n\n getState() {\n return this.on\n }\n}\n\nexport function torchControl(\n mode: TorchMode,\n supported: boolean,\n): TorchStatus {\n if (!supported) {\n return {\n mode,\n supported: false,\n on: false,\n visible: false,\n mutable: false,\n automatic: mode === 'auto',\n }\n }\n if (mode === 'alwaysOn' || mode === 'alwaysOff') {\n return {\n mode,\n supported: true,\n on: mode === 'alwaysOn',\n visible: false,\n mutable: false,\n automatic: false,\n }\n }\n return {\n mode,\n supported: true,\n on: mode === 'defaultOn',\n visible: true,\n mutable: mode !== 'auto',\n automatic: mode === 'auto',\n }\n}\n\nexport function meanFrameLuminance(pixels: Uint8ClampedArray) {\n const pixelCount = Math.floor(pixels.length / 4)\n if (!pixelCount) return 0\n let luminance = 0\n for (let offset = 0; offset < pixelCount * 4; offset += 4) {\n luminance += pixels[offset] * 0.299 +\n pixels[offset + 1] * 0.587 +\n pixels[offset + 2] * 0.114\n }\n return luminance / pixelCount\n}\n\nexport function isNearBlackFrame(\n pixels: Uint8ClampedArray,\n blackThreshold = NEAR_BLACK_LUMINANCE,\n) {\n if (pixels.length < 4) return true\n const pixelCount = Math.floor(pixels.length / 4)\n let visiblePixels = 0\n for (let offset = 0; offset < pixelCount * 4; offset += 4) {\n const value = pixels[offset] * 0.299 +\n pixels[offset + 1] * 0.587 +\n pixels[offset + 2] * 0.114\n if (value > blackThreshold * 2) visiblePixels += 1\n }\n return meanFrameLuminance(pixels) <= blackThreshold &&\n visiblePixels / pixelCount < 0.01\n}\n\nfunction sampleCanvasLuminance(source: CanvasImageSource, width: number, height: number) {\n if (!width || !height) return 0\n const sample = document.createElement('canvas')\n sample.width = Math.min(32, width)\n sample.height = Math.min(32, height)\n const context = sample.getContext('2d', { willReadFrequently: true })\n if (!context) return 0\n context.drawImage(source, 0, 0, sample.width, sample.height)\n return meanFrameLuminance(context.getImageData(0, 0, sample.width, sample.height).data)\n}\n\nfunction canvasLuminance(canvas: HTMLCanvasElement) {\n return sampleCanvasLuminance(canvas, canvas.width, canvas.height)\n}\n\ntype VideoFrameCallbackElement = HTMLVideoElement & Partial<{\n requestVideoFrameCallback: (callback: () => void) => number\n cancelVideoFrameCallback: (handle: number) => void\n}>\n\n/**\n * Keeps an offscreen copy of the most recent non-black video frame. WebKit can\n * blank a `<video>` at the moment of a tap, teardown, or compositing change, so\n * capture must not depend on the pixels available at that exact instant.\n */\nfunction startFrameMirror(video: VideoFrameCallbackElement, minIntervalMs = 120) {\n const canvas = document.createElement('canvas')\n const context = canvas.getContext('2d')\n const supportsFrameCallback = typeof video.requestVideoFrameCallback === 'function'\n let running = true\n let handle = 0\n let lastCopyAt = 0\n let lastGoodAt = 0\n let liveLuminance = 0\n let mirrorLuminance = 0\n\n const schedule = () => {\n if (!running) return\n handle = supportsFrameCallback\n ? video.requestVideoFrameCallback!(grab)\n : requestAnimationFrame(grab)\n }\n\n function grab() {\n if (!running) return\n const { videoWidth, videoHeight } = video\n const now = performance.now()\n if (context && videoWidth && videoHeight && now - lastCopyAt >= minIntervalMs) {\n lastCopyAt = now\n liveLuminance = sampleCanvasLuminance(video, videoWidth, videoHeight)\n if (liveLuminance > NEAR_BLACK_LUMINANCE) {\n if (canvas.width !== videoWidth || canvas.height !== videoHeight) {\n canvas.width = videoWidth\n canvas.height = videoHeight\n }\n context.drawImage(video, 0, 0, videoWidth, videoHeight)\n mirrorLuminance = liveLuminance\n lastGoodAt = now\n }\n }\n schedule()\n }\n\n schedule()\n return {\n stop() {\n running = false\n if (supportsFrameCallback) video.cancelVideoFrameCallback?.(handle)\n else cancelAnimationFrame(handle)\n },\n getFrame: () => lastGoodAt ? canvas : undefined,\n getLiveLuminance: () => liveLuminance,\n getMirrorLuminance: () => mirrorLuminance,\n getMirrorAgeMs: () => lastGoodAt ? performance.now() - lastGoodAt : Infinity,\n }\n}\n\nfunction cloneFrame(source: HTMLCanvasElement) {\n const copy = document.createElement('canvas')\n copy.width = source.width\n copy.height = source.height\n copy.getContext('2d')?.drawImage(source, 0, 0)\n return copy\n}\n\n/** Blink may software-scale the preview unless `resizeMode` is `none`. */\nexport function preferNativeCameraResize(engine: BrowserEngine) {\n return engine.engine === 'blink'\n}\n\nexport function mobileCameraConstraints(\n options: CameraOptions = {},\n engine = detectBrowserEngine(),\n): MediaStreamConstraints {\n const width: ConstrainULongRange = { ideal: options.idealWidth ?? 3840 }\n const height: ConstrainULongRange = { ideal: options.idealHeight ?? 2160 }\n if (options.maxWidth) width.max = options.maxWidth\n if (options.maxHeight) height.max = options.maxHeight\n const video: MediaTrackConstraints & { resizeMode?: ConstrainDOMString } = {\n facingMode: { ideal: options.facingMode ?? 'environment' },\n width,\n height,\n frameRate: { ideal: options.maxFrameRate ?? 30, max: options.maxFrameRate ?? 30 },\n }\n if (preferNativeCameraResize(engine)) video.resizeMode = { ideal: 'none' }\n return {\n audio: false,\n video,\n }\n}\n\n/** Long-edge cap that keeps the source aspect. Never upscales. */\nexport function scaledFrameSize(\n width: number,\n height: number,\n maxDimension?: number,\n) {\n const scale = maxDimension\n ? Math.min(1, maxDimension / Math.max(width, height))\n : 1\n return {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n}\n\n/**\n * Long-edge memory cap for `capturePhoto()` stills. Preview and analysis\n * are independent: the live stream stays at the negotiated 3840×2160-class\n * size, and DocAligner sees a 520–1600 working copy. Only a still whose\n * long edge exceeds this is scaled, with high-quality smoothing.\n */\nexport const STILL_MAX_EDGE = 4096\n\n/**\n * Bump a granted preview toward the largest same-aspect size the camera\n * advertises. Chrome often opens at 1080p even after a 4K ideal.\n */\nexport function highestPracticalTrackConstraints(\n settings: { width?: number; height?: number },\n capabilities?: { width?: { max?: number }; height?: { max?: number } },\n): MediaTrackConstraints | undefined {\n const width = settings.width\n const height = settings.height\n const maxWidth = capabilities?.width?.max\n const maxHeight = capabilities?.height?.max\n if (!width || !height || !maxWidth || !maxHeight) return undefined\n const scale = Math.min(maxWidth / width, maxHeight / height)\n if (scale <= 1.05) return undefined\n return {\n width: { ideal: Math.round(width * scale) },\n height: { ideal: Math.round(height * scale) },\n }\n}\n\nasync function applyHighestPracticalResolution(track: MediaStreamTrack) {\n const next = highestPracticalTrackConstraints(\n track.getSettings(),\n typeof track.getCapabilities === 'function' ? track.getCapabilities() : undefined,\n )\n if (!next) return\n try {\n await track.applyConstraints(next)\n } catch {\n // Keep the granted stream if the camera rejects the bump.\n }\n}\n\ntype ImageCaptureLike = {\n takePhoto: (settings?: { imageWidth?: number; imageHeight?: number }) => Promise<Blob>\n getPhotoCapabilities?: () => Promise<{\n imageWidth?: PhotoSizeRange\n imageHeight?: PhotoSizeRange\n }>\n getPhotoSettings?: () => Promise<{ imageWidth?: number; imageHeight?: number }>\n}\n\nasync function decodeStillBitmap(blob: Blob) {\n try {\n return await createImageBitmap(blob, {\n imageOrientation: 'from-image',\n colorSpaceConversion: 'none',\n })\n } catch {\n return await createImageBitmap(blob)\n }\n}\n\nasync function aimMeteringAtCenter(track: MediaStreamTrack) {\n try {\n await track.applyConstraints({\n advanced: [{ pointsOfInterest: [{ x: 0.5, y: 0.5 }] } as MediaTrackConstraintSet],\n })\n await new Promise((resolve) => window.setTimeout(resolve, 180))\n } catch {\n // Chrome Camera2 focuses continuously; some devices reject POI.\n }\n}\n\nasync function blobToStillCanvas(blob: Blob) {\n const bitmap = await decodeStillBitmap(blob)\n const size = scaledFrameSize(bitmap.width, bitmap.height, STILL_MAX_EDGE)\n const canvas = document.createElement('canvas')\n canvas.width = size.width\n canvas.height = size.height\n const context = canvas.getContext('2d')\n if (!context) {\n bitmap.close?.()\n throw canvasUnavailable()\n }\n const scaled = size.width !== bitmap.width || size.height !== bitmap.height\n context.imageSmoothingEnabled = scaled\n context.imageSmoothingQuality = 'high'\n context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)\n bitmap.close?.()\n return canvas\n}\n\nasync function captureTrackStill(track: MediaStreamTrack) {\n const ImageCaptureApi = (globalThis as typeof globalThis & {\n ImageCapture?: new (track: MediaStreamTrack) => ImageCaptureLike\n }).ImageCapture\n if (!ImageCaptureApi) return undefined\n await aimMeteringAtCenter(track)\n const capture = new ImageCaptureApi(track)\n const capabilities = capture.getPhotoCapabilities\n ? await capture.getPhotoCapabilities()\n : undefined\n const settings = maxPhotoSettings(capabilities)\n let blob: Blob\n try {\n blob = await capture.takePhoto(settings)\n } catch {\n // No PhotoSettings: Chrome's current size defaults to the video format.\n blob = await capture.takePhoto()\n }\n const frame = await blobToStillCanvas(blob)\n return {\n frame,\n requested: settings,\n photoMax: {\n width: capabilities?.imageWidth?.max,\n height: capabilities?.imageHeight?.max,\n },\n }\n}\n\nexport function captureVideoFrame(video: HTMLVideoElement, maxDimension?: number) {\n if (!video.videoWidth || !video.videoHeight) {\n throw new Error('The camera is not ready to capture a frame.')\n }\n const size = scaledFrameSize(video.videoWidth, video.videoHeight, maxDimension)\n const canvas = document.createElement('canvas')\n canvas.width = size.width\n canvas.height = size.height\n const context = canvas.getContext('2d')\n if (!context) throw canvasUnavailable()\n context.drawImage(video, 0, 0, canvas.width, canvas.height)\n return canvas\n}\n\nfunction cameraConstraintCandidates(options: CameraOptions) {\n const engine = detectBrowserEngine()\n if (options.idealWidth || options.idealHeight || options.maxWidth || options.maxHeight) {\n return [mobileCameraConstraints(options, engine)]\n }\n return [\n mobileCameraConstraints({ ...options, idealWidth: 3840, idealHeight: 2160 }, engine),\n mobileCameraConstraints({ ...options, idealWidth: 2560, idealHeight: 1440 }, engine),\n mobileCameraConstraints({ ...options, idealWidth: 1920, idealHeight: 1080 }, engine),\n ]\n}\n\n/**\n * Opens the rear camera on `video`.\n *\n * @throws {LicenseError} LicenseError when scan is not licensed. Torch mode other than\n * `alwaysOff` also requires the torch feature. The camera does not start.\n * @throws {ScannerError} ScannerError `secure-context` when the page is not HTTPS.\n * `localhost` is allowed. `canvas` when a captured frame cannot get canvas 2D.\n */\nexport async function startCamera(\n video: HTMLVideoElement,\n options: CameraOptions = {},\n): Promise<CameraSession> {\n await assertLicense('scan')\n const torchMode = options.torch ?? 'alwaysOff'\n if (torchMode !== 'alwaysOff') await assertLicense('torch')\n if (!window.isSecureContext && location.hostname !== 'localhost') {\n throw new ScannerError('secure-context', 'Camera access requires HTTPS.')\n }\n if (!navigator.mediaDevices?.getUserMedia) {\n throw new Error('Live camera access is unavailable. Use the native camera picker instead.')\n }\n video.muted = true\n video.autoplay = true\n video.playsInline = true\n video.setAttribute('playsinline', '')\n let stream: MediaStream | undefined\n let resolutionError: unknown\n for (const constraints of cameraConstraintCandidates(options)) {\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraints)\n break\n } catch (cause) {\n resolutionError = cause\n if (!(cause instanceof DOMException) || cause.name !== 'OverconstrainedError') throw cause\n }\n }\n if (!stream) throw resolutionError ?? new Error('No rear camera resolution is available.')\n video.srcObject = stream\n await video.play()\n const track = stream.getVideoTracks()[0]\n if (!track) {\n for (const streamTrack of stream.getTracks()) streamTrack.stop()\n throw new Error('The camera did not provide a video track.')\n }\n await applyHighestPracticalResolution(track)\n const mirror = startFrameMirror(video)\n const hasImageCapture = 'ImageCapture' in globalThis\n const capabilities = typeof track.getCapabilities === 'function'\n ? track.getCapabilities() as MediaTrackCapabilities & { torch?: boolean }\n : undefined\n let torchStatus = torchControl(torchMode, capabilities?.torch === true)\n let torchUpdatePending = false\n const applyTorch = async (enabled: boolean) => {\n if (!torchStatus.supported || track.readyState !== 'live') return false\n try {\n await track.applyConstraints({\n advanced: [{ torch: enabled } as MediaTrackConstraintSet],\n })\n torchStatus = { ...torchStatus, on: enabled }\n return true\n } catch {\n // Some browsers report a torch capability but reject its constraint.\n // Fail closed and hide the control without disturbing the live track.\n torchStatus = {\n ...torchStatus,\n supported: false,\n on: false,\n visible: false,\n mutable: false,\n }\n return false\n }\n }\n\n if (torchStatus.on) await applyTorch(true)\n\n const autoTorch = torchMode === 'auto' && torchStatus.supported\n ? new AutoTorchController()\n : undefined\n const autoTorchTimer = autoTorch\n ? window.setInterval(() => {\n if (torchUpdatePending || !torchStatus.supported) return\n const requested = autoTorch.update(mirror.getLiveLuminance())\n if (requested === undefined || requested === torchStatus.on) return\n torchUpdatePending = true\n void applyTorch(requested).finally(() => {\n torchUpdatePending = false\n })\n }, 350)\n : 0\n\n const diagnostics = (): CameraDiagnostics => {\n const bounds = video.getBoundingClientRect()\n return {\n videoWidth: video.videoWidth,\n videoHeight: video.videoHeight,\n readyState: video.readyState,\n paused: video.paused,\n connected: video.isConnected,\n rendered: bounds.width > 0 && bounds.height > 0,\n trackReadyState: track.readyState ?? 'missing',\n trackEnabled: track.enabled,\n trackMuted: track.muted,\n liveLuminance: mirror.getLiveLuminance(),\n mirrorLuminance: mirror.getMirrorLuminance(),\n mirrorAgeMs: mirror.getMirrorAgeMs(),\n hasImageCapture,\n torchMode: torchStatus.mode,\n torchSupported: torchStatus.supported,\n torchOn: torchStatus.on,\n torch: { ...torchStatus },\n engine: detectBrowserEngine(),\n }\n }\n\n return {\n stream,\n get torchMode() {\n return torchStatus.mode\n },\n get torchSupported() {\n return torchStatus.supported\n },\n get torchOn() {\n return torchStatus.on\n },\n capture: (maxDimension) => captureVideoFrame(video, maxDimension),\n // Copy the preview before any await. WebKit can blank the element during\n // the tap that triggers capture. Outside WebKit, prefer ImageCapture's\n // max-size still even when its aspect differs from the preview. The\n // <video> frame is only the live view and is too soft for OCR.\n async capturePhoto() {\n let liveFrame: HTMLCanvasElement | undefined\n let liveLuminance = 0\n try {\n liveFrame = captureVideoFrame(video)\n liveLuminance = canvasLuminance(liveFrame)\n } catch {\n liveFrame = undefined\n }\n const mirrorFrame = mirror.getFrame()\n let stillFrame: HTMLCanvasElement | undefined\n let stillFailed = false\n let stillPreviewSized = false\n let photoRequest: { imageWidth?: number; imageHeight?: number } | undefined\n let photoMax: { width?: number; height?: number } | undefined\n if (shouldUseImageCapture(detectBrowserEngine(), hasImageCapture)) {\n try {\n const still = await captureTrackStill(track)\n stillFrame = still?.frame\n photoRequest = still?.requested\n photoMax = still?.photoMax\n } catch {\n stillFailed = true\n stillFrame = undefined\n }\n }\n const previewSize = { width: video.videoWidth, height: video.videoHeight }\n const stillLuminance = stillFrame ? canvasLuminance(stillFrame) : 0\n const stillIsBetter = Boolean(\n stillFrame &&\n stillLuminance > NEAR_BLACK_LUMINANCE &&\n stillBeatsPreview(stillFrame, previewSize),\n )\n if (stillFrame && stillLuminance > NEAR_BLACK_LUMINANCE && !stillIsBetter) {\n stillPreviewSized = true\n }\n if (stillIsBetter && stillFrame) {\n console.info('[exige-scanner] capture', {\n method: 'image-capture',\n frame: `${stillFrame.width}×${stillFrame.height}`,\n video: `${video.videoWidth}×${video.videoHeight}`,\n photoMax: photoMax ? `${photoMax.width ?? '—'}×${photoMax.height ?? '—'}` : undefined,\n photoRequest,\n aspectMatch: stillMatchesPreview(stillFrame, previewSize),\n })\n return {\n frame: stillFrame,\n method: 'image-capture' as const,\n settings: track.getSettings(),\n luminance: stillLuminance,\n diagnostics: diagnostics(),\n }\n }\n const usableLive = liveFrame && liveLuminance > NEAR_BLACK_LUMINANCE\n ? liveFrame\n : undefined\n const snapshot = usableLive ?? (mirrorFrame ? cloneFrame(mirrorFrame) : undefined)\n if (!snapshot) {\n throw new Error(\n 'The camera preview produced no visible pixels. Keep the scanner on screen, wait for the preview, and retake.',\n )\n }\n const fallbackReason = stillPreviewSized\n ? 'image-capture-preview-size' as const\n : stillFrame\n ? 'image-capture-empty' as const\n : stillFailed\n ? 'image-capture-failed' as const\n : usableLive\n ? undefined\n : 'video-frame-empty' as const\n console.info('[exige-scanner] capture', {\n method: usableLive ? 'video-frame' : 'live-mirror',\n frame: `${snapshot.width}×${snapshot.height}`,\n video: `${video.videoWidth}×${video.videoHeight}`,\n photoMax: photoMax ? `${photoMax.width ?? '—'}×${photoMax.height ?? '—'}` : undefined,\n photoRequest,\n fallbackReason,\n })\n return {\n frame: snapshot,\n method: usableLive ? 'video-frame' as const : 'live-mirror' as const,\n settings: track.getSettings(),\n fallbackReason,\n luminance: usableLive ? liveLuminance : mirror.getMirrorLuminance(),\n diagnostics: diagnostics(),\n }\n },\n getSettings: () => track.getSettings(),\n getDiagnostics: diagnostics,\n getTorchStatus: () => ({ ...torchStatus }),\n async setTorch(enabled) {\n if (!torchStatus.mutable) return false\n return applyTorch(enabled)\n },\n stop() {\n if (autoTorchTimer) window.clearInterval(autoTorchTimer)\n mirror.stop()\n for (const track of stream.getTracks()) track.stop()\n if (video.srcObject === stream) video.srcObject = null\n },\n }\n}\n\n/** True when `input.click()` can still open the system camera. */\nexport function hasTransientUserActivation() {\n const activation = typeof navigator === 'undefined' ? undefined : navigator.userActivation\n if (!activation) return true\n return activation.isActive\n}\n\n/**\n * Opens the phone Camera app via `<input capture=\"environment\">` and returns\n * that JPEG. Chrome `ImageCapture.takePhoto()` cannot match Camera2/CameraX\n * quality: it is a single `TEMPLATE_STILL_CAPTURE` frame with no HDR+, Night\n * Sight, or OEM ISP, and PhotoSettings cannot set JPEG quality. Must run\n * from a user gesture (`useEffect` after `setState` loses it; a layout\n * effect in the same click does not).\n */\nexport async function pickNativeCameraStill(): Promise<HTMLCanvasElement> {\n const input = document.createElement('input')\n input.type = 'file'\n input.accept = 'image/*'\n input.capture = 'environment'\n input.setAttribute('capture', 'environment')\n const file = await new Promise<File>((resolve, reject) => {\n input.addEventListener('change', () => {\n const chosen = input.files?.[0]\n if (chosen) resolve(chosen)\n else reject(new Error('No photo was selected.'))\n }, { once: true })\n input.addEventListener('cancel', () => {\n reject(new Error('No photo was selected.'))\n }, { once: true })\n input.click()\n })\n return blobToStillCanvas(file)\n}\n","import type { DocumentQuad } from './types'\n\nexport interface CastShadowRegion {\n x: number\n y: number\n width: number\n height: number\n}\n\nexport interface CastShadowAnalysis {\n strong: boolean\n strength: number\n darkness: number\n areaRatio: number\n region?: CastShadowRegion\n}\n\nfunction percentile(values: number[], fraction: number) {\n if (!values.length) return 0\n const sorted = [...values].sort((first, second) => first - second)\n return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * fraction))]\n}\n\n/**\n * Finds a connected, page-sized dark blob in any direction. A component must\n * cover meaningful area and contain local contrast, distinguishing cast\n * shadows over printed paper from a dark border or isolated illustration.\n */\nexport function analyzeCastShadowLuminance(\n luminance: Uint8Array,\n width: number,\n height: number,\n gridSize = 12,\n): CastShadowAnalysis {\n if (!width || !height || luminance.length < width * height) {\n return { strong: false, strength: 0, darkness: 0, areaRatio: 0 }\n }\n const columns = Math.min(gridSize, width)\n const rows = Math.min(gridSize, height)\n const cells: Array<{ mean: number; deviation: number }> = []\n for (let row = 0; row < rows; row += 1) {\n const top = Math.floor(row * height / rows)\n const bottom = Math.max(top + 1, Math.floor((row + 1) * height / rows))\n for (let column = 0; column < columns; column += 1) {\n const left = Math.floor(column * width / columns)\n const right = Math.max(left + 1, Math.floor((column + 1) * width / columns))\n let sum = 0\n let squared = 0\n let count = 0\n for (let y = top; y < bottom; y += 1) {\n for (let x = left; x < right; x += 1) {\n const value = luminance[y * width + x]\n sum += value\n squared += value * value\n count += 1\n }\n }\n const mean = sum / count\n cells.push({\n mean,\n deviation: Math.sqrt(Math.max(0, squared / count - mean * mean)),\n })\n }\n }\n\n const brightPaper = percentile(cells.map((cell) => cell.mean), 0.8)\n const dark = cells.map((cell) =>\n brightPaper - cell.mean >= 24 &&\n cell.mean >= 35,\n )\n const visited = new Uint8Array(cells.length)\n const components: number[][] = []\n for (let start = 0; start < cells.length; start += 1) {\n if (!dark[start] || visited[start]) continue\n const component: number[] = []\n const queue = [start]\n visited[start] = 1\n while (queue.length) {\n const index = queue.shift()!\n component.push(index)\n const row = Math.floor(index / columns)\n const column = index % columns\n for (const [nextColumn, nextRow] of [\n [column - 1, row],\n [column + 1, row],\n [column, row - 1],\n [column, row + 1],\n ]) {\n if (\n nextColumn < 0 ||\n nextColumn >= columns ||\n nextRow < 0 ||\n nextRow >= rows\n ) continue\n const next = nextRow * columns + nextColumn\n if (dark[next] && !visited[next]) {\n visited[next] = 1\n queue.push(next)\n }\n }\n }\n components.push(component)\n }\n\n let best: CastShadowAnalysis = {\n strong: false,\n strength: 0,\n darkness: 0,\n areaRatio: 0,\n }\n for (const component of components) {\n const areaRatio = component.length / cells.length\n if (areaRatio < 0.06 || areaRatio > 0.75) continue\n const darkness = component.reduce(\n (total, index) => total + brightPaper - cells[index].mean,\n 0,\n ) / component.length\n const printedCells = component.filter((index) => cells[index].deviation >= 9).length\n const printRatio = printedCells / component.length\n if (printRatio < 0.08 && darkness < 42) continue\n const columnsInComponent = component.map((index) => index % columns)\n const rowsInComponent = component.map((index) => Math.floor(index / columns))\n const minColumn = Math.min(...columnsInComponent)\n const maxColumn = Math.max(...columnsInComponent)\n const minRow = Math.min(...rowsInComponent)\n const maxRow = Math.max(...rowsInComponent)\n const padding = 1\n const left = Math.max(0, minColumn - padding) / columns\n const top = Math.max(0, minRow - padding) / rows\n const right = Math.min(columns, maxColumn + padding + 1) / columns\n const bottom = Math.min(rows, maxRow + padding + 1) / rows\n const strength = darkness * Math.sqrt(areaRatio) * (0.75 + Math.min(0.25, printRatio))\n if (strength > best.strength) {\n best = {\n strong: strength >= 10,\n strength,\n darkness,\n areaRatio,\n region: {\n x: left,\n y: top,\n width: right - left,\n height: bottom - top,\n },\n }\n }\n }\n return best\n}\n\nfunction localMeanAt(\n integral: Uint32Array,\n stride: number,\n width: number,\n height: number,\n x: number,\n y: number,\n radius: number,\n) {\n const top = Math.max(0, y - radius)\n const bottom = Math.min(height, y + radius + 1)\n const left = Math.max(0, x - radius)\n const right = Math.min(width, x + radius + 1)\n const area = Math.max(1, (right - left) * (bottom - top))\n return (\n integral[bottom * stride + right] -\n integral[top * stride + right] -\n integral[bottom * stride + left] +\n integral[top * stride + left]\n ) / area\n}\n\nfunction integralImage(luminance: Uint8Array, width: number, height: number) {\n const stride = width + 1\n const integral = new Uint32Array((width + 1) * (height + 1))\n for (let y = 1; y <= height; y += 1) {\n let row = 0\n for (let x = 1; x <= width; x += 1) {\n row += luminance[(y - 1) * width + x - 1]\n integral[y * stride + x] = integral[(y - 1) * stride + x] + row\n }\n }\n return { integral, stride }\n}\n\nexport function flattenIlluminationLuminance(\n luminance: Uint8Array,\n width: number,\n height: number,\n radius = Math.max(12, Math.round(Math.max(width, height) / 32)),\n) {\n const { integral, stride } = integralImage(luminance, width, height)\n const output = new Uint8Array(luminance.length)\n for (let y = 0; y < height; y += 1) {\n for (let x = 0; x < width; x += 1) {\n const background = localMeanAt(\n integral,\n stride,\n width,\n height,\n x,\n y,\n radius,\n )\n output[y * width + x] = Math.max(\n 0,\n Math.min(255, Math.round(luminance[y * width + x] * 235 / Math.max(24, background))),\n )\n }\n }\n return output\n}\n\n/**\n * Bradley–Roth local-mean threshold. A pixel is ink when it is darker\n * than the neighborhood mean. One page-wide Otsu cut cannot keep both\n * lit paper and a soft shade as paper.\n */\nexport function adaptiveThresholdLuminance(\n luminance: Uint8Array,\n width: number,\n height: number,\n radius = Math.max(8, Math.round(Math.max(width, height) / 64)),\n sensitivity = 0.12,\n) {\n const { integral, stride } = integralImage(luminance, width, height)\n const output = new Uint8Array(luminance.length)\n const gain = 1 - sensitivity\n for (let y = 0; y < height; y += 1) {\n for (let x = 0; x < width; x += 1) {\n const mean = localMeanAt(integral, stride, width, height, x, y, radius)\n output[y * width + x] = luminance[y * width + x] < mean * gain ? 0 : 255\n }\n }\n return output\n}\n\nfunction quadBounds(quad: DocumentQuad, width: number, height: number) {\n const points = [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft]\n const left = Math.max(0, Math.min(...points.map((point) => point.x)))\n const top = Math.max(0, Math.min(...points.map((point) => point.y)))\n const right = Math.min(width, Math.max(...points.map((point) => point.x)))\n const bottom = Math.min(height, Math.max(...points.map((point) => point.y)))\n return { left, top, width: right - left, height: bottom - top }\n}\n\nexport function analyzeCanvasCastShadow(\n canvas: HTMLCanvasElement,\n quad: DocumentQuad,\n): CastShadowAnalysis {\n const bounds = quadBounds(quad, canvas.width, canvas.height)\n if (bounds.width <= 0 || bounds.height <= 0) {\n return { strong: false, strength: 0, darkness: 0, areaRatio: 0 }\n }\n const sample = document.createElement('canvas')\n sample.width = 60\n sample.height = 60\n const context = sample.getContext('2d', { willReadFrequently: true })\n if (!context) return { strong: false, strength: 0, darkness: 0, areaRatio: 0 }\n context.drawImage(\n canvas,\n bounds.left,\n bounds.top,\n bounds.width,\n bounds.height,\n 0,\n 0,\n sample.width,\n sample.height,\n )\n const pixels = context.getImageData(0, 0, sample.width, sample.height).data\n const luminance = new Uint8Array(sample.width * sample.height)\n for (let pixel = 0, offset = 0; pixel < luminance.length; pixel += 1, offset += 4) {\n luminance[pixel] = Math.round(\n pixels[offset] * 0.299 +\n pixels[offset + 1] * 0.587 +\n pixels[offset + 2] * 0.114,\n )\n }\n return analyzeCastShadowLuminance(luminance, sample.width, sample.height)\n}\n","import { captureVideoFrame } from './camera'\nimport { canvasUnavailable, ScannerError } from './errors'\nimport { assertLicense } from './license'\nimport { detectDocument, type ScanOptions } from './scan'\nimport { analyzeCanvasCastShadow } from './lighting'\nimport type {\n DocumentDetectionResult,\n DocumentModelStatus,\n DocumentQuad,\n Point,\n} from './types'\n\nexport type AutoCaptureMode = 'defaultOn' | 'defaultOff' | 'alwaysOn' | 'alwaysOff' | 'only'\nexport type FinderSource = HTMLVideoElement | MediaStream | HTMLCanvasElement\nexport type FinderState = 'seeking' | 'detecting' | 'unstable' | 'ready' | 'captured'\nexport type FinderGuidanceReason =\n | 'place-document'\n | 'move-closer'\n | 'move-farther-away'\n | 'straighten-camera'\n | 'hold-still'\n | 'ready'\n\nexport interface QuadFill {\n /** Raw quad bounds width divided by the analysis frame width. */\n widthFill: number\n /** Raw quad bounds height divided by the analysis frame height. */\n heightFill: number\n /** Fill on the limiting axis: `max(widthFill, heightFill)`. */\n limitingFill: number\n /** Shoelace polygon area divided by the analysis frame area. Diagnostic only. */\n areaFill: number\n /** Long side divided by short side of the raw quad. */\n aspectRatio: number\n}\n\nexport interface FinderGuidance {\n hint: string\n reason: FinderGuidanceReason\n /**\n * Fill on the limiting axis of the raw quad: the larger of its width and\n * height fill. A tall receipt that fills the frame height is fully framed\n * even though its bounding box covers little frame area.\n */\n fillRatio: number\n /** Component fills, polygon area fill, and aspect ratio behind `fillRatio`. */\n fill: QuadFill\n readyForAutoCapture: boolean\n}\n\nexport interface FinderLighting {\n castShadow: boolean\n strength: number\n hint?: string\n}\n\nexport function selectFinderHint(\n guidance: FinderGuidance,\n lighting: FinderLighting,\n) {\n return lighting.castShadow &&\n (guidance.reason === 'hold-still' || guidance.reason === 'ready')\n ? lighting.hint ?? guidance.hint\n : guidance.hint\n}\n\nexport interface AutoCaptureControl {\n visible: boolean\n checked: boolean\n mutable: boolean\n}\n\nexport interface FinderStatus {\n state: FinderState\n confidence: number\n quad?: DocumentQuad\n guidance: FinderGuidance\n lighting: FinderLighting\n stableFrames: number\n requiredStableFrames: number\n autoCapture: AutoCaptureControl\n sourceWidth?: number\n sourceHeight?: number\n detector?: DocumentDetectionResult['detector']\n modelStatus?: DocumentModelStatus\n modelProvider?: DocumentDetectionResult['modelProvider']\n modelError?: string\n modelNote?: string\n inferenceMs?: number\n}\n\nexport interface FinderCapture {\n frame: HTMLCanvasElement\n detection?: DocumentDetectionResult\n reason: 'auto' | 'manual'\n}\n\nexport interface FinderOptions {\n source: FinderSource\n autoCapture: AutoCaptureMode\n /** Supplies the final full-resolution frame while finder analysis stays bounded. */\n captureFrame?: () => HTMLCanvasElement | Promise<HTMLCanvasElement>\n onStatus?: (status: FinderStatus) => void\n onCapture?: (capture: FinderCapture) => void | Promise<void>\n /** Reports capture failures, including automatic captures, instead of swallowing them. */\n onCaptureError?: (error: Error) => void\n /** Consecutive stable raw detections required. Defaults to 4. */\n stableFrames?: number\n /** Minimum detector confidence on the normalized 0–1 scale. Defaults to 0.72. */\n confidenceThreshold?: number\n /** Maximum normalized corner movement while entering ready. Defaults to 0.024. */\n cornerTolerance?: number\n /** Movement allowed after ready before dropping out. Defaults to 0.036. */\n exitCornerTolerance?: number\n intervalMs?: number\n /** Maximum analysis-frame long edge. Defaults to 1600. Detection then uses a 520px working image. */\n maxFrameDimension?: number\n guidance?: FinderGuidanceOptions\n detection?: ScanOptions\n playShutterSound?: boolean\n}\n\nexport interface FinderSession {\n stop: () => void\n capture: () => Promise<FinderCapture>\n setAutoCapture: (enabled: boolean) => boolean\n getStatus: () => FinderStatus\n}\n\nexport async function snapshotBeforeCaptureFeedback<T>(\n snapshot: () => T | Promise<T>,\n feedback: () => void,\n) {\n const captured = await snapshot()\n feedback()\n return captured\n}\n\nexport function autoCaptureControl(mode: AutoCaptureMode): AutoCaptureControl {\n if (mode === 'alwaysOn' || mode === 'only') return { visible: false, checked: true, mutable: false }\n if (mode === 'alwaysOff') return { visible: false, checked: false, mutable: false }\n return {\n visible: true,\n checked: mode === 'defaultOn',\n mutable: true,\n }\n}\n\nfunction cornerList(quad: DocumentQuad): Point[] {\n return [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft]\n}\n\nexport interface StabilityOptions {\n stableFrames: number\n confidenceThreshold: number\n cornerTolerance: number\n exitCornerTolerance?: number\n}\n\nexport interface FinderGuidanceOptions {\n confidenceThreshold?: number\n /** Limiting-axis fill required to enter ready. Defaults to 0.72. */\n minFillRatio?: number\n /** Limiting-axis fill allowed after ready before exiting. Defaults to 0.64. */\n exitFillRatio?: number\n /** Long-to-short side ratio that makes a document high-aspect. Defaults to 2.2. */\n highAspectRatio?: number\n /** Long-side fill required to enter ready on a high-aspect document. Defaults to 0.8. */\n highAspectFillRatio?: number\n /** Long-side fill allowed after ready on a high-aspect document. Defaults to 0.72. */\n highAspectExitFillRatio?: number\n /** Edge clearance required to enter ready. Defaults to 0.015. */\n edgeMarginRatio?: number\n /** Edge clearance allowed after ready. Defaults to 0.005. */\n exitEdgeMarginRatio?: number\n /** Opposite-edge ratio required to enter ready. Defaults to 0.48. */\n minPerspectiveRatio?: number\n /** Opposite-edge ratio allowed after ready. Defaults to 0.4. */\n exitMinPerspectiveRatio?: number\n}\n\nexport const DEFAULT_FINDER_STABLE_FRAMES = 4\nexport const DEFAULT_FINDER_CONFIDENCE_THRESHOLD = 0.72\nexport const DEFAULT_FINDER_CORNER_TOLERANCE = 0.024\nexport const DEFAULT_FINDER_EXIT_CORNER_TOLERANCE = 0.036\nexport const DEFAULT_FINDER_MIN_FILL_RATIO = 0.72\nexport const DEFAULT_FINDER_EXIT_FILL_RATIO = 0.64\nexport const DEFAULT_FINDER_HIGH_ASPECT_RATIO = 2.2\n/** Extra long-side fill asked of a high-aspect document, above the base target. */\nexport const DEFAULT_FINDER_HIGH_ASPECT_FILL_MARGIN = 0.08\nexport const DEFAULT_FINDER_EDGE_MARGIN_RATIO = 0.015\nexport const DEFAULT_FINDER_EXIT_EDGE_MARGIN_RATIO = 0.005\nexport const DEFAULT_FINDER_MIN_PERSPECTIVE_RATIO = 0.48\nexport const DEFAULT_FINDER_EXIT_MIN_PERSPECTIVE_RATIO = 0.40\nexport const DEFAULT_FINDER_MAX_FRAME_DIMENSION = 1600\n\nexport interface FinderDetectionLog {\n level: 'info' | 'warn'\n /** Stable identity used to throttle repeated samples of the same failure. */\n key: string\n summary: string\n detail: Record<string, string | number>\n}\n\n/** One console record for a finder sample. Failures are warnings; a found page is info. */\nexport function finderDetectionLog(\n detection: Pick<\n DocumentDetectionResult,\n | 'status'\n | 'message'\n | 'confidence'\n | 'modelStatus'\n | 'modelError'\n | 'modelProvider'\n | 'modelNote'\n | 'inferenceMs'\n | 'sourceWidth'\n | 'sourceHeight'\n >,\n frame?: { width: number; height: number },\n): FinderDetectionLog {\n const found = detection.status === 'success' && detection.modelStatus !== 'failed'\n const detail: Record<string, string | number> = {\n status: detection.status,\n confidence: Number(detection.confidence.toFixed(3)),\n source: `${detection.sourceWidth}×${detection.sourceHeight}`,\n }\n if (frame?.width && frame?.height) detail.video = `${frame.width}×${frame.height}`\n if (detection.modelStatus) detail.modelStatus = detection.modelStatus\n if (detection.modelProvider) detail.provider = detection.modelProvider\n if (detection.modelError) detail.modelError = detection.modelError\n if (detection.modelNote) detail.modelNote = detection.modelNote\n if (detection.inferenceMs !== undefined) detail.inferenceMs = Math.round(detection.inferenceMs)\n if (!found && detection.message) detail.message = detection.message\n const summary = found\n ? 'document found'\n : detection.modelStatus === 'failed'\n ? 'document not found (ML failed)'\n : `document not found (${detection.status})`\n return {\n level: found ? 'info' : 'warn',\n key: [\n summary,\n detail.modelStatus ?? '',\n detail.modelError ?? '',\n detail.provider ?? '',\n detail.modelNote ?? '',\n detail.source,\n detail.video ?? '',\n ].join('|'),\n summary,\n detail,\n }\n}\n\nfunction polygonArea(points: Point[]) {\n let area = 0\n for (let index = 0; index < points.length; index += 1) {\n const current = points[index]\n const next = points[(index + 1) % points.length]\n area += current.x * next.y - next.x * current.y\n }\n return Math.abs(area) / 2\n}\n\nfunction distance(first: Point, second: Point) {\n return Math.hypot(first.x - second.x, first.y - second.y)\n}\n\nconst EMPTY_FILL: QuadFill = {\n widthFill: 0,\n heightFill: 0,\n limitingFill: 0,\n areaFill: 0,\n aspectRatio: 1,\n}\n\n/**\n * Measures how much of each frame axis the raw quad occupies. A document can\n * only grow until its limiting axis reaches a frame edge, so the larger of the\n * two axis fills — not the bounding-box area — describes how well it is framed.\n */\nexport function measureQuadFill(\n quad: DocumentQuad,\n frameWidth: number,\n frameHeight: number,\n): QuadFill {\n const points = cornerList(quad)\n const xs = points.map(({ x }) => x)\n const ys = points.map(({ y }) => y)\n const widthFill = (Math.max(...xs) - Math.min(...xs)) / Math.max(1, frameWidth)\n const heightFill = (Math.max(...ys) - Math.min(...ys)) / Math.max(1, frameHeight)\n const [topLeft, topRight, bottomRight, bottomLeft] = points\n const horizontal = Math.max(\n distance(topLeft, topRight),\n distance(bottomLeft, bottomRight),\n )\n const vertical = Math.max(\n distance(topLeft, bottomLeft),\n distance(topRight, bottomRight),\n )\n return {\n widthFill,\n heightFill,\n limitingFill: Math.max(widthFill, heightFill),\n areaFill: polygonArea(points) / Math.max(1, frameWidth * frameHeight),\n aspectRatio: Math.max(horizontal, vertical) /\n Math.max(1, Math.min(horizontal, vertical)),\n }\n}\n\n/**\n * Fill the limiting axis must reach. High-aspect documents are asked for a\n * little more of the long side, because their short side can never fill and\n * the long side is the only axis carrying resolution. The target never exceeds\n * what the edge margin physically allows.\n */\nexport function limitingFillTarget(\n fill: QuadFill,\n previouslyReady: boolean,\n edgeMarginRatio: number,\n options: FinderGuidanceOptions = {},\n) {\n const base = previouslyReady\n ? options.exitFillRatio ?? DEFAULT_FINDER_EXIT_FILL_RATIO\n : options.minFillRatio ?? DEFAULT_FINDER_MIN_FILL_RATIO\n const highAspectRatio = options.highAspectRatio ?? DEFAULT_FINDER_HIGH_ASPECT_RATIO\n if (fill.aspectRatio < highAspectRatio) return base\n const configured = previouslyReady\n ? options.highAspectExitFillRatio\n : options.highAspectFillRatio\n return Math.min(\n configured ?? base + DEFAULT_FINDER_HIGH_ASPECT_FILL_MARGIN,\n 1 - edgeMarginRatio * 2,\n )\n}\n\nexport function selectFinderGuidance(\n detection: DocumentDetectionResult,\n stability: { ready: boolean; previouslyReady?: boolean },\n options: FinderGuidanceOptions = {},\n): FinderGuidance {\n const confidenceThreshold =\n options.confidenceThreshold ?? DEFAULT_FINDER_CONFIDENCE_THRESHOLD\n if (\n detection.status !== 'success' ||\n !detection.quad ||\n detection.confidence < confidenceThreshold ||\n !detection.sourceWidth ||\n !detection.sourceHeight\n ) {\n return {\n hint: 'Place the document in the frame',\n reason: 'place-document',\n fillRatio: 0,\n fill: EMPTY_FILL,\n readyForAutoCapture: false,\n }\n }\n\n const points = cornerList(detection.quad)\n const fill = measureQuadFill(\n detection.quad,\n detection.sourceWidth,\n detection.sourceHeight,\n )\n const fillRatio = fill.limitingFill\n const edgeMarginRatio = stability.previouslyReady\n ? options.exitEdgeMarginRatio ?? DEFAULT_FINDER_EXIT_EDGE_MARGIN_RATIO\n : options.edgeMarginRatio ?? DEFAULT_FINDER_EDGE_MARGIN_RATIO\n const marginX = detection.sourceWidth * edgeMarginRatio\n const marginY = detection.sourceHeight * edgeMarginRatio\n const clippingRisk = points.some(({ x, y }) =>\n x <= marginX ||\n x >= detection.sourceWidth - marginX ||\n y <= marginY ||\n y >= detection.sourceHeight - marginY,\n )\n if (clippingRisk) {\n return {\n hint: 'Move farther away',\n reason: 'move-farther-away',\n fillRatio,\n fill,\n readyForAutoCapture: false,\n }\n }\n\n const [topLeft, topRight, bottomRight, bottomLeft] = points\n const top = distance(topLeft, topRight)\n const right = distance(topRight, bottomRight)\n const bottom = distance(bottomRight, bottomLeft)\n const left = distance(bottomLeft, topLeft)\n const oppositeRatio = Math.min(\n Math.min(top, bottom) / Math.max(1, Math.max(top, bottom)),\n Math.min(left, right) / Math.max(1, Math.max(left, right)),\n )\n const minPerspectiveRatio = stability.previouslyReady\n ? options.exitMinPerspectiveRatio ?? DEFAULT_FINDER_EXIT_MIN_PERSPECTIVE_RATIO\n : options.minPerspectiveRatio ?? DEFAULT_FINDER_MIN_PERSPECTIVE_RATIO\n if (oppositeRatio < minPerspectiveRatio) {\n return {\n hint: 'Hold the camera straight',\n reason: 'straighten-camera',\n fillRatio,\n fill,\n readyForAutoCapture: false,\n }\n }\n\n // Both axes have slack only when the limiting one does, so a skinny document\n // that already fills its long axis is never told to move closer.\n const fillTarget = limitingFillTarget(\n fill,\n stability.previouslyReady === true,\n edgeMarginRatio,\n options,\n )\n if (fillRatio < fillTarget) {\n return {\n hint: 'Move closer',\n reason: 'move-closer',\n fillRatio,\n fill,\n readyForAutoCapture: false,\n }\n }\n\n return {\n hint: 'Hold still',\n reason: stability.ready ? 'ready' : 'hold-still',\n fillRatio,\n fill,\n readyForAutoCapture: stability.ready,\n }\n}\n\nexport class QuadStabilityTracker {\n private previous?: DocumentQuad\n private count = 0\n private ready = false\n private readonly options: StabilityOptions\n\n constructor(options: StabilityOptions) {\n this.options = options\n }\n\n reset() {\n this.previous = undefined\n this.count = 0\n this.ready = false\n }\n\n update(detection: DocumentDetectionResult) {\n if (\n detection.status !== 'success' ||\n !detection.quad ||\n detection.confidence < this.options.confidenceThreshold\n ) {\n this.reset()\n return { stableFrames: 0, ready: false, movement: Infinity }\n }\n const diagonal = Math.hypot(detection.sourceWidth, detection.sourceHeight)\n const movement = this.previous\n ? Math.max(...cornerList(detection.quad).map((point, index) => {\n const previous = cornerList(this.previous!)[index]\n return Math.hypot(point.x - previous.x, point.y - previous.y) / Math.max(1, diagonal)\n }))\n : Infinity\n const exitTolerance = this.options.exitCornerTolerance ??\n Math.max(this.options.cornerTolerance, DEFAULT_FINDER_EXIT_CORNER_TOLERANCE)\n if (this.ready && this.previous && movement <= exitTolerance) {\n this.count = Math.max(this.options.stableFrames, this.count + 1)\n } else {\n this.ready = false\n this.count = this.previous && movement <= this.options.cornerTolerance\n ? this.count + 1\n : 1\n if (this.count >= this.options.stableFrames) this.ready = true\n }\n this.previous = detection.quad\n return {\n stableFrames: this.count,\n ready: this.ready,\n movement,\n }\n }\n}\n\nfunction cloneCanvas(source: HTMLCanvasElement, maxDimension: number) {\n const scale = Math.min(1, maxDimension / Math.max(source.width, source.height))\n const output = document.createElement('canvas')\n output.width = Math.max(1, Math.round(source.width * scale))\n output.height = Math.max(1, Math.round(source.height * scale))\n const context = output.getContext('2d')\n if (!context) throw canvasUnavailable()\n context.drawImage(source, 0, 0, output.width, output.height)\n return output\n}\n\nfunction playShutter() {\n const AudioContextClass = window.AudioContext ??\n (window as typeof window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext\n if (!AudioContextClass) return\n const context = new AudioContextClass()\n const length = Math.round(context.sampleRate * 0.09)\n const buffer = context.createBuffer(1, length, context.sampleRate)\n const channel = buffer.getChannelData(0)\n for (let index = 0; index < length; index += 1) {\n const envelope = Math.exp(-index / (context.sampleRate * 0.018))\n channel[index] = (Math.random() * 2 - 1) * envelope\n }\n const source = context.createBufferSource()\n const filter = context.createBiquadFilter()\n const gain = context.createGain()\n filter.type = 'bandpass'\n filter.frequency.value = 1400\n gain.gain.value = 0.42\n source.buffer = buffer\n source.connect(filter).connect(gain).connect(context.destination)\n source.start()\n source.onended = () => void context.close()\n}\n\nasync function videoForStream(stream: MediaStream) {\n const video = document.createElement('video')\n video.muted = true\n video.autoplay = true\n video.playsInline = true\n video.srcObject = stream\n await video.play()\n return video\n}\n\n/**\n * Watches a camera or canvas for a stable document.\n * Detection quality is reported on `FinderStatus`, not thrown.\n * Worker startup and DocAligner HTTP failures are caught on each tick and\n * reported as `modelStatus: 'failed'` with `modelError`. The camera stays up.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed. The finder does not start.\n */\nexport async function startFinder(options: FinderOptions): Promise<FinderSession> {\n await assertLicense('scan')\n const control = autoCaptureControl(options.autoCapture)\n const tracker = new QuadStabilityTracker({\n stableFrames: options.stableFrames ?? DEFAULT_FINDER_STABLE_FRAMES,\n confidenceThreshold:\n options.confidenceThreshold ?? DEFAULT_FINDER_CONFIDENCE_THRESHOLD,\n cornerTolerance: options.cornerTolerance ?? DEFAULT_FINDER_CORNER_TOLERANCE,\n exitCornerTolerance:\n options.exitCornerTolerance ?? DEFAULT_FINDER_EXIT_CORNER_TOLERANCE,\n })\n const maxDimension = options.maxFrameDimension ?? DEFAULT_FINDER_MAX_FRAME_DIMENSION\n const interval = options.intervalMs ?? 140\n const detectionOptions: ScanOptions = {\n minDimension: 220,\n maxAnalysisDimension: 520,\n ...options.detection,\n }\n const source: HTMLVideoElement | HTMLCanvasElement =\n typeof MediaStream !== 'undefined' && options.source instanceof MediaStream\n ? await videoForStream(options.source)\n : options.source as HTMLVideoElement | HTMLCanvasElement\n let running = true\n let captureStarted = false\n let guidanceReady = false\n let timer = 0\n let latestDetection: DocumentDetectionResult | undefined\n let lastDetectionLogKey = ''\n let lastDetectionLogAt = 0\n let status: FinderStatus = {\n state: 'detecting',\n confidence: 0,\n guidance: {\n hint: 'Place the document in the frame',\n reason: 'place-document',\n fillRatio: 0,\n fill: EMPTY_FILL,\n readyForAutoCapture: false,\n },\n lighting: { castShadow: false, strength: 0 },\n stableFrames: 0,\n requiredStableFrames: options.stableFrames ?? DEFAULT_FINDER_STABLE_FRAMES,\n autoCapture: { ...control },\n }\n\n const frame = () => {\n if (source instanceof HTMLCanvasElement) return cloneCanvas(source, maxDimension)\n return captureVideoFrame(source, maxDimension)\n }\n const emit = (next: FinderStatus) => {\n status = next\n options.onStatus?.(next)\n }\n const logDetection = (detection: DocumentDetectionResult) => {\n const frame = source instanceof HTMLVideoElement\n ? { width: source.videoWidth, height: source.videoHeight }\n : { width: source.width, height: source.height }\n const entry = finderDetectionLog(detection, frame)\n const now = performance.now()\n if (entry.key === lastDetectionLogKey && now - lastDetectionLogAt < 2000) return\n lastDetectionLogKey = entry.key\n lastDetectionLogAt = now\n console[entry.level](`[exige-scanner] ${entry.summary}`, entry.detail)\n }\n const stop = () => {\n running = false\n window.clearTimeout(timer)\n if (source instanceof HTMLVideoElement && source !== options.source) source.srcObject = null\n }\n const capture = async (reason: FinderCapture['reason'] = 'manual') => {\n if (captureStarted) throw new Error('A finder capture is already in progress.')\n captureStarted = true\n let capturedFrame: HTMLCanvasElement\n try {\n capturedFrame = await snapshotBeforeCaptureFeedback(\n options.captureFrame ?? frame,\n () => {\n emit({ ...status, state: 'captured' })\n if (options.playShutterSound !== false) playShutter()\n stop()\n },\n )\n } catch (error) {\n // Leave the finder usable so the end user can retake after a blank frame.\n captureStarted = false\n throw error instanceof Error ? error : new Error('The camera frame could not be captured.')\n }\n const result: FinderCapture = { frame: capturedFrame, detection: latestDetection, reason }\n await options.onCapture?.(result)\n return result\n }\n const tick = async () => {\n if (!running || captureStarted) return\n try {\n const current = frame()\n const detection = await detectDocument(current, detectionOptions)\n latestDetection = detection\n logDetection(detection)\n const shadow = detection.quad\n ? analyzeCanvasCastShadow(current, detection.quad)\n : { strong: false, strength: 0 }\n const lighting: FinderLighting = shadow.strong\n ? {\n castShadow: true,\n strength: shadow.strength,\n hint: 'Tilt to move the shadow off the page',\n }\n : { castShadow: false, strength: shadow.strength }\n const stability = tracker.update(detection)\n const guidance = selectFinderGuidance(detection, {\n ...stability,\n previouslyReady: guidanceReady,\n }, {\n confidenceThreshold:\n options.confidenceThreshold ?? DEFAULT_FINDER_CONFIDENCE_THRESHOLD,\n ...options.guidance,\n })\n guidanceReady = guidance.readyForAutoCapture\n const nextState: FinderState =\n detection.status !== 'success' || guidance.reason === 'place-document'\n ? 'seeking'\n : guidance.readyForAutoCapture\n ? 'ready'\n : 'unstable'\n emit({\n state: nextState,\n confidence: detection.confidence,\n quad: detection.quad,\n guidance,\n lighting,\n stableFrames: stability.stableFrames,\n requiredStableFrames: status.requiredStableFrames,\n autoCapture: { ...control },\n sourceWidth: detection.sourceWidth,\n sourceHeight: detection.sourceHeight,\n detector: detection.detector,\n modelStatus: detection.modelStatus,\n modelProvider: detection.modelProvider,\n modelError: detection.modelError,\n modelNote: detection.modelNote,\n inferenceMs: detection.inferenceMs,\n })\n if (guidance.readyForAutoCapture && control.checked) {\n try {\n await capture('auto')\n return\n } catch (error) {\n tracker.reset()\n guidanceReady = false\n options.onCaptureError?.(\n error instanceof Error ? error : new Error('Automatic capture failed.'),\n )\n }\n }\n } catch (error) {\n tracker.reset()\n guidanceReady = false\n const failure = error instanceof ScannerError\n ? {\n detector: 'ml' as const,\n modelStatus: 'failed' as const,\n modelError: error.message,\n }\n : {\n modelError: error instanceof Error ? error.message : 'Finder tick failed.',\n }\n logDetection({\n status: 'no-document',\n confidence: 0,\n message: failure.modelError ?? 'Finder tick failed.',\n sourceWidth: 0,\n sourceHeight: 0,\n ...failure,\n })\n emit({\n state: 'seeking',\n confidence: 0,\n guidance: {\n hint: 'Place the document in the frame',\n reason: 'place-document',\n fillRatio: 0,\n fill: EMPTY_FILL,\n readyForAutoCapture: false,\n },\n lighting: { castShadow: false, strength: 0 },\n stableFrames: 0,\n requiredStableFrames: status.requiredStableFrames,\n autoCapture: { ...control },\n ...failure,\n })\n }\n if (running) timer = window.setTimeout(() => void tick(), interval)\n }\n\n options.onStatus?.(status)\n void tick()\n return {\n stop,\n capture: () => capture('manual'),\n setAutoCapture(enabled) {\n if (!control.mutable || captureStarted) return false\n control.checked = enabled\n emit({ ...status, autoCapture: { ...control } })\n return true\n },\n getStatus: () => status,\n }\n}\n"],"mappings":";AAeA,IAAa,IAAb,cAAkC,MAAM;CACtC;CAEA,YAAY,GAAwB,GAAiB;EAGnD,AAFA,MAAM,CAAO,GACb,KAAK,OAAO,gBACZ,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,IAAkC;CAChD,OAAO,IAAI,EAAa,UAAU,2CAA2C;AAC/E;;;ACrBA,SAAgB,EAAiB,GAA2B;CAC1D,IAAM,IAAa,EAAM,WAAW,KAAK,GAAG,CAAC,CAAC,WAAW,KAAK,GAAG,GAC3D,IAAS,IAAa,IAAI,QAAQ,IAAK,EAAW,SAAS,KAAM,CAAC,GAClE,IAAS,KAAK,CAAM,GACpB,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAA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