yamchart 0.10.1 → 0.10.2

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.
Files changed (82) hide show
  1. package/dist/{advisor-5TJDNAY7.js → advisor-5F73GF54.js} +12 -12
  2. package/dist/{chunk-S2CH4HUZ.js → chunk-25ES7MGF.js} +4 -4
  3. package/dist/{chunk-QUIDZO5G.js → chunk-5CRXV5PQ.js} +22 -6
  4. package/dist/chunk-5CRXV5PQ.js.map +1 -0
  5. package/dist/chunk-7HWFVUGP.js +1239 -0
  6. package/dist/chunk-7HWFVUGP.js.map +1 -0
  7. package/dist/{chunk-5FHV22X2.js → chunk-PYVROL7Z.js} +4 -4
  8. package/dist/{chunk-64CI3HSY.js → chunk-UOSOZT47.js} +15 -8
  9. package/dist/{chunk-64CI3HSY.js.map → chunk-UOSOZT47.js.map} +1 -1
  10. package/dist/{chunk-ZBCQNWVN.js → chunk-WVSDQNAN.js} +5 -5
  11. package/dist/{chunk-UFDQ3C7Q.js → chunk-X3UG6T3Q.js} +257 -257
  12. package/dist/chunk-X3UG6T3Q.js.map +1 -0
  13. package/dist/{connection-utils-FEUWER5I.js → connection-utils-HNX3473B.js} +5 -5
  14. package/dist/{describe-MEP72B56.js → describe-KDGXFPDQ.js} +7 -7
  15. package/dist/{dev-H6SJZ5UA.js → dev-KOWFGDOP.js} +933 -127
  16. package/dist/dev-KOWFGDOP.js.map +1 -0
  17. package/dist/dev-supervisor-JXLVGEHP.js +43 -0
  18. package/dist/dev-supervisor-JXLVGEHP.js.map +1 -0
  19. package/dist/{dist-5DQO6L2S.js → dist-LK3ZG74Q.js} +5 -5
  20. package/dist/{dist-PPAD6KOM.js → dist-WMP7BFKP.js} +24 -2
  21. package/dist/{dist-XNCED7JW.js → dist-YB5RBWCC.js} +4 -4
  22. package/dist/index.js +65 -42
  23. package/dist/index.js.map +1 -1
  24. package/dist/{init-SECXKD5G.js → init-TJJVKMEN.js} +24 -5
  25. package/dist/init-TJJVKMEN.js.map +1 -0
  26. package/dist/public/assets/DataView-BfwnWnLH.js +9 -0
  27. package/dist/public/assets/{EventManagement-BnmeJDQl.js → EventManagement-BIkVUSCe.js} +2 -2
  28. package/dist/public/assets/ExplorePage-CeaAulqT.js +1 -0
  29. package/dist/public/assets/{LoginPage-CzaFkkjg.js → LoginPage-4WeNcdRi.js} +1 -1
  30. package/dist/public/assets/{PublicViewer-irjxqH6a.js → PublicViewer-CkW-G56D.js} +1 -1
  31. package/dist/public/assets/{SetupWizard-ConWIcmy.js → SetupWizard-CwTr3PCy.js} +1 -1
  32. package/dist/public/assets/{ShareManagement-CP4wdwLR.js → ShareManagement-DSon6CoC.js} +1 -1
  33. package/dist/public/assets/{SourceDetailView-DZS5518E.js → SourceDetailView-BA4XVKqV.js} +1 -1
  34. package/dist/public/assets/UserManagement-BWD2Ugkv.js +1 -0
  35. package/dist/public/assets/{index-C1X8RW4Z.css → index-Cb4omrVn.css} +1 -1
  36. package/dist/public/assets/{index-jlfTO7f5.js → index-iR9gLdl9.js} +41 -41
  37. package/dist/public/assets/{index.es-CgnvEWi5.js → index.es-BuEtjxhO.js} +1 -1
  38. package/dist/public/assets/{jspdf.es.min-Cw5WefMt.js → jspdf.es.min-CScx2_oK.js} +3 -3
  39. package/dist/public/index.html +2 -2
  40. package/dist/{query-2H3YOPI2.js → query-7XHKSZ5H.js} +5 -5
  41. package/dist/sample-YNSJ3I3T.js +76 -0
  42. package/dist/sample-YNSJ3I3T.js.map +1 -0
  43. package/dist/{search-IPE4ISFB.js → search-NKRXXLRS.js} +7 -7
  44. package/dist/semantic-DD7P4634.js +30 -0
  45. package/dist/{semantic-K3MYXXJI.js → semantic-NBAX4WU4.js} +39 -4
  46. package/dist/semantic-NBAX4WU4.js.map +1 -0
  47. package/dist/{source-resolver-HZQLOODU.js → source-resolver-7NY3KEZ2.js} +7 -7
  48. package/dist/source-resolver-7NY3KEZ2.js.map +1 -0
  49. package/dist/{sync-warehouse-TUNULDUY.js → sync-warehouse-PK7HXW7U.js} +15 -11
  50. package/dist/sync-warehouse-PK7HXW7U.js.map +1 -0
  51. package/dist/{tables-K5NAN2WK.js → tables-WQTRZSXR.js} +7 -7
  52. package/dist/templates/default/docs/yamchart-reference.md +26 -0
  53. package/dist/{test-SRHVOXZB.js → test-MKNKUR3N.js} +19 -7
  54. package/dist/test-MKNKUR3N.js.map +1 -0
  55. package/package.json +5 -5
  56. package/dist/chunk-QUIDZO5G.js.map +0 -1
  57. package/dist/chunk-UFDQ3C7Q.js.map +0 -1
  58. package/dist/chunk-ZIY22VO7.js +0 -1190
  59. package/dist/chunk-ZIY22VO7.js.map +0 -1
  60. package/dist/dev-H6SJZ5UA.js.map +0 -1
  61. package/dist/init-SECXKD5G.js.map +0 -1
  62. package/dist/public/assets/DataView-DUCz_96y.js +0 -9
  63. package/dist/public/assets/ExplorePage-kk4z9ldZ.js +0 -1
  64. package/dist/public/assets/UserManagement-AubGd9hl.js +0 -1
  65. package/dist/sample-ODUGGSFA.js +0 -42
  66. package/dist/sample-ODUGGSFA.js.map +0 -1
  67. package/dist/semantic-K3MYXXJI.js.map +0 -1
  68. package/dist/sync-warehouse-TUNULDUY.js.map +0 -1
  69. package/dist/test-SRHVOXZB.js.map +0 -1
  70. /package/dist/{advisor-5TJDNAY7.js.map → advisor-5F73GF54.js.map} +0 -0
  71. /package/dist/{chunk-S2CH4HUZ.js.map → chunk-25ES7MGF.js.map} +0 -0
  72. /package/dist/{chunk-5FHV22X2.js.map → chunk-PYVROL7Z.js.map} +0 -0
  73. /package/dist/{chunk-ZBCQNWVN.js.map → chunk-WVSDQNAN.js.map} +0 -0
  74. /package/dist/{connection-utils-FEUWER5I.js.map → connection-utils-HNX3473B.js.map} +0 -0
  75. /package/dist/{describe-MEP72B56.js.map → describe-KDGXFPDQ.js.map} +0 -0
  76. /package/dist/{dist-5DQO6L2S.js.map → dist-LK3ZG74Q.js.map} +0 -0
  77. /package/dist/{dist-PPAD6KOM.js.map → dist-WMP7BFKP.js.map} +0 -0
  78. /package/dist/{dist-XNCED7JW.js.map → dist-YB5RBWCC.js.map} +0 -0
  79. /package/dist/{query-2H3YOPI2.js.map → query-7XHKSZ5H.js.map} +0 -0
  80. /package/dist/{search-IPE4ISFB.js.map → search-NKRXXLRS.js.map} +0 -0
  81. /package/dist/{source-resolver-HZQLOODU.js.map → semantic-DD7P4634.js.map} +0 -0
  82. /package/dist/{tables-K5NAN2WK.js.map → tables-WQTRZSXR.js.map} +0 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { resolve, basename, dirname, join } from 'path';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { validateProject } from './commands/validate.js';\nimport { findProjectRoot, loadEnvFile } from './utils/config.js';\nimport pc from 'picocolors';\nimport * as output from './utils/output.js';\nimport { checkForUpdate } from './utils/update-check.js';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'));\n\nconst program = new Command();\n\nprogram\n .name('yamchart')\n .description('Git-native business intelligence dashboards')\n .version(pkg.version);\n\nprogram.option('--env <name>', 'Environment to use (from environments block, or YAMCHART_ENV)');\n\n// Propagate --env to process.env so all downstream callers pick it up\nprogram.hook('preAction', () => {\n const opts = program.opts();\n if (opts.env) {\n process.env.YAMCHART_ENV = opts.env;\n }\n});\n\nprogram\n .command('validate')\n .description('Validate configuration files')\n .argument('[path]', 'Path to yamchart project', '.')\n .option('--dry-run', 'Connect to database and test queries with EXPLAIN')\n .option('-c, --connection <name>', 'Connection to use for dry-run')\n .option('--json', 'Output as JSON')\n .action(async (path: string, options: { dryRun?: boolean; connection?: string; json?: boolean }) => {\n const startPath = resolve(path);\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n if (options.json) {\n console.log(JSON.stringify({ success: false, error: 'yamchart.yaml not found' }));\n } else {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n }\n process.exit(2);\n }\n\n // Load .env file\n loadEnvFile(projectDir);\n\n if (!options.json) {\n output.header('Validating yamchart project...');\n }\n\n const result = await validateProject(projectDir, {\n dryRun: options.dryRun ?? false,\n connection: options.connection,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n // Print results\n for (const error of result.errors) {\n output.error(error.file);\n output.detail(error.message);\n if (error.suggestion) {\n output.detail(error.suggestion);\n }\n }\n\n for (const warning of result.warnings) {\n output.warning(warning.file);\n output.detail(warning.message);\n }\n\n output.newline();\n\n if (result.success) {\n output.success(`Schema: ${result.stats.passed} passed`);\n } else {\n output.error(`Schema: ${result.stats.passed} passed, ${result.stats.failed} failed`);\n }\n\n if (result.dryRunStats) {\n output.newline();\n if (result.dryRunStats.failed === 0) {\n output.success(`Queries: ${result.dryRunStats.passed} passed (EXPLAIN OK)`);\n } else {\n output.error(`Queries: ${result.dryRunStats.passed} passed, ${result.dryRunStats.failed} failed`);\n }\n }\n\n output.newline();\n\n if (result.success) {\n output.success('Validation passed');\n } else {\n output.error(`Validation failed with ${result.errors.length} error(s)`);\n }\n }\n\n process.exit(result.success ? 0 : 1);\n });\n\nprogram\n .command('dev')\n .description('Start development server with hot reload')\n .argument('[path]', 'Path to yamchart project', '.')\n .option('-p, --port <number>', 'Port to listen on', '3001')\n .option('--api-only', 'Only serve API, no web UI')\n .option('--no-open', 'Do not open browser automatically')\n .action(async (path: string, options: { port: string; apiOnly?: boolean; open: boolean }) => {\n const startPath = resolve(path);\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n const globalOpts = program.opts();\n const { runDevServer } = await import('./commands/dev.js');\n\n await runDevServer(projectDir, {\n port: parseInt(options.port, 10),\n apiOnly: options.apiOnly ?? false,\n open: options.open,\n version: pkg.version,\n env: globalOpts.env,\n });\n });\n\nprogram\n .command('init')\n .description('Create a new yamchart project')\n .argument('[directory]', 'Target directory', '.')\n .option('--example', 'Create full example project with sample database')\n .option('--empty', 'Create only yamchart.yaml (no connections, models, or charts)')\n .option('--force', 'Overwrite existing files')\n .action(async (directory: string, options: { example?: boolean; empty?: boolean; force?: boolean }) => {\n const { initProject } = await import('./commands/init.js');\n const targetDir = resolve(directory);\n\n const result = await initProject(targetDir, options);\n\n if (!result.success) {\n output.error(result.error || 'Failed to create project');\n process.exit(1);\n }\n\n output.newline();\n output.success(`Created ${directory === '.' ? basename(targetDir) : directory}/`);\n for (const file of result.files.slice(0, 10)) {\n output.detail(file);\n }\n if (result.files.length > 10) {\n output.detail(`... and ${result.files.length - 10} more files`);\n }\n output.newline();\n output.info(`Run \\`cd ${directory === '.' ? basename(targetDir) : directory} && yamchart dev\\` to start.`);\n });\n\nprogram\n .command('sync-dbt')\n .description('Sync dbt project metadata into AI-readable catalog')\n .option('-s, --source <type>', 'Source type: local, github, dbt-cloud', 'local')\n .option('-p, --path <dir>', 'Path to dbt project (for local source)')\n .option('--repo <repo>', 'GitHub repository (for github source)')\n .option('--branch <branch>', 'Git branch (for github source)', 'main')\n .option('-i, --include <patterns...>', 'Include glob patterns')\n .option('-e, --exclude <patterns...>', 'Exclude glob patterns')\n .option('-t, --tag <tags...>', 'Filter by dbt tags')\n .option('--refresh', 'Re-sync using saved configuration')\n .option('--target-database <database>', 'Override database in ref() paths (e.g. switch from dev to prod)')\n .action(async (options: {\n source: 'local' | 'github' | 'dbt-cloud';\n path?: string;\n repo?: string;\n branch?: string;\n include?: string[];\n exclude?: string[];\n tag?: string[];\n refresh?: boolean;\n targetDatabase?: string;\n }) => {\n const { syncDbt, loadSyncConfig } = await import('./commands/sync-dbt.js');\n\n // Find project root\n const projectDir = await findProjectRoot(process.cwd());\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n // Handle refresh mode\n if (options.refresh) {\n const savedConfig = await loadSyncConfig(projectDir);\n if (!savedConfig) {\n output.error('No saved sync config found');\n output.detail('Run sync-dbt without --refresh first');\n process.exit(1);\n }\n output.info(`Re-syncing from ${savedConfig.source}:${savedConfig.path || savedConfig.repo}`);\n }\n\n const spin = output.spinner('Syncing dbt metadata...');\n\n const result = await syncDbt(projectDir, {\n source: options.source,\n path: options.path,\n repo: options.repo,\n branch: options.branch,\n include: options.include || [],\n exclude: options.exclude || [],\n tags: options.tag || [],\n refresh: options.refresh,\n targetDatabase: options.targetDatabase,\n });\n\n spin.stop();\n\n if (!result.success) {\n output.error(result.error || 'Sync failed');\n process.exit(1);\n }\n\n output.success(`Synced ${result.modelsIncluded} models to .yamchart/catalog.md`);\n if (result.modelsExcluded > 0) {\n output.detail(`${result.modelsExcluded} models filtered out`);\n }\n\n // Show lineage warnings\n if (result.warnings) {\n for (const w of result.warnings) {\n output.warning(w);\n }\n }\n\n // Check for database mismatch (skip if --target-database was used)\n if (!options.targetDatabase) {\n try {\n const { readFile } = await import('fs/promises');\n const { resolveConnection } = await import('./commands/connection-utils.js');\n const { detectDatabaseMismatch } = await import('./dbt/rewrite-database.js');\n const catalogJsonStr = await readFile(join(projectDir, '.yamchart', 'catalog.json'), 'utf-8');\n const catalogData = JSON.parse(catalogJsonStr);\n const connection = await resolveConnection(projectDir, undefined, program.opts().env);\n // Extract database from connection config (varies by type)\n const connDb = (connection as Record<string, any>).config?.database as string | undefined;\n const mismatch = detectDatabaseMismatch(catalogData.models, connDb);\n if (mismatch.mismatch) {\n output.warning(\n `Catalog tables reference database \"${mismatch.catalogDatabase}\" but your default ` +\n `connection uses \"${mismatch.connectionDatabase}\". Models using ref() may query the wrong database.`\n );\n output.detail(\n `To fix: yamchart sync-dbt --refresh --target-database ${mismatch.connectionDatabase}`\n );\n }\n } catch {\n // Connection not configured or unreadable — skip silently\n }\n }\n });\n\nprogram\n .command('generate')\n .description('Generate SQL model stubs from dbt catalog')\n .argument('[model]', 'Specific model to generate (optional)')\n .option('--yolo', 'Skip all prompts, use defaults for everything')\n .action(async (model: string | undefined, options: { yolo?: boolean }) => {\n const { generate } = await import('./commands/generate.js');\n\n const projectDir = await findProjectRoot(process.cwd());\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n const result = await generate(projectDir, {\n model,\n yolo: options.yolo,\n });\n\n if (!result.success) {\n output.error(result.error || 'Generate failed');\n process.exit(1);\n }\n\n output.success(`Generated ${result.filesCreated} model stubs`);\n if (result.filesSkipped > 0) {\n output.detail(`${result.filesSkipped} files skipped`);\n }\n });\n\nprogram\n .command('test')\n .description('Run model tests (@returns schema checks and @tests data assertions)')\n .argument('[model]', 'Specific model to test (optional, tests all if omitted)')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .action(async (model: string | undefined, options: { connection?: string; json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n if (options.json) {\n console.log(JSON.stringify({ success: false, error: 'yamchart.yaml not found' }));\n } else {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n }\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { testProject, formatTestOutput } = await import('./commands/test.js');\n const result = await testProject(projectDir, model, {\n connection: options.connection,\n json: options.json,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n formatTestOutput(result, result.connectionName);\n }\n\n process.exit(result.success ? 0 : 1);\n } catch (err) {\n if (options.json) {\n console.log(\n JSON.stringify({ success: false, error: err instanceof Error ? err.message : String(err) }),\n );\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(2);\n }\n });\n\nprogram\n .command('update')\n .description('Check for yamchart updates')\n .action(async () => {\n const { runUpdate } = await import('./commands/update.js');\n await runUpdate(pkg.version);\n });\n\nprogram\n .command('reset-password')\n .description('Reset a user password (requires auth to be enabled)')\n .requiredOption('-e, --email <email>', 'Email address of the user')\n .action(async (options: { email: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n const { resetPassword } = await import('./commands/reset-password.js');\n await resetPassword(projectDir, options.email);\n });\n\nprogram\n .command('tables')\n .description('List tables and views in the connected database')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('-s, --schema <name>', 'Filter to schema')\n .option('-d, --database <name>', 'Filter to database (Snowflake/Databricks)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .option('--compare', 'Compare local metadata against live database')\n .action(async (options: { connection?: string; schema?: string; database?: string; json?: boolean; source?: string; compare?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n if (options.compare) {\n const { resolveTablesSource } = await import('./commands/source-resolver.js');\n const { compareTables, formatCompareTables } = await import('./commands/compare.js');\n\n let localResult;\n try {\n localResult = await resolveTablesSource(projectDir, 'catalog', options.connection, {\n schema: options.schema,\n database: options.database,\n });\n } catch {\n try {\n localResult = await resolveTablesSource(projectDir, 'model', options.connection, {\n schema: options.schema,\n database: options.database,\n });\n } catch {\n output.error('Cannot compare — no local metadata found. Run `yamchart sync-dbt` or `yamchart sync-warehouse` first.');\n process.exit(1);\n }\n }\n\n const dbResult = await resolveTablesSource(projectDir, 'db', options.connection, {\n schema: options.schema,\n database: options.database,\n });\n const diffs = compareTables(localResult.tables, dbResult.tables);\n\n if (options.json) {\n console.log(JSON.stringify(diffs, null, 2));\n } else {\n console.log(formatCompareTables(localResult.source, diffs));\n }\n return;\n }\n\n const { listTables } = await import('./commands/tables.js');\n const result = await listTables(projectDir, {\n ...options,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.tables, null, 2));\n } else {\n const sourceLabel = result.source === 'db'\n ? `${result.connectionName} (${result.connectionType})`\n : `Source: ${result.source}`;\n output.header(`Tables in ${sourceLabel}`);\n if (result.tables.length === 0) {\n output.info('No tables found');\n } else {\n for (const table of result.tables) {\n const schema = table.schema ? `${table.schema}.` : '';\n const typeLabel = table.type === 'VIEW' ? pc.dim(' (view)') : '';\n console.log(` ${schema}${table.name}${typeLabel}`);\n }\n output.newline();\n output.info(`${result.tables.length} table(s) found${result.durationMs > 0 ? ` (${result.durationMs.toFixed(0)}ms)` : ''}`);\n }\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('describe')\n .description('Show columns and types for a table')\n .argument('<table>', 'Table name (can be fully qualified, e.g. schema.table)')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .option('--compare', 'Compare local metadata against live database')\n .action(async (table: string, options: { connection?: string; json?: boolean; source?: string; compare?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n if (options.compare) {\n const { resolveDescribeSource } = await import('./commands/source-resolver.js');\n const { compareColumns, formatCompareColumns } = await import('./commands/compare.js');\n\n let localResult;\n try {\n localResult = await resolveDescribeSource(projectDir, table, 'catalog', options.connection);\n } catch {\n try {\n localResult = await resolveDescribeSource(projectDir, table, 'model', options.connection);\n } catch {\n output.error('Cannot compare — no local metadata found. Run `yamchart sync-dbt` or `yamchart sync-warehouse` first.');\n process.exit(1);\n }\n }\n\n const dbResult = await resolveDescribeSource(projectDir, table, 'db', options.connection);\n const diffs = compareColumns(localResult.columns, dbResult.columns);\n\n if (options.json) {\n console.log(JSON.stringify(diffs, null, 2));\n } else {\n console.log(formatCompareColumns(localResult.table, localResult.source, diffs));\n }\n return;\n }\n\n const { describeTable } = await import('./commands/describe.js');\n const result = await describeTable(projectDir, table, {\n ...options,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.columns, null, 2));\n } else {\n if (result.resolvedFrom) {\n output.detail(`Resolved \"${result.resolvedFrom}\" → ${result.table}`);\n }\n const sourceLabel = result.source === 'db'\n ? `${result.connectionName} (${result.connectionType})`\n : `Source: ${result.source}`;\n output.header(`${result.table} (${sourceLabel})`);\n\n const nameWidth = Math.max(4, ...result.columns.map((c) => c.name.length));\n const typeWidth = Math.max(4, ...result.columns.map((c) => c.type.length));\n\n console.log(` ${'name'.padEnd(nameWidth)} ${'type'.padEnd(typeWidth)} nullable`);\n console.log(` ${'─'.repeat(nameWidth)} ${'─'.repeat(typeWidth)} ${'─'.repeat(8)}`);\n\n for (const col of result.columns) {\n const nullable = col.nullable === 'YES' ? pc.dim('yes') : 'no';\n console.log(` ${col.name.padEnd(nameWidth)} ${pc.dim(col.type.padEnd(typeWidth))} ${nullable}`);\n }\n\n output.newline();\n output.info(`${result.columns.length} column(s)${result.durationMs > 0 ? ` (${result.durationMs.toFixed(0)}ms)` : ''}`);\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('query')\n .description('Execute SQL against a connection')\n .argument('<sql>', 'SQL query to execute')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .option('-l, --limit <number>', 'Max rows to return (default: 100)')\n .action(async (sql: string, options: { connection?: string; json?: boolean; limit?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { executeQuery } = await import('./commands/query.js');\n const { formatTable, formatJSON } = await import('./commands/connection-utils.js');\n\n const limit = options.limit ? parseInt(options.limit, 10) : undefined;\n const result = await executeQuery(projectDir, sql, {\n connection: options.connection,\n json: options.json,\n limit,\n });\n\n if (options.json) {\n console.log(formatJSON(result));\n } else {\n console.log(formatTable(result));\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('sample')\n .description('Show sample rows from a table or dbt model')\n .argument('<table>', 'Table name or dbt model name')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('-l, --limit <number>', 'Rows to show (default: 5)')\n .option('--json', 'Output as JSON')\n .action(async (table: string, options: { connection?: string; json?: boolean; limit?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { sampleTable } = await import('./commands/sample.js');\n const { formatTable, formatJSON } = await import('./commands/connection-utils.js');\n\n const limit = options.limit ? parseInt(options.limit, 10) : undefined;\n const result = await sampleTable(projectDir, table, {\n connection: options.connection,\n json: options.json,\n limit,\n });\n\n if (options.json) {\n console.log(formatJSON(result));\n } else {\n if (result.resolvedFrom) {\n output.detail(`Resolved \"${result.resolvedFrom}\" → ${result.table}`);\n }\n console.log(formatTable(result));\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('search')\n .description('Search for tables and columns by keyword')\n .argument('<keyword>', 'Keyword to search for')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .action(async (keyword: string, options: { connection?: string; json?: boolean; source?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { searchDatabase } = await import('./commands/search.js');\n const result = await searchDatabase(projectDir, keyword, {\n ...options,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.results, null, 2));\n } else {\n const sourceLabel = result.source === 'db'\n ? `${result.connectionName} (${result.connectionType})`\n : `Source: ${result.source}`;\n output.header(`Search results for \"${result.keyword}\" in ${sourceLabel}`);\n\n const tables = result.results.filter((r) => r.type === 'table');\n const columns = result.results.filter((r) => r.type === 'column');\n\n if (tables.length > 0) {\n output.newline();\n console.log(' Tables:');\n for (const t of tables) {\n const qualified = t.schema ? `${t.schema}.${t.table}` : t.table;\n console.log(` ${qualified}`);\n }\n }\n\n if (columns.length > 0) {\n output.newline();\n console.log(' Columns:');\n const nameWidth = Math.max(...columns.map((c) => {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n return qualified.length;\n }));\n for (const c of columns) {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n const colType = c.columnType ? pc.dim(c.columnType) : '';\n console.log(` ${qualified.padEnd(nameWidth + 2)}${colType}`);\n }\n }\n\n if (result.results.length === 0) {\n output.detail('No matches found');\n }\n\n output.newline();\n output.info(`${result.results.length} result(s)${result.durationMs > 0 ? ` (${result.durationMs.toFixed(0)}ms)` : ''}`);\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nconst catalogCmd = program\n .command('catalog')\n .description('Explore cached local metadata (no database connection needed)');\n\ncatalogCmd\n .command('tables')\n .description('List tables from cached catalog')\n .option('-s, --schema <name>', 'Filter to schema')\n .option('--json', 'Output as JSON')\n .action(async (options: { schema?: string; json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { listTables } = await import('./commands/tables.js');\n const result = await listTables(projectDir, {\n source: 'catalog',\n schema: options.schema,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.tables, null, 2));\n } else {\n output.header('Tables (from catalog)');\n if (result.tables.length === 0) {\n output.info('No tables found in catalog');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else {\n const filtered = options.schema\n ? result.tables.filter((t) => t.schema.toLowerCase().includes(options.schema!.toLowerCase()))\n : result.tables;\n for (const table of filtered) {\n const schema = table.schema ? `${table.schema}.` : '';\n const typeLabel = table.type === 'VIEW' ? pc.dim(' (view)') : table.type === 'SOURCE' ? pc.dim(' (source)') : '';\n console.log(` ${schema}${table.name}${typeLabel}`);\n }\n output.newline();\n output.info(`${filtered.length} table(s) from catalog`);\n }\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('No catalog found')) {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\ncatalogCmd\n .command('describe')\n .description('Show cached columns and types for a table')\n .argument('<table>', 'Table name or model name')\n .option('--json', 'Output as JSON')\n .action(async (table: string, options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { describeTable } = await import('./commands/describe.js');\n const result = await describeTable(projectDir, table, { source: 'catalog' });\n\n if (options.json) {\n console.log(JSON.stringify(result.columns, null, 2));\n } else {\n if (result.resolvedFrom) {\n output.detail(`Resolved \"${result.resolvedFrom}\" → ${result.table}`);\n }\n output.header(`${result.table} (from catalog)`);\n\n const nameWidth = Math.max(4, ...result.columns.map((c) => c.name.length));\n const typeWidth = Math.max(4, ...result.columns.map((c) => c.type.length));\n\n console.log(` ${'name'.padEnd(nameWidth)} ${'type'.padEnd(typeWidth)} nullable`);\n console.log(` ${'─'.repeat(nameWidth)} ${'─'.repeat(typeWidth)} ${'─'.repeat(8)}`);\n\n for (const col of result.columns) {\n const nullable = col.nullable === 'YES' ? pc.dim('yes') : 'no';\n console.log(` ${col.name.padEnd(nameWidth)} ${pc.dim(col.type.padEnd(typeWidth))} ${nullable}`);\n }\n\n output.newline();\n output.info(`${result.columns.length} column(s)`);\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('No catalog found')) {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else if (err instanceof Error && err.message.includes('not found in catalog')) {\n output.error(err.message);\n output.detail('Try `yamchart catalog search` to find available tables');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\ncatalogCmd\n .command('search')\n .description('Search cached metadata for tables and columns')\n .argument('<keyword>', 'Keyword to search for')\n .option('--json', 'Output as JSON')\n .action(async (keyword: string, options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { searchDatabase } = await import('./commands/search.js');\n const result = await searchDatabase(projectDir, keyword, { source: 'catalog' });\n\n if (options.json) {\n console.log(JSON.stringify(result.results, null, 2));\n } else {\n output.header(`Search results for \"${keyword}\" (from catalog)`);\n\n const tables = result.results.filter((r) => r.type === 'table');\n const columns = result.results.filter((r) => r.type === 'column');\n\n if (tables.length > 0) {\n output.newline();\n console.log(' Tables:');\n for (const t of tables) {\n const qualified = t.schema ? `${t.schema}.${t.table}` : t.table;\n console.log(` ${qualified}`);\n }\n }\n\n if (columns.length > 0) {\n output.newline();\n console.log(' Columns:');\n const nameWidth = Math.max(...columns.map((c) => {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n return qualified.length;\n }));\n for (const c of columns) {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n const colType = c.columnType ? pc.dim(c.columnType) : '';\n console.log(` ${qualified.padEnd(nameWidth + 2)}${colType}`);\n }\n }\n\n if (result.results.length === 0) {\n output.detail('No matches found in catalog');\n output.detail('Try `yamchart search <keyword>` to search the live database');\n }\n\n output.newline();\n output.info(`${result.results.length} result(s) from catalog`);\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('No catalog found')) {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\ncatalogCmd\n .command('status')\n .description('Show catalog sync status')\n .option('--json', 'Output as JSON')\n .action(async (options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const catalogPath = join(projectDir, '.yamchart', 'catalog.json');\n\n let catalogData: { syncedAt?: string; source?: { type: string }; models?: Array<{ source?: string; columns?: unknown[] }> };\n try {\n catalogData = JSON.parse(await readFile(catalogPath, 'utf-8'));\n } catch {\n if (options.json) {\n console.log(JSON.stringify({ exists: false }));\n } else {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n }\n process.exit(1);\n return;\n }\n\n const models = catalogData.models || [];\n const dbtModels = models.filter((m) => m.source === 'dbt');\n const warehouseModels = models.filter((m) => m.source === 'warehouse');\n const sourceModels = models.filter((m) => m.source === 'dbt-source');\n const totalColumns = models.reduce((sum, m) => sum + (m.columns?.length || 0), 0);\n\n // Try to load warehouse sync state\n let syncState: { syncedAt?: string; connection?: string; schemas?: string[] } | null = null;\n try {\n const syncPath = join(projectDir, '.yamchart', 'warehouse-sync.json');\n syncState = JSON.parse(await readFile(syncPath, 'utf-8'));\n } catch {\n // No sync state\n }\n\n if (options.json) {\n console.log(JSON.stringify({\n exists: true,\n syncedAt: catalogData.syncedAt,\n source: catalogData.source,\n models: models.length,\n dbtModels: dbtModels.length,\n warehouseModels: warehouseModels.length,\n sourceModels: sourceModels.length,\n totalColumns,\n warehouseSync: syncState ? {\n syncedAt: syncState.syncedAt,\n connection: syncState.connection,\n schemas: syncState.schemas,\n } : null,\n }, null, 2));\n } else {\n output.header('Catalog Status');\n console.log(` Last synced: ${catalogData.syncedAt || 'unknown'}`);\n console.log(` Models: ${models.length} total (${dbtModels.length} dbt, ${warehouseModels.length} warehouse, ${sourceModels.length} sources)`);\n console.log(` Columns: ${totalColumns}`);\n\n if (syncState) {\n output.newline();\n console.log(` Warehouse sync:`);\n console.log(` Connection: ${syncState.connection || 'default'}`);\n console.log(` Schemas: ${syncState.schemas?.join(', ') || 'all'}`);\n console.log(` Last sync: ${syncState.syncedAt || 'unknown'}`);\n }\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('sync-warehouse')\n .description('Sync warehouse table metadata into the catalog')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('-s, --schema <schemas>', 'Comma-separated schemas to sync')\n .option('-d, --database <name>', 'Database to sync (Snowflake/Databricks)')\n .option('--skip-samples', 'Skip sample row collection')\n .option('--refresh', 'Re-run with saved connection/schema config')\n .option('--full', 'Force full re-sync (ignore incremental state)')\n .option('--json', 'Output sync summary as JSON')\n .action(async (options) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { runSyncWarehouse } = await import('./commands/sync-warehouse.js');\n await runSyncWarehouse(projectDir, options);\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('lineage')\n .description('Show upstream dependencies for a model')\n .argument('<model>', 'Model name to trace lineage for')\n .option('--depth <n>', 'Maximum depth to trace (default: unlimited)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .action(async (model: string, options: { depth?: string; json?: boolean; source?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { getLineage } = await import('./commands/lineage.js');\n const depth = options.depth ? parseInt(options.depth, 10) : undefined;\n const result = await getLineage(projectDir, model, {\n depth,\n json: options.json,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.tree, null, 2));\n } else {\n console.log(result.rendered);\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('ENOENT')) {\n output.error('No catalog found. Run `yamchart sync-dbt` first.');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\nprogram\n .command('advisor')\n .description('AI-powered dbt model advisor — suggests improvements informed by your BI layer')\n .argument('[question]', 'Question to ask, or \"audit\" for comprehensive analysis')\n .option('--top <n>', 'Limit audit suggestions (default: 5)')\n .option('--json', 'Output as JSON')\n .option('--dbt-path <path>', 'Override the synced dbt project path')\n .option('-c, --connection <name>', 'Connection to use for warehouse introspection')\n .action(async (question: string | undefined, options: { top?: string; json?: boolean; dbtPath?: string; connection?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n if (options.json) {\n console.log(JSON.stringify({ success: false, error: 'yamchart.yaml not found' }));\n } else {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n }\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n const { runAdvisor } = await import('./commands/advisor.js');\n await runAdvisor(projectDir, question, {\n top: options.top ? parseInt(options.top, 10) : 5,\n json: options.json,\n dbtPath: options.dbtPath,\n connection: options.connection,\n });\n });\n\nconst semanticCmd = program\n .command('semantic')\n .description('Explore the semantic layer — auto-generated measures and dimensions from your catalog')\n .option('--json', 'Output as JSON')\n .action(async (options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { readFile } = await import('fs/promises');\n const catalogPath = join(projectDir, '.yamchart', 'catalog.json');\n const catalogJson = JSON.parse(await readFile(catalogPath, 'utf-8'));\n\n const { listSemanticEntities } = await import('./commands/semantic.js');\n const result = listSemanticEntities(catalogJson);\n\n if (options.json) {\n console.log(JSON.stringify(result.entities, null, 2));\n return;\n }\n\n if (result.entities.length === 0) {\n output.info('No semantic entities found.');\n output.detail('Run `yamchart sync-dbt` or `yamchart sync-warehouse` to populate the catalog.');\n return;\n }\n\n output.header(`Semantic Layer — ${result.entities.length} entities`);\n\n for (const entity of result.entities) {\n console.log(` ${pc.bold(entity.name)}`);\n console.log(` ${pc.dim(entity.source_table)}`);\n if (entity.description) {\n console.log(` ${entity.description}`);\n }\n if (entity.measures.length > 0) {\n console.log(` Measures: ${entity.measures.map((m) => `${m.name} (${pc.dim(m.type)})`).join(', ')}`);\n }\n if (entity.dimensions.length > 0) {\n console.log(` Dimensions: ${entity.dimensions.map((d) => `${d.name} (${pc.dim(d.type)})`).join(', ')}`);\n }\n console.log();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('ENOENT')) {\n output.error('No catalog found. Run `yamchart sync-dbt` or `yamchart sync-warehouse` first.');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\nsemanticCmd\n .command('query')\n .description('Run a structured query against the semantic layer')\n .requiredOption('-e, --entity <name>', 'Entity name (e.g. fct_revenue)')\n .requiredOption('-m, --measures <measures>', 'Comma-separated measure names')\n .option('-d, --dimensions <dimensions>', 'Comma-separated dimension names')\n .option('-f, --filter <filter...>', 'Filters in format dimension=value')\n .option('--order <field>', 'Order by field')\n .option('--desc', 'Order descending (default: ascending)')\n .option('-l, --limit <n>', 'Row limit (default: 100)')\n .option('-c, --connection <name>', 'Connection to use')\n .option('--json', 'Output as JSON')\n .option('--sql', 'Print compiled SQL only (do not execute)')\n .action(async (options: {\n entity: string;\n measures: string;\n dimensions?: string;\n filter?: string[];\n order?: string;\n desc?: boolean;\n limit?: string;\n connection?: string;\n json?: boolean;\n sql?: boolean;\n }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { readFile } = await import('fs/promises');\n const catalogPath = join(projectDir, '.yamchart', 'catalog.json');\n const catalogJson = JSON.parse(await readFile(catalogPath, 'utf-8'));\n\n const { querySemanticEntity } = await import('./commands/semantic.js');\n\n // Parse filters: \"region=US\" → { dimension: 'region', operator: 'equals', value: 'US' }\n const filters = (options.filter || []).map((f) => {\n const eqIdx = f.indexOf('=');\n if (eqIdx === -1) throw new Error(`Invalid filter format: \"${f}\". Use dimension=value`);\n return {\n dimension: f.slice(0, eqIdx),\n operator: 'equals' as const,\n value: f.slice(eqIdx + 1),\n };\n });\n\n const result = querySemanticEntity(catalogJson, {\n entity: options.entity,\n measures: options.measures.split(',').map((s) => s.trim()),\n dimensions: options.dimensions ? options.dimensions.split(',').map((s) => s.trim()) : [],\n filters,\n order_by: options.order ? { field: options.order, direction: options.desc ? 'desc' : 'asc' } : undefined,\n limit: options.limit ? parseInt(options.limit, 10) : 100,\n });\n\n // --sql: just print the SQL\n if (options.sql) {\n console.log(result.sql);\n return;\n }\n\n // Execute the query\n const { resolveConnection, createConnector, formatTable, formatJSON } = await import('./commands/connection-utils.js');\n const connection = await resolveConnection(projectDir, options.connection, program.opts().env);\n const connector = createConnector(connection, projectDir);\n\n const start = performance.now();\n await connector.connect();\n const queryResult = await connector.execute(result.sql);\n await connector.disconnect();\n const durationMs = Math.round((performance.now() - start) * 100) / 100;\n\n if (options.json) {\n console.log(formatJSON({\n columns: queryResult.columns,\n rows: queryResult.rows,\n rowCount: queryResult.rows.length,\n durationMs,\n }));\n } else {\n output.detail(`Entity: ${result.entityName}`);\n output.detail(`SQL: ${result.sql.replace(/\\n/g, ' ').slice(0, 120)}...`);\n output.newline();\n console.log(formatTable({\n columns: queryResult.columns,\n rows: queryResult.rows,\n rowCount: queryResult.rows.length,\n durationMs,\n }));\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('ENOENT')) {\n output.error('No catalog found. Run `yamchart sync-dbt` or `yamchart sync-warehouse` first.');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\nprogram.parse();\n\n// Passive update check — runs in background, prints on exit if outdated\nlet updateNotification: string | null = null;\n\ncheckForUpdate(pkg.version).then((update) => {\n if (update) {\n updateNotification = `\\n Update available: ${update.current} → ${update.latest}\\n Run: yamchart update to see what's new\\n`;\n }\n});\n\nprocess.on('exit', () => {\n if (updateNotification) {\n // Use dim styling so it doesn't compete with command output\n console.error(`\\n${pc.dim(updateNotification)}`);\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,eAAe;AACxB,SAAS,SAAS,UAAU,SAAS,YAAY;AACjD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAG9B,OAAO,QAAQ;AAIf,IAAM,YAAY,QAAQ,cAAc,YAAY,GAAG,CAAC;AACxD,IAAM,MAAM,KAAK,MAAM,aAAa,KAAK,WAAW,iBAAiB,GAAG,OAAO,CAAC;AAEhF,IAAM,UAAU,IAAI,QAAQ;AAE5B,QACG,KAAK,UAAU,EACf,YAAY,6CAA6C,EACzD,QAAQ,IAAI,OAAO;AAEtB,QAAQ,OAAO,gBAAgB,+DAA+D;AAG9F,QA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","warning"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { resolve, basename, dirname, join } from 'path';\nimport { readFileSync } from 'fs';\nimport { fileURLToPath } from 'url';\nimport { validateProject } from './commands/validate.js';\nimport { findProjectRoot, loadEnvFile } from './utils/config.js';\nimport pc from 'picocolors';\nimport * as output from './utils/output.js';\nimport { checkForUpdate } from './utils/update-check.js';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst pkg = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'));\n\nconst program = new Command();\n\nprogram\n .name('yamchart')\n .description('Git-native business intelligence dashboards')\n .version(pkg.version);\n\nprogram.option('--env <name>', 'Environment to use (from environments block, or YAMCHART_ENV)');\n\n// Propagate --env to process.env so all downstream callers pick it up\nprogram.hook('preAction', () => {\n const opts = program.opts();\n if (opts.env) {\n process.env.YAMCHART_ENV = opts.env;\n }\n});\n\nprogram\n .command('validate')\n .description('Validate configuration files')\n .argument('[path]', 'Path to yamchart project', '.')\n .option('--dry-run', 'Connect to database and test queries with EXPLAIN')\n .option('-c, --connection <name>', 'Connection to use for dry-run')\n .option('--json', 'Output as JSON')\n .action(async (path: string, options: { dryRun?: boolean; connection?: string; json?: boolean }) => {\n const startPath = resolve(path);\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n if (options.json) {\n console.log(JSON.stringify({ success: false, error: 'yamchart.yaml not found' }));\n } else {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n }\n process.exit(2);\n }\n\n // Load .env file\n loadEnvFile(projectDir);\n\n if (!options.json) {\n output.header('Validating yamchart project...');\n }\n\n const result = await validateProject(projectDir, {\n dryRun: options.dryRun ?? false,\n connection: options.connection,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n // Print results\n for (const error of result.errors) {\n output.error(error.file);\n output.detail(error.message);\n if (error.suggestion) {\n output.detail(error.suggestion);\n }\n }\n\n for (const warning of result.warnings) {\n output.warning(warning.file);\n output.detail(warning.message);\n }\n\n output.newline();\n\n if (result.success) {\n output.success(`Schema: ${result.stats.passed} passed`);\n } else {\n output.error(`Schema: ${result.stats.passed} passed, ${result.stats.failed} failed`);\n }\n\n if (result.dryRunStats) {\n output.newline();\n if (result.dryRunStats.failed === 0) {\n output.success(`Queries: ${result.dryRunStats.passed} passed (EXPLAIN OK)`);\n } else {\n output.error(`Queries: ${result.dryRunStats.passed} passed, ${result.dryRunStats.failed} failed`);\n }\n }\n\n output.newline();\n\n if (result.success) {\n output.success('Validation passed');\n } else {\n output.error(`Validation failed with ${result.errors.length} error(s)`);\n }\n }\n\n process.exit(result.success ? 0 : 1);\n });\n\nprogram\n .command('dev')\n .description('Start development server with hot reload')\n .argument('[path]', 'Path to yamchart project', '.')\n .option('-p, --port <number>', 'Port to listen on', '3001')\n .option('--api-only', 'Only serve API, no web UI')\n .option('--no-open', 'Do not open browser automatically')\n .action(async (path: string, options: { port: string; apiOnly?: boolean; open: boolean }) => {\n // Parent process: supervise + re-spawn the server child on exit-75 (apply-config restart).\n // The child sets YAMCHART_DEV_CHILD=1 and runs the actual server below.\n if (process.env.YAMCHART_DEV_CHILD !== '1') {\n const { superviseDevServer } = await import('./commands/dev-supervisor.js');\n superviseDevServer(process.argv.slice(2));\n return;\n }\n // Supervised child — fall through to run the dev server.\n const startPath = resolve(path);\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n const globalOpts = program.opts();\n const { runDevServer } = await import('./commands/dev.js');\n\n await runDevServer(projectDir, {\n port: parseInt(options.port, 10),\n apiOnly: options.apiOnly ?? false,\n open: options.open,\n version: pkg.version,\n env: globalOpts.env,\n });\n });\n\nprogram\n .command('init')\n .description('Create a new yamchart project')\n .argument('[directory]', 'Target directory', '.')\n .option('--example', 'Create full example project with sample database')\n .option('--empty', 'Create only yamchart.yaml (no connections, models, or charts)')\n .option('--force', 'Overwrite existing files')\n .action(async (directory: string, options: { example?: boolean; empty?: boolean; force?: boolean }) => {\n const { initProject } = await import('./commands/init.js');\n const targetDir = resolve(directory);\n\n const result = await initProject(targetDir, options);\n\n if (!result.success) {\n output.error(result.error || 'Failed to create project');\n process.exit(1);\n }\n\n output.newline();\n output.success(`Created ${directory === '.' ? basename(targetDir) : directory}/`);\n for (const file of result.files.slice(0, 10)) {\n output.detail(file);\n }\n if (result.files.length > 10) {\n output.detail(`... and ${result.files.length - 10} more files`);\n }\n output.newline();\n output.info(`Run \\`cd ${directory === '.' ? basename(targetDir) : directory} && yamchart dev\\` to start.`);\n });\n\nprogram\n .command('sync-dbt')\n .description('Sync dbt project metadata into AI-readable catalog')\n .option('-s, --source <type>', 'Source type: local, github, dbt-cloud', 'local')\n .option('-p, --path <dir>', 'Path to dbt project (for local source)')\n .option('--repo <repo>', 'GitHub repository (for github source)')\n .option('--branch <branch>', 'Git branch (for github source)', 'main')\n .option('-i, --include <patterns...>', 'Include glob patterns')\n .option('-e, --exclude <patterns...>', 'Exclude glob patterns')\n .option('-t, --tag <tags...>', 'Filter by dbt tags')\n .option('--refresh', 'Re-sync using saved configuration')\n .option('--target-database <database>', 'Override database in ref() paths (e.g. switch from dev to prod)')\n .action(async (options: {\n source: 'local' | 'github' | 'dbt-cloud';\n path?: string;\n repo?: string;\n branch?: string;\n include?: string[];\n exclude?: string[];\n tag?: string[];\n refresh?: boolean;\n targetDatabase?: string;\n }) => {\n const { syncDbt, loadSyncConfig } = await import('./commands/sync-dbt.js');\n\n // Find project root\n const projectDir = await findProjectRoot(process.cwd());\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n // Handle refresh mode\n if (options.refresh) {\n const savedConfig = await loadSyncConfig(projectDir);\n if (!savedConfig) {\n output.error('No saved sync config found');\n output.detail('Run sync-dbt without --refresh first');\n process.exit(1);\n }\n output.info(`Re-syncing from ${savedConfig.source}:${savedConfig.path || savedConfig.repo}`);\n }\n\n const spin = output.spinner('Syncing dbt metadata...');\n\n const result = await syncDbt(projectDir, {\n source: options.source,\n path: options.path,\n repo: options.repo,\n branch: options.branch,\n include: options.include || [],\n exclude: options.exclude || [],\n tags: options.tag || [],\n refresh: options.refresh,\n targetDatabase: options.targetDatabase,\n });\n\n spin.stop();\n\n if (!result.success) {\n output.error(result.error || 'Sync failed');\n process.exit(1);\n }\n\n output.success(`Synced ${result.modelsIncluded} models to .yamchart/catalog.md`);\n if (result.modelsExcluded > 0) {\n output.detail(`${result.modelsExcluded} models filtered out`);\n }\n\n // Show lineage warnings\n if (result.warnings) {\n for (const w of result.warnings) {\n output.warning(w);\n }\n }\n\n // Check for database mismatch (skip if --target-database was used)\n if (!options.targetDatabase) {\n try {\n const { readFile } = await import('fs/promises');\n const { resolveConnection } = await import('./commands/connection-utils.js');\n const { detectDatabaseMismatch } = await import('./dbt/rewrite-database.js');\n const catalogJsonStr = await readFile(join(projectDir, '.yamchart', 'catalog.json'), 'utf-8');\n const catalogData = JSON.parse(catalogJsonStr);\n const connection = await resolveConnection(projectDir, undefined, program.opts().env);\n // Extract database from connection config (varies by type)\n const connDb = (connection as Record<string, any>).config?.database as string | undefined;\n const mismatch = detectDatabaseMismatch(catalogData.models, connDb);\n if (mismatch.mismatch) {\n output.warning(\n `Catalog tables reference database \"${mismatch.catalogDatabase}\" but your default ` +\n `connection uses \"${mismatch.connectionDatabase}\". Models using ref() may query the wrong database.`\n );\n output.detail(\n `To fix: yamchart sync-dbt --refresh --target-database ${mismatch.connectionDatabase}`\n );\n }\n } catch {\n // Connection not configured or unreadable — skip silently\n }\n }\n });\n\nprogram\n .command('generate')\n .description('Generate SQL model stubs from dbt catalog')\n .argument('[model]', 'Specific model to generate (optional)')\n .option('--yolo', 'Skip all prompts, use defaults for everything')\n .action(async (model: string | undefined, options: { yolo?: boolean }) => {\n const { generate } = await import('./commands/generate.js');\n\n const projectDir = await findProjectRoot(process.cwd());\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n const result = await generate(projectDir, {\n model,\n yolo: options.yolo,\n });\n\n if (!result.success) {\n output.error(result.error || 'Generate failed');\n process.exit(1);\n }\n\n output.success(`Generated ${result.filesCreated} model stubs`);\n if (result.filesSkipped > 0) {\n output.detail(`${result.filesSkipped} files skipped`);\n }\n });\n\nprogram\n .command('test')\n .description('Run model tests (@returns schema checks and @tests data assertions)')\n .argument('[model]', 'Specific model to test (optional, tests all if omitted)')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .action(async (model: string | undefined, options: { connection?: string; json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n if (options.json) {\n console.log(JSON.stringify({ success: false, error: 'yamchart.yaml not found' }));\n } else {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n }\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { testProject, formatTestOutput } = await import('./commands/test.js');\n const result = await testProject(projectDir, model, {\n connection: options.connection,\n json: options.json,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result, null, 2));\n } else {\n formatTestOutput(result, result.connectionName);\n }\n\n process.exit(result.success ? 0 : 1);\n } catch (err) {\n if (options.json) {\n console.log(\n JSON.stringify({ success: false, error: err instanceof Error ? err.message : String(err) }),\n );\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(2);\n }\n });\n\nprogram\n .command('update')\n .description('Check for yamchart updates')\n .action(async () => {\n const { runUpdate } = await import('./commands/update.js');\n await runUpdate(pkg.version);\n });\n\nprogram\n .command('reset-password')\n .description('Reset a user password (requires auth to be enabled)')\n .requiredOption('-e, --email <email>', 'Email address of the user')\n .action(async (options: { email: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n const { resetPassword } = await import('./commands/reset-password.js');\n await resetPassword(projectDir, options.email);\n });\n\nprogram\n .command('tables')\n .description('List tables and views in the connected database')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('-s, --schema <name>', 'Filter to schema')\n .option('-d, --database <name>', 'Filter to database (Snowflake/Databricks)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .option('--compare', 'Compare local metadata against live database')\n .action(async (options: { connection?: string; schema?: string; database?: string; json?: boolean; source?: string; compare?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n if (options.compare) {\n const { resolveTablesSource } = await import('./commands/source-resolver.js');\n const { compareTables, formatCompareTables } = await import('./commands/compare.js');\n\n let localResult;\n try {\n localResult = await resolveTablesSource(projectDir, 'catalog', options.connection, {\n schema: options.schema,\n database: options.database,\n });\n } catch {\n try {\n localResult = await resolveTablesSource(projectDir, 'model', options.connection, {\n schema: options.schema,\n database: options.database,\n });\n } catch {\n output.error('Cannot compare — no local metadata found. Run `yamchart sync-dbt` or `yamchart sync-warehouse` first.');\n process.exit(1);\n }\n }\n\n const dbResult = await resolveTablesSource(projectDir, 'db', options.connection, {\n schema: options.schema,\n database: options.database,\n });\n const diffs = compareTables(localResult.tables, dbResult.tables);\n\n if (options.json) {\n console.log(JSON.stringify(diffs, null, 2));\n } else {\n console.log(formatCompareTables(localResult.source, diffs));\n }\n return;\n }\n\n const { listTables } = await import('./commands/tables.js');\n const result = await listTables(projectDir, {\n ...options,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.tables, null, 2));\n } else {\n const sourceLabel = result.source === 'db'\n ? `${result.connectionName} (${result.connectionType})`\n : `Source: ${result.source}`;\n output.header(`Tables in ${sourceLabel}`);\n if (result.tables.length === 0) {\n output.info('No tables found');\n } else {\n for (const table of result.tables) {\n const schema = table.schema ? `${table.schema}.` : '';\n const typeLabel = table.type === 'VIEW' ? pc.dim(' (view)') : '';\n console.log(` ${schema}${table.name}${typeLabel}`);\n }\n output.newline();\n output.info(`${result.tables.length} table(s) found${result.durationMs > 0 ? ` (${result.durationMs.toFixed(0)}ms)` : ''}`);\n }\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('describe')\n .description('Show columns and types for a table')\n .argument('<table>', 'Table name (can be fully qualified, e.g. schema.table)')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .option('--compare', 'Compare local metadata against live database')\n .action(async (table: string, options: { connection?: string; json?: boolean; source?: string; compare?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n if (options.compare) {\n const { resolveDescribeSource } = await import('./commands/source-resolver.js');\n const { compareColumns, formatCompareColumns } = await import('./commands/compare.js');\n\n let localResult;\n try {\n localResult = await resolveDescribeSource(projectDir, table, 'catalog', options.connection);\n } catch {\n try {\n localResult = await resolveDescribeSource(projectDir, table, 'model', options.connection);\n } catch {\n output.error('Cannot compare — no local metadata found. Run `yamchart sync-dbt` or `yamchart sync-warehouse` first.');\n process.exit(1);\n }\n }\n\n const dbResult = await resolveDescribeSource(projectDir, table, 'db', options.connection);\n const diffs = compareColumns(localResult.columns, dbResult.columns);\n\n if (options.json) {\n console.log(JSON.stringify(diffs, null, 2));\n } else {\n console.log(formatCompareColumns(localResult.table, localResult.source, diffs));\n }\n return;\n }\n\n const { describeTable } = await import('./commands/describe.js');\n const result = await describeTable(projectDir, table, {\n ...options,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.columns, null, 2));\n } else {\n if (result.resolvedFrom) {\n output.detail(`Resolved \"${result.resolvedFrom}\" → ${result.table}`);\n }\n const sourceLabel = result.source === 'db'\n ? `${result.connectionName} (${result.connectionType})`\n : `Source: ${result.source}`;\n output.header(`${result.table} (${sourceLabel})`);\n\n const nameWidth = Math.max(4, ...result.columns.map((c) => c.name.length));\n const typeWidth = Math.max(4, ...result.columns.map((c) => c.type.length));\n\n console.log(` ${'name'.padEnd(nameWidth)} ${'type'.padEnd(typeWidth)} nullable`);\n console.log(` ${'─'.repeat(nameWidth)} ${'─'.repeat(typeWidth)} ${'─'.repeat(8)}`);\n\n for (const col of result.columns) {\n const nullable = col.nullable === 'YES' ? pc.dim('yes') : 'no';\n console.log(` ${col.name.padEnd(nameWidth)} ${pc.dim(col.type.padEnd(typeWidth))} ${nullable}`);\n }\n\n output.newline();\n output.info(`${result.columns.length} column(s)${result.durationMs > 0 ? ` (${result.durationMs.toFixed(0)}ms)` : ''}`);\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('query')\n .description('Execute SQL against a connection')\n .argument('<sql>', 'SQL query to execute')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .option('-l, --limit <number>', 'Max rows to return (default: 100)')\n .action(async (sql: string, options: { connection?: string; json?: boolean; limit?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { executeQuery } = await import('./commands/query.js');\n const { formatTable, formatJSON } = await import('./commands/connection-utils.js');\n\n const limit = options.limit ? parseInt(options.limit, 10) : undefined;\n const result = await executeQuery(projectDir, sql, {\n connection: options.connection,\n json: options.json,\n limit,\n });\n\n if (options.json) {\n console.log(formatJSON(result));\n } else {\n console.log(formatTable(result));\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('sample')\n .description('Show sample rows from a table or dbt model')\n .argument('<table>', 'Table name or dbt model name')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('-l, --limit <number>', 'Rows to show (default: 5)')\n .option('--json', 'Output as JSON')\n .action(async (table: string, options: { connection?: string; json?: boolean; limit?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { sampleTable } = await import('./commands/sample.js');\n const { formatTable, formatJSON } = await import('./commands/connection-utils.js');\n\n const limit = options.limit ? parseInt(options.limit, 10) : undefined;\n const result = await sampleTable(projectDir, table, {\n connection: options.connection,\n json: options.json,\n limit,\n });\n\n if (options.json) {\n console.log(formatJSON(result));\n } else {\n if (result.resolvedFrom) {\n output.detail(`Resolved \"${result.resolvedFrom}\" → ${result.table}`);\n }\n console.log(formatTable(result));\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('search')\n .description('Search for tables and columns by keyword')\n .argument('<keyword>', 'Keyword to search for')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .action(async (keyword: string, options: { connection?: string; json?: boolean; source?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { searchDatabase } = await import('./commands/search.js');\n const result = await searchDatabase(projectDir, keyword, {\n ...options,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.results, null, 2));\n } else {\n const sourceLabel = result.source === 'db'\n ? `${result.connectionName} (${result.connectionType})`\n : `Source: ${result.source}`;\n output.header(`Search results for \"${result.keyword}\" in ${sourceLabel}`);\n\n const tables = result.results.filter((r) => r.type === 'table');\n const columns = result.results.filter((r) => r.type === 'column');\n\n if (tables.length > 0) {\n output.newline();\n console.log(' Tables:');\n for (const t of tables) {\n const qualified = t.schema ? `${t.schema}.${t.table}` : t.table;\n console.log(` ${qualified}`);\n }\n }\n\n if (columns.length > 0) {\n output.newline();\n console.log(' Columns:');\n const nameWidth = Math.max(...columns.map((c) => {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n return qualified.length;\n }));\n for (const c of columns) {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n const colType = c.columnType ? pc.dim(c.columnType) : '';\n console.log(` ${qualified.padEnd(nameWidth + 2)}${colType}`);\n }\n }\n\n if (result.results.length === 0) {\n output.detail('No matches found');\n }\n\n output.newline();\n output.info(`${result.results.length} result(s)${result.durationMs > 0 ? ` (${result.durationMs.toFixed(0)}ms)` : ''}`);\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nconst catalogCmd = program\n .command('catalog')\n .description('Explore cached local metadata (no database connection needed)');\n\ncatalogCmd\n .command('tables')\n .description('List tables from cached catalog')\n .option('-s, --schema <name>', 'Filter to schema')\n .option('--json', 'Output as JSON')\n .action(async (options: { schema?: string; json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { listTables } = await import('./commands/tables.js');\n const result = await listTables(projectDir, {\n source: 'catalog',\n schema: options.schema,\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.tables, null, 2));\n } else {\n output.header('Tables (from catalog)');\n if (result.tables.length === 0) {\n output.info('No tables found in catalog');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else {\n const filtered = options.schema\n ? result.tables.filter((t) => t.schema.toLowerCase().includes(options.schema!.toLowerCase()))\n : result.tables;\n for (const table of filtered) {\n const schema = table.schema ? `${table.schema}.` : '';\n const typeLabel = table.type === 'VIEW' ? pc.dim(' (view)') : table.type === 'SOURCE' ? pc.dim(' (source)') : '';\n console.log(` ${schema}${table.name}${typeLabel}`);\n }\n output.newline();\n output.info(`${filtered.length} table(s) from catalog`);\n }\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('No catalog found')) {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\ncatalogCmd\n .command('describe')\n .description('Show cached columns and types for a table')\n .argument('<table>', 'Table name or model name')\n .option('--json', 'Output as JSON')\n .action(async (table: string, options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { describeTable } = await import('./commands/describe.js');\n const result = await describeTable(projectDir, table, { source: 'catalog' });\n\n if (options.json) {\n console.log(JSON.stringify(result.columns, null, 2));\n } else {\n if (result.resolvedFrom) {\n output.detail(`Resolved \"${result.resolvedFrom}\" → ${result.table}`);\n }\n output.header(`${result.table} (from catalog)`);\n\n const nameWidth = Math.max(4, ...result.columns.map((c) => c.name.length));\n const typeWidth = Math.max(4, ...result.columns.map((c) => c.type.length));\n\n console.log(` ${'name'.padEnd(nameWidth)} ${'type'.padEnd(typeWidth)} nullable`);\n console.log(` ${'─'.repeat(nameWidth)} ${'─'.repeat(typeWidth)} ${'─'.repeat(8)}`);\n\n for (const col of result.columns) {\n const nullable = col.nullable === 'YES' ? pc.dim('yes') : 'no';\n console.log(` ${col.name.padEnd(nameWidth)} ${pc.dim(col.type.padEnd(typeWidth))} ${nullable}`);\n }\n\n output.newline();\n output.info(`${result.columns.length} column(s)`);\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('No catalog found')) {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else if (err instanceof Error && err.message.includes('not found in catalog')) {\n output.error(err.message);\n output.detail('Try `yamchart catalog search` to find available tables');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\ncatalogCmd\n .command('search')\n .description('Search cached metadata for tables and columns')\n .argument('<keyword>', 'Keyword to search for')\n .option('--json', 'Output as JSON')\n .action(async (keyword: string, options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { searchDatabase } = await import('./commands/search.js');\n const result = await searchDatabase(projectDir, keyword, { source: 'catalog' });\n\n if (options.json) {\n console.log(JSON.stringify(result.results, null, 2));\n } else {\n output.header(`Search results for \"${keyword}\" (from catalog)`);\n\n const tables = result.results.filter((r) => r.type === 'table');\n const columns = result.results.filter((r) => r.type === 'column');\n\n if (tables.length > 0) {\n output.newline();\n console.log(' Tables:');\n for (const t of tables) {\n const qualified = t.schema ? `${t.schema}.${t.table}` : t.table;\n console.log(` ${qualified}`);\n }\n }\n\n if (columns.length > 0) {\n output.newline();\n console.log(' Columns:');\n const nameWidth = Math.max(...columns.map((c) => {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n return qualified.length;\n }));\n for (const c of columns) {\n const qualified = c.schema ? `${c.schema}.${c.table}.${c.column}` : `${c.table}.${c.column}`;\n const colType = c.columnType ? pc.dim(c.columnType) : '';\n console.log(` ${qualified.padEnd(nameWidth + 2)}${colType}`);\n }\n }\n\n if (result.results.length === 0) {\n output.detail('No matches found in catalog');\n output.detail('Try `yamchart search <keyword>` to search the live database');\n }\n\n output.newline();\n output.info(`${result.results.length} result(s) from catalog`);\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('No catalog found')) {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\ncatalogCmd\n .command('status')\n .description('Show catalog sync status')\n .option('--json', 'Output as JSON')\n .action(async (options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const catalogPath = join(projectDir, '.yamchart', 'catalog.json');\n\n let catalogData: { syncedAt?: string; source?: { type: string }; models?: Array<{ source?: string; columns?: unknown[] }> };\n try {\n catalogData = JSON.parse(await readFile(catalogPath, 'utf-8'));\n } catch {\n if (options.json) {\n console.log(JSON.stringify({ exists: false }));\n } else {\n output.error('No catalog found');\n output.detail('Run `yamchart sync-warehouse` or `yamchart sync-dbt` to populate');\n }\n process.exit(1);\n return;\n }\n\n const models = catalogData.models || [];\n const dbtModels = models.filter((m) => m.source === 'dbt');\n const warehouseModels = models.filter((m) => m.source === 'warehouse');\n const sourceModels = models.filter((m) => m.source === 'dbt-source');\n const totalColumns = models.reduce((sum, m) => sum + (m.columns?.length || 0), 0);\n\n // Try to load warehouse sync state\n let syncState: { syncedAt?: string; connection?: string; schemas?: string[] } | null = null;\n try {\n const syncPath = join(projectDir, '.yamchart', 'warehouse-sync.json');\n syncState = JSON.parse(await readFile(syncPath, 'utf-8'));\n } catch {\n // No sync state\n }\n\n if (options.json) {\n console.log(JSON.stringify({\n exists: true,\n syncedAt: catalogData.syncedAt,\n source: catalogData.source,\n models: models.length,\n dbtModels: dbtModels.length,\n warehouseModels: warehouseModels.length,\n sourceModels: sourceModels.length,\n totalColumns,\n warehouseSync: syncState ? {\n syncedAt: syncState.syncedAt,\n connection: syncState.connection,\n schemas: syncState.schemas,\n } : null,\n }, null, 2));\n } else {\n output.header('Catalog Status');\n console.log(` Last synced: ${catalogData.syncedAt || 'unknown'}`);\n console.log(` Models: ${models.length} total (${dbtModels.length} dbt, ${warehouseModels.length} warehouse, ${sourceModels.length} sources)`);\n console.log(` Columns: ${totalColumns}`);\n\n if (syncState) {\n output.newline();\n console.log(` Warehouse sync:`);\n console.log(` Connection: ${syncState.connection || 'default'}`);\n console.log(` Schemas: ${syncState.schemas?.join(', ') || 'all'}`);\n console.log(` Last sync: ${syncState.syncedAt || 'unknown'}`);\n }\n }\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('sync-warehouse')\n .description('Sync warehouse table metadata into the catalog')\n .option('-c, --connection <name>', 'Connection to use (overrides default)')\n .option('-s, --schema <schemas>', 'Comma-separated schemas to sync')\n .option('-d, --database <name>', 'Database to sync (Snowflake/Databricks)')\n .option('--skip-samples', 'Skip sample row collection')\n .option('--refresh', 'Re-run with saved connection/schema config')\n .option('--full', 'Force full re-sync (ignore incremental state)')\n .option('--json', 'Output sync summary as JSON')\n .action(async (options) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { runSyncWarehouse } = await import('./commands/sync-warehouse.js');\n await runSyncWarehouse(projectDir, options);\n } catch (err) {\n output.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n });\n\nprogram\n .command('lineage')\n .description('Show upstream dependencies for a model')\n .argument('<model>', 'Model name to trace lineage for')\n .option('--depth <n>', 'Maximum depth to trace (default: unlimited)')\n .option('--json', 'Output as JSON')\n .option('--source <type>', 'Data source: auto, catalog, model, or db (default: auto)')\n .action(async (model: string, options: { depth?: string; json?: boolean; source?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { getLineage } = await import('./commands/lineage.js');\n const depth = options.depth ? parseInt(options.depth, 10) : undefined;\n const result = await getLineage(projectDir, model, {\n depth,\n json: options.json,\n source: (options.source as any) || 'auto',\n });\n\n if (options.json) {\n console.log(JSON.stringify(result.tree, null, 2));\n } else {\n console.log(result.rendered);\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('ENOENT')) {\n output.error('No catalog found. Run `yamchart sync-dbt` first.');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\nprogram\n .command('advisor')\n .description('AI-powered dbt model advisor — suggests improvements informed by your BI layer')\n .argument('[question]', 'Question to ask, or \"audit\" for comprehensive analysis')\n .option('--top <n>', 'Limit audit suggestions (default: 5)')\n .option('--json', 'Output as JSON')\n .option('--dbt-path <path>', 'Override the synced dbt project path')\n .option('-c, --connection <name>', 'Connection to use for warehouse introspection')\n .action(async (question: string | undefined, options: { top?: string; json?: boolean; dbtPath?: string; connection?: string }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n if (options.json) {\n console.log(JSON.stringify({ success: false, error: 'yamchart.yaml not found' }));\n } else {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n }\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n const { runAdvisor } = await import('./commands/advisor.js');\n await runAdvisor(projectDir, question, {\n top: options.top ? parseInt(options.top, 10) : 5,\n json: options.json,\n dbtPath: options.dbtPath,\n connection: options.connection,\n });\n });\n\nconst semanticCmd = program\n .command('semantic')\n .description('Explore the semantic layer — curated semantic/*.yaml definitions or auto-generated from catalog')\n .option('--json', 'Output as JSON')\n .action(async (options: { json?: boolean }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n output.detail('Run this command from a yamchart project directory');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { loadSemanticDefinitions } = await import('@yamchart/query/semantic');\n const { listSemanticDefinitions, listSemanticEntities } = await import('./commands/semantic.js');\n\n // Prefer curated semantic/*.yaml definitions; fall back to catalog-derived entities\n const defs = loadSemanticDefinitions(projectDir);\n let result;\n let source: 'curated' | 'catalog';\n\n if (defs.length > 0) {\n result = listSemanticDefinitions(defs);\n source = 'curated';\n } else {\n const { readFile } = await import('fs/promises');\n const catalogPath = join(projectDir, '.yamchart', 'catalog.json');\n const catalogJson = JSON.parse(await readFile(catalogPath, 'utf-8'));\n result = listSemanticEntities(catalogJson);\n source = 'catalog';\n }\n\n if (options.json) {\n console.log(JSON.stringify(result.entities, null, 2));\n return;\n }\n\n if (result.entities.length === 0) {\n output.info('No semantic entities found.');\n output.detail('Add YAML files to semantic/ or run `yamchart sync-dbt` / `yamchart sync-warehouse` to populate the catalog.');\n return;\n }\n\n output.header(`Semantic Layer — ${result.entities.length} entities (${source === 'curated' ? 'semantic/*.yaml' : 'catalog'})`);\n\n for (const entity of result.entities) {\n console.log(` ${pc.bold(entity.name)}`);\n console.log(` ${pc.dim(entity.source_table)}`);\n if (entity.description) {\n console.log(` ${entity.description}`);\n }\n if (entity.measures.length > 0) {\n console.log(` Measures: ${entity.measures.map((m) => `${m.name} (${pc.dim(m.type)})`).join(', ')}`);\n }\n if (entity.dimensions.length > 0) {\n console.log(` Dimensions: ${entity.dimensions.map((d) => `${d.name} (${pc.dim(d.type)})`).join(', ')}`);\n }\n console.log();\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('ENOENT')) {\n output.error('No catalog found. Add semantic/*.yaml files or run `yamchart sync-dbt` / `yamchart sync-warehouse` first.');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\nsemanticCmd\n .command('query')\n .description('Run a structured query against the semantic layer')\n .requiredOption('-e, --entity <name>', 'Entity name (e.g. fct_revenue)')\n .requiredOption('-m, --measures <measures>', 'Comma-separated measure names')\n .option('-d, --dimensions <dimensions>', 'Comma-separated dimension names')\n .option('-f, --filter <filter...>', 'Filters in format dimension=value')\n .option('--order <field>', 'Order by field')\n .option('--desc', 'Order descending (default: ascending)')\n .option('-l, --limit <n>', 'Row limit (default: 100)')\n .option('-c, --connection <name>', 'Connection to use')\n .option('--json', 'Output as JSON')\n .option('--sql', 'Print compiled SQL only (do not execute)')\n .action(async (options: {\n entity: string;\n measures: string;\n dimensions?: string;\n filter?: string[];\n order?: string;\n desc?: boolean;\n limit?: string;\n connection?: string;\n json?: boolean;\n sql?: boolean;\n }) => {\n const startPath = resolve('.');\n const projectDir = await findProjectRoot(startPath);\n\n if (!projectDir) {\n output.error('yamchart.yaml not found');\n process.exit(2);\n }\n\n loadEnvFile(projectDir);\n\n try {\n const { loadSemanticDefinitions } = await import('@yamchart/query/semantic');\n const { querySemanticDefinition, querySemanticEntity } = await import('./commands/semantic.js');\n\n // Parse filters: \"region=US\" → { dimension: 'region', operator: 'equals', value: 'US' }\n const filters = (options.filter || []).map((f) => {\n const eqIdx = f.indexOf('=');\n if (eqIdx === -1) throw new Error(`Invalid filter format: \"${f}\". Use dimension=value`);\n return {\n dimension: f.slice(0, eqIdx),\n operator: 'equals' as const,\n value: f.slice(eqIdx + 1),\n };\n });\n\n const queryInput = {\n entity: options.entity,\n measures: options.measures.split(',').map((s) => s.trim()),\n dimensions: options.dimensions ? options.dimensions.split(',').map((s) => s.trim()) : [],\n filters,\n order_by: options.order ? { field: options.order, direction: options.desc ? 'desc' : 'asc' } : undefined,\n limit: options.limit ? parseInt(options.limit, 10) : 100,\n };\n\n // Prefer curated semantic/*.yaml definitions; fall back to catalog-derived entities\n const defs = loadSemanticDefinitions(projectDir);\n let result;\n\n if (defs.length > 0) {\n result = querySemanticDefinition(defs, queryInput);\n } else {\n const { readFile } = await import('fs/promises');\n const catalogPath = join(projectDir, '.yamchart', 'catalog.json');\n const catalogJson = JSON.parse(await readFile(catalogPath, 'utf-8'));\n result = querySemanticEntity(catalogJson, queryInput);\n }\n\n // --sql: just print the SQL\n if (options.sql) {\n console.log(result.sql);\n return;\n }\n\n // Execute the query\n const { resolveConnection, createConnector, formatTable, formatJSON } = await import('./commands/connection-utils.js');\n const connection = await resolveConnection(projectDir, options.connection, program.opts().env);\n const connector = createConnector(connection, projectDir);\n\n const start = performance.now();\n await connector.connect();\n const queryResult = await connector.execute(result.sql);\n await connector.disconnect();\n const durationMs = Math.round((performance.now() - start) * 100) / 100;\n\n if (options.json) {\n console.log(formatJSON({\n columns: queryResult.columns,\n rows: queryResult.rows,\n rowCount: queryResult.rows.length,\n durationMs,\n }));\n } else {\n output.detail(`Entity: ${result.entityName}`);\n output.detail(`SQL: ${result.sql.replace(/\\n/g, ' ').slice(0, 120)}...`);\n output.newline();\n console.log(formatTable({\n columns: queryResult.columns,\n rows: queryResult.rows,\n rowCount: queryResult.rows.length,\n durationMs,\n }));\n }\n } catch (err) {\n if (err instanceof Error && err.message.includes('ENOENT')) {\n output.error('No catalog found. Add semantic/*.yaml files or run `yamchart sync-dbt` / `yamchart sync-warehouse` first.');\n } else {\n output.error(err instanceof Error ? err.message : String(err));\n }\n process.exit(1);\n }\n });\n\nprogram.parse();\n\n// Passive update check — runs in background, prints on exit if outdated\nlet updateNotification: string | null = null;\n\ncheckForUpdate(pkg.version).then((update) => {\n if (update) {\n updateNotification = `\\n Update available: ${update.current} → ${update.latest}\\n Run: yamchart update to see what's new\\n`;\n }\n});\n\nprocess.on('exit', () => {\n if (updateNotification) {\n // Use dim styling so it doesn't compete with command output\n console.error(`\\n${pc.dim(updateNotification)}`);\n }\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;A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AY;AAAA,QACrB,MAAM,YAAY;AAAA,QAClB,UAAU,YAAY,KAAK;AAAA,QAC3B;AAAA,MACF,CAAC,CAAC;AAAA,IACJ,OAAO;AACL,MAAO,OAAO,WAAW,OAAO,UAAU,EAAE;AAC5C,MAAO,OAAO,QAAQ,OAAO,IAAI,QAAQ,OAAO,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC,KAAK;AACvE,MAAO,QAAQ;AACf,cAAQ,IAAI,YAAY;AAAA,QACtB,SAAS,YAAY;AAAA,QACrB,MAAM,YAAY;AAAA,QAClB,UAAU,YAAY,KAAK;AAAA,QAC3B;AAAA,MACF,CAAC,CAAC;AAAA,IACJ;AAAA,EACF,SAAS,KAAK;AACZ,QAAI,eAAe,SAAS,IAAI,QAAQ,SAAS,QAAQ,GAAG;AAC1D,MAAO,MAAM,2GAA2G;AAAA,IAC1H,OAAO;AACL,MAAO,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAC/D;AACA,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF,CAAC;AAEH,QAAQ,MAAM;AAGd,IAAI,qBAAoC;AAExC,eAAe,IAAI,OAAO,EAAE,KAAK,CAAC,WAAW;AAC3C,MAAI,QAAQ;AACV,yBAAqB;AAAA,sBAAyB,OAAO,OAAO,WAAM,OAAO,MAAM;AAAA;AAAA;AAAA,EACjF;AACF,CAAC;AAED,QAAQ,GAAG,QAAQ,MAAM;AACvB,MAAI,oBAAoB;AAEtB,YAAQ,MAAM;AAAA,EAAK,GAAG,IAAI,kBAAkB,CAAC,EAAE;AAAA,EACjD;AACF,CAAC;","names":["error","warning"]}
@@ -72,14 +72,33 @@ async function initProject(projectDir, options) {
72
72
  };
73
73
  }
74
74
  const gitignorePath = join(projectDir, ".gitignore");
75
- const gitignoreEntry = "yamchart.local.yaml";
75
+ const gitignoreEntries = [
76
+ "yamchart.local.yaml",
77
+ "",
78
+ "# Runtime config layer (UI-edited; secrets encrypted) \u2014 never commit",
79
+ ".yamchart/runtime-config.json",
80
+ ".yamchart/.config-secret",
81
+ "runtime-config.json",
82
+ ".config-secret"
83
+ ];
76
84
  try {
77
85
  const existing = await readFile(gitignorePath, "utf-8");
78
- if (!existing.includes("yamchart.local.yaml")) {
79
- await writeFile(gitignorePath, existing.trimEnd() + "\n" + gitignoreEntry + "\n", "utf-8");
86
+ const existingLines = existing.split("\n").map((l) => l.trim());
87
+ const missing = gitignoreEntries.filter(
88
+ (entry) => entry === "" || !existingLines.includes(entry)
89
+ );
90
+ const toAppend = missing.filter(
91
+ (entry, i) => !(entry === "" && (i === 0 || missing[i - 1] === ""))
92
+ );
93
+ if (toAppend.some((entry) => entry !== "")) {
94
+ await writeFile(
95
+ gitignorePath,
96
+ existing.trimEnd() + "\n" + toAppend.join("\n").trimEnd() + "\n",
97
+ "utf-8"
98
+ );
80
99
  }
81
100
  } catch {
82
- await writeFile(gitignorePath, gitignoreEntry + "\n", "utf-8");
101
+ await writeFile(gitignorePath, gitignoreEntries.join("\n").trimStart() + "\n", "utf-8");
83
102
  }
84
103
  if (!files.includes(".gitignore")) {
85
104
  files.push(".gitignore");
@@ -132,4 +151,4 @@ async function copyDirectory(srcDir, destDir, files, projectName, basePath = "")
132
151
  export {
133
152
  initProject
134
153
  };
135
- //# sourceMappingURL=init-SECXKD5G.js.map
154
+ //# sourceMappingURL=init-TJJVKMEN.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/init.ts"],"sourcesContent":["import { mkdir, readFile, writeFile, access, readdir, copyFile } from 'fs/promises';\nimport { join, dirname, basename } from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nexport interface InitOptions {\n empty?: boolean;\n example?: boolean;\n force?: boolean;\n}\n\nexport interface InitResult {\n success: boolean;\n files: string[];\n error?: string;\n}\n\n/**\n * Check if a directory exists and is accessible.\n */\nasync function directoryExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get the templates directory path.\n * Handles both development (src/commands) and production (dist/) contexts.\n */\nasync function getTemplatesDir(): Promise<string> {\n // In production (dist/), templates are at dist/templates\n const distTemplates = join(__dirname, 'templates');\n if (await directoryExists(distTemplates)) {\n return distTemplates;\n }\n\n // In development (src/commands), templates are at src/templates\n const srcTemplates = join(__dirname, '../templates');\n if (await directoryExists(srcTemplates)) {\n return srcTemplates;\n }\n\n throw new Error('Templates not found. Reinstall yamchart or check installation.');\n}\n\n/**\n * Get the examples directory path.\n * Handles both development and production contexts.\n */\nasync function getExamplesDir(): Promise<string> {\n // In production (dist/): dist -> cli -> apps -> yamchart -> examples\n const distExamples = join(__dirname, '../../../examples');\n if (await directoryExists(distExamples)) {\n return distExamples;\n }\n\n // In development (src/commands): src/commands -> src -> cli -> apps -> yamchart -> examples\n const srcExamples = join(__dirname, '../../../../examples');\n if (await directoryExists(srcExamples)) {\n return srcExamples;\n }\n\n throw new Error('Example assets not found. Reinstall yamchart or use default mode.');\n}\n\nexport async function initProject(projectDir: string, options: InitOptions): Promise<InitResult> {\n const projectName = basename(projectDir);\n const files: string[] = [];\n\n // Check if yamchart.yaml already exists\n const yamchartYamlPath = join(projectDir, 'yamchart.yaml');\n try {\n await access(yamchartYamlPath);\n if (!options.force) {\n return {\n success: false,\n files: [],\n error: `${yamchartYamlPath} already exists. Use --force to overwrite.`,\n };\n }\n } catch {\n // File doesn't exist, continue\n }\n\n // Create project directory and assets dir\n await mkdir(projectDir, { recursive: true });\n await mkdir(join(projectDir, 'assets'), { recursive: true });\n\n try {\n if (options.example) {\n // Copy example project\n const examplesDir = await getExamplesDir();\n await copyDirectory(examplesDir, projectDir, files, projectName);\n } else if (options.empty) {\n // Empty mode - only yamchart.yaml\n const templateDir = join(await getTemplatesDir(), 'empty');\n await copyTemplate(templateDir, projectDir, files, projectName);\n } else {\n // Default mode - minimal working project\n const templateDir = join(await getTemplatesDir(), 'default');\n await copyTemplate(templateDir, projectDir, files, projectName);\n }\n } catch (err) {\n return {\n success: false,\n files: [],\n error: err instanceof Error ? err.message : 'Failed to create project',\n };\n }\n\n // Ensure local overrides and runtime config secrets are gitignored\n const gitignorePath = join(projectDir, '.gitignore');\n const gitignoreEntries = [\n 'yamchart.local.yaml',\n '',\n '# Runtime config layer (UI-edited; secrets encrypted) — never commit',\n '.yamchart/runtime-config.json',\n '.yamchart/.config-secret',\n 'runtime-config.json',\n '.config-secret',\n ];\n try {\n const existing = await readFile(gitignorePath, 'utf-8');\n const existingLines = existing.split('\\n').map((l) => l.trim());\n const missing = gitignoreEntries.filter(\n (entry) => entry === '' || !existingLines.includes(entry)\n );\n // Drop a leading blank line if nothing meaningful precedes it\n const toAppend = missing.filter(\n (entry, i) => !(entry === '' && (i === 0 || missing[i - 1] === ''))\n );\n if (toAppend.some((entry) => entry !== '')) {\n await writeFile(\n gitignorePath,\n existing.trimEnd() + '\\n' + toAppend.join('\\n').trimEnd() + '\\n',\n 'utf-8'\n );\n }\n } catch {\n // No .gitignore exists, create one\n await writeFile(gitignorePath, gitignoreEntries.join('\\n').trimStart() + '\\n', 'utf-8');\n }\n if (!files.includes('.gitignore')) {\n files.push('.gitignore');\n }\n\n return { success: true, files };\n}\n\nasync function copyTemplate(\n templateDir: string,\n targetDir: string,\n files: string[],\n projectName: string,\n basePath: string = ''\n): Promise<void> {\n const entries = await readdir(templateDir, { withFileTypes: true });\n\n for (const entry of entries) {\n const srcPath = join(templateDir, entry.name);\n const destPath = join(targetDir, entry.name);\n const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name;\n\n if (entry.isDirectory()) {\n await mkdir(destPath, { recursive: true });\n await copyTemplate(srcPath, destPath, files, projectName, relativePath);\n } else {\n let content = await readFile(srcPath, 'utf-8');\n content = content.replace(/\\{\\{name\\}\\}/g, projectName);\n await writeFile(destPath, content, 'utf-8');\n files.push(relativePath);\n }\n }\n}\n\nasync function copyDirectory(\n srcDir: string,\n destDir: string,\n files: string[],\n projectName: string,\n basePath: string = ''\n): Promise<void> {\n const entries = await readdir(srcDir, { withFileTypes: true });\n\n for (const entry of entries) {\n // Skip node_modules, lock files, and hidden files (except .claude)\n if (\n entry.name === 'node_modules' ||\n entry.name === 'pnpm-lock.yaml' ||\n entry.name === 'package-lock.json' ||\n entry.name === 'yarn.lock' ||\n entry.name === 'package.json' ||\n (entry.name.startsWith('.') && entry.name !== '.claude')\n ) {\n continue;\n }\n\n const srcPath = join(srcDir, entry.name);\n const destPath = join(destDir, entry.name);\n const relativePath = basePath ? `${basePath}/${entry.name}` : entry.name;\n\n if (entry.isDirectory()) {\n await mkdir(destPath, { recursive: true });\n await copyDirectory(srcPath, destPath, files, projectName, relativePath);\n } else {\n // For binary files (like .duckdb), copy directly\n if (entry.name.endsWith('.duckdb')) {\n await copyFile(srcPath, destPath);\n } else {\n // For text files, replace project name in yamchart.yaml\n let content = await readFile(srcPath, 'utf-8');\n if (entry.name === 'yamchart.yaml') {\n content = content.replace(/^name:\\s*\\S+/m, `name: ${projectName}`);\n }\n await writeFile(destPath, content, 'utf-8');\n }\n files.push(relativePath);\n }\n }\n}\n"],"mappings":";;;AAAA,SAAS,OAAO,UAAU,WAAW,QAAQ,SAAS,gBAAgB;AACtE,SAAS,MAAM,SAAS,gBAAgB;AACxC,SAAS,qBAAqB;AAE9B,IAAM,YAAY,QAAQ,cAAc,YAAY,GAAG,CAAC;AAiBxD,eAAe,gBAAgB,MAAgC;AAC7D,MAAI;AACF,UAAM,OAAO,IAAI;AACjB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,eAAe,kBAAmC;AAEhD,QAAM,gBAAgB,KAAK,WAAW,WAAW;AACjD,MAAI,MAAM,gBAAgB,aAAa,GAAG;AACxC,WAAO;AAAA,EACT;AAGA,QAAM,eAAe,KAAK,WAAW,cAAc;AACnD,MAAI,MAAM,gBAAgB,YAAY,GAAG;AACvC,WAAO;AAAA,EACT;AAEA,QAAM,IAAI,MAAM,gEAAgE;AAClF;AAMA,eAAe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j as e,v as J,u as M,U as V,w as P,A as Z,V as Q,f as L,a as ee}from"./index-iR9gLdl9.js";import{a as b}from"./echarts-DtOYsfLX.js";import{l as G}from"./data-3vtzSuAZ.js";async function Y(){return N("/admin/config")}const oe=o=>N("/admin/connections/test",{method:"POST",body:JSON.stringify(o)}),te=(o,t)=>N(t?`/admin/connections/${encodeURIComponent(o.name)}`:"/admin/connections",{method:t?"PUT":"POST",body:JSON.stringify(o)}),se=o=>N(`/admin/connections/${encodeURIComponent(o)}`,{method:"DELETE"}),re=o=>N("/admin/knowledge-db/test",{method:"POST",body:JSON.stringify({url:o})}),ne=o=>N("/admin/knowledge-db",{method:"PUT",body:JSON.stringify({url:o})}),ae=o=>N("/admin/knowledge-db/migrate",{method:"POST",body:JSON.stringify({url:o})}),ce=()=>N("/admin/knowledge-db/reembed",{method:"POST",body:JSON.stringify({})}),le=o=>N("/admin/ai",{method:"PUT",body:JSON.stringify(o)}),ie=(o,t)=>N("/admin/ai/test",{method:"POST",body:JSON.stringify({provider:o,kind:t})}),de=["postgres","mysql","bigquery","snowflake","duckdb","sqlite"],E={postgres:[{key:"config.host",label:"Host"},{key:"config.port",label:"Port",numeric:!0},{key:"config.database",label:"Database"},{key:"config.schema",label:"Schema"},{key:"secrets.user",label:"User"},{key:"secrets.password",label:"Password",secret:!0}],mysql:[{key:"config.host",label:"Host"},{key:"config.port",label:"Port",numeric:!0},{key:"config.database",label:"Database"},{key:"secrets.user",label:"User"},{key:"secrets.password",label:"Password",secret:!0}],bigquery:[{key:"config.project_id",label:"Project ID"},{key:"config.dataset",label:"Dataset"},{key:"config.location",label:"Location"},{key:"secrets.credentials_json",label:"Service Account JSON",secret:!0}],snowflake:[{key:"config.account",label:"Account"},{key:"config.warehouse",label:"Warehouse"},{key:"config.database",label:"Database"},{key:"config.schema",label:"Schema"},{key:"config.role",label:"Role"},{key:"secrets.user",label:"User"},{key:"secrets.password",label:"Password",secret:!0}],duckdb:[{key:"config.path",label:"Path"}],sqlite:[{key:"config.path",label:"Path"}]};function pe(o,t,n){const[s,a]=t.split(".");!s||!a||(o[s]=o[s]??{},o[s][a]=n)}function ue(o){if(!o)return{};const t={},n=E[o.type]??[];for(const s of n){if(s.secret)continue;const[a,i]=s.key.split(".");if(!a||!i)continue;const d=o[a],l=d==null?void 0:d[i];l!=null&&(t[s.key]=String(l))}return t}function ye({mode:o,initial:t,onClose:n,onApplying:s}){const[a,i]=b.useState((t==null?void 0:t.type)??"postgres"),[d,l]=b.useState((t==null?void 0:t.name)??""),[p,g]=b.useState(()=>ue(t)),[u,j]=b.useState(null),[v,r]=b.useState(!1),[m,y]=b.useState(null);b.useEffect(()=>{const x=w=>{w.key==="Escape"&&n()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[n]);const h=()=>{const x={name:d,type:a,config:{},secrets:{}};for(const w of E[a]){const S=p[w.key];S===void 0||S===""||pe(x,w.key,w.numeric?Number(S):S)}return Object.keys(x.secrets).length===0&&delete x.secrets,x},c=async()=>{r(!0),y(null);try{j(await oe(h()))}catch(x){y(x instanceof Error?x.message:"Test failed")}finally{r(!1)}},k=async()=>{r(!0),y(null);try{await te(h(),o==="edit"),s(),n()}catch(x){y(x instanceof Error?x.message:"Save failed")}finally{r(!1)}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40",onClick:n,children:e.jsxs("div",{className:"bg-[var(--surface)] rounded-lg p-6 w-[480px] max-h-[85vh] overflow-auto",onClick:x=>x.stopPropagation(),style:{backgroundColor:"var(--yc-color-surface)",color:"var(--yc-color-text)"},children:[e.jsx("h2",{className:"text-lg font-semibold mb-4",children:o==="add"?"Add data source":"Edit data source"}),e.jsxs("label",{className:"block text-sm mb-2",children:["Name",e.jsx("input",{"aria-label":"Name",className:"mt-1 w-full border rounded px-2 py-1",value:d,disabled:o==="edit",onChange:x=>l(x.target.value),style:{borderColor:"var(--yc-color-border)",backgroundColor:"var(--yc-color-bg)"}})]}),e.jsxs("label",{className:"block text-sm mb-2",children:["Type",e.jsx("select",{"aria-label":"Type",className:"mt-1 w-full border rounded px-2 py-1",value:a,disabled:o==="edit",onChange:x=>{i(x.target.value),j(null)},style:{borderColor:"var(--yc-color-border)",backgroundColor:"var(--yc-color-bg)"},children:de.map(x=>e.jsx("option",{value:x,children:x},x))})]}),E[a].map(x=>e.jsxs("label",{className:"block text-sm mb-2",children:[x.label,e.jsx("input",{"aria-label":x.label,type:x.secret?"password":"text",className:"mt-1 w-full border rounded px-2 py-1",placeholder:o==="edit"&&x.secret?"Leave blank to keep current":void 0,value:p[x.key]??"",onChange:w=>g(S=>({...S,[x.key]:w.target.value})),style:{borderColor:"var(--yc-color-border)",backgroundColor:"var(--yc-color-bg)"}})]},x.key)),u&&e.jsx("p",{className:u.status==="healthy"?"text-green-600":"text-red-600",children:u.status==="healthy"?`Healthy (${u.latencyMs}ms)`:`Unhealthy: ${u.error}`}),m&&e.jsx("p",{className:"text-red-600 text-sm",children:m}),e.jsxs("div",{className:"flex gap-2 justify-end mt-4",children:[e.jsx("button",{className:"px-3 py-1",onClick:n,children:"Cancel"}),e.jsx("button",{className:"px-3 py-1 border rounded",disabled:v,onClick:c,children:"Test"}),e.jsx("button",{className:"px-3 py-1 bg-blue-600 text-white rounded",disabled:v,onClick:k,children:"Save"})]})]})})}function D({label:o,value:t}){return e.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[e.jsx("span",{style:{fontSize:"18px",fontWeight:600,color:"var(--yc-color-text)"},children:t}),e.jsx("span",{style:{fontSize:"12px",color:"var(--yc-color-text-secondary)"},children:o})]})}const q={fontSize:"13px",fontWeight:500,background:"none",border:"none",padding:0,cursor:"pointer"};function xe({source:o,onOpen:t,admin:n,onEdit:s,onDelete:a}){const i=(n==null?void 0:n.source)==="runtime",d=(n==null?void 0:n.source)==="git";return e.jsxs("div",{onClick:()=>t(o.name),style:{border:"1px solid var(--yc-color-border)",borderRadius:"8px",padding:"16px",background:"var(--yc-color-surface)",cursor:"pointer",display:"flex",flexDirection:"column",gap:"12px"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[e.jsx("span",{style:{fontSize:"15px",fontWeight:600,color:"var(--yc-color-text)"},children:o.name}),e.jsx("span",{style:{fontSize:"11px",fontWeight:500,padding:"2px 8px",borderRadius:"9999px",background:"var(--yc-color-bg)",color:"var(--yc-color-text-secondary)",border:"1px solid var(--yc-color-border)",letterSpacing:"0.04em"},children:o.type.toUpperCase()})]}),e.jsxs("div",{style:{display:"flex",gap:"24px"},children:[e.jsx(D,{label:"Tables",value:o.counts.tables}),e.jsx(D,{label:"Hunches",value:o.counts.pendingHunches}),e.jsx(D,{label:"Blindspots",value:o.counts.openBlindspots})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"16px"},children:[e.jsx("button",{onClick:l=>{l.stopPropagation(),t(o.name)},style:{...q,color:"var(--yc-color-primary)"},children:"Open →"}),i&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:l=>{l.stopPropagation(),s==null||s(n)},style:{...q,color:"var(--yc-color-text-secondary)"},children:"Edit"}),e.jsx("button",{onClick:l=>{l.stopPropagation(),a==null||a(n)},style:{...q,color:"var(--yc-color-danger)"},children:"Delete"})]}),d&&e.jsx("span",{title:"Defined in your project's connections/ directory — edit it in Git.",style:{fontSize:"11px",color:"var(--yc-color-text-secondary)",border:"1px solid var(--yc-color-border)",borderRadius:"9999px",padding:"2px 8px"},children:"managed in Git"})]})]})}function me(o){if(o&&typeof o=="object"&&"data"in o){const t=o.data;if(Array.isArray(t==null?void 0:t.references))return t.references}return[]}function he(o){return{name:o.name,type:o.type,config:o.config??{},secrets:o.secrets}}function ge(){const o=J(),t=M(h=>h.auth),n=V(h=>h.setApplying),s=t.status==="disabled"||t.status==="authenticated"&&t.user.role==="admin",[a,i]=b.useState(null),[d,l]=b.useState(null),{data:p,isLoading:g,error:u}=P({queryKey:["sources"],queryFn:G}),{data:j}=P({queryKey:["admin","config"],queryFn:Y,enabled:s}),v={};for(const h of(j==null?void 0:j.connections)??[])v[h.name]=h;const r=h=>{window.location.hash=`/data/sources/${encodeURIComponent(h)}`},m=()=>{n(!0),o.invalidateQueries({queryKey:["sources"]}),o.invalidateQueries({queryKey:["admin","config"]})},y=async h=>{if(l(null),!!window.confirm(`Delete data source "${h.name}"? This applies on restart.`))try{await se(h.name),m()}catch(c){if(c instanceof Z&&c.status===409){const k=me(c);l(k.length?`In use by ${k.map(x=>`${x.kind} "${x.name}"`).join(", ")} — remove or update these first.`:c.message||`"${h.name}" is in use by charts or models — remove or update those first.`)}else l(c instanceof Error?c.message:"Delete failed")}};return e.jsxs("div",{className:"p-6 w-full",children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between"},children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-1",style:{color:"var(--yc-color-text)"},children:"Data Sources"}),e.jsx("p",{className:"text-sm mb-4",style:{color:"var(--yc-color-text-secondary)"},children:"Your connected data sources. Open one to browse its tables and add business context."})]}),s&&e.jsx("button",{onClick:()=>i({mode:"add"}),className:"text-sm font-medium rounded px-3 py-1.5",style:{backgroundColor:"var(--yc-color-primary)",color:"#fff"},children:"Add data source"})]}),d&&e.jsx("p",{className:"text-sm mb-3",style:{color:"var(--yc-color-danger)"},children:d}),u&&e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-danger)"},children:"Failed to load sources."}),g?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"Loading…"}):!p||p.length===0?e.jsxs("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:["No connections configured. Add one in your project's ",e.jsx("code",{children:"connections/"})," directory."]}):e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(260px, 1fr))",gap:"16px"},children:p.map(h=>e.jsx(xe,{source:h,onOpen:r,admin:s?v[h.name]:void 0,onEdit:c=>i({mode:"edit",initial:he(c)}),onDelete:y},h.name))}),a&&e.jsx(ye,{mode:a.mode,initial:a.mode==="edit"?a.initial:void 0,onClose:()=>i(null),onApplying:m})]})}function X(o){const t=o.match(/event:\s*(\w+)\s*\ndata:\s*(\{[\s\S]*\})/);if(!t)return null;try{return{event:t[1],data:JSON.parse(t[2])}}catch{return null}}async function R(o,t="pending"){const n=new URLSearchParams({status:t,...o?{connection:o}:{}}),s=await fetch(`/api/hunches?${n}`);if(!s.ok)throw new Error("Failed to load hunches");return s.json()}async function fe(o,t){return(await fetch(`/api/hunches/${o}/confirm`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{sql:t}:{})})).json()}async function be(o){return(await fetch(`/api/hunches/${o}/reject`,{method:"POST"})).json()}async function ve(o){return(await fetch(`/api/hunches/${o}/run`,{method:"POST"})).json()}async function je(o,t){const s=(await fetch("/api/learn",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connection:o})})).body.getReader(),a=new TextDecoder;let i="";for(;;){const{done:d,value:l}=await s.read();if(d)break;i+=a.decode(l,{stream:!0});const p=i.split(`
2
+
3
+ `);i=p.pop()??"";for(const g of p){const u=X(g+`
4
+
5
+ `);u&&t(u)}}}async function A(o="open",t){const n=new URLSearchParams({status:o});return t&&n.set("connection",t),(await fetch(`/api/blindspots?${n}`)).json()}async function ke(o,t){return(await fetch(`/api/blindspots/${o}/answer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answer:t})})).json()}async function K(o){return(await fetch(`/api/blindspots/${o}/dismiss`,{method:"POST"})).json()}async function Se(o,t){const s=(await fetch("/api/blindspots/scan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({connection:o})})).body.getReader(),a=new TextDecoder;let i="";for(;;){const{done:d,value:l}=await s.read();if(d)break;i+=a.decode(l,{stream:!0});const p=i.split(`
6
+
7
+ `);i=p.pop()??"";for(const g of p){const u=X(g+`
8
+
9
+ `);u&&t(u)}}}const B=Q(o=>({learning:!1,hunches:[],setLearning:t=>o({learning:t}),setPhase:t=>o({phase:t}),setHunches:t=>o({hunches:t}),removeHunch:t=>o(n=>({hunches:n.hunches.filter(s=>s.id!==t)}))}));function U({hunch:o,onConfirm:t,onReject:n,onRun:s,running:a,runError:i}){const[d,l]=b.useState(o.sql);return e.jsxs("div",{className:"rounded-lg p-4 mb-3",style:{border:"1px solid var(--yc-color-border)",backgroundColor:"var(--yc-color-surface)"},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-medium",style:{color:"var(--yc-color-text)"},children:o.question}),o.confidence!=null&&e.jsxs("span",{className:"text-xs whitespace-nowrap",style:{color:"var(--yc-color-text-muted)"},children:[Math.round(o.confidence*100),"%"]})]}),o.rationale&&e.jsx("p",{className:"text-sm mt-1",style:{color:"var(--yc-color-text-secondary)"},children:o.rationale}),e.jsx("textarea",{className:"w-full font-mono text-sm mt-2 p-2 rounded",style:{backgroundColor:"var(--yc-color-input-bg)",border:"1px solid var(--yc-color-border)",color:"var(--yc-color-text)"},rows:3,value:d,onChange:p=>l(p.target.value),spellCheck:!1}),i&&e.jsx("p",{className:"text-xs mt-2",style:{color:"var(--yc-color-danger)"},children:i}),o.lastRunSample&&e.jsx("div",{className:"text-xs mt-2 overflow-auto max-h-40 rounded p-2",style:{backgroundColor:"var(--yc-color-input-bg)",color:"var(--yc-color-text-secondary)"},children:e.jsx("pre",{className:"font-mono",children:JSON.stringify(o.lastRunSample.rows.slice(0,5),null,2)})}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx("button",{onClick:()=>t(o.id,d),className:"px-3 py-1 rounded text-white text-sm hover:opacity-90",style:{backgroundColor:"var(--yc-color-primary)"},children:"Confirm"}),e.jsx("button",{onClick:()=>s(o.id,d),disabled:a,className:"px-3 py-1 rounded text-sm hover:opacity-80 disabled:opacity-50",style:{border:"1px solid var(--yc-color-border)",color:"var(--yc-color-text)"},children:a?"Running…":"Run"}),e.jsx("button",{onClick:()=>n(o.id),className:"px-3 py-1 rounded text-sm hover:opacity-80",style:{border:"1px solid var(--yc-color-border)",color:"var(--yc-color-text-secondary)"},children:"Reject"})]})]})}function we({connection:o}={}){var F,H,W;const{data:t}=L(),n=((F=t==null?void 0:t.defaults)==null?void 0:F.connection)??((W=(H=t==null?void 0:t.connections)==null?void 0:H[0])==null?void 0:W.name)??"",s=o??n,[a,i]=b.useState("pending"),d=B(f=>f.hunches),l=B(f=>f.setHunches),p=B(f=>f.removeHunch),[g,u]=b.useState(null),[j,v]=b.useState({}),{data:r,isLoading:m,error:y}=P({queryKey:["hunches",s,"pending"],queryFn:()=>R(s||void 0,"pending"),enabled:!!s&&a==="pending"}),{data:h,isLoading:c,error:k}=P({queryKey:["hunches",s,"confirmed"],queryFn:()=>R(s||void 0,"confirmed"),enabled:!!s&&a==="approved"});b.useEffect(()=>{r&&l(r)},[r,l]);const x=async(f,C)=>{p(f);try{await fe(f,C)}catch{l(await R(s||void 0,"pending"))}},w=async f=>{p(f);try{await be(f)}catch{l(await R(s||void 0,"pending"))}},S=async f=>{u(f),v(C=>{const T={...C};return delete T[f],T});try{const C=await ve(f);C.error?v(T=>({...T,[f]:C.error})):C.sample&&l(B.getState().hunches.map(T=>T.id===f?{...T,lastRunSample:C.sample}:T))}finally{u(null)}},$=(f,C)=>e.jsx("button",{onClick:()=>i(f),style:{color:a===f?"var(--yc-color-primary)":"var(--yc-color-text-secondary)",borderBottom:a===f?"2px solid var(--yc-color-primary)":"2px solid transparent",paddingBottom:"6px",marginRight:"16px",background:"none",border:"none",cursor:"pointer",fontSize:"14px",fontWeight:a===f?600:400},children:C});return e.jsxs("div",{className:"p-6 max-w-3xl mx-auto w-full",children:[e.jsx("h2",{className:"text-lg font-semibold mb-1",style:{color:"var(--yc-color-text)"},children:"Hunches"}),e.jsx("p",{className:"text-sm mb-4",style:{color:"var(--yc-color-text-secondary)"},children:"Confirm, edit, run, or reject the questions learned from your source."}),e.jsxs("div",{style:{display:"flex",borderBottom:"1px solid var(--yc-color-border)",marginBottom:"16px"},children:[$("pending","Pending"),$("approved","Approved")]}),a==="pending"&&e.jsxs(e.Fragment,{children:[!s&&e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"No connection configured."}),y&&e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-danger)"},children:"Failed to load hunches."}),m?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"Loading…"}):d.length===0?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"No pending hunches. Learn this source to generate some."}):d.map(f=>e.jsx(U,{hunch:f,onConfirm:x,onReject:w,onRun:S,running:g===f.id,runError:j[f.id]},f.id))]}),a==="approved"&&e.jsxs(e.Fragment,{children:[k&&e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-danger)"},children:"Failed to load approved hunches."}),c?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"Loading…"}):!h||h.length===0?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"No approved hunches yet. Confirm some from the Pending tab."}):h.map(f=>e.jsx(U,{hunch:f,onConfirm:x,onReject:w,onRun:S,running:g===f.id},f.id))]})]})}const O=Q(o=>({scanning:!1,blindspots:[],setScanning:t=>o({scanning:t}),setPhase:t=>o({phase:t}),setBlindspots:t=>o({blindspots:t}),removeBlindspot:t=>o(n=>({blindspots:n.blindspots.filter(s=>s.id!==t)}))}));function Ce({blindspot:o,onAnswer:t,onDismiss:n,onAccept:s}){const[a,i]=b.useState(""),d=o.kind==="opportunity";return e.jsxs("div",{className:"rounded-lg p-4 mb-3",style:{border:"1px solid var(--yc-color-border)",backgroundColor:"var(--yc-color-surface)"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs px-2 py-0.5 rounded-full",style:{border:"1px solid var(--yc-color-border)",color:"var(--yc-color-text-secondary)"},children:d?"opportunity":"context"}),e.jsx("h3",{className:"font-medium",style:{color:"var(--yc-color-text)"},children:o.title})]}),e.jsx("p",{className:"text-sm mt-1",style:{color:"var(--yc-color-text-secondary)"},children:o.detail}),d&&o.suggestedModel&&e.jsxs("div",{className:"text-xs mt-2 p-2 rounded",style:{backgroundColor:"var(--yc-color-input-bg)"},children:[e.jsx("div",{className:"font-mono",style:{color:"var(--yc-color-text)"},children:o.suggestedModel.name}),e.jsx("div",{style:{color:"var(--yc-color-text-secondary)"},children:o.suggestedModel.description}),o.suggestedModel.columns.length>0&&e.jsxs("div",{className:"mt-1",style:{color:"var(--yc-color-text-secondary)"},children:["cols: ",o.suggestedModel.columns.map(l=>l.name).join(", ")]})]}),!d&&e.jsx("textarea",{className:"w-full text-sm mt-2 p-2 rounded",style:{backgroundColor:"var(--yc-color-input-bg)",border:"1px solid var(--yc-color-border)",color:"var(--yc-color-text)"},rows:2,placeholder:"Explain this in business terms…",value:a,onChange:l=>i(l.target.value)}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[d?e.jsx("button",{onClick:()=>s(o.id),className:"px-3 py-1 rounded text-white text-sm hover:opacity-90",style:{backgroundColor:"var(--yc-color-primary)"},children:"Accept"}):e.jsx("button",{onClick:()=>t(o.id,a),className:"px-3 py-1 rounded text-white text-sm hover:opacity-90",style:{backgroundColor:"var(--yc-color-primary)"},children:"Save"}),e.jsx("button",{onClick:()=>n(o.id),className:"px-3 py-1 rounded text-sm hover:opacity-80",style:{border:"1px solid var(--yc-color-border)",color:"var(--yc-color-text-secondary)"},children:"Dismiss"})]})]})}function Ne({connection:o}={}){var m,y,h;const{data:t}=L(),n=((m=t==null?void 0:t.defaults)==null?void 0:m.connection)??((h=(y=t==null?void 0:t.connections)==null?void 0:y[0])==null?void 0:h.name)??"",s=o??n,a=O(c=>c.blindspots),i=O(c=>c.setBlindspots),d=O(c=>c.removeBlindspot),l=ee(c=>c.addToast),{data:p,isLoading:g,error:u}=P({queryKey:["blindspots",s,"open"],queryFn:()=>A("open",s||void 0),enabled:!!s});b.useEffect(()=>{p&&i(p)},[p,i]);const j=async(c,k)=>{if(k.trim()){d(c);try{await ke(c,k)}catch{i(await A("open",s||void 0))}}},v=async c=>{d(c);try{await K(c)}catch{i(await A("open",s||void 0))}},r=async c=>{d(c);try{await K(c),l("Sent to the dbt advisor — coming soon")}catch{i(await A("open",s||void 0))}};return e.jsxs("div",{className:"p-6 max-w-3xl mx-auto w-full",children:[e.jsx("h2",{className:"text-lg font-semibold mb-1",style:{color:"var(--yc-color-text)"},children:"Blindspots"}),e.jsx("p",{className:"text-sm mb-4",style:{color:"var(--yc-color-text-secondary)"},children:"Where the system lacks business context, plus useful marts it thinks are missing."}),u&&e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-danger)"},children:"Failed to load blindspots."}),g?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"Loading…"}):a.length===0?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:'No open blindspots. Use "Scan Data Source" to find some.'}):a.map(c=>e.jsx(Ce,{blindspot:c,onAnswer:j,onDismiss:v,onAccept:r},c.id))]})}function Te({connection:o}={}){var d,l,p;const{data:t}=L(),n=((d=t==null?void 0:t.defaults)==null?void 0:d.connection)??((p=(l=t==null?void 0:t.connections)==null?void 0:l[0])==null?void 0:p.name)??"",s=o??n,{data:a,isLoading:i}=P({queryKey:["coverage",s],queryFn:async()=>{const g=s?`?connection=${encodeURIComponent(s)}`:"";return(await fetch(`/api/coverage${g}`)).json()},enabled:!!s});return e.jsxs("div",{className:"p-6 max-w-3xl mx-auto w-full",children:[e.jsx("h2",{className:"text-lg font-semibold mb-1",style:{color:"var(--yc-color-text)"},children:"Coverage"}),e.jsx("p",{className:"text-sm mb-4",style:{color:"var(--yc-color-text-secondary)"},children:"How many hunches and blindspots each warehouse table has."}),i?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"Loading…"}):!a||a.length===0?e.jsx("p",{className:"text-sm",style:{color:"var(--yc-color-text-secondary)"},children:"No profile data yet. Run a scan to see coverage."}):e.jsx("div",{className:"rounded-lg overflow-hidden",style:{border:"1px solid var(--yc-color-border)"},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse"},children:[e.jsx("thead",{children:e.jsxs("tr",{style:{backgroundColor:"var(--yc-color-surface)"},children:[e.jsx("th",{style:{padding:"10px 16px",textAlign:"left",fontSize:"12px",fontWeight:600,color:"var(--yc-color-text-secondary)",borderBottom:"1px solid var(--yc-color-border)",textTransform:"uppercase",letterSpacing:"0.05em"},children:"Table"}),e.jsx("th",{style:{padding:"10px 16px",textAlign:"center",fontSize:"12px",fontWeight:600,color:"var(--yc-color-text-secondary)",borderBottom:"1px solid var(--yc-color-border)",textTransform:"uppercase",letterSpacing:"0.05em",width:"120px"},children:"Hunches"}),e.jsx("th",{style:{padding:"10px 16px",textAlign:"center",fontSize:"12px",fontWeight:600,color:"var(--yc-color-text-secondary)",borderBottom:"1px solid var(--yc-color-border)",textTransform:"uppercase",letterSpacing:"0.05em",width:"120px"},children:"Blindspots"})]})}),e.jsx("tbody",{children:a.map((g,u)=>e.jsxs("tr",{style:{borderBottom:u<a.length-1?"1px solid var(--yc-color-border)":"none"},children:[e.jsx("td",{style:{padding:"10px 16px",fontFamily:"monospace",fontSize:"13px",color:"var(--yc-color-text)"},children:g.name}),e.jsx("td",{style:{padding:"10px 16px",textAlign:"center"},children:e.jsx(_,{count:g.hunches,color:"green"})}),e.jsx("td",{style:{padding:"10px 16px",textAlign:"center"},children:e.jsx(_,{count:g.blindspots,color:"amber"})})]},g.name))})]})})]})}function _({count:o,color:t}){if(o===0)return e.jsx("span",{style:{display:"inline-block",minWidth:"28px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:500,textAlign:"center",backgroundColor:"var(--yc-color-surface)",color:"var(--yc-color-text-secondary)",border:"1px solid var(--yc-color-border)"},children:"0"});const n=t==="green"?{backgroundColor:"rgba(34, 197, 94, 0.15)",color:"#15803d",border:"1px solid rgba(34, 197, 94, 0.3)"}:{backgroundColor:"rgba(245, 158, 11, 0.15)",color:"#b45309",border:"1px solid rgba(245, 158, 11, 0.3)"};return e.jsx("span",{style:{display:"inline-block",minWidth:"28px",padding:"2px 8px",borderRadius:"9999px",fontSize:"12px",fontWeight:600,textAlign:"center",...n},children:o})}function Be(o){return o==="profiling"?"Profiling source…":o==="generating"?"Generating hunches…":o==="blindspots"?"Scanning for blindspots…":o==="error"?"Something went wrong.":"Scanning…"}function I({connection:o,onComplete:t}){const[n,s]=b.useState(!1),[a,i]=b.useState(void 0),d=async()=>{if(!o)return;s(!0),i("profiling");let l=[],p=!1;try{if(await je(o,u=>{u.event==="status"?u.data.phase==="generating"&&i("generating"):u.event==="done"?l=u.data.hunches??[]:u.event==="error"&&(p=!0,i("error"))}),p)return;i("blindspots");let g=[];await Se(o,u=>{u.event==="done"?g=u.data.blindspots??[]:u.event==="error"&&(p=!0,i("error"))}),p||t(l,g)}catch{i("error")}finally{s(!1)}};return e.jsxs("div",{className:"rounded-lg p-5 mb-4 flex items-center justify-between gap-4",style:{border:"1px solid var(--yc-color-border)",backgroundColor:"var(--yc-color-surface)"},children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",style:{color:"var(--yc-color-text)"},children:"Scan Data Source"}),e.jsx("p",{className:"text-sm mt-1",style:{color:"var(--yc-color-text-secondary)"},children:o?e.jsxs(e.Fragment,{children:["Profile ",e.jsx("span",{className:"font-mono",children:o}),", generate hunches, and scan for blindspots."]}):"No connection configured."}),n&&e.jsx("p",{className:"text-sm mt-2",style:{color:"var(--yc-color-primary)"},children:Be(a)}),a==="error"&&!n&&e.jsx("p",{className:"text-sm mt-2",style:{color:"var(--yc-color-danger)"},children:"Something went wrong. Please try again."})]}),e.jsx("button",{onClick:d,disabled:n||!o,className:"px-4 py-2 rounded text-white text-sm whitespace-nowrap hover:opacity-90 disabled:opacity-50",style:{backgroundColor:"var(--yc-color-primary)"},children:n?"Scanning…":"Scan Data Source"})]})}function Pe({onApplying:o}){const[t,n]=b.useState(""),[s,a]=b.useState(!1),[i,d]=b.useState(null),l=async v=>{a(!0),d(null);try{await v()}catch(r){d({kind:"err",text:r instanceof Error?r.message:"Failed"})}finally{a(!1)}},p=()=>l(async()=>{const v=await re(t);d(v.ok?{kind:"ok",text:"Connection OK — schema ready."}:{kind:"err",text:v.error??"Connection failed"})}),g=()=>l(async()=>{const r=(await ae(t)).migrated;d({kind:"ok",text:`Copied ${r.hunches} hunches, ${r.blindspots} blindspots, ${r.knowledgeDocs} docs, ${r.embeddings} embeddings.`})}),u=()=>l(async()=>{const v=await ce();d({kind:"ok",text:`Rebuilt ${v.embedded} embeddings.`})}),j=()=>l(async()=>{await ne(t),o()});return e.jsxs("div",{style:{padding:"24px",maxWidth:640},children:[e.jsx("h3",{style:{fontSize:16,fontWeight:600,marginBottom:8},children:"Knowledge database"}),e.jsx("p",{style:{fontSize:13,color:"var(--yc-color-text-secondary)",marginBottom:16},children:"Postgres connection for learned Hunches, Blindspots, knowledge docs, and embeddings. Changing it restarts the server."}),e.jsx("label",{htmlFor:"kdb-url",style:{display:"block",fontSize:13,marginBottom:4},children:"Database URL"}),e.jsx("input",{id:"kdb-url","aria-label":"Database URL",type:"password",value:t,onChange:v=>n(v.target.value),placeholder:"postgres://user:pass@host:5432/db",style:{width:"100%",padding:"6px 8px",borderRadius:6,border:"1px solid var(--yc-color-border)",backgroundColor:"var(--yc-color-surface)",color:"var(--yc-color-text)"}}),i&&e.jsx("p",{style:{marginTop:12,fontSize:13,color:i.kind==="ok"?"var(--yc-color-success, #16a34a)":"var(--yc-color-danger, #dc2626)"},children:i.text}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:16,flexWrap:"wrap"},children:[e.jsx("button",{disabled:s||!t.trim(),onClick:p,children:"Test"}),e.jsx("button",{disabled:s||!t.trim(),onClick:g,children:"Copy existing knowledge →"}),e.jsx("button",{disabled:s,onClick:u,children:"Rebuild embeddings now"}),e.jsx("button",{disabled:s||!t.trim(),onClick:j,style:{marginLeft:"auto",background:"var(--yc-color-primary)",color:"#fff",padding:"6px 14px",borderRadius:6},children:"Save & restart"})]})]})}const Re=["anthropic","openai","gemini","ollama","ollama_cloud","openai_compatible"],Ae=["hunch_generation","blindspot_scan","answer","advisor"];function Oe({onApplying:o}){const[t,n]=b.useState(null),[s,a]=b.useState(!1),[i,d]=b.useState(null);if(b.useEffect(()=>{Y().then(r=>n(r.ai??{providers:{}}))},[]),!t)return e.jsx("div",{style:{padding:24},children:"Loading…"});const l=t.providers??{},p=r=>n({...r}),g=(r,m)=>{const y=l[r]??{provider:"anthropic"};p({...t,providers:{...l,[r]:{...y,...m}}})},u=async r=>{a(!0),d(null);try{await r()}catch(m){d({kind:"err",text:m instanceof Error?m.message:"Failed"})}finally{a(!1)}},j=r=>u(async()=>{const m=l[r],y=m.api_key&&m.api_key.startsWith("••••")?{...m,api_key:void 0}:m,h=await ie(y,"llm");d(h.ok?{kind:"ok",text:`${r}: OK`}:{kind:"err",text:`${r}: ${h.error??"failed"}`})}),v=()=>u(async()=>{var m,y,h;const r=JSON.parse(JSON.stringify(t));for(const c of Object.values(r.providers??{}))(m=c.api_key)!=null&&m.startsWith("••••")&&delete c.api_key;(h=(y=r.embedding)==null?void 0:y.api_key)!=null&&h.startsWith("••••")&&delete r.embedding.api_key,r.tasks&&(r.tasks=Object.fromEntries(Object.entries(r.tasks).filter(([,c])=>c))),await le(r),o()});return e.jsxs("div",{style:{padding:24,maxWidth:720},children:[e.jsx("h3",{style:{fontSize:16,fontWeight:600,marginBottom:8},children:"AI providers"}),e.jsx("p",{style:{fontSize:13,color:"var(--yc-color-text-secondary)",marginBottom:16},children:"Configure the LLM providers, per-task routing, and the embedding model. API keys are encrypted at rest; saving restarts the server."}),e.jsxs("label",{style:{display:"block",fontSize:13,marginBottom:12},children:["Default provider",e.jsx("input",{"aria-label":"Default provider",value:t.default??"",onChange:r=>p({...t,default:r.target.value}),style:{display:"block",marginTop:4,padding:"6px 8px",borderRadius:6,border:"1px solid var(--yc-color-border)",background:"var(--yc-color-surface)",color:"var(--yc-color-text)"}})]}),Object.entries(l).map(([r,m])=>e.jsxs("div",{style:{border:"1px solid var(--yc-color-border)",borderRadius:8,padding:12,marginBottom:12},children:[e.jsx("strong",{style:{fontSize:14},children:r}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginTop:8},children:[e.jsxs("label",{style:{fontSize:12},children:["Type",e.jsx("select",{"aria-label":`${r} type`,value:m.provider,onChange:y=>g(r,{provider:y.target.value}),style:{display:"block",width:"100%",marginTop:2},children:Re.map(y=>e.jsx("option",{value:y,children:y},y))})]}),e.jsxs("label",{style:{fontSize:12},children:["Model",e.jsx("input",{"aria-label":`${r} model`,value:m.model??"",onChange:y=>g(r,{model:y.target.value}),style:{display:"block",width:"100%",marginTop:2}})]}),e.jsxs("label",{style:{fontSize:12},children:["Base URL",e.jsx("input",{"aria-label":`${r} base_url`,value:m.base_url??"",onChange:y=>g(r,{base_url:y.target.value}),style:{display:"block",width:"100%",marginTop:2}})]}),e.jsxs("label",{style:{fontSize:12},children:["API key",e.jsx("input",{"aria-label":`${r} api_key`,type:"password",placeholder:"leave blank to keep current",value:m.api_key??"",onChange:y=>g(r,{api_key:y.target.value}),style:{display:"block",width:"100%",marginTop:2}})]})]}),e.jsx("button",{disabled:s,onClick:()=>j(r),style:{marginTop:8},children:"Test"})]},r)),e.jsx("h4",{style:{fontSize:14,fontWeight:600,margin:"16px 0 8px"},children:"Task routing"}),Ae.map(r=>{var m;return e.jsxs("label",{style:{display:"block",fontSize:13,marginBottom:6},children:[r,e.jsxs("select",{"aria-label":`route ${r}`,value:((m=t.tasks)==null?void 0:m[r])??"",onChange:y=>p({...t,tasks:{...t.tasks,[r]:y.target.value}}),style:{marginLeft:8},children:[e.jsx("option",{value:"",children:"(default)"}),Object.keys(l).map(y=>e.jsx("option",{value:y,children:y},y))]})]},r)}),i&&e.jsx("p",{style:{marginTop:12,fontSize:13,color:i.kind==="ok"?"var(--yc-color-success, #16a34a)":"var(--yc-color-danger, #dc2626)"},children:i.text}),e.jsx("div",{style:{marginTop:16},children:e.jsx("button",{disabled:s,onClick:v,style:{background:"var(--yc-color-primary)",color:"#fff",padding:"6px 14px",borderRadius:6},children:"Save & restart"})})]})}const De=[{id:"sources",label:"Data Sources"},{id:"hunches",label:"Hunches"},{id:"blindspots",label:"Blindspots"},{id:"coverage",label:"Coverage"}];function z({value:o,onChange:t}){const{data:n}=P({queryKey:["sources"],queryFn:G});return e.jsxs("div",{style:{padding:"12px 24px 0",display:"flex",alignItems:"center",gap:"8px"},children:[e.jsx("label",{htmlFor:"source-selector",style:{fontSize:"13px",color:"var(--yc-color-text-secondary)",whiteSpace:"nowrap"},children:"Source:"}),e.jsxs("select",{id:"source-selector",value:o,onChange:s=>t(s.target.value),style:{fontSize:"13px",padding:"4px 8px",borderRadius:"6px",border:"1px solid var(--yc-color-border)",backgroundColor:"var(--yc-color-surface)",color:"var(--yc-color-text)",cursor:"pointer"},children:[e.jsx("option",{value:"",children:"All sources"}),n==null?void 0:n.map(s=>e.jsx("option",{value:s.name,children:s.name},s.name))]})]})}function Le({tab:o,onTabChange:t}){const[n,s]=b.useState(""),[a,i]=b.useState(""),[d,l]=b.useState(""),p=M(c=>c.auth),g=p.status==="disabled"||p.status==="authenticated"&&p.user.role==="admin",u=V(c=>c.setApplying),j=J(),v=B(c=>c.setHunches),r=O(c=>c.setBlindspots),m=o==="blindspots"?a:n,y=(c,k)=>{const x=new Set(B.getState().hunches.map(S=>S.id)),w=c.filter(S=>!x.has(S.id));v([...w,...B.getState().hunches]),r(k),j.invalidateQueries({queryKey:["hunches"]}),j.invalidateQueries({queryKey:["blindspots"]})},h=(c,k)=>e.jsx("button",{onClick:()=>t(c),style:{color:o===c?"var(--yc-color-primary)":"var(--yc-color-text-secondary)",borderBottom:o===c?"2px solid var(--yc-color-primary)":"2px solid transparent",paddingBottom:"6px",marginRight:"16px",background:"none",border:"none",cursor:"pointer",fontSize:"14px",fontWeight:o===c?600:400},children:k},c);return e.jsxs("div",{className:"flex flex-col h-full w-full",children:[e.jsxs("div",{style:{display:"flex",borderBottom:"1px solid var(--yc-color-border)",padding:"16px 24px 0"},children:[De.map(c=>h(c.id,c.label)),g&&h("settings","Settings")]}),e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[o==="sources"&&e.jsx(ge,{}),o==="hunches"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{value:n,onChange:s}),m&&e.jsx("div",{className:"px-6 pt-4",children:e.jsx(I,{connection:m,onComplete:y})}),e.jsx(we,{connection:n||void 0})]}),o==="blindspots"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{value:a,onChange:i}),m&&e.jsx("div",{className:"px-6 pt-4",children:e.jsx(I,{connection:m,onComplete:y})}),e.jsx(Ne,{connection:a||void 0})]}),o==="coverage"&&e.jsxs(e.Fragment,{children:[e.jsx(z,{value:d,onChange:l}),e.jsx(Te,{connection:d||void 0})]}),o==="settings"&&g&&e.jsxs(e.Fragment,{children:[e.jsx(Pe,{onApplying:()=>u(!0)}),e.jsx(Oe,{onApplying:()=>u(!0)})]})]})]})}export{Le as DataView};