okrapdf 0.12.1 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/bin.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * okra CLI — Agent-friendly PDF extraction and collection queries.\n *\n * Global flags:\n * -j, --json Structured JSON output\n * -q, --quiet Suppress progress (just data to stdout)\n * -o, --output Write output to file (CSV/JSON/ZIP)\n *\n * Action commands (agent-grade):\n * okra upload <source> # Upload + wait\n * okra collection list # List collections\n * okra collection query <name> \"<question>\" # Fan-out → CSV\n *\n * Review commands (existing):\n * okra tree / find / page / search / tables / history / toc\n *\n * Exit codes: 0=success, 1=client error, 2=server error\n */\n\nimport { Command } from 'commander';\nimport { writeFileSync } from 'fs';\nimport { OkraClient } from '../client';\nimport {\n tree,\n formatTreeOutput,\n find,\n formatFindOutput,\n formatStats,\n pageGet,\n pageEdit,\n pageResolve,\n pageVersions,\n formatPageOutput,\n formatVersionsOutput,\n search,\n formatSearchOutput,\n tables,\n formatTablesOutput,\n history,\n formatHistoryOutput,\n toc,\n formatTocOutput,\n authLogin,\n authSetKey,\n authStatus,\n authWhoAmI,\n authToken,\n authLogout,\n upload,\n collectionList,\n collectionSetVisibility,\n collectionQueryRaw,\n collectionExport,\n formatCollectionList,\n formatCollectionCsv,\n formatCollectionTable,\n formatQueryJsonl,\n formatCollectionExportFlat,\n} from './commands';\nimport { getApiKey, getBaseUrl } from './config';\nimport { handleError, writeOutput, progress } from './output';\nimport type { GlobalFlags } from './output';\n\nconst program = new Command();\nprogram.showHelpAfterError();\nprogram.showSuggestionAfterError();\n\nprogram\n .name('okra')\n .description('OkraPDF CLI — upload PDFs, query collections, extract data')\n .version('0.12.1')\n .option('-j, --json', 'Output JSON (structured, machine-readable)')\n .option('-q, --quiet', 'Suppress progress and human-readable frills')\n .option('-o, --output <file>', 'Write output to file instead of stdout');\n\n/** Read global flags from program.opts(). */\nfunction globals(): GlobalFlags {\n return program.opts();\n}\n\n// Create client with proper config priority:\n// 1. Environment variable (OKRA_API_KEY)\n// 2. Project config (.okrarc, .okra.json)\n// 3. Global config (~/.okra/config.json)\nfunction getClient(): OkraClient {\n const apiKey = getApiKey();\n const baseUrl = getBaseUrl();\n\n if (!apiKey) {\n const g = globals();\n if (g.json) {\n process.stderr.write(JSON.stringify({ error: 'No API key found', code: 401 }) + '\\n');\n } else {\n process.stderr.write(\n 'No API key found.\\n\\n' +\n ' Get one: https://docs.okrapdf.com/api-keys\\n' +\n ' Then: export OKRA_API_KEY=\"okra_xxx\"\\n' +\n ' Or: npx okra auth login\\n\\n' +\n ' Docs: https://docs.okrapdf.com\\n' +\n ' Discord: https://discord.gg/BHNmbZVs\\n',\n );\n }\n process.exit(1);\n }\n\n return new OkraClient({ apiKey, baseUrl });\n}\n\n// ============================================================================\n// upload command\n// ============================================================================\nasync function runUploadCommand(source: string, options: { wait?: boolean }): Promise<void> {\n const g = globals();\n try {\n const client = getClient();\n const result = await upload(client, source, {\n ...g,\n noWait: options.wait === false,\n });\n\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n const lines = [`Done — ${result.pages ?? '?'} pages`, ''];\n lines.push(` ${result.id}`);\n if (result.urls) {\n const short = result.id.slice(0, 11) + '...';\n lines.push('');\n lines.push(` Markdown: ${result.urls.full_md.replace(result.id, short)}`);\n lines.push(` Page 1: ${result.urls.page_png.replace(result.id, short).replace('{N}', '1')}`);\n lines.push(` Completion: ${result.urls.completion.replace(result.id, short)}`);\n lines.push('');\n lines.push(' URL patterns:');\n lines.push(' /v1/documents/{id}/pg_{N}.md page markdown');\n lines.push(' /v1/documents/{id}/d_shimmer/pg_{N}.png page image');\n lines.push(' /v1/documents/{id}/full.md full document');\n lines.push('');\n lines.push(' Docs: https://docs.okrapdf.com Discord: https://discord.gg/BHNmbZVs');\n }\n writeOutput(lines.join('\\n'), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n}\n\nfunction registerUploadCommand(commandName: string, description: string): void {\n program\n .command(`${commandName} <source>`)\n .description(description)\n .option('--no-wait', 'Fire-and-forget (don\\'t wait for processing)')\n .action(async (source, options) => {\n await runUploadCommand(source, options);\n });\n}\n\nregisterUploadCommand('upload', 'Upload a PDF (file path or URL), wait for processing');\nregisterUploadCommand('extract', 'Alias for upload (compatibility)');\n\n// ============================================================================\n// status command\n// ============================================================================\nprogram\n .command('status <docId>')\n .description('Get document processing status')\n .action(async (docId) => {\n const g = globals();\n try {\n const client = getClient();\n const status = await client.status(docId);\n if (g.json) {\n writeOutput(JSON.stringify(status), g.output);\n } else {\n const lines = [\n `Document: ${docId}`,\n `Phase: ${status.phase}`,\n ];\n if (typeof status.pagesCompleted === 'number' || typeof status.pagesTotal === 'number') {\n lines.push(`Pages: ${status.pagesCompleted ?? '?'} / ${status.pagesTotal ?? '?'}`);\n }\n writeOutput(lines.join('\\n'), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// chat command\n// ============================================================================\nprogram\n .command('chat <question>')\n .description('Ask a question about a processed document')\n .requiredOption('--doc <id>', 'Document ID')\n .option('--model <name>', 'Override model')\n .action(async (question, options) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await client.generate(options.doc, question, options.model ? { model: options.model } : undefined);\n\n if (g.json) {\n writeOutput(JSON.stringify({ docId: options.doc, question, ...result }), g.output);\n } else {\n writeOutput(result.answer, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// collection command\n// ============================================================================\nconst collectionCmd = program\n .command('collection')\n .alias('collections')\n .alias('col')\n .description('Collection operations');\n\ncollectionCmd\n .command('list')\n .alias('ls')\n .description('List available collections')\n .action(async () => {\n const g = globals();\n try {\n const client = getClient();\n const rows = await collectionList(client, g);\n writeOutput(formatCollectionList(rows, g.json), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('query <nameOrId> <question>')\n .description('Fan-out query across collection documents')\n .option('--schema <file>', 'JSON Schema file for structured extraction')\n .action(async (nameOrId, question, options) => {\n const g = globals();\n try {\n const client = getClient();\n const { results, summary } = await collectionQueryRaw(\n client,\n nameOrId,\n question,\n { ...g, schema: options.schema },\n );\n\n // Determine output format based on flags\n if (g.json) {\n // --json: JSONL events to stdout\n writeOutput(formatQueryJsonl(results), g.output);\n } else if (g.output && g.output.endsWith('.csv')) {\n // -o file.csv → CSV\n writeOutput(formatCollectionCsv(results), g.output);\n } else if (g.output) {\n // -o file.json or other → JSON\n writeOutput(JSON.stringify({ results, summary }), g.output);\n } else {\n // Default: compact table to stdout\n writeOutput(formatCollectionTable(results));\n }\n\n progress(\n `${summary.completed} completed, ${summary.failed} failed — $${summary.total_cost_usd.toFixed(4)}`,\n g.quiet,\n );\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('publish <nameOrId>')\n .description('Make a collection publicly queryable')\n .action(async (nameOrId) => {\n const g = globals();\n try {\n const client = getClient();\n await collectionSetVisibility(client, nameOrId, 'public');\n if (g.json) {\n writeOutput(JSON.stringify({ ok: true, visibility: 'public', collection: nameOrId }), g.output);\n } else {\n writeOutput(\n `Published \"${nameOrId}\"\\n` +\n `Share with: okra collection query ${nameOrId} \"your question\"`,\n g.output,\n );\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('unpublish <nameOrId>')\n .description('Make a collection private (owner-only)')\n .action(async (nameOrId) => {\n const g = globals();\n try {\n const client = getClient();\n await collectionSetVisibility(client, nameOrId, 'private');\n if (g.json) {\n writeOutput(JSON.stringify({ ok: true, visibility: 'private', collection: nameOrId }), g.output);\n } else {\n writeOutput(`Unpublished \"${nameOrId}\" — now private`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('export <nameOrId>')\n .description('Export pre-computed markdown for all documents in a collection')\n .option('--flat', 'Concatenated markdown with # headers + === separators')\n .option('--zip', 'One markdown file per document in a .zip archive')\n .action(async (nameOrId, options) => {\n const g = globals();\n try {\n const client = getClient();\n\n if (options.flat && options.zip) {\n throw new Error('Use either --flat or --zip, not both');\n }\n\n if (options.zip) {\n const bytes = await collectionExport(client, nameOrId, { ...g, zip: true });\n const safeBase = String(nameOrId)\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^[-_.]+|[-_.]+$/g, '') || 'collection-export';\n const outputPath = g.output || `${safeBase}.zip`;\n writeFileSync(outputPath, bytes);\n progress(`Wrote → ${outputPath}`, g.quiet);\n\n if (g.json) {\n writeOutput(JSON.stringify({\n format: 'zip',\n file: outputPath,\n bytes: bytes.byteLength,\n }));\n }\n return;\n }\n\n const result = await collectionExport(client, nameOrId, { ...g, flat: options.flat });\n\n if (options.flat) {\n writeOutput(formatCollectionExportFlat(result), g.output);\n } else if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n // Default: structured JSON\n writeOutput(JSON.stringify(result, null, 2), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// auth command - Authentication management\n// ============================================================================\nconst authCmd = program.command('auth').description('Manage authentication');\n\nauthCmd\n .command('login')\n .description('Save API key to global config')\n .option('-k, --key <apiKey>', 'Set API key non-interactively')\n .action(async (options) => {\n try {\n await authLogin(options.key);\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('set-key <apiKey>')\n .description('Save API key to global config (non-interactive)')\n .action(async (apiKey) => {\n try {\n await authSetKey(apiKey);\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('status')\n .description('Show authentication status')\n .action(async () => {\n try {\n await authStatus();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('whoami')\n .description('Show current auth identity (alias for status)')\n .action(async () => {\n try {\n await authWhoAmI();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('token')\n .description('Print active API key to stdout')\n .action(async () => {\n try {\n await authToken();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('logout')\n .description('Remove API key from global config')\n .action(async () => {\n try {\n await authLogout();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\n// ============================================================================\n// tree command - Document verification tree\n// ============================================================================\nprogram\n .command('tree <jobId>')\n .description('Show document verification tree')\n .option('-s, --status <status>', 'Filter by status (complete|partial|pending|flagged|empty|gap)')\n .option('-e, --entity <type>', 'Filter by entity type (table|figure|footnote)')\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'text')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await tree(client, jobId, {\n status: options.status,\n entity: options.entity,\n });\n writeOutput(formatTreeOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// find command - jQuery-like entity search\n// ============================================================================\nprogram\n .command('find <jobId> <selector>')\n .description('Find entities using jQuery-like selectors')\n .option('-k, --top-k <n>', 'Limit results', parseInt)\n .option('-c, --min-confidence <n>', 'Minimum confidence (0-1)', parseFloat)\n .option('-p, --pages <range>', 'Page range (e.g., 1-10)')\n .option('--sort <by>', 'Sort by (confidence|page|type)')\n .option('--stats', 'Show aggregate statistics')\n .option('-f, --format <format>', 'Output format (text|json|entities|ids)', 'text')\n .action(async (jobId, selector, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const pageRange = options.pages\n ? options.pages.split('-').map(Number) as [number, number]\n : undefined;\n\n const result = await find(client, jobId, selector, {\n topK: options.topK,\n minConfidence: options.minConfidence,\n pageRange,\n sortBy: options.sort,\n });\n\n if (options.stats && fmt === 'text') {\n writeOutput(formatStats(result.stats), g.output);\n } else {\n writeOutput(formatFindOutput(result, fmt, options.stats), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// page command - Page content operations\n// ============================================================================\nconst pageCmd = program.command('page').description('Page content operations');\n\npageCmd\n .command('get <jobId> <pageNum>')\n .description('Get page content')\n .option('-v, --version <n>', 'Specific version', parseInt)\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'markdown')\n .action(async (jobId, pageNum, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const content = await pageGet(client, jobId, parseInt(pageNum), {\n version: options.version,\n });\n writeOutput(formatPageOutput(content, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\npageCmd\n .command('edit <jobId> <pageNum>')\n .description('Edit page content (reads from stdin)')\n .action(async (jobId, pageNum) => {\n const g = globals();\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n const content = Buffer.concat(chunks).toString('utf8');\n\n const client = getClient();\n const result = await pageEdit(client, jobId, parseInt(pageNum), content);\n if (g.json) {\n writeOutput(JSON.stringify({ version: result.version }), g.output);\n } else {\n writeOutput(`Saved as version ${result.version}`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\npageCmd\n .command('resolve <jobId> <pageNum> <resolution>')\n .description('Resolve page verification status')\n .option('-c, --classification <class>', 'Classification')\n .option('-r, --reason <reason>', 'Reason')\n .action(async (jobId, pageNum, resolution, options) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await pageResolve(client, jobId, parseInt(pageNum), {\n resolution,\n classification: options.classification,\n reason: options.reason,\n });\n if (g.json) {\n writeOutput(JSON.stringify({ success: result.success }), g.output);\n } else {\n writeOutput(result.success ? 'Resolved' : 'Failed', g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\npageCmd\n .command('versions <jobId> <pageNum>')\n .description('List page versions')\n .option('-f, --format <format>', 'Output format (text|json)', 'text')\n .action(async (jobId, pageNum, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const versions = await pageVersions(client, jobId, parseInt(pageNum));\n writeOutput(formatVersionsOutput(versions, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// search command - Full-text search\n// ============================================================================\nprogram\n .command('search <jobId> <query>')\n .description('Search page content')\n .option('-f, --format <format>', 'Output format (text|json)', 'text')\n .action(async (jobId, query, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await search(client, jobId, query);\n writeOutput(formatSearchOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// tables command - List tables\n// ============================================================================\nprogram\n .command('tables <jobId>')\n .description('List extracted tables')\n .option('-p, --page <n>', 'Filter by page', parseInt)\n .option('-s, --status <status>', 'Filter by status (pending|verified|flagged|rejected)')\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'text')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await tables(client, jobId, {\n page: options.page,\n status: options.status,\n });\n writeOutput(formatTablesOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// history command - Verification audit trail\n// ============================================================================\nprogram\n .command('history <jobId>')\n .description('Show verification history')\n .option('-l, --limit <n>', 'Limit entries', parseInt, 50)\n .option('-f, --format <format>', 'Output format (text|json)', 'text')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await history(client, jobId, { limit: options.limit });\n writeOutput(formatHistoryOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// toc command - Table of contents extraction\n// ============================================================================\nprogram\n .command('toc <jobId>')\n .description('Extract table of contents from PDF')\n .option('--max-depth <n>', 'Maximum TOC depth', parseInt)\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'text')\n .option('--watch', 'Watch live extraction events via WebSocket')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await toc(client, jobId, {\n maxDepth: options.maxDepth,\n watch: options.watch,\n });\n writeOutput(formatTocOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nprogram.parse();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,SAAS,eAAe;AACxB,SAAS,qBAAqB;AA2C9B,IAAM,UAAU,IAAI,QAAQ;AAC5B,QAAQ,mBAAmB;AAC3B,QAAQ,yBAAyB;AAEjC,QACG,KAAK,MAAM,EACX,YAAY,iEAA4D,EACxE,QAAQ,QAAQ,EAChB,OAAO,cAAc,4CAA4C,EACjE,OAAO,eAAe,6CAA6C,EACnE,OAAO,uBAAuB,wCAAwC;AAGzE,SAAS,UAAuB;AAC9B,SAAO,QAAQ,KAAK;AACtB;AAMA,SAAS,YAAwB;AAC/B,QAAM,SAAS,UAAU;AACzB,QAAM,UAAU,WAAW;AAE3B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,QAAQ;AAClB,QAAI,EAAE,MAAM;AACV,cAAQ,OAAO,MAAM,KAAK,UAAU,EAAE,OAAO,oBAAoB,MAAM,IAAI,CAAC,IAAI,IAAI;AAAA,IACtF,OAAO;AACL,cAAQ,OAAO;AAAA,QACb;AAAA,MAMF;AAAA,IACF;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,SAAO,IAAI,WAAW,EAAE,QAAQ,QAAQ,CAAC;AAC3C;AAKA,eAAe,iBAAiB,QAAgB,SAA4C;AAC1F,QAAM,IAAI,QAAQ;AAClB,MAAI;AACF,UAAM,SAAS,UAAU;AACzB,UAAM,SAAS,MAAM,OAAO,QAAQ,QAAQ;AAAA,MAC1C,GAAG;AAAA,MACH,QAAQ,QAAQ,SAAS;AAAA,IAC3B,CAAC;AAED,QAAI,EAAE,MAAM;AACV,kBAAY,KAAK,UAAU,MAAM,GAAG,EAAE,MAAM;AAAA,IAC9C,OA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F,CAAC;AAEH,QAAQ,MAAM;","names":[]}
1
+ {"version":3,"sources":["../../src/cli/bin.ts","../../package.json"],"sourcesContent":["#!/usr/bin/env node\n/**\n * okra CLI — Agent-friendly PDF extraction and collection queries.\n *\n * Global flags:\n * -j, --json Structured JSON output\n * -q, --quiet Suppress progress (just data to stdout)\n * -o, --output Write output to file (CSV/JSON/ZIP)\n *\n * Action commands (agent-grade):\n * okra upload <source> # Upload + wait\n * okra extract <source> --schema schema.json # Upload + structured extract\n * okra extract <docId> --schema schema.json # Extract from existing doc\n * okra list # List documents\n * okra read <id> [--pages 1-5] # Full markdown\n * okra delete <id> # Delete document\n * okra chat \"<question>\" --doc <id> # Ask a question\n * okra collection list # List collections\n * okra collection query <name> \"<question>\" # Fan-out → CSV\n * okra collection extract <name> --schema s.json # Experimental structured extract → CSV\n *\n * Review commands:\n * okra tree / find / page / search / tables / history / toc\n *\n * Exit codes: 0=success, 1=client error, 2=server error\n */\n\nimport { Command } from 'commander';\nimport { realpathSync, writeFileSync } from 'fs';\nimport { resolve } from 'path';\nimport { pathToFileURL } from 'url';\nimport packageJson from '../../package.json';\nimport { OkraClient } from '../client';\nimport {\n tree,\n formatTreeOutput,\n find,\n formatFindOutput,\n formatStats,\n pageGet,\n pageEdit,\n pageResolve,\n pageVersions,\n formatPageOutput,\n formatVersionsOutput,\n search,\n formatSearchOutput,\n tables,\n formatTablesOutput,\n history,\n formatHistoryOutput,\n toc,\n formatTocOutput,\n authLogin,\n authSetKey,\n authStatus,\n authWhoAmI,\n authToken,\n authLogout,\n upload,\n listDocuments,\n formatDocumentList,\n deleteDocument,\n readDocument,\n collectionList,\n collectionCreate,\n collectionShow,\n collectionDelete,\n collectionAddDocs,\n collectionRemoveDocs,\n collectionSetVisibility,\n collectionQueryRaw,\n collectionExport,\n formatCollectionList,\n formatCollectionDetail,\n formatCollectionCsv,\n formatCollectionTable,\n formatQueryJsonl,\n formatCollectionExportFlat,\n formatExtractCsv,\n formatExtractTable,\n formatExtractJson,\n localDoctor,\n localIngest,\n localPage,\n localSearch,\n localStatus,\n localSummary,\n localTables,\n} from './commands';\nimport { getApiKey, getBaseUrl } from './config';\nimport { handleError, writeOutput, progress } from './output';\nimport type { GlobalFlags } from './output';\n\nexport const CLI_VERSION = packageJson.version;\nexport const PRIMARY_COMMANDS = ['auth', 'upload', 'extract', 'chat', 'list', 'read', 'delete', 'collection'] as const;\nexport const ADVANCED_COMMANDS = ['status', 'tree', 'find', 'page', 'search', 'tables', 'history', 'toc', 'local'] as const;\nexport const PRIMARY_COLLECTION_SUBCOMMANDS = ['list', 'query'] as const;\nexport const ADVANCED_COLLECTION_SUBCOMMANDS = ['create', 'show', 'delete', 'add', 'remove', 'publish', 'unpublish', 'export'] as const;\nexport const ROOT_HELP_FOOTER = [\n '',\n 'Primary workflows:',\n ' okra auth login',\n ' okra upload ./report.pdf',\n ' okra chat \"Summarize this document\" --doc doc-abc123',\n ' okra extract ./report.pdf --schema ./schema.json',\n ' okra collection query earnings \"What changed quarter over quarter?\" -o earnings.csv',\n '',\n 'Advanced inspection and local-only commands are intentionally hidden from',\n 'default help during the v0.14 clean-house release candidate.',\n].join('\\n');\nexport const COLLECTION_HELP_FOOTER = [\n '',\n 'Stable v0.14 collection workflow:',\n ' okra collection query <name> \"<question>\"',\n '',\n 'Experimental structured fan-out remains available via:',\n ' okra collection query <name> \"<question>\" --schema ./schema.json',\n ' okra collection extract <name> --schema ./schema.json',\n '',\n 'Advanced collection management commands remain available but are',\n 'intentionally hidden from default help during the clean-house release',\n 'candidate.',\n].join('\\n');\n\nexport const program = new Command();\nprogram.showHelpAfterError();\nprogram.showSuggestionAfterError();\n\nprogram\n .name('okra')\n .description('Okra CLI — upload PDFs, chat with documents, and extract structured data')\n .version(CLI_VERSION)\n .option('-j, --json', 'Output JSON (structured, machine-readable)')\n .option('-q, --quiet', 'Suppress progress and human-readable frills')\n .option('-o, --output <file>', 'Write output to file instead of stdout');\nprogram.addHelpText(\n 'after',\n ROOT_HELP_FOOTER,\n);\n\n/** Read global flags from program.opts(). */\nfunction globals(): GlobalFlags {\n return program.opts();\n}\n\nexport function getMissingApiKeyMessage(): string {\n return [\n 'No API key found.',\n '',\n 'Set one up with:',\n ' okra auth login',\n ' export OKRA_API_KEY=\"okra_xxx\"',\n '',\n 'Get your API key at:',\n ' https://app.okrapdf.com/settings',\n '',\n 'CLI docs:',\n ' https://docs.okrapdf.com/api-reference/cli',\n ].join('\\n');\n}\n\nfunction formatDocumentReadyMessage(docId: string, pages?: number): string {\n return [\n `Ready: ${docId}${typeof pages === 'number' ? ` (${pages} pages)` : ''}`,\n '',\n 'Next:',\n ` okra chat \"Summarize this document\" --doc ${docId}`,\n ` okra read ${docId}`,\n ` okra extract ${docId} --schema ./schema.json`,\n ].join('\\n');\n}\n\nfunction formatQueuedDocumentMessage(docId: string): string {\n return [\n `Queued: ${docId}`,\n '',\n 'Next:',\n ` okra status ${docId}`,\n '',\n 'Once processing finishes:',\n ` okra chat \"Summarize this document\" --doc ${docId}`,\n ` okra read ${docId}`,\n ].join('\\n');\n}\n\nfunction isDirectExecution(): boolean {\n const entry = process.argv[1];\n if (!entry) return false;\n try {\n return import.meta.url === pathToFileURL(realpathSync(resolve(entry))).href;\n } catch {\n return import.meta.url === pathToFileURL(resolve(entry)).href;\n }\n}\n\n// Create client with proper config priority:\n// 1. Environment variable (OKRA_API_KEY)\n// 2. Project config (.okrarc, .okra.json)\n// 3. Global config (~/.okra/config.json)\nfunction getClient(): OkraClient {\n const apiKey = getApiKey();\n const baseUrl = getBaseUrl();\n\n if (!apiKey) {\n const g = globals();\n if (g.json) {\n process.stderr.write(JSON.stringify({ error: 'No API key found', code: 401 }) + '\\n');\n } else {\n process.stderr.write(getMissingApiKeyMessage() + '\\n');\n }\n process.exit(1);\n }\n\n return new OkraClient({ apiKey, baseUrl });\n}\n\nfunction writeLocalResult(result: unknown, humanText: string): void {\n const g = globals();\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(humanText, g.output);\n }\n}\n\nconst localCmd = program\n .command('local', { hidden: true })\n .description('Offline PDF tools for local OpenClaw/opencode harnesses');\n\nlocalCmd\n .command('ingest <source>')\n .description('Ingest a local PDF into the offline document store')\n .option('--data-dir <path>', 'Override local document store path')\n .action(async (source, options) => {\n const g = globals();\n try {\n const result = localIngest(source, { dataDir: options.dataDir });\n writeLocalResult(\n result,\n `Indexed ${result.filename} as ${result.documentId} (${result.pageCount} pages, ${result.charCount} chars)`,\n );\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nlocalCmd\n .command('status')\n .description('Get local document status')\n .requiredOption('--doc <id>', 'Local document ID')\n .option('--data-dir <path>', 'Override local document store path')\n .action(async (options) => {\n const g = globals();\n try {\n const result = localStatus(options.doc, { dataDir: options.dataDir });\n writeLocalResult(\n result,\n `${result.documentId}: ${result.status} (${result.pagesWithText}/${result.pageCount} pages with text)`,\n );\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nlocalCmd\n .command('summary')\n .description('Produce an extractive summary of a local PDF')\n .requiredOption('--doc <id>', 'Local document ID')\n .option('--data-dir <path>', 'Override local document store path')\n .action(async (options) => {\n const g = globals();\n try {\n const result = localSummary(options.doc, { dataDir: options.dataDir });\n writeLocalResult(result, result.summary);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nlocalCmd\n .command('search')\n .description('Search within a local PDF')\n .requiredOption('--doc <id>', 'Local document ID')\n .requiredOption('--query <text>', 'Search query')\n .option('--data-dir <path>', 'Override local document store path')\n .action(async (options) => {\n const g = globals();\n try {\n const result = localSearch(options.doc, options.query, { dataDir: options.dataDir });\n const preview = result.matches.map((match) => `p.${match.page}: ${match.snippet}`).join('\\n');\n writeLocalResult(result, preview || `No matches found for \"${options.query}\"`);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nlocalCmd\n .command('page')\n .description('Read one extracted page from a local PDF')\n .requiredOption('--doc <id>', 'Local document ID')\n .requiredOption('--page <n>', '1-indexed page number', parseInt)\n .option('--data-dir <path>', 'Override local document store path')\n .action(async (options) => {\n const g = globals();\n try {\n const result = localPage(options.doc, options.page, { dataDir: options.dataDir });\n writeLocalResult(result, result.text);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nlocalCmd\n .command('tables')\n .description('Detect table-like layout blocks from a local PDF')\n .requiredOption('--doc <id>', 'Local document ID')\n .option('--query <text>', 'Optional query to rank table-like blocks')\n .option('--data-dir <path>', 'Override local document store path')\n .action(async (options) => {\n const g = globals();\n try {\n const result = localTables(options.doc, options.query, { dataDir: options.dataDir });\n const preview = result.tables\n .map((table) => `p.${table.page} (${table.rowCount} rows)\\n${table.preview}`)\n .join('\\n\\n');\n writeLocalResult(result, preview || 'No table-like blocks found');\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nlocalCmd\n .command('doctor')\n .description('Check local offline PDF tool availability')\n .option('--data-dir <path>', 'Override local document store path')\n .action(async (options) => {\n const g = globals();\n try {\n const result = localDoctor({ dataDir: options.dataDir });\n const human = [\n `data dir: ${result.dataDir}`,\n `pdftotext: ${result.tools.pdftotext.available ? result.tools.pdftotext.path : 'missing'}`,\n `pdfinfo: ${result.tools.pdfinfo.available ? result.tools.pdfinfo.path : 'missing'}`,\n `pdftoppm: ${result.tools.pdftoppm.available ? result.tools.pdftoppm.path : 'missing'}`,\n `tesseract: ${result.tools.tesseract.available ? result.tools.tesseract.path : 'missing'}`,\n ].join('\\n');\n writeLocalResult(result, human);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// upload command\n// ============================================================================\nasync function runUploadCommand(source: string, options: { wait?: boolean; vendorOptions?: string }): Promise<void> {\n const g = globals();\n try {\n const client = getClient();\n let vendorOptions: Record<string, unknown> | undefined;\n if (options.vendorOptions) {\n try {\n vendorOptions = JSON.parse(options.vendorOptions);\n } catch {\n process.stderr.write('Error: --vendor-options must be valid JSON\\n');\n process.exit(1);\n }\n }\n\n const result = await upload(client, source, {\n ...g,\n noWait: options.wait === false,\n vendorOptions,\n });\n\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(\n options.wait === false\n ? formatQueuedDocumentMessage(result.id)\n : formatDocumentReadyMessage(result.id, result.pages),\n g.output,\n );\n }\n } catch (error) {\n handleError(error, g.json);\n }\n}\n\nfunction registerUploadCommand(commandName: string, description: string): void {\n program\n .command(`${commandName} <source>`)\n .description(description)\n .summary('Upload a PDF and wait for processing')\n .option('--no-wait', 'Fire-and-forget (don\\'t wait for processing)')\n .option('--vendor-options <json>', 'JSON vendor-specific options (e.g., \\'{\"model\":\"gemini-3.1-pro\",\"parse_mode\":\"parse_page_with_agent\"}\\')')\n .action(async (source, options) => {\n await runUploadCommand(source, options);\n });\n}\n\nregisterUploadCommand('upload', 'Upload a PDF (file path or URL), wait for processing');\n\n// ============================================================================\n// extract command — structured extraction from existing doc or upload + extract\n// ============================================================================\nprogram\n .command('extract <source>')\n .description('Extract structured data from a document (doc ID, URL, or file path)')\n .summary('Upload a PDF and extract structured data')\n .option('--no-wait', \"Fire-and-forget (don't wait for processing)\")\n .option('--schema <file>', 'JSON Schema file or inline JSON for structured extraction')\n .option('--prompt <query>', 'Extraction prompt (default: \"Extract all data according to the schema\")')\n .action(async (source, options) => {\n const g = globals();\n try {\n const client = getClient();\n const { readFileSync } = await import('fs');\n\n // Resolve doc ID: if source looks like an existing doc, skip upload\n const isExistingDoc = /^(?:ocr|doc)-[A-Za-z0-9_-]+$/.test(source);\n let docId: string;\n\n if (isExistingDoc) {\n docId = source;\n } else {\n // Upload first\n const result = await upload(client, source, {\n ...g,\n noWait: options.wait === false,\n });\n docId = result.id;\n\n // If no schema and no-wait, just show upload result\n if (!options.schema || options.wait === false) {\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(\n options.wait === false\n ? formatQueuedDocumentMessage(docId)\n : formatDocumentReadyMessage(docId, result.pages),\n g.output,\n );\n }\n return;\n }\n }\n\n // Schema is required for existing docs, optional for uploads\n if (!options.schema) {\n if (isExistingDoc) {\n writeOutput('Error: --schema is required when extracting from an existing document.', g.output);\n process.exitCode = 1;\n return;\n }\n return;\n }\n\n // Load schema — support file path or inline JSON\n let schemaJson: Record<string, unknown>;\n const schemaArg: string = options.schema;\n if (schemaArg.startsWith('{')) {\n schemaJson = JSON.parse(schemaArg);\n } else {\n schemaJson = JSON.parse(readFileSync(schemaArg, 'utf8'));\n }\n\n const prompt = options.prompt || 'Extract all data from this document according to the schema.';\n\n progress(`Extracting from ${docId}…`, g.quiet);\n const extraction = await client.generate(docId, prompt, { schema: schemaJson });\n\n if (g.json) {\n writeOutput(JSON.stringify({\n doc_id: docId,\n data: extraction.data ?? extraction.answer,\n }), g.output);\n } else if (g.output && g.output.endsWith('.csv')) {\n // CSV output for single doc — one header row + one data row\n const data = (extraction.data ?? {}) as Record<string, unknown>;\n const keys = Object.keys(data);\n const header = ['doc_id', ...keys].join(',');\n const values = keys.map((k) => {\n const v = data[k];\n if (v == null) return '';\n if (typeof v === 'string') return `\"${String(v).replace(/\"/g, '\"\"')}\"`;\n return String(v);\n });\n writeOutput([header, [docId, ...values].join(',')].join('\\n'), g.output);\n } else {\n writeOutput(JSON.stringify(extraction.data ?? extraction.answer, null, 2), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// status command\n// ============================================================================\nprogram\n .command('status <docId>', { hidden: true })\n .description('Get document processing status')\n .action(async (docId) => {\n const g = globals();\n try {\n const client = getClient();\n const status = await client.status(docId);\n if (g.json) {\n writeOutput(JSON.stringify(status), g.output);\n } else {\n const lines = [\n `Document: ${docId}`,\n `Phase: ${status.phase}`,\n ];\n if (typeof status.pagesCompleted === 'number' || typeof status.pagesTotal === 'number') {\n lines.push(`Pages: ${status.pagesCompleted ?? '?'} / ${status.pagesTotal ?? '?'}`);\n }\n writeOutput(lines.join('\\n'), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// chat command\n// ============================================================================\nprogram\n .command('chat <question>')\n .description('Ask a question about a processed document')\n .summary('Ask a question about one document')\n .requiredOption('--doc <id>', 'Document ID')\n .option('--model <name>', 'Override model')\n .option('--stream', 'Stream response tokens as they arrive')\n .action(async (question, options) => {\n const g = globals();\n try {\n const client = getClient();\n\n if (options.stream) {\n let fullText = '';\n for await (const event of client.stream(options.doc, question, {\n model: options.model,\n })) {\n if (event.type === 'text_delta') {\n fullText += event.text;\n if (!g.json) process.stdout.write(event.text);\n } else if (event.type === 'done') {\n if (!g.json) process.stdout.write('\\n');\n if (g.json) {\n writeOutput(\n JSON.stringify({ docId: options.doc, question, answer: fullText }),\n g.output,\n );\n }\n } else if (event.type === 'error') {\n throw new Error(event.message);\n }\n }\n return;\n }\n\n const result = await client.generate(options.doc, question, options.model ? { model: options.model } : undefined);\n\n if (g.json) {\n writeOutput(JSON.stringify({ docId: options.doc, question, ...result }), g.output);\n } else {\n writeOutput(result.answer, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// list command\n// ============================================================================\nprogram\n .command('list')\n .alias('ls')\n .description('List all documents')\n .summary('List your documents')\n .action(async () => {\n const g = globals();\n try {\n const client = getClient();\n const { documents } = await listDocuments(client, g);\n writeOutput(formatDocumentList(documents, g.json), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// delete command\n// ============================================================================\nprogram\n .command('delete <docId>')\n .alias('rm')\n .description('Delete a document')\n .summary('Delete one document')\n .action(async (docId) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await deleteDocument(client, docId, g);\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(`Deleted ${docId}`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// read command\n// ============================================================================\nprogram\n .command('read <docId>')\n .description('Read document as markdown')\n .summary('Read document markdown')\n .option('-p, --pages <range>', 'Page range (e.g., 1-5, 10-15)')\n .action(async (docId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await readDocument(client, docId, { ...g, pages: options.pages });\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(result.markdown, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// collection command\n// ============================================================================\nconst collectionCmd = program\n .command('collection')\n .alias('collections')\n .alias('col')\n .description('Collection operations');\ncollectionCmd.summary('Query across collections');\ncollectionCmd.addHelpText(\n 'after',\n COLLECTION_HELP_FOOTER,\n);\n\ncollectionCmd\n .command('list')\n .alias('ls')\n .description('List available collections')\n .summary('List collections')\n .action(async () => {\n const g = globals();\n try {\n const client = getClient();\n const rows = await collectionList(client, g);\n writeOutput(formatCollectionList(rows, g.json), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('create <name>', { hidden: true })\n .description('Create a new collection')\n .option('--description <text>', 'Collection description')\n .option('--docs <ids>', 'Comma-separated document IDs to seed')\n .action(async (name, options) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await collectionCreate(client, name, { ...g, ...options });\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(`Created collection \"${result.name}\" (${result.id})`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('show <nameOrId>', { hidden: true })\n .description('Show collection details and documents')\n .action(async (nameOrId) => {\n const g = globals();\n try {\n const client = getClient();\n const detail = await collectionShow(client, nameOrId);\n writeOutput(formatCollectionDetail(detail, g.json), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('delete <nameOrId>', { hidden: true })\n .alias('rm')\n .description('Delete a collection (documents are preserved)')\n .action(async (nameOrId) => {\n const g = globals();\n try {\n const client = getClient();\n await collectionDelete(client, nameOrId);\n if (g.json) {\n writeOutput(JSON.stringify({ ok: true, deleted: nameOrId }), g.output);\n } else {\n writeOutput(`Deleted collection \"${nameOrId}\"`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('add <nameOrId> <docIds...>', { hidden: true })\n .description('Add documents to a collection')\n .action(async (nameOrId, docIds) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await collectionAddDocs(client, nameOrId, docIds);\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(`Added ${docIds.length} document(s) to \"${nameOrId}\"`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('remove <nameOrId> <docIds...>', { hidden: true })\n .description('Remove documents from a collection')\n .action(async (nameOrId, docIds) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await collectionRemoveDocs(client, nameOrId, docIds);\n if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n writeOutput(`Removed ${docIds.length} document(s) from \"${nameOrId}\"`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('query <nameOrId> <question>')\n .description('Fan-out query across collection documents')\n .summary('Ask the same question across a collection')\n .option('--schema <file>', 'Experimental: JSON Schema file for structured extraction')\n .action(async (nameOrId, question, options) => {\n const g = globals();\n try {\n const client = getClient();\n const { results, summary } = await collectionQueryRaw(\n client,\n nameOrId,\n question,\n { ...g, schema: options.schema },\n );\n\n // Determine output format based on flags\n if (g.json) {\n // --json: JSONL events to stdout\n writeOutput(formatQueryJsonl(results), g.output);\n } else if (g.output && g.output.endsWith('.csv')) {\n // -o file.csv → CSV\n writeOutput(formatCollectionCsv(results), g.output);\n } else if (g.output) {\n // -o file.json or other → JSON\n writeOutput(JSON.stringify({ results, summary }), g.output);\n } else {\n // Default: compact table to stdout\n writeOutput(formatCollectionTable(results));\n }\n\n progress(\n `${summary.completed} completed, ${summary.failed} failed — $${summary.total_cost_usd.toFixed(4)}`,\n g.quiet,\n );\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('extract <nameOrId>', { hidden: true })\n .description('Experimental: extract structured data from all documents in a collection')\n .summary('Experimental structured extraction')\n .requiredOption('--schema <file>', 'Experimental: JSON Schema file or inline JSON for structured extraction')\n .option('--prompt <query>', 'Extraction prompt (default: auto-generated from schema)')\n .action(async (nameOrId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const { readFileSync } = await import('fs');\n\n // Load schema — support file path or inline JSON\n let schemaJson: Record<string, unknown>;\n const schemaArg: string = options.schema;\n if (schemaArg.startsWith('{')) {\n schemaJson = JSON.parse(schemaArg);\n } else {\n schemaJson = JSON.parse(readFileSync(schemaArg, 'utf8'));\n }\n\n const prompt = options.prompt || 'Extract all data from this document according to the schema.';\n\n const { results, summary } = await collectionQueryRaw(\n client,\n nameOrId,\n prompt,\n { ...g, schema: schemaJson },\n );\n\n // Use structured formatters that flatten data keys into columns\n if (g.json) {\n writeOutput(formatExtractJson(results), g.output);\n } else if (g.output && g.output.endsWith('.csv')) {\n writeOutput(formatExtractCsv(results), g.output);\n } else if (g.output) {\n // Non-csv file output → JSON\n writeOutput(formatExtractJson(results), g.output);\n } else {\n // Default: table to stdout with flattened data columns\n writeOutput(formatExtractTable(results));\n }\n\n progress(\n `\\n${summary.completed} documents — $${summary.total_cost_usd.toFixed(4)} total`,\n g.quiet,\n );\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('publish <nameOrId>', { hidden: true })\n .description('Make a collection publicly queryable')\n .action(async (nameOrId) => {\n const g = globals();\n try {\n const client = getClient();\n await collectionSetVisibility(client, nameOrId, 'public');\n if (g.json) {\n writeOutput(JSON.stringify({ ok: true, visibility: 'public', collection: nameOrId }), g.output);\n } else {\n writeOutput(\n `Published \"${nameOrId}\"\\n` +\n `Share with: okra collection query ${nameOrId} \"your question\"`,\n g.output,\n );\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('unpublish <nameOrId>', { hidden: true })\n .description('Make a collection private (owner-only)')\n .action(async (nameOrId) => {\n const g = globals();\n try {\n const client = getClient();\n await collectionSetVisibility(client, nameOrId, 'private');\n if (g.json) {\n writeOutput(JSON.stringify({ ok: true, visibility: 'private', collection: nameOrId }), g.output);\n } else {\n writeOutput(`Unpublished \"${nameOrId}\" — now private`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\ncollectionCmd\n .command('export <nameOrId>', { hidden: true })\n .description('Export pre-computed markdown for all documents in a collection')\n .option('--flat', 'Concatenated markdown with # headers + === separators')\n .option('--zip', 'One markdown file per document in a .zip archive')\n .action(async (nameOrId, options) => {\n const g = globals();\n try {\n const client = getClient();\n\n if (options.flat && options.zip) {\n throw new Error('Use either --flat or --zip, not both');\n }\n\n if (options.zip) {\n const bytes = await collectionExport(client, nameOrId, { ...g, zip: true });\n const safeBase = String(nameOrId)\n .trim()\n .replace(/[^A-Za-z0-9._-]+/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^[-_.]+|[-_.]+$/g, '') || 'collection-export';\n const outputPath = g.output || `${safeBase}.zip`;\n writeFileSync(outputPath, bytes);\n progress(`Wrote → ${outputPath}`, g.quiet);\n\n if (g.json) {\n writeOutput(JSON.stringify({\n format: 'zip',\n file: outputPath,\n bytes: bytes.byteLength,\n }));\n }\n return;\n }\n\n const result = await collectionExport(client, nameOrId, { ...g, flat: options.flat });\n\n if (options.flat) {\n writeOutput(formatCollectionExportFlat(result), g.output);\n } else if (g.json) {\n writeOutput(JSON.stringify(result), g.output);\n } else {\n // Default: structured JSON\n writeOutput(JSON.stringify(result, null, 2), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// auth command - Authentication management\n// ============================================================================\nconst authCmd = program.command('auth').description('Manage authentication');\n\nauthCmd\n .command('login')\n .description('Save API key to global config')\n .option('-k, --key <apiKey>', 'Set API key non-interactively')\n .action(async (options) => {\n try {\n await authLogin(options.key);\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('set-key <apiKey>')\n .description('Save API key to global config (non-interactive)')\n .action(async (apiKey) => {\n try {\n await authSetKey(apiKey);\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('status')\n .description('Show authentication status')\n .action(async () => {\n try {\n await authStatus();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('whoami')\n .description('Show current auth identity (alias for status)')\n .action(async () => {\n try {\n await authWhoAmI();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('token')\n .description('Print active API key to stdout')\n .action(async () => {\n try {\n await authToken();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\nauthCmd\n .command('logout')\n .description('Remove API key from global config')\n .action(async () => {\n try {\n await authLogout();\n } catch (error) {\n handleError(error, globals().json);\n }\n });\n\n// ============================================================================\n// tree command - Document verification tree\n// ============================================================================\nprogram\n .command('tree <jobId>', { hidden: true })\n .description('Show document verification tree')\n .option('-s, --status <status>', 'Filter by status (complete|partial|pending|flagged|empty|gap)')\n .option('-e, --entity <type>', 'Filter by entity type (table|figure|footnote)')\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'text')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await tree(client, jobId, {\n status: options.status,\n entity: options.entity,\n });\n writeOutput(formatTreeOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// find command - jQuery-like entity search\n// ============================================================================\nprogram\n .command('find <jobId> <selector>', { hidden: true })\n .description('Find entities using jQuery-like selectors')\n .option('-k, --top-k <n>', 'Limit results', parseInt)\n .option('-c, --min-confidence <n>', 'Minimum confidence (0-1)', parseFloat)\n .option('-p, --pages <range>', 'Page range (e.g., 1-10)')\n .option('--sort <by>', 'Sort by (confidence|page|type)')\n .option('--stats', 'Show aggregate statistics')\n .option('-f, --format <format>', 'Output format (text|json|entities|ids)', 'text')\n .action(async (jobId, selector, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const pageRange = options.pages\n ? options.pages.split('-').map(Number) as [number, number]\n : undefined;\n\n const result = await find(client, jobId, selector, {\n topK: options.topK,\n minConfidence: options.minConfidence,\n pageRange,\n sortBy: options.sort,\n });\n\n if (options.stats && fmt === 'text') {\n writeOutput(formatStats(result.stats), g.output);\n } else {\n writeOutput(formatFindOutput(result, fmt, options.stats), g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// page command - Page content operations\n// ============================================================================\nconst pageCmd = program.command('page', { hidden: true }).description('Page content operations');\n\npageCmd\n .command('get <jobId> <pageNum>')\n .description('Get page content')\n .option('-v, --version <n>', 'Specific version', parseInt)\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'markdown')\n .action(async (jobId, pageNum, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const content = await pageGet(client, jobId, parseInt(pageNum), {\n version: options.version,\n });\n writeOutput(formatPageOutput(content, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\npageCmd\n .command('edit <jobId> <pageNum>')\n .description('Edit page content (reads from stdin)')\n .action(async (jobId, pageNum) => {\n const g = globals();\n try {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk);\n }\n const content = Buffer.concat(chunks).toString('utf8');\n\n const client = getClient();\n const result = await pageEdit(client, jobId, parseInt(pageNum), content);\n if (g.json) {\n writeOutput(JSON.stringify({ version: result.version }), g.output);\n } else {\n writeOutput(`Saved as version ${result.version}`, g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\npageCmd\n .command('resolve <jobId> <pageNum> <resolution>')\n .description('Resolve page verification status')\n .option('-c, --classification <class>', 'Classification')\n .option('-r, --reason <reason>', 'Reason')\n .action(async (jobId, pageNum, resolution, options) => {\n const g = globals();\n try {\n const client = getClient();\n const result = await pageResolve(client, jobId, parseInt(pageNum), {\n resolution,\n classification: options.classification,\n reason: options.reason,\n });\n if (g.json) {\n writeOutput(JSON.stringify({ success: result.success }), g.output);\n } else {\n writeOutput(result.success ? 'Resolved' : 'Failed', g.output);\n }\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\npageCmd\n .command('versions <jobId> <pageNum>')\n .description('List page versions')\n .option('-f, --format <format>', 'Output format (text|json)', 'text')\n .action(async (jobId, pageNum, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const versions = await pageVersions(client, jobId, parseInt(pageNum));\n writeOutput(formatVersionsOutput(versions, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// search command - Full-text search\n// ============================================================================\nprogram\n .command('search <jobId> <query>', { hidden: true })\n .description('Search page content')\n .option('-f, --format <format>', 'Output format (text|json)', 'text')\n .action(async (jobId, query, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await search(client, jobId, query);\n writeOutput(formatSearchOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// tables command - List tables\n// ============================================================================\nprogram\n .command('tables <jobId>', { hidden: true })\n .description('List extracted tables')\n .option('-p, --page <n>', 'Filter by page', parseInt)\n .option('-s, --status <status>', 'Filter by status (pending|verified|flagged|rejected)')\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'text')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await tables(client, jobId, {\n page: options.page,\n status: options.status,\n });\n writeOutput(formatTablesOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// history command - Verification audit trail\n// ============================================================================\nprogram\n .command('history <jobId>', { hidden: true })\n .description('Show verification history')\n .option('-l, --limit <n>', 'Limit entries', parseInt, 50)\n .option('-f, --format <format>', 'Output format (text|json)', 'text')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await history(client, jobId, { limit: options.limit });\n writeOutput(formatHistoryOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\n// ============================================================================\n// toc command - Table of contents extraction\n// ============================================================================\nprogram\n .command('toc <jobId>', { hidden: true })\n .description('Extract table of contents from PDF')\n .option('--max-depth <n>', 'Maximum TOC depth', parseInt)\n .option('-f, --format <format>', 'Output format (text|json|markdown)', 'text')\n .option('--watch', 'Watch live extraction events via WebSocket')\n .action(async (jobId, options) => {\n const g = globals();\n try {\n const client = getClient();\n const fmt = g.json ? 'json' : options.format;\n const result = await toc(client, jobId, {\n maxDepth: options.maxDepth,\n watch: options.watch,\n });\n writeOutput(formatTocOutput(result, fmt), g.output);\n } catch (error) {\n handleError(error, g.json);\n }\n });\n\nif (isDirectExecution()) {\n void program.parseAsync();\n}\n","{\n \"name\": \"okrapdf\",\n \"version\": \"0.14.0\",\n \"okraApi\": \"^1.14.0\",\n \"description\": \"OkraPDF — upload a PDF, get an API. Runtime client, React hooks, and CLI.\",\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n }\n },\n \"./doc\": {\n \"import\": {\n \"types\": \"./dist/url.d.ts\",\n \"default\": \"./dist/url.js\"\n }\n },\n \"./browser\": {\n \"import\": {\n \"types\": \"./dist/browser.d.ts\",\n \"default\": \"./dist/browser.js\"\n }\n },\n \"./worker\": {\n \"import\": {\n \"types\": \"./dist/worker.d.ts\",\n \"default\": \"./dist/worker.js\"\n }\n },\n \"./react\": {\n \"import\": {\n \"types\": \"./dist/react/index.d.ts\",\n \"default\": \"./dist/react/index.js\"\n }\n },\n \"./cli\": {\n \"import\": {\n \"types\": \"./dist/cli/index.d.ts\",\n \"default\": \"./dist/cli/index.js\"\n }\n }\n },\n \"bin\": {\n \"okra\": \"./dist/cli/bin.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"docs:cli\": \"node ./scripts/generate-cli-docs.mjs\",\n \"docs:cli:check\": \"node ./scripts/generate-cli-docs.mjs --check\",\n \"test\": \"vitest run --exclude '**/**.e2e.test.ts'\",\n \"test:e2e\": \"vitest run src/client.e2e.test.ts\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"commander\": \"^12.0.0\",\n \"ws\": \"^8.19.0\",\n \"zod\": \"^4.3.6\"\n },\n \"peerDependencies\": {\n \"react\": \">=18\"\n },\n \"peerDependenciesMeta\": {\n \"react\": {\n \"optional\": true\n }\n },\n \"devDependencies\": {\n \"@types/node\": \"^20.14.0\",\n \"@types/react\": \"^18.2.0\",\n \"@types/ws\": \"^8.18.1\",\n \"react\": \"^18.2.0\",\n \"tsup\": \"^8.0.0\",\n \"typescript\": \"^5.5.0\",\n \"vitest\": \"^2.0.0\"\n },\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/okrapdf/okrapdf-sdk\"\n },\n \"homepage\": \"https://okrapdf.com\",\n \"author\": \"OkraPDF\",\n \"keywords\": [\n \"pdf\",\n \"ocr\",\n \"document\",\n \"extraction\",\n \"api\",\n \"sdk\",\n \"structured-output\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAS,eAAe;AACxB,SAAS,cAAc,qBAAqB;AAC5C,SAAS,eAAe;AACxB,SAAS,qBAAqB;;;AC9B9B;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,SAAW;AAAA,EACX,aAAe;AAAA,EACf,MAAQ;AAAA,EACR,SAAW;AAAA,IACT,KAAK;AAAA,MACH,QAAU;AAAA,QACR,OAAS;AAAA,QACT,SAAW;AAAA,MACb;AAAA,IACF;AAAA,IACA,SAAS;AAAA,MACP,QAAU;AAAA,QACR,OA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O,QAAQ;AAAA,IACjB,CAAC;AACD,gBAAY,gBAAgB,QAAQ,GAAG,GAAG,EAAE,MAAM;AAAA,EACpD,SAAS,OAAO;AACd,gBAAY,OAAO,EAAE,IAAI;AAAA,EAC3B;AACF,CAAC;AAEH,IAAI,kBAAkB,GAAG;AACvB,OAAK,QAAQ,WAAW;AAC1B;","names":[]}
@@ -1,5 +1,5 @@
1
- import { O as OkraClient } from '../client-p82YcAs3.js';
2
- import '../types-DDm2eEL0.js';
1
+ import { O as OkraClient } from '../client-D4A0dQ4h.js';
2
+ import '../types-SYOi8k1l.js';
3
3
  import 'zod';
4
4
 
5
5
  /**
package/dist/cli/index.js CHANGED
@@ -36,7 +36,8 @@ import {
36
36
  toc,
37
37
  tree,
38
38
  writeGlobalConfig
39
- } from "../chunk-XOHPZW3V.js";
39
+ } from "../chunk-ETARIBOV.js";
40
+ import "../chunk-MSZQPLMQ.js";
40
41
  import "../chunk-NIZM2ETT.js";
41
42
  export {
42
43
  authLogin,
@@ -1,10 +1,11 @@
1
- import { b as UploadInput, S as SessionCreateOptions, O as OkraSession, c as SessionAttachOptions, C as CollectionSummary, d as Collection, e as CollectionQueryOptions, f as CollectionQueryStream, g as CollectionExportOptions, h as CollectionMarkdownExport, i as OkraClientOptions, j as UploadOptions, k as DocumentConfigUpdate, l as DocumentConfigResult, R as ReparseOptions, m as ReparseResult, A as ApplyWorkflowOptions, n as ApplyWorkflowResult, o as ApiKeyWorkflowConfigResponse, p as DocumentStatus, W as WaitOptions, P as Page, E as EntitiesResponse, Q as QueryResult, L as LogsOptions, q as LogEntry, r as CompletionOptions, s as CompletionEvent, G as GenerateOptions, t as GenerateResult, u as StructuredSchema, v as PublishResult, w as ShareLinkOptions, x as ShareLinkResult } from './types-DDm2eEL0.js';
1
+ import { a4 as UploadInput, a0 as SessionCreateOptions, a as OkraSession, $ as SessionAttachOptions, w as CollectionSummary, m as Collection, t as CollectionQueryOptions, v as CollectionQueryStream, q as CollectionExportOptions, r as CollectionMarkdownExport, O as OkraClientOptions, a5 as UploadOptions, F as DocumentConfigUpdate, B as DocumentConfigResult, Z as ReparseOptions, _ as ReparseResult, k as ApplyWorkflowOptions, l as ApplyWorkflowResult, A as ApiKeyWorkflowConfigResponse, D as DocumentStatus, W as WaitOptions, c as Page, E as EntitiesResponse, Q as QueryResult, L as LogsOptions, d as LogEntry, C as CompletionOptions, b as CompletionEvent, G as GenerateOptions, h as GenerateResult, i as StructuredSchema, H as DocumentListItem, x as DeleteDocumentResult, X as ReadDocumentOptions, Y as ReadDocumentResult, e as PublishResult, f as ShareLinkOptions, g as ShareLinkResult } from './types-SYOi8k1l.js';
2
2
 
3
3
  declare class OkraClient {
4
4
  private readonly baseUrl;
5
5
  private readonly apiKey?;
6
6
  private readonly sharedSecret?;
7
7
  private readonly fetchImpl;
8
+ private documentStatusRoute;
8
9
  readonly sessions: {
9
10
  create: (sourceOrDocId: UploadInput, options?: SessionCreateOptions) => Promise<OkraSession>;
10
11
  from: (documentId: string, options?: SessionAttachOptions) => OkraSession;
@@ -51,6 +52,9 @@ declare class OkraClient {
51
52
  schema: StructuredSchema<T>;
52
53
  }): Promise<GenerateResult<T>>;
53
54
  private generateStructured;
55
+ listDocuments(signal?: AbortSignal): Promise<DocumentListItem[]>;
56
+ deleteDocument(documentId: string, signal?: AbortSignal): Promise<DeleteDocumentResult>;
57
+ read(documentId: string, options?: ReadDocumentOptions): Promise<ReadDocumentResult>;
54
58
  modelEndpoint(documentId: string): string;
55
59
  publish(documentId: string, signal?: AbortSignal): Promise<PublishResult>;
56
60
  shareLink(documentId: string, options?: ShareLinkOptions): Promise<ShareLinkResult>;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { O as OkraClient } from './client-p82YcAs3.js';
2
- import { y as ProcessingCapabilities, i as OkraClientOptions, O as OkraSession, r as CompletionOptions, s as CompletionEvent, z as SessionState, p as DocumentStatus, W as WaitOptions, P as Page, E as EntitiesResponse, Q as QueryResult, L as LogsOptions, q as LogEntry, v as PublishResult, w as ShareLinkOptions, x as ShareLinkResult, G as GenerateOptions, t as GenerateResult, u as StructuredSchema, B as RuntimeErrorCode, F as StructuredOutputErrorCode } from './types-DDm2eEL0.js';
3
- export { o as ApiKeyWorkflowConfigResponse, A as ApplyWorkflowOptions, n as ApplyWorkflowResult, d as Collection, H as CollectionDocument, I as CollectionExportEvent, J as CollectionExportFormat, g as CollectionExportOptions, h as CollectionMarkdownExport, K as CollectionQueryEvent, e as CollectionQueryOptions, M as CollectionQueryResult, f as CollectionQueryStream, C as CollectionSummary, D as DocUrlOptions, N as DocumentAnswer, l as DocumentConfigResult, k as DocumentConfigUpdate, T as DocumentMarkdownExport, V as Entity, X as JsonSchema, Y as MarkdownPage, Z as OkraCollections, _ as PageBlock, $ as PageEntity, R as ReparseOptions, m as ReparseResult, c as SessionAttachOptions, S as SessionCreateOptions, a0 as ShareLinkCapabilities, a1 as ShareLinkLinks, a2 as StructuredOutputMeta, b as UploadInput, j as UploadOptions, a3 as UploadRedactOptions, a4 as UploadRedactPiiOptions, U as UrlBuilderOptions, a5 as WorkflowPhase, a6 as WorkflowPhaseConfig, a7 as WorkflowTier } from './types-DDm2eEL0.js';
1
+ import { O as OkraClient } from './client-D4A0dQ4h.js';
2
+ import { P as ProcessingCapabilities, O as OkraClientOptions, a as OkraSession, C as CompletionOptions, b as CompletionEvent, S as SessionState, D as DocumentStatus, W as WaitOptions, c as Page, E as EntitiesResponse, Q as QueryResult, L as LogsOptions, d as LogEntry, e as PublishResult, f as ShareLinkOptions, g as ShareLinkResult, G as GenerateOptions, h as GenerateResult, i as StructuredSchema, R as RuntimeErrorCode, j as StructuredOutputErrorCode } from './types-SYOi8k1l.js';
3
+ export { A as ApiKeyWorkflowConfigResponse, k as ApplyWorkflowOptions, l as ApplyWorkflowResult, m as Collection, n as CollectionDocument, o as CollectionExportEvent, p as CollectionExportFormat, q as CollectionExportOptions, r as CollectionMarkdownExport, s as CollectionQueryEvent, t as CollectionQueryOptions, u as CollectionQueryResult, v as CollectionQueryStream, w as CollectionSummary, x as DeleteDocumentResult, y as DocUrlOptions, z as DocumentAnswer, B as DocumentConfigResult, F as DocumentConfigUpdate, H as DocumentListItem, I as DocumentListResponse, J as DocumentMarkdownExport, K as Entity, M as JsonSchema, N as MarkdownPage, T as OkraCollections, U as PageBlock, V as PageEntity, X as ReadDocumentOptions, Y as ReadDocumentResult, Z as ReparseOptions, _ as ReparseResult, $ as SessionAttachOptions, a0 as SessionCreateOptions, a1 as ShareLinkCapabilities, a2 as ShareLinkLinks, a3 as StructuredOutputMeta, a4 as UploadInput, a5 as UploadOptions, a6 as UploadRedactOptions, a7 as UploadRedactPiiOptions, a8 as UrlBuilderOptions, a9 as WorkflowPhase, aa as WorkflowPhaseConfig, ab as WorkflowTier } from './types-SYOi8k1l.js';
4
4
  export { doc } from './url.js';
5
5
  import 'zod';
6
6
 
@@ -136,4 +136,146 @@ declare class StructuredOutputError extends OkraRuntimeError {
136
136
  constructor(code: StructuredOutputErrorCode, message: string, status: number, details?: unknown);
137
137
  }
138
138
 
139
- export { type ChatStreamServerEvent, CompletionEvent, CompletionOptions, type CreateOkraOptions, DEFAULT_WORKFLOW_CAPABILITIES, DocumentStatus, EntitiesResponse, type ExtractionPhase, GenerateOptions, GenerateResult, LogEntry, LogsOptions, OkraClient, OkraClientOptions, type OkraMiddleware, type OkraProvider, OkraClient as OkraRuntime, OkraRuntimeError, OkraSession, Page, ProcessingCapabilities, PublishResult, QueryResult, RuntimeErrorCode, SessionState, ShareLinkOptions, ShareLinkResult, StructuredOutputError, StructuredOutputErrorCode, StructuredSchema, WORKFLOW_PRESETS, WaitOptions, type WorkflowPresetName, type WsSendFn, WsSession, type WsSessionOptions, type WsSubscribeFn, createOkra, withCache, withQualityScore, withSecret, workflowPreset };
139
+ type LocalDocumentStatus = 'processing' | 'ready' | 'failed';
140
+ interface LocalToolAvailability {
141
+ available: boolean;
142
+ path: string | null;
143
+ }
144
+ interface LocalDocumentExtractor {
145
+ pdftotext: LocalToolAvailability;
146
+ pdfinfo: LocalToolAvailability;
147
+ pdftoppm: LocalToolAvailability;
148
+ tesseract: LocalToolAvailability;
149
+ ocrUsed: boolean;
150
+ }
151
+ interface LocalDocumentPageRecord {
152
+ pageNumber: number;
153
+ textPath: string;
154
+ charCount: number;
155
+ excerpt: string;
156
+ ocrApplied: boolean;
157
+ }
158
+ interface LocalDocumentRecord {
159
+ documentId: string;
160
+ filename: string;
161
+ storedPath: string;
162
+ sourcePath: string;
163
+ status: LocalDocumentStatus;
164
+ pageCount: number;
165
+ charCount: number;
166
+ createdAt: string;
167
+ updatedAt: string;
168
+ error: string | null;
169
+ extractor: LocalDocumentExtractor;
170
+ pages: LocalDocumentPageRecord[];
171
+ }
172
+ interface LocalCitation {
173
+ page: number;
174
+ snippet: string;
175
+ score?: number;
176
+ }
177
+ interface LocalTableCandidate {
178
+ page: number;
179
+ preview: string;
180
+ rowCount: number;
181
+ score?: number;
182
+ }
183
+ interface LocalDoctorReport {
184
+ ok: boolean;
185
+ dataDir: string;
186
+ tools: {
187
+ pdftotext: LocalToolAvailability;
188
+ pdfinfo: LocalToolAvailability;
189
+ pdftoppm: LocalToolAvailability;
190
+ tesseract: LocalToolAvailability;
191
+ };
192
+ }
193
+
194
+ declare function ingestLocalDocument(sourcePath: string, dataDir?: string): {
195
+ storedPath: string;
196
+ documentId: string;
197
+ filename: string;
198
+ status: LocalDocumentStatus;
199
+ pageCount: number;
200
+ charCount: number;
201
+ createdAt: string;
202
+ updatedAt: string;
203
+ error: string | null;
204
+ extractor: LocalDocumentExtractor;
205
+ };
206
+ declare function getLocalDocumentStatus(documentId: string, dataDir?: string): {
207
+ pagesWithText: number;
208
+ documentId: string;
209
+ filename: string;
210
+ status: LocalDocumentStatus;
211
+ pageCount: number;
212
+ charCount: number;
213
+ createdAt: string;
214
+ updatedAt: string;
215
+ error: string | null;
216
+ extractor: LocalDocumentExtractor;
217
+ };
218
+ declare function summarizeLocalDocument(documentId: string, dataDir?: string): {
219
+ summary: string;
220
+ citations: LocalCitation[];
221
+ documentId: string;
222
+ filename: string;
223
+ status: LocalDocumentStatus;
224
+ pageCount: number;
225
+ charCount: number;
226
+ createdAt: string;
227
+ updatedAt: string;
228
+ error: string | null;
229
+ extractor: LocalDocumentExtractor;
230
+ };
231
+ declare function searchLocalDocument(documentId: string, query: string, dataDir?: string): {
232
+ query: string;
233
+ matches: {
234
+ page: number;
235
+ snippet: string;
236
+ score: number;
237
+ }[];
238
+ documentId: string;
239
+ filename: string;
240
+ status: LocalDocumentStatus;
241
+ pageCount: number;
242
+ charCount: number;
243
+ createdAt: string;
244
+ updatedAt: string;
245
+ error: string | null;
246
+ extractor: LocalDocumentExtractor;
247
+ };
248
+ declare function readLocalPage(documentId: string, pageNumber: number, dataDir?: string): {
249
+ page: number;
250
+ text: string;
251
+ ocrApplied: boolean;
252
+ documentId: string;
253
+ filename: string;
254
+ status: LocalDocumentStatus;
255
+ pageCount: number;
256
+ charCount: number;
257
+ createdAt: string;
258
+ updatedAt: string;
259
+ error: string | null;
260
+ extractor: LocalDocumentExtractor;
261
+ };
262
+ declare function findLocalTables(documentId: string, query?: string, dataDir?: string): {
263
+ query: string | undefined;
264
+ tables: {
265
+ page: number;
266
+ preview: string;
267
+ rowCount: number;
268
+ }[];
269
+ documentId: string;
270
+ filename: string;
271
+ status: LocalDocumentStatus;
272
+ pageCount: number;
273
+ charCount: number;
274
+ createdAt: string;
275
+ updatedAt: string;
276
+ error: string | null;
277
+ extractor: LocalDocumentExtractor;
278
+ };
279
+ declare function doctorLocalHarness(dataDir?: string): LocalDoctorReport;
280
+
281
+ export { type ChatStreamServerEvent, CompletionEvent, CompletionOptions, type CreateOkraOptions, DEFAULT_WORKFLOW_CAPABILITIES, DocumentStatus, EntitiesResponse, type ExtractionPhase, GenerateOptions, GenerateResult, type LocalCitation, type LocalDoctorReport, type LocalDocumentExtractor, type LocalDocumentPageRecord, type LocalDocumentRecord, type LocalDocumentStatus, type LocalTableCandidate, type LocalToolAvailability, LogEntry, LogsOptions, OkraClient, OkraClientOptions, type OkraMiddleware, type OkraProvider, OkraClient as OkraRuntime, OkraRuntimeError, OkraSession, Page, ProcessingCapabilities, PublishResult, QueryResult, RuntimeErrorCode, SessionState, ShareLinkOptions, ShareLinkResult, StructuredOutputError, StructuredOutputErrorCode, StructuredSchema, WORKFLOW_PRESETS, WaitOptions, type WorkflowPresetName, type WsSendFn, WsSession, type WsSessionOptions, type WsSubscribeFn, createOkra, doctorLocalHarness, findLocalTables, getLocalDocumentStatus, ingestLocalDocument, readLocalPage, searchLocalDocument, summarizeLocalDocument, withCache, withQualityScore, withSecret, workflowPreset };
package/dist/index.js CHANGED
@@ -1,6 +1,15 @@
1
1
  import {
2
2
  doc
3
- } from "./chunk-QKII53VN.js";
3
+ } from "./chunk-HPTXRSWK.js";
4
+ import {
5
+ doctorLocalHarness,
6
+ findLocalTables,
7
+ getLocalDocumentStatus,
8
+ ingestLocalDocument,
9
+ readLocalPage,
10
+ searchLocalDocument,
11
+ summarizeLocalDocument
12
+ } from "./chunk-MSZQPLMQ.js";
4
13
  import {
5
14
  DEFAULT_WORKFLOW_CAPABILITIES,
6
15
  WORKFLOW_PRESETS,
@@ -9,10 +18,10 @@ import {
9
18
  withQualityScore,
10
19
  withSecret,
11
20
  workflowPreset
12
- } from "./chunk-YVUL6ZLA.js";
21
+ } from "./chunk-7BAEYVWG.js";
13
22
  import {
14
23
  OkraClient
15
- } from "./chunk-2HJPTW6S.js";
24
+ } from "./chunk-YGIBZV5J.js";
16
25
  import {
17
26
  OkraRuntimeError,
18
27
  StructuredOutputError
@@ -157,6 +166,13 @@ export {
157
166
  WsSession,
158
167
  createOkra,
159
168
  doc,
169
+ doctorLocalHarness,
170
+ findLocalTables,
171
+ getLocalDocumentStatus,
172
+ ingestLocalDocument,
173
+ readLocalPage,
174
+ searchLocalDocument,
175
+ summarizeLocalDocument,
160
176
  withCache,
161
177
  withQualityScore,
162
178
  withSecret,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ws-session.ts"],"sourcesContent":["/**\n * WsSession — OkraSession adapter that routes `stream()` over an existing\n * WebSocket connection instead of HTTP SSE.\n *\n * All non-streaming methods delegate to the inner HTTP-backed session.\n * Only `stream()` is overridden to send CHAT_COMPLETION over WS and yield\n * CompletionEvents from CHAT_STREAM_* responses.\n *\n * Usage:\n * const wsSession = new WsSession(httpSession, { send, subscribe });\n * const chat = useChat({ session: wsSession });\n */\n\nimport type {\n OkraSession,\n CompletionEvent,\n CompletionOptions,\n DocumentStatus,\n WaitOptions,\n Page,\n EntitiesResponse,\n QueryResult,\n PublishResult,\n ShareLinkOptions,\n ShareLinkResult,\n GenerateOptions,\n GenerateResult,\n SessionState,\n StructuredSchema,\n} from './types';\n\n// Chat stream event types — mirrors @okrapdf/schemas ChatStreamServerEvent\n// Inlined to avoid adding @okrapdf/schemas as a dependency of the published SDK.\n\nexport type ChatStreamServerEvent =\n | { type: 'CHAT_STREAM_START'; requestId: string }\n | { type: 'CHAT_STREAM_DELTA'; requestId: string; delta: string }\n | { type: 'CHAT_STREAM_DONE'; requestId: string; usage?: { inputTokens: number; outputTokens: number; costUsd: number }; model?: string }\n | { type: 'CHAT_STREAM_ERROR'; requestId: string; error: string };\n\n/** Function that sends a JSON string over the WebSocket. Returns false if WS is closed. */\nexport type WsSendFn = (message: string) => boolean;\n\n/** Subscribe to chat stream events. Returns unsubscribe function. */\nexport type WsSubscribeFn = (\n requestId: string,\n handler: (event: ChatStreamServerEvent) => void,\n) => () => void;\n\nexport interface WsSessionOptions {\n /** Send JSON string over the existing WebSocket connection */\n send: WsSendFn;\n /** Subscribe to CHAT_STREAM_* events for a given requestId */\n subscribe: WsSubscribeFn;\n}\n\nfunction uuid(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport class WsSession implements OkraSession {\n readonly id: string;\n readonly modelEndpoint: string;\n readonly model?: string;\n\n #inner: OkraSession;\n #opts: WsSessionOptions;\n\n constructor(inner: OkraSession, opts: WsSessionOptions) {\n this.#inner = inner;\n this.#opts = opts;\n this.id = inner.id;\n this.modelEndpoint = inner.modelEndpoint;\n this.model = inner.model;\n }\n\n // ── Overridden: stream via WebSocket ──────────────────────────────────────\n\n async *stream(\n query: string,\n options?: CompletionOptions,\n ): AsyncGenerator<CompletionEvent> {\n const requestId = uuid();\n\n // Build message history (single user message for now — matches HTTP path)\n const messages = [{ role: 'user', content: query }];\n\n const sent = this.#opts.send(JSON.stringify({\n type: 'CHAT_COMPLETION',\n requestId,\n messages,\n }));\n\n if (!sent) {\n yield { type: 'error', message: 'WebSocket not connected' };\n return;\n }\n\n // Create a promise-based event queue\n type QueueItem =\n | { done: false; event: ChatStreamServerEvent }\n | { done: true };\n\n const queue: QueueItem[] = [];\n let resolve: (() => void) | null = null;\n let finished = false;\n\n const unsubscribe = this.#opts.subscribe(requestId, (event) => {\n if (finished) return;\n queue.push({ done: false, event });\n resolve?.();\n });\n\n const cleanup = () => {\n finished = true;\n unsubscribe();\n };\n\n // Handle abort signal\n if (options?.signal) {\n options.signal.addEventListener('abort', () => {\n cleanup();\n queue.push({ done: true });\n resolve?.();\n }, { once: true });\n }\n\n try {\n let fullText = '';\n\n while (true) {\n if (queue.length === 0) {\n await new Promise<void>((r) => { resolve = r; });\n resolve = null;\n }\n\n const item = queue.shift();\n if (!item || item.done) break;\n\n const evt = item.event;\n\n switch (evt.type) {\n case 'CHAT_STREAM_START':\n // No CompletionEvent for start — just skip\n break;\n\n case 'CHAT_STREAM_DELTA':\n fullText += evt.delta;\n yield { type: 'text_delta', text: evt.delta };\n break;\n\n case 'CHAT_STREAM_DONE':\n yield { type: 'done', answer: fullText };\n cleanup();\n return;\n\n case 'CHAT_STREAM_ERROR':\n yield { type: 'error', message: evt.error };\n cleanup();\n return;\n }\n }\n } finally {\n cleanup();\n }\n }\n\n // ── Delegated to inner HTTP session ───────────────────────────────────────\n\n state(): SessionState { return this.#inner.state(); }\n setModel(model: string): Promise<void> { return this.#inner.setModel(model); }\n status(signal?: AbortSignal): Promise<DocumentStatus> { return this.#inner.status(signal); }\n wait(options?: WaitOptions): Promise<DocumentStatus> { return this.#inner.wait(options); }\n pages(options?: { range?: string; signal?: AbortSignal }): Promise<Page[]> { return this.#inner.pages(options); }\n page(pageNumber: number, signal?: AbortSignal): Promise<Page> { return this.#inner.page(pageNumber, signal); }\n entities(options?: { type?: string; limit?: number; offset?: number; signal?: AbortSignal }): Promise<EntitiesResponse> { return this.#inner.entities(options); }\n downloadUrl(): string { return this.#inner.downloadUrl(); }\n query(sql: string, signal?: AbortSignal): Promise<QueryResult> { return this.#inner.query(sql, signal); }\n logs(options?: import('./types').LogsOptions): Promise<import('./types').LogEntry[]> { return this.#inner.logs(options); }\n publish(signal?: AbortSignal): Promise<PublishResult> { return this.#inner.publish(signal); }\n shareLink(options?: ShareLinkOptions): Promise<ShareLinkResult> { return this.#inner.shareLink(options); }\n\n prompt(query: string, options?: GenerateOptions & { schema?: undefined }): Promise<GenerateResult>;\n prompt<T>(query: string, options: GenerateOptions & { schema: StructuredSchema<T> }): Promise<GenerateResult<T>>;\n prompt<T = undefined>(query: string, options?: GenerateOptions): Promise<GenerateResult<T>> {\n if (options?.schema !== undefined) {\n return this.#inner.prompt(query, options as GenerateOptions & { schema: StructuredSchema<unknown> }) as Promise<GenerateResult<T>>;\n }\n return this.#inner.prompt(query, options as GenerateOptions & { schema?: undefined }) as Promise<GenerateResult<T>>;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwDA,SAAS,OAAe;AACtB,MAAI,OAAO,WAAW,eAAe,OAAO,OAAO,eAAe,YAAY;AAC5E,WAAO,OAAO,WAAW;AAAA,EAC3B;AACA,SAAO,GAAG,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AACjE;AAEO,IA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Q,MAAM;AAAA,EAAG;AAAA,EAC5F,UAAU,SAAsD;AAAE,WAAO,KAAK,OAAO,UAAU,OAAO;AAAA,EAAG;AAAA,EAIzG,OAAsB,OAAe,SAAuD;AAC1F,QAAI,SAAS,WAAW,QAAW;AACjC,aAAO,KAAK,OAAO,OAAO,OAAO,OAAkE;AAAA,IACrG;AACA,WAAO,KAAK,OAAO,OAAO,OAAO,OAAmD;AAAA,EACtF;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/ws-session.ts"],"sourcesContent":["/**\n * WsSession — OkraSession adapter that routes `stream()` over an existing\n * WebSocket connection instead of HTTP SSE.\n *\n * All non-streaming methods delegate to the inner HTTP-backed session.\n * Only `stream()` is overridden to send CHAT_COMPLETION over WS and yield\n * CompletionEvents from CHAT_STREAM_* responses.\n *\n * Usage:\n * const wsSession = new WsSession(httpSession, { send, subscribe });\n * const chat = useChat({ session: wsSession });\n */\n\nimport type {\n OkraSession,\n CompletionEvent,\n CompletionOptions,\n DocumentStatus,\n WaitOptions,\n Page,\n EntitiesResponse,\n QueryResult,\n PublishResult,\n ShareLinkOptions,\n ShareLinkResult,\n GenerateOptions,\n GenerateResult,\n SessionState,\n StructuredSchema,\n} from './types';\n\n// Chat stream event types — mirrors @okrapdf/schemas ChatStreamServerEvent\n// Inlined to avoid adding @okrapdf/schemas as a dependency of the published SDK.\n\nexport type ChatStreamServerEvent =\n | { type: 'CHAT_STREAM_START'; requestId: string }\n | { type: 'CHAT_STREAM_DELTA'; requestId: string; delta: string }\n | { type: 'CHAT_STREAM_DONE'; requestId: string; usage?: { inputTokens: number; outputTokens: number; costUsd: number }; model?: string }\n | { type: 'CHAT_STREAM_ERROR'; requestId: string; error: string };\n\n/** Function that sends a JSON string over the WebSocket. Returns false if WS is closed. */\nexport type WsSendFn = (message: string) => boolean;\n\n/** Subscribe to chat stream events. Returns unsubscribe function. */\nexport type WsSubscribeFn = (\n requestId: string,\n handler: (event: ChatStreamServerEvent) => void,\n) => () => void;\n\nexport interface WsSessionOptions {\n /** Send JSON string over the existing WebSocket connection */\n send: WsSendFn;\n /** Subscribe to CHAT_STREAM_* events for a given requestId */\n subscribe: WsSubscribeFn;\n}\n\nfunction uuid(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {\n return crypto.randomUUID();\n }\n return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport class WsSession implements OkraSession {\n readonly id: string;\n readonly modelEndpoint: string;\n readonly model?: string;\n\n #inner: OkraSession;\n #opts: WsSessionOptions;\n\n constructor(inner: OkraSession, opts: WsSessionOptions) {\n this.#inner = inner;\n this.#opts = opts;\n this.id = inner.id;\n this.modelEndpoint = inner.modelEndpoint;\n this.model = inner.model;\n }\n\n // ── Overridden: stream via WebSocket ──────────────────────────────────────\n\n async *stream(\n query: string,\n options?: CompletionOptions,\n ): AsyncGenerator<CompletionEvent> {\n const requestId = uuid();\n\n // Build message history (single user message for now — matches HTTP path)\n const messages = [{ role: 'user', content: query }];\n\n const sent = this.#opts.send(JSON.stringify({\n type: 'CHAT_COMPLETION',\n requestId,\n messages,\n }));\n\n if (!sent) {\n yield { type: 'error', message: 'WebSocket not connected' };\n return;\n }\n\n // Create a promise-based event queue\n type QueueItem =\n | { done: false; event: ChatStreamServerEvent }\n | { done: true };\n\n const queue: QueueItem[] = [];\n let resolve: (() => void) | null = null;\n let finished = false;\n\n const unsubscribe = this.#opts.subscribe(requestId, (event) => {\n if (finished) return;\n queue.push({ done: false, event });\n resolve?.();\n });\n\n const cleanup = () => {\n finished = true;\n unsubscribe();\n };\n\n // Handle abort signal\n if (options?.signal) {\n options.signal.addEventListener('abort', () => {\n cleanup();\n queue.push({ done: true });\n resolve?.();\n }, { once: true });\n }\n\n try {\n let fullText = '';\n\n while (true) {\n if (queue.length === 0) {\n await new Promise<void>((r) => { resolve = r; });\n resolve = null;\n }\n\n const item = queue.shift();\n if (!item || item.done) break;\n\n const evt = item.event;\n\n switch (evt.type) {\n case 'CHAT_STREAM_START':\n // No CompletionEvent for start — just skip\n break;\n\n case 'CHAT_STREAM_DELTA':\n fullText += evt.delta;\n yield { type: 'text_delta', text: evt.delta };\n break;\n\n case 'CHAT_STREAM_DONE':\n yield { type: 'done', answer: fullText };\n cleanup();\n return;\n\n case 'CHAT_STREAM_ERROR':\n yield { type: 'error', message: evt.error };\n cleanup();\n return;\n }\n }\n } finally {\n cleanup();\n }\n }\n\n // ── Delegated to inner HTTP session ───────────────────────────────────────\n\n state(): SessionState { return this.#inner.state(); }\n setModel(model: string): Promise<void> { return this.#inner.setModel(model); }\n status(signal?: AbortSignal): Promise<DocumentStatus> { return this.#inner.status(signal); }\n wait(options?: WaitOptions): Promise<DocumentStatus> { return this.#inner.wait(options); }\n pages(options?: { range?: string; signal?: AbortSignal }): Promise<Page[]> { return this.#inner.pages(options); }\n page(pageNumber: number, signal?: AbortSignal): Promise<Page> { return this.#inner.page(pageNumber, signal); }\n entities(options?: { type?: string; limit?: number; offset?: number; signal?: AbortSignal }): Promise<EntitiesResponse> { return this.#inner.entities(options); }\n downloadUrl(): string { return this.#inner.downloadUrl(); }\n query(sql: string, signal?: AbortSignal): Promise<QueryResult> { return this.#inner.query(sql, signal); }\n logs(options?: import('./types').LogsOptions): Promise<import('./types').LogEntry[]> { return this.#inner.logs(options); }\n publish(signal?: AbortSignal): Promise<PublishResult> { return this.#inner.publish(signal); }\n shareLink(options?: ShareLinkOptions): Promise<ShareLinkResult> { return this.#inner.shareLink(options); }\n\n prompt(query: string, options?: GenerateOptions & { schema?: undefined }): Promise<GenerateResult>;\n prompt<T>(query: string, options: GenerateOptions & { schema: StructuredSchema<T> }): Promise<GenerateResult<T>>;\n prompt<T = undefined>(query: string, options?: GenerateOptions): Promise<GenerateResult<T>> {\n if (options?.schema !== undefined) {\n return this.#inner.prompt(query, options as GenerateOptions & { schema: StructuredSchema<unknown> }) as Promise<GenerateResult<T>>;\n }\n return this.#inner.prompt(query, options as GenerateOptions & { schema?: undefined }) as Promise<GenerateResult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AAAA,EAAG;AAAA,EAChK,cAAsB;AAAE,WAAO,KAAK,OAAO,YAAY;AAAA,EAAG;AAAA,EAC1D,MAAM,KAAa,QAA4C;AAAE,WAAO,KAAK,OAAO,MAAM,KAAK,MAAM;AAAA,EAAG;AAAA,EACxG,KAAK,SAAgF;AAAE,WAAO,KAAK,OAAO,KAAK,OAAO;AAAA,EAAG;AAAA,EACzH,QAAQ,QAA8C;AAAE,WAAO,KAAK,OAAO,QAAQ,MAAM;AAAA,EAAG;AAAA,EAC5F,UAAU,SAAsD;AAAE,WAAO,KAAK,OAAO,UAAU,OAAO;AAAA,EAAG;AAAA,EAIzG,OAAsB,OAAe,SAAuD;AAC1F,QAAI,SAAS,WAAW,QAAW;AACjC,aAAO,KAAK,OAAO,OAAO,OAAO,OAAkE;AAAA,IACrG;AACA,WAAO,KAAK,OAAO,OAAO,OAAO,OAAmD;AAAA,EACtF;AACF;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
- import { O as OkraClient } from '../client-p82YcAs3.js';
3
- import { O as OkraSession, p as DocumentStatus, P as Page, u as StructuredSchema, t as GenerateResult } from '../types-DDm2eEL0.js';
4
- export { s as CompletionEvent } from '../types-DDm2eEL0.js';
2
+ import { O as OkraClient } from '../client-D4A0dQ4h.js';
3
+ import { a as OkraSession, D as DocumentStatus, c as Page, i as StructuredSchema, h as GenerateResult } from '../types-SYOi8k1l.js';
4
+ export { b as CompletionEvent } from '../types-SYOi8k1l.js';
5
5
  import 'zod';
6
6
 
7
7
  interface OkraContextValue {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createOkra
3
- } from "../chunk-YVUL6ZLA.js";
4
- import "../chunk-2HJPTW6S.js";
3
+ } from "../chunk-7BAEYVWG.js";
4
+ import "../chunk-YGIBZV5J.js";
5
5
  import "../chunk-NIZM2ETT.js";
6
6
 
7
7
  // src/react/provider.ts