@akal/supaforge 0.0.31 → 0.0.33

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 (79) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +29 -11
  3. package/dist/base-command.d.ts +1 -0
  4. package/dist/base-command.js +2 -2
  5. package/dist/{chunk-BHYLBKYD.js → chunk-2SELREHW.js} +5 -5
  6. package/dist/{chunk-5Z3SAIQS.js → chunk-3HGAV5CC.js} +97 -831
  7. package/dist/{chunk-XMYMIURR.js → chunk-4IVN7QVY.js} +119 -39
  8. package/dist/{chunk-NXRSAVRU.js → chunk-6LJERPUN.js} +28 -7
  9. package/dist/{chunk-4OU7KO5Y.js → chunk-6Q7MHFBM.js} +2 -2
  10. package/dist/{chunk-PARSNTBD.js → chunk-7NAZGZPV.js} +56 -25
  11. package/dist/{chunk-VOXZWQ3N.js → chunk-BUOWHE36.js} +372 -9
  12. package/dist/{chunk-TQJSQLWA.js → chunk-DMIWAJRB.js} +38 -10
  13. package/dist/{chunk-LQXF65MC.js → chunk-GEHPTPNZ.js} +3 -3
  14. package/dist/chunk-GZREXCQZ.js +207 -0
  15. package/dist/{chunk-YVDSR4GM.js → chunk-MIRLB5JM.js} +51 -23
  16. package/dist/{chunk-KIFJGON5.js → chunk-NTUASFQ3.js} +2 -2
  17. package/dist/{chunk-5QQBTLWO.js → chunk-ORQJVE57.js} +3 -3
  18. package/dist/{chunk-VMTBLHN2.js → chunk-SC2XHGIS.js} +2 -2
  19. package/dist/{chunk-X6V2GGDZ.js → chunk-SQPCWGQO.js} +388 -64
  20. package/dist/chunk-UWAVXC57.js +916 -0
  21. package/dist/commands/clone.js +10 -10
  22. package/dist/commands/diff.d.ts +16 -0
  23. package/dist/commands/diff.js +11 -12
  24. package/dist/commands/hukam.js +11 -12
  25. package/dist/commands/mcp.d.ts +1 -0
  26. package/dist/commands/mcp.js +18 -9
  27. package/dist/commands/migrate/baseline.js +3 -3
  28. package/dist/commands/migrate/create.js +5 -6
  29. package/dist/commands/migrate/list.js +4 -4
  30. package/dist/commands/migrate/run.js +5 -6
  31. package/dist/commands/report.js +3 -3
  32. package/dist/commands/restore.js +11 -13
  33. package/dist/commands/snapshot.js +6 -8
  34. package/dist/commands/sync.js +11 -12
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +16 -16
  37. package/package.json +10 -8
  38. package/bin/dev.js +0 -10
  39. package/dist/base-command.js.map +0 -1
  40. package/dist/chunk-4OU7KO5Y.js.map +0 -1
  41. package/dist/chunk-5QQBTLWO.js.map +0 -1
  42. package/dist/chunk-5Z3SAIQS.js.map +0 -1
  43. package/dist/chunk-6WAMNZLO.js.map +0 -1
  44. package/dist/chunk-BHYLBKYD.js.map +0 -1
  45. package/dist/chunk-BLKJWDTL.js.map +0 -1
  46. package/dist/chunk-DQQ5E563.js.map +0 -1
  47. package/dist/chunk-G2DIPIYU.js.map +0 -1
  48. package/dist/chunk-H5MJ5DFX.js +0 -16
  49. package/dist/chunk-H5MJ5DFX.js.map +0 -1
  50. package/dist/chunk-KIFJGON5.js.map +0 -1
  51. package/dist/chunk-LQXF65MC.js.map +0 -1
  52. package/dist/chunk-NXRSAVRU.js.map +0 -1
  53. package/dist/chunk-PARSNTBD.js.map +0 -1
  54. package/dist/chunk-RRMI5CZD.js +0 -376
  55. package/dist/chunk-RRMI5CZD.js.map +0 -1
  56. package/dist/chunk-SF3YA42C.js +0 -506
  57. package/dist/chunk-SF3YA42C.js.map +0 -1
  58. package/dist/chunk-TQJSQLWA.js.map +0 -1
  59. package/dist/chunk-VMTBLHN2.js.map +0 -1
  60. package/dist/chunk-VOXZWQ3N.js.map +0 -1
  61. package/dist/chunk-X6V2GGDZ.js.map +0 -1
  62. package/dist/chunk-XMYMIURR.js.map +0 -1
  63. package/dist/chunk-YVDSR4GM.js.map +0 -1
  64. package/dist/commands/clone.js.map +0 -1
  65. package/dist/commands/diff.js.map +0 -1
  66. package/dist/commands/help.js.map +0 -1
  67. package/dist/commands/hukam.js.map +0 -1
  68. package/dist/commands/init.js.map +0 -1
  69. package/dist/commands/mcp.js.map +0 -1
  70. package/dist/commands/migrate/baseline.js.map +0 -1
  71. package/dist/commands/migrate/create.js.map +0 -1
  72. package/dist/commands/migrate/list.js.map +0 -1
  73. package/dist/commands/migrate/run.js.map +0 -1
  74. package/dist/commands/report.js.map +0 -1
  75. package/dist/commands/restore.js.map +0 -1
  76. package/dist/commands/snapshot.js.map +0 -1
  77. package/dist/commands/sync.js.map +0 -1
  78. package/dist/help.js.map +0 -1
  79. package/dist/index.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/defaults.ts","../src/config.ts","../src/env-loader.ts","../src/constants.ts","../src/ui.ts"],"sourcesContent":["/** Supabase internal schemas to ignore by default during drift scanning. */\nexport const DEFAULT_IGNORE_SCHEMAS = [\n 'auth',\n 'storage',\n 'realtime',\n // Supabase's own realtime internals live in _realtime (underscore), a\n // different schema from 'realtime'. Its tables are owned by supabase_admin,\n // so reporting \"RLS not enabled\" on them is a finding nobody can act on —\n // it dragged the posture score down with unfixable noise.\n '_realtime',\n 'vault',\n 'net',\n 'graphql_public',\n 'supabase_migrations',\n 'pgsodium',\n 'pgtle',\n 'supabase_functions',\n 'extensions',\n 'pg_catalog',\n 'information_schema',\n]\n\n/**\n * Every schema whose contents belong to Supabase rather than the project.\n *\n * DEFAULT_IGNORE_SCHEMAS plus the ones a scan never lists because nothing in\n * them is diffed, but which still hold objects and grants a project cannot\n * recreate: pg_cron's `cron`, the pooler's `pgbouncer`, and pg_graphql's\n * `graphql`. Grants in these differ between Supabase versions, not between\n * anybody's decisions, and a restore must never clear them.\n */\nexport const SUPABASE_PLATFORM_SCHEMAS = [\n ...DEFAULT_IGNORE_SCHEMAS,\n 'cron',\n 'pgbouncer',\n 'graphql',\n]\n\n/**\n * The schemas a schema diff leaves out: the project's `ignoreSchemas`, and\n * always the platform's own — those above, and the self-hosted stack's\n * `_realtime` and `_analytics`, and pgsodium's `pgsodium_masks`. Every other\n * schema is compared.\n */\nexport function schemaDiffIgnores(ignoreSchemas: readonly string[] = DEFAULT_IGNORE_SCHEMAS): string[] {\n return [...new Set([...ignoreSchemas, ...SUPABASE_PLATFORM_SCHEMAS.filter(s => !DEFAULT_IGNORE_SCHEMAS.includes(s)),\n '_realtime', '_analytics', 'pgsodium_masks'])]\n}\n\n/** Hint text shown during `supaforge init` to guide users through the Supabase UI. */\nexport const INIT_HINTS = {\n DB_URL: [\n ' In Supabase: click \"Connect\" (top bar) -> Direct -> Session pooler -> URI -> copy the Connection string.',\n ' Format: postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres\\n',\n ],\n PROJECT_URL: [\n ' Dashboard overview \\u2192 click Copy \\u2192 Project URL, or Project Settings \\u2192 General \\u2192 Project ID.',\n ],\n ACCESS_TOKEN: [\n ' supabase.com/dashboard/account/tokens \\u2192 Generate new token.',\n ' This is a personal access token for the Supabase Management API (auth config, edge functions).\\n',\n ],\n DATA_TABLES: [\n ' Reference-data tables are rows that should be identical across environments',\n ' (e.g. countries, currencies, feature_flags, plans).\\n',\n ],\n} as const\n\n/** Error fragment for a relation that simply doesn't exist (expected for optional features). */\nexport const RELATION_NOT_FOUND = 'does not exist'\n\n/**\n * The checks a local clone can only report noise for.\n *\n * A clone is vanilla PostgreSQL restored from a pg_dump: the Supabase-managed\n * layers have no local equivalent, and Postgres Roles & Grants is the same\n * story — Supabase's service roles do not exist on a plain server, so every\n * one of them reads as drift. On the diff that prompted issue #47 that was 227\n * findings, all of them clone artefacts, confirmed by a remote-to-remote diff\n * reporting zero.\n *\n * One list because the same advice was written out by hand in three places and\n * had already drifted into three different answers. Roles was in none of them:\n * it arrived as Layer 14, after the clone advice was written for a 13-layer set.\n */\nexport const CLONE_NOISE_CHECKS = [\n 'storage',\n 'auth',\n 'edge-functions',\n 'vault',\n 'realtime',\n // different schema from 'realtime'. Its tables are owned by supabase_admin,\n // so reporting \"RLS not enabled\" on them is a finding nobody can act on —\n // it dragged the posture score down with unfixable noise.\n 'roles',\n] as const\n\n/** The `--skip=` flags that suppress clone-only noise, as one command fragment. */\nexport const CLONE_SKIP_FLAGS = CLONE_NOISE_CHECKS.map(c => `--skip=${c}`).join(' ')\n","import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport type { SupaForgeConfig, EnvironmentConfig } from './types/config'\nimport { DEFAULT_IGNORE_SCHEMAS } from './defaults'\nimport { loadEnvFiles } from './env-loader'\n\nconst CONFIG_FILENAME = 'supaforge.config.json'\n\n/** Match $VAR or ${VAR} references. */\nconst ENV_VAR_RE = /\\$\\{([^}]+)\\}|\\$([A-Z_][A-Z0-9_]*)/gi\n\n/**\n * Expand $VAR and ${VAR} references in a string using process.env.\n * Returns the original token unchanged if the env var is not set.\n */\nexport function expandEnvVars(value: string): string {\n return value.replace(ENV_VAR_RE, (match, braced, bare) => {\n const name = braced ?? bare\n return process.env[name] ?? match\n })\n}\n\n/**\n * Extract the project ref from a Supabase Project URL or return the value as-is\n * if it's already a bare ref.\n *\n * Accepted formats:\n * - https://abcdef123456.supabase.co\n * - https://abcdef123456.supabase.co/\n * - abcdef123456 (bare ref, returned unchanged)\n */\nexport function parseProjectRef(value: string): string {\n const trimmed = value.trim()\n try {\n const url = new URL(trimmed)\n const match = url.hostname.match(/^([^.]+)\\.supabase\\.co$/)\n if (match) return match[1]\n } catch {\n // Not a URL — treat as bare ref\n }\n return trimmed\n}\n\n/**\n * Expand env var references in all sensitive environment fields (dbUrl, accessToken).\n * Also normalises projectRef from full URL to bare ref.\n */\nfunction expandEnvironments(\n environments: Record<string, EnvironmentConfig>,\n): Record<string, EnvironmentConfig> {\n const result: Record<string, EnvironmentConfig> = {}\n for (const [name, env] of Object.entries(environments)) {\n result[name] = {\n ...env,\n dbUrl: expandEnvVars(env.dbUrl),\n ...(env.accessToken ? { accessToken: expandEnvVars(env.accessToken) } : {}),\n ...(env.projectRef ? { projectRef: parseProjectRef(env.projectRef) } : {}),\n }\n }\n return result\n}\n\nexport async function loadConfig(cwd = process.cwd()): Promise<SupaForgeConfig> {\n await loadEnvFiles(cwd)\n const configPath = resolve(cwd, CONFIG_FILENAME)\n const raw = await readFile(configPath, 'utf-8')\n const config = JSON.parse(raw) as SupaForgeConfig\n return resolveConfig(config)\n}\n\nexport function resolveConfig(config: SupaForgeConfig): SupaForgeConfig {\n return {\n ...config,\n environments: expandEnvironments(config.environments),\n ignoreSchemas: config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS,\n }\n}\n\nexport function validateConfig(config: SupaForgeConfig): string[] {\n const errors: string[] = []\n\n if (!config.environments || typeof config.environments !== 'object') {\n errors.push('environments is required and must be an object')\n return errors\n }\n\n if (Object.keys(config.environments).length < 2) {\n errors.push('At least two environments are required')\n }\n\n if (!config.source) errors.push('\"source\" environment name is required')\n if (!config.target) errors.push('\"target\" environment name is required')\n\n if (config.source && !config.environments[config.source]) {\n errors.push(`Source environment \"${config.source}\" not found in environments`)\n }\n if (config.target && !config.environments[config.target]) {\n errors.push(`Target environment \"${config.target}\" not found in environments`)\n }\n\n if (config.source && config.target && config.source === config.target) {\n errors.push('Source and target must be different environments')\n }\n\n for (const [name, env] of Object.entries(config.environments)) {\n if (!env.dbUrl) errors.push(`Environment \"${name}\" is missing dbUrl`)\n }\n\n return errors\n}\n\n/**\n * Validate config for single-environment operations (snapshot, clone, backup, restore).\n * Only requires that the specified environment exists and has a dbUrl.\n */\nexport function validateSingleEnvConfig(config: SupaForgeConfig, envName: string): string[] {\n const errors: string[] = []\n\n if (!config.environments || typeof config.environments !== 'object') {\n errors.push('environments is required and must be an object')\n return errors\n }\n\n if (!config.environments[envName]) {\n errors.push(`Environment \"${envName}\" not found in environments`)\n return errors\n }\n\n if (!config.environments[envName].dbUrl) {\n errors.push(`Environment \"${envName}\" is missing dbUrl`)\n }\n\n return errors\n}\n","import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\n\n/**\n * Environment file candidates in descending priority order.\n * Follows the Next.js / Vite / CRA convention:\n * .env.{NODE_ENV}.local → .env.local → .env.{NODE_ENV} → .env\n *\n * All matching files are loaded (earlier entries win for duplicate keys).\n * Files that don't exist are silently skipped.\n */\nexport const ENV_FILE_PRIORITY = [\n '.env.local',\n '.env',\n] as const\n\n/**\n * Build the prioritised .env file list, inserting NODE_ENV-specific\n * variants when NODE_ENV is set (e.g. production, staging, development).\n *\n * Returns paths in descending priority — first file wins per key.\n */\nexport function buildEnvFilePriority(nodeEnv?: string): readonly string[] {\n if (!nodeEnv) return ENV_FILE_PRIORITY\n\n // .env.{NODE_ENV}.local → .env.local → .env.{NODE_ENV} → .env\n return [\n `.env.${nodeEnv}.local`,\n '.env.local',\n `.env.${nodeEnv}`,\n '.env',\n ]\n}\n\n/**\n * Parse a single .env file into a key-value map.\n * Handles KEY=value, KEY=\"value\", KEY='value', empty lines, and # comments.\n * Multi-line values are not supported.\n */\nexport function parseEnvContent(content: string): Map<string, string> {\n const result = new Map<string, string>()\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#')) continue\n\n const eqIndex = trimmed.indexOf('=')\n if (eqIndex < 1) continue\n\n const key = trimmed.slice(0, eqIndex).trim()\n let value = trimmed.slice(eqIndex + 1).trim()\n\n // Strip matching quotes\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1)\n }\n\n result.set(key, value)\n }\n\n return result\n}\n\nexport interface EnvLoadResult {\n /** Files that were found and loaded, in priority order. */\n loaded: string[]\n /** Total number of env vars injected into process.env. */\n injected: number\n}\n\n/**\n * Auto-detect and load .env files into process.env.\n *\n * Standard priority (industry convention matching Next.js / Vite / CRA):\n * .env.{NODE_ENV}.local → .env.local → .env.{NODE_ENV} → .env\n *\n * Never overwrites existing process.env values — system env always wins.\n * Returns metadata about which files were loaded.\n */\nexport async function loadEnvFiles(cwd = process.cwd()): Promise<EnvLoadResult> {\n const nodeEnv = process.env.NODE_ENV\n const candidates = buildEnvFilePriority(nodeEnv)\n const loaded: string[] = []\n let injected = 0\n\n // Track keys we've already set from higher-priority files\n const seen = new Set<string>()\n\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate)\n if (!existsSync(fullPath)) continue\n\n let content: string\n try {\n content = await readFile(fullPath, 'utf-8')\n } catch {\n continue\n }\n\n loaded.push(candidate)\n const entries = parseEnvContent(content)\n\n for (const [key, value] of entries) {\n // System env always wins, then higher-priority files\n if (key in process.env || seen.has(key)) continue\n process.env[key] = value\n seen.add(key)\n injected++\n }\n }\n\n return { loaded, injected }\n}\n","// ─── Directory & File Paths ──────────────────────────────────────────────────\n\n/** Root directory for all SupaForge local state. */\nexport const SUPAFORGE_DIR = '.supaforge'\n\n/** Subdirectory under SUPAFORGE_DIR for snapshot storage. */\nexport const SNAPSHOTS_SUBDIR = 'snapshots'\n\n/** Subdirectory under SUPAFORGE_DIR for migration files. */\nexport const MIGRATIONS_SUBDIR = 'migrations'\n\n/** Filename for snapshot manifests. */\nexport const SNAPSHOT_MANIFEST_FILE = 'manifest.json'\n\n/** File path (relative to cwd) for branch tracking. */\nexport const BRANCHES_FILE = `${SUPAFORGE_DIR}/branches.json`\n\n// ─── Supabase Management API ────────────────────────────────────────────────\n\n/** Supabase Management API base URL for project-level endpoints. */\nexport const SUPABASE_MGMT_API = 'https://api.supabase.com/v1/projects'\n\n// ─── Timeouts ────────────────────────────────────────────────────────────────\n\n/**\n * Default timeout for @dbdiff/cli execution (5 minutes).\n *\n * Large Supabase schemas can take several minutes to diff. The previous\n * 2-minute limit silently killed the process mid-run, surfacing dbdiff's\n * last progress log line as a bogus \"error\". Override at runtime with the\n * SUPAFORGE_DBDIFF_TIMEOUT environment variable (value in seconds), or per\n * environment via checks.schema.timeout in supaforge.config.json.\n *\n * Raised from 300s: the schema pre-scan made the common case much faster, so\n * the runs still approaching the ceiling are precisely the ones that need\n * headroom, and a timeout costs the whole layer rather than degrading it.\n */\nexport const DBDIFF_EXEC_TIMEOUT_MS = 600_000\n\n/**\n * Default bound on establishing a PostgreSQL connection (15 seconds).\n *\n * `pg` defaults connectionTimeoutMillis to 0 — wait forever. That is invisible\n * for the common failures, because the socket layer errors out on its own: a\n * refused connection fails immediately, an unroutable host after the OS TCP\n * timeout. But a host that *accepts* the connection and then never completes\n * the startup handshake — a paused container, a dropped VPN tunnel, an\n * overloaded server — leaves nothing to time it out, and the command blocks\n * indefinitely with no output (issue #44).\n *\n * 15s is long enough for a slow link and short enough to fail usefully.\n * Override with SUPAFORGE_CONNECT_TIMEOUT (in seconds).\n */\nexport const DB_CONNECT_TIMEOUT_MS = 15_000\n\n/**\n * Bound on the preflight version probe (15 seconds).\n *\n * The handshake can complete on a server that then stalls before answering,\n * so bounding the connect alone still leaves a way to hang. Applied only to\n * the probe — a scan or migration query is legitimately long-running and must\n * not inherit this.\n */\nexport const DB_PROBE_TIMEOUT_MS = 15_000\n\n/** Max stdout/stderr buffer for @dbdiff/cli (10 MB). */\nexport const DBDIFF_MAX_BUFFER = 10 * 1024 * 1024\n\n/** Timeout for pg_dump | pg_restore pipeline (30 minutes). */\nexport const PG_PIPELINE_TIMEOUT_MS = 1_800_000\n\n/** Interval between progress reports during clone (1 second). */\nexport const CLONE_PROGRESS_INTERVAL_MS = 1_000\n\n/** Timeout for container runtime detection commands (5 seconds). */\nexport const RUNTIME_DETECT_TIMEOUT_MS = 5_000\n\n/** Timeout for removing stopped containers (10 seconds). */\nexport const CONTAINER_RM_TIMEOUT_MS = 10_000\n\n/** Timeout for starting a new container (60 seconds). */\nexport const CONTAINER_START_TIMEOUT_MS = 60_000\n\n// ─── Scoring Weights ─────────────────────────────────────────────────────────\n\n/** Score penalty per critical drift issue. */\nexport const SCORE_PENALTY_CRITICAL = 15\n\n/** Score penalty per warning drift issue. */\nexport const SCORE_PENALTY_WARNING = 5\n\n/** Score penalty per info drift issue. */\nexport const SCORE_PENALTY_INFO = 1\n\n/** Score penalty per errored check (cannot confirm clean). */\nexport const SCORE_PENALTY_ERROR = 3\n\n/** Maximum (perfect) drift score. */\nexport const SCORE_MAX = 100\n\n// ─── Render / Formatting ─────────────────────────────────────────────────────\n\n/** Padding width for check status lines in terminal output. */\nexport const CHECK_LINE_PADDING = 40\n\n// ─── Clone-specific Schemas ──────────────────────────────────────────────────\n\n/**\n * Additional Supabase-internal schemas to exclude from pg_dump when cloning.\n * These reference extensions (pg_graphql, pgsodium, supautils, etc.)\n * unavailable in vanilla PostgreSQL.\n *\n * Combined with DEFAULT_IGNORE_SCHEMAS from defaults.ts to form the\n * full exclusion list for `supaforge clone`.\n */\nexport const CLONE_EXTRA_EXCLUDE_SCHEMAS = [\n 'graphql',\n '_realtime',\n '_analytics',\n 'pgsodium_masks',\n]\n\n// ─── Migration Tracking ──────────────────────────────────────────────────────\n\n/** Schema name for Supabase migration tracking. */\nexport const MIGRATIONS_SCHEMA = 'supabase_migrations'\n\n/** Unqualified table name for migration records. */\nexport const MIGRATIONS_TABLE_NAME = 'schema_migrations'\n\n/** Fully qualified migration tracking table name. */\nexport const MIGRATIONS_TABLE = `${MIGRATIONS_SCHEMA}.${MIGRATIONS_TABLE_NAME}`\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\n/** Maximum number of objects to list per Supabase Storage API call. */\nexport const STORAGE_LIST_LIMIT = 1000\n\n// ─── Run Log ─────────────────────────────────────────────────────────────────\n\n/** Directory (relative to home) where the run log is stored. */\nexport const RUN_LOG_DIR = '.supaforge'\n\n/** Filename for the run log. */\nexport const RUN_LOG_FILE = 'run-log.jsonl'\n\n/** Maximum number of run log entries to keep. */\nexport const RUN_LOG_MAX_ENTRIES = 500\n","import { colorize } from '@oclif/core/ux'\n\ntype Style = Parameters<typeof colorize>[0]\n\n/** Apply an oclif color/style to text. */\nexport const c = (style: Style, text: string): string => colorize(style, text)\n\n/** Green text for success messages. */\nexport const ok = (text: string): string => c('green', text)\n\n/** Yellow text for warnings. */\nexport const warn = (text: string): string => c('yellow', text)\n\n/** Dim text for hints and secondary info. */\nexport const dim = (text: string): string => c('dim', text)\n\n/** Cyan text for commands and URIs. */\nexport const cmd = (text: string): string => c('cyan', text)\n\n/** Bold text for headings and emphasis. */\nexport const bold = (text: string): string => c('bold', text)\n\n/** Log an array of hint lines in dim. */\nexport function printHints(lines: readonly string[], log: (msg: string) => void): void {\n for (const line of lines) {\n log(dim(line))\n }\n}\n\nconst BANNER = `\n ███████╗██╗ ██╗██████╗ █████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗\n ██╔════╝██║ ██║██╔══██╗██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝\n ███████╗██║ ██║██████╔╝███████║█████╗ ██║ ██║██████╔╝██║ ███╗█████╗\n ╚════██║██║ ██║██╔═══╝ ██╔══██║██╔══╝ ██║ ██║██╔══██╗██║ ██║██╔══╝\n ███████║╚██████╔╝██║ ██║ ██║██║ ╚██████╔╝██║ ██║╚██████╔╝███████╗\n ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝`\n\nconst TAGLINE = ' precision developer tools, built to last'\nconst CREDIT = 'by Akal'\n\n/** Minimum terminal width needed to render the full ASCII banner without wrapping. */\nconst BANNER_MIN_WIDTH = 80\n\n/** Print the SupaForge ASCII banner. Falls back to a compact header on narrow terminals. */\nexport function printBanner(log: (msg: string) => void): void {\n const cols = process.stdout.columns ?? BANNER_MIN_WIDTH\n if (cols >= BANNER_MIN_WIDTH) {\n log(c('greenBright', BANNER))\n } else {\n log(c('greenBright', '\\n ⚒ SupaForge'))\n }\n log(` ${dim(TAGLINE)} ${dim('·')} ${dim(CREDIT)}\\n`)\n}\n"],"mappings":";AACO,IAAM,yBAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;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OAAO,WAAW;AACvC,MAAI,QAAQ,kBAAkB;AAC5B,QAAI,EAAE,eAAe,MAAM,CAAC;AAAA,EAC9B,OAAO;AACL,QAAI,EAAE,eAAe,uBAAkB,CAAC;AAAA,EAC1C;AACA,MAAI,KAAK,IAAI,OAAO,CAAC,KAAK,IAAI,MAAG,CAAC,KAAK,IAAI,MAAM,CAAC;AAAA,CAAI;AACxD;","names":["c","readFile","resolve","resolve","readFile"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commands/migrate/run.ts"],"sourcesContent":["import { Flags } from '@oclif/core'\nimport { BaseCommand } from '../../base-command.js'\nimport {\n ensureMigrationsTable,\n getAppliedVersions,\n getPendingMigrations,\n runMigration,\n} from '../../migrate.js'\nimport { ok, warn, dim, bold } from '../../ui.js'\nimport { isDestructiveSql } from '../../dbdiff.js'\nimport { splitSqlStatements } from '../../utils/sql-split.js'\nimport { readFile } from 'node:fs/promises'\nimport { errMsg } from '../../utils/error.js'\n\n/**\n * Execute pending migrations against a Supabase environment.\n *\n * Reads local migration files, executes unapplied ones in order,\n * and records each in supabase_migrations.schema_migrations.\n *\n * Previews unless given `--apply`, like every other command that writes. It\n * used to be the one exception, executing unless given `--dry-run`, so the\n * habit every other command teaches — run it bare to see what it would do —\n * ran migrations against whichever environment was named. `--dry-run` is\n * still accepted, and still previews.\n *\n * Replaces `supabase db push` for self-hosted Supabase instances.\n */\nexport default class MigrateRun extends BaseCommand {\n static override description = 'Execute pending migrations against a Supabase environment'\n\n static override examples = [\n '<%= config.bin %> migrate run --env=prod',\n '<%= config.bin %> migrate run --env=prod --apply',\n '<%= config.bin %> migrate run --env=prod --up-to=003 --apply',\n ]\n\n static override flags = {\n env: Flags.string({\n char: 'e',\n description: 'Target environment to run migrations against',\n }),\n apply: Flags.boolean({\n description: 'Execute the pending migrations (previews without it)',\n default: false,\n exclusive: ['dry-run'],\n }),\n 'dry-run': Flags.boolean({\n description: 'Preview which migrations would run (the default; kept for existing scripts)',\n default: false,\n }),\n 'up-to': Flags.string({\n description: 'Stop after applying this migration version (inclusive)',\n }),\n 'allow-destructive': Flags.boolean({\n description: 'Permit migrations that drop tables or columns, delete rows, or drop policies',\n default: false,\n }),\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(MigrateRun)\n\n const config = await this.loadConfigOrFail()\n const { envName, env } = this.resolveEnv(config, flags.env)\n const dir = this.resolveMigrationsDir(config)\n\n // Preflight: verify database is reachable\n const pre = this.createPreflight('Migrate run preflight checks')\n .addDatabase('Target', envName, env.dbUrl)\n await this.runPreflight(pre, 'Migrate run')\n\n this.log(`${bold('migrate run')} → ${dim(envName)} (${dim(this.redactUrl(env.dbUrl))})\\n`)\n\n // The history is created only when migrations are applied: a preview\n // writes nothing, not even the table that records what ran.\n if (flags.apply) await ensureMigrationsTable(env.dbUrl)\n const applied = await getAppliedVersions(env.dbUrl)\n let pending = await getPendingMigrations(dir, applied)\n\n if (pending.length === 0) {\n this.log(`${ok('All migrations are up to date.')} ✓`)\n return\n }\n\n // Apply --up-to filter\n if (flags['up-to']) {\n const cutoff = flags['up-to']\n const idx = pending.findIndex(m => m.version === cutoff)\n if (idx === -1) {\n if (applied.has(cutoff)) {\n this.log(`${ok(`Version \"${cutoff}\" is already applied.`)} ✓`)\n return\n }\n this.error(`Version \"${cutoff}\" not found in pending migrations. Available: ${pending.map(m => m.version).join(', ')}`)\n }\n pending = pending.slice(0, idx + 1)\n }\n\n this.log(`Found ${bold(String(pending.length))} pending migration(s):\\n`)\n for (const m of pending) {\n this.log(` ${dim('○')} ${m.filename}`)\n }\n\n // A DROP TABLE in a migration file used to run with no opt-in at all,\n // while `diff --apply` held the same statement back (issue #88). The gate\n // is the same one, and the same flag opens it. Listed in the preview too,\n // so it is not first heard of when the apply refuses.\n const destructive = flags['allow-destructive'] ? [] : await findDestructiveStatements(pending)\n if (destructive.length > 0) {\n this.log('')\n this.log(warn(`${destructive.length} destructive statement(s) in the pending migrations:`))\n for (const { filename, sql } of destructive) {\n this.log(` ${warn('✗')} ${filename}`)\n this.log(` ${dim(truncateSql(sql))}`)\n }\n }\n\n if (!flags.apply) {\n this.log(`\\n${dim('Preview only — nothing was applied.')} Re-run with ${bold('--apply')} to execute`\n + (destructive.length > 0 ? `, and ${bold('--allow-destructive')} for the statements above.` : '.'))\n return\n }\n\n if (destructive.length > 0) {\n this.log(`\\n${warn('Nothing was applied.')} Re-run with ${bold('--allow-destructive')} to proceed.`)\n this.exit(1)\n }\n\n this.log('')\n\n // Execute migrations in order\n let applied_count = 0\n for (const migration of pending) {\n try {\n const result = await runMigration(env.dbUrl, migration)\n applied_count++\n this.log(` ${ok('✓')} ${result.filename} ${dim(`(${result.durationMs}ms)`)}`)\n } catch (err) {\n this.log(` ${warn('✗')} ${migration.filename}: ${err instanceof Error ? err.message : String(err)}`)\n this.log(`\\n${warn(`Stopped after ${applied_count} migration(s) due to error.`)}`)\n this.exit(1)\n }\n }\n\n this.log(`\\n${ok(`Applied ${applied_count} migration(s) successfully.`)} ✓`)\n }\n}\n\n/**\n * Destructive statements across a set of pending migration files.\n *\n * The SQL lives in the files rather than on the objects — `runMigration` reads\n * each one as it goes — so this reads them too. `readFileFn` is injectable for\n * the same reason `runMigration`'s is: so this can be tested without a\n * filesystem.\n *\n * Flat rather than grouped by file: the caller prints one line per statement,\n * and a migration with several destructive statements is worth seeing in full.\n * A file that cannot be read is not silently treated as safe — it is reported,\n * and `runMigration` will fail on it in a moment anyway.\n */\nexport async function findDestructiveStatements(\n migrations: Array<{ filename: string; path: string }>,\n readFileFn: (path: string) => Promise<string> = (path) => readFile(path, 'utf-8'),\n): Promise<Array<{ filename: string; sql: string }>> {\n const found: Array<{ filename: string; sql: string }> = []\n\n for (const migration of migrations) {\n let sql: string\n try {\n sql = await readFileFn(migration.path)\n } catch (err) {\n found.push({ filename: migration.filename, sql: `<unreadable: ${errMsg(err)}>` })\n continue\n }\n\n for (const statement of splitSqlStatements(sql)) {\n if (isDestructiveSql(statement)) {\n found.push({ filename: migration.filename, sql: statement })\n }\n }\n }\n\n return found\n}\n\n/**\n * One line of SQL for a listing, whatever the statement's shape.\n *\n * Comment lines are dropped first: the first statement of a file carries the\n * file's header, and a generated one its unit marker, which otherwise filled\n * the line before the statement began.\n */\nexport function truncateSql(sql: string): string {\n const oneLine = sql.split('\\n').filter(l => !/^\\s*--/.test(l)).join(' ').replace(/\\s+/g, ' ').trim()\n return oneLine.length > 100 ? `${oneLine.slice(0, 97)}...` : oneLine\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAWtB,SAAS,gBAAgB;AAiBzB,IAAqB,aAArB,MAAqB,oBAAmB,YAAY;AAAA,EAClD,OAAgB,cAAc;AAAA,EAE9B,OAAgB,WAAW;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,OAAgB,QAAQ;AAAA,IACtB,KAAK,MAAM,OAAO;AAAA,MAChB,MAAM;AAAA,MACN,aAAa;AAAA,IACf,CAAC;AAAA,IACD,OAAO,MAAM,QAAQ;AAAA,MACnB,aAAa;AAAA,MACb,SAAS;AAAA,MACT,WAAW,CAAC,SAAS;AAAA,IACvB,CAAC;AAAA,IACD,WAAW,MAAM,QAAQ;AAAA,MACvB,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,IACD,SAAS,MAAM,OAAO;AAAA,MACpB,aAAa;AAAA,IACf,CAAC;AAAA,IACD,qBAAqB,MAAM,QAAQ;AAAA,MACjC,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MAAqB;AACzB,UAAM,EAAE,MAAM,IAAI,MAAM,KAAK,MAAM,WAAU;AAE7C,UAAM,SAAS,MAAM,KAAK,iBAAiB;AAC3C,UAAM,EAAE,SAAS,IAAI,IAAI,KAAK,WAAW,QAAQ,MAAM,GAAG;AAC1D,UAAM,MAAM,KAAK,qBAAqB,MAAM;AAG5C,UAAM,MAAM,KAAK,gBAAgB,8B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AAa,YAAY;AAClC,QAAI;AACJ,QAAI;AACF,YAAM,MAAM,WAAW,UAAU,IAAI;AAAA,IACvC,SAAS,KAAK;AACZ,YAAM,KAAK,EAAE,UAAU,UAAU,UAAU,KAAK,gBAAgB,OAAO,GAAG,CAAC,IAAI,CAAC;AAChF;AAAA,IACF;AAEA,eAAW,aAAa,mBAAmB,GAAG,GAAG;AAC/C,UAAI,iBAAiB,SAAS,GAAG;AAC/B,cAAM,KAAK,EAAE,UAAU,UAAU,UAAU,KAAK,UAAU,CAAC;AAAA,MAC7D;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AASO,SAAS,YAAY,KAAqB;AAC/C,QAAM,UAAU,IAAI,MAAM,IAAI,EAAE,OAAO,OAAK,CAAC,SAAS,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,EAAE,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACnG,SAAO,QAAQ,SAAS,MAAM,GAAG,QAAQ,MAAM,GAAG,EAAE,CAAC,QAAQ;AAC/D;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/tips.ts"],"sourcesContent":["import { dim, cmd } from './ui.js'\nimport type { CheckName } from './types/drift.js'\nimport { CLONE_SKIP_FLAGS } from './defaults.js'\n\n// ─── Context ──────────────────────────────────────────────────────────────────\n\nexport interface TipContext {\n /** Which top-level command just ran. */\n command: 'diff' | 'clone' | 'snapshot' | 'restore'\n /** diff: total drift issues found. */\n driftTotal?: number\n /** diff: checks that had drift, in order of severity. */\n driftedChecks?: CheckName[]\n /** diff: checks that were skipped (via --skip or config). */\n skippedChecks?: CheckName[]\n /** diff: checks that failed to run. Drift is unknown for these. */\n erroredChecks?: CheckName[]\n /** diff: whether --detail was used. */\n detail?: boolean\n /** diff: whether --apply was used. */\n apply?: boolean\n /** diff: whether --check narrowed to a single check. */\n singleCheck?: CheckName\n /**\n * diff: whether the source environment is a local clone.\n *\n * Changes what `--apply` means. Clone → remote reshapes a shared environment\n * to match a vanilla-PostgreSQL copy, which includes dropping the roles,\n * grants and policies the clone never had — 227 of 601 findings on the diff\n * that prompted issue #48. Recommending it generically in that direction is\n * advice a first-time user should not follow.\n */\n sourceIsClone?: boolean\n /** clone: whether --apply completed successfully (not dry-run). */\n cloneApplied?: boolean\n /** clone: whether --schema-only was used. */\n schemaOnly?: boolean\n /** snapshot: whether --migration was used. */\n snapshotMigration?: boolean\n /** snapshot: whether --list was used. */\n snapshotList?: boolean\n}\n\n// ─── Tip type ─────────────────────────────────────────────────────────────────\n\ninterface Tip {\n text: string\n}\n\n// ─── Contextual tip pools ─────────────────────────────────────────────────────\n\n/**\n * How to word the `--apply` suggestion for this diff.\n *\n * From a clone it is a warning rather than a suggestion: the same command that\n * promotes local work to a remote will, run from a clone, push the clone's\n * *absences* to the remote too.\n */\nfunction applyTip(sourceIsClone: boolean | undefined, driftedChecks: CheckName[]): Tip {\n if (!sourceIsClone) {\n return { text: `Add ${cmd('--apply')} to push all fixes to the target in one shot.` }\n }\n const layer = driftedChecks[0] ?? 'schema'\n return {\n text:\n `Source is a local clone — ${cmd('--apply')} would reshape the target to match it, ` +\n `including dropping roles, grants and policies the clone never had. ` +\n `Scope it first: ${cmd(`--check=${layer} --apply --dry-run`)}.`,\n }\n}\n\nfunction diffTips(ctx: TipContext): Tip[] {\n const tips: Tip[] = []\n const { driftTotal = 0, driftedChecks = [], detail, apply, singleCheck, skippedChecks = [], erroredChecks = [], sourceIsClone } = ctx\n\n if (apply) {\n // Post-apply tips\n if (driftTotal > 0) {\n tips.push({ text: `Re-run ${cmd('supaforge diff')} to verify everything is clean.` })\n tips.push({ text: `Take a snapshot after a successful sync: ${cmd('supaforge snapshot')}.` })\n } else {\n tips.push({ text: `No drift to apply — run ${cmd('supaforge snapshot')} to lock in this clean state.` })\n }\n return tips\n }\n\n if (driftTotal > 0 && !detail) {\n // Summary mode with drift\n tips.push({ text: `Add ${cmd('--detail')} to see the full SQL for each issue.` })\n tips.push(applyTip(sourceIsClone, driftedChecks))\n if (driftedChecks.length > 1) {\n tips.push({ text: `Focus on one layer: ${cmd(`--check=${driftedChecks[0]}`)} to see just that check.` })\n }\n if (skippedChecks.length === 0) {\n tips.push({ text: `Post-clone? Use ${cmd(CLONE_SKIP_FLAGS)} to suppress clone-only noise, roles and grants included.` })\n }\n } else if (driftTotal > 0 && detail) {\n // Detail mode with drift\n tips.push(\n sourceIsClone\n ? applyTip(sourceIsClone, driftedChecks)\n : { text: `Run ${cmd('supaforge diff --apply')} to execute all the SQL fixes above.` },\n )\n if (driftedChecks.length > 1) {\n tips.push({ text: `Fix one layer at a time: ${cmd(`--check=${driftedChecks[0]} --apply`)}.` })\n }\n } else if (driftTotal === 0) {\n tips.push(...noDriftTips(erroredChecks, singleCheck))\n }\n\n return tips\n}\n\nfunction cloneTips(ctx: TipContext): Tip[] {\n if (!ctx.cloneApplied) {\n // Dry-run — hint to add --apply\n return [{ text: `Looks good? Add ${cmd('--apply')} to execute the clone.` }]\n }\n\n // Post-clone: most important tip is about skipping non-Postgres checks\n return [\n {\n text: `Diff against this clone with: ${cmd(`supaforge diff ${CLONE_SKIP_FLAGS}`)} — or add ${cmd('\"checks\": { \"exclude\": [...] }')} to config to make it permanent.`,\n },\n { text: `Restore from a snapshot any time: ${cmd('supaforge restore --env=local --from-snapshot=latest --apply')}.` },\n { text: `Run ${cmd('supaforge snapshot')} on the remote after a deploy to track incremental drift.` },\n ]\n}\n\nfunction snapshotTips(ctx: TipContext): Tip[] {\n if (ctx.snapshotList) {\n return [\n { text: `Clean up old snapshots with ${cmd('supaforge snapshot --prune')} (keeps last 7 by default).` },\n { text: `Restore into an environment: ${cmd('supaforge restore --env=local --from-snapshot=latest --apply')}.` },\n ]\n }\n if (ctx.snapshotMigration) {\n return [\n { text: `Migration files live in ${cmd('.supaforge/migrations/')} — commit them to version-control.` },\n { text: `Replay all migrations: ${cmd('supaforge restore --env=local --from-migrations --apply')}.` },\n ]\n }\n return [\n { text: `Add ${cmd('--migration')} to also generate an incremental diff against the previous snapshot.` },\n { text: `List all snapshots: ${cmd('supaforge snapshot --list')}.` },\n { text: `Restore this snapshot: ${cmd('supaforge restore --env=local --from-snapshot=latest --apply')}.` },\n ]\n}\n\nfunction restoreTips(_ctx: TipContext): Tip[] {\n return [\n { text: `After a restore, run ${cmd('supaforge diff')} to confirm the environment matches the source.` },\n { text: `Take a new snapshot to lock in the restored state: ${cmd('supaforge snapshot')}.` },\n ]\n}\n\n// ─── General tips pool (fallback) ────────────────────────────────────────────\n\nconst GENERAL_TIPS: Tip[] = [\n { text: `${cmd('supaforge hukam')} is an alias for ${cmd('diff')} — same flags, different vibe 🙏` },\n { text: `Use ${cmd('--source=X --target=Y')} to compare any two environments without editing config.` },\n { text: `Store credentials in ${cmd('.env')} — SupaForge auto-loads it. Config supports ${cmd('$VAR')} references.` },\n { text: `Add ${cmd('\"checks\": { \"exclude\": [\"storage\",\"vault\"] }')} to config to permanently skip noisy checks.` },\n { text: `Run ${cmd('supaforge diff --json')} for machine-readable output — useful in scripts and CI.` },\n { text: `Connect AI agents: add ${cmd('supaforge mcp')} to your Claude Desktop / Cursor MCP config.` },\n { text: `Enable row-level data drift: add ${cmd('\"checks\": { \"data\": { \"tables\": [\"plans\",\"flags\"] } }')} to config.` },\n { text: `${cmd('supaforge diff --include-files')} also checks file-level storage drift (checksums).` },\n { text: `${cmd('supaforge sync')} is shorthand for ${cmd('diff --apply')} — detects and fixes drift in one step.` },\n { text: `Preview an apply in dependency order without running it: ${cmd('supaforge diff --apply --dry-run')}.` },\n { text: `Apply a reviewed subset by id: ${cmd(\"supaforge diff --apply --only='schema-create-*'\")}.` },\n]\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Pick the most relevant tip for the current context.\n * Returns null when no tip applies (e.g. --json mode — caller should gate on that).\n */\n/**\n * Tips for a scan that found no drift.\n *\n * \"No drift\" and \"nothing was measured\" look identical in the totals but mean\n * opposite things, so they get different advice. Telling a user their\n * environments are in sync when the only check errored is the most actively\n * misleading output the tool can produce (issue #29).\n *\n * Extracted from pickTip rather than added as another branch: the extra\n * condition took that function from 17 to 21 cognitive complexity.\n */\nfunction noDriftTips(erroredChecks: CheckName[], singleCheck?: CheckName): Array<{ text: string }> {\n if (erroredChecks.length > 0) {\n const noun = erroredChecks.length === 1 ? 'check' : 'checks'\n const names = erroredChecks.join(', ')\n return [\n { text: `${erroredChecks.length} ${noun} could not run (${names}) — drift is unknown, not zero.` },\n { text: `Re-run with ${cmd('--detail')} to see why, then fix the cause before trusting this result.` },\n ]\n }\n\n const tips = [\n { text: `Environments are in sync — run ${cmd('supaforge snapshot')} to capture this state.` },\n { text: `Wire this into CI: ${cmd('supaforge diff')} exits 1 on critical drift.` },\n ]\n if (!singleCheck) {\n tips.push({ text: `Deep-dive a specific layer: ${cmd('supaforge diff --check=rls --detail')}.` })\n }\n return tips\n}\n\nexport function pickTip(ctx: TipContext, seed?: number): string | null {\n let pool: Tip[]\n\n switch (ctx.command) {\n case 'diff': pool = diffTips(ctx); break\n case 'clone': pool = cloneTips(ctx); break\n case 'snapshot': pool = snapshotTips(ctx); break\n case 'restore': pool = restoreTips(ctx); break\n default: pool = []\n }\n\n // Fall back to general pool if contextual pool is empty\n if (pool.length === 0) pool = GENERAL_TIPS\n\n // Mix in a general tip occasionally (every ~3 runs) when the contextual pool\n // is smaller than 3, so users see variety over time.\n if (pool.length < 3 && GENERAL_TIPS.length > 0) {\n const generalIdx = (seed ?? Date.now()) % GENERAL_TIPS.length\n pool = [...pool, GENERAL_TIPS[generalIdx]]\n }\n\n const idx = (seed ?? Date.now()) % pool.length\n const tip = pool[idx]\n return `\\n${dim('tip:')} ${tip.text}`\n}\n\n/** Format and return a tip line ready to log, or empty string if none. */\nexport function renderTip(ctx: TipContext): string {\n return pickTip(ctx) ?? ''\n}\n"],"mappings":";;;;;;;AA0DA,SAAS,SAAS,eAAoC,eAAiC;AACrF,MAAI,CAAC,eAAe;AAClB,WAAO,EAAE,MAAM,OAAO,IAAI,SAAS,CAAC,gDAAgD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M,uCAAkC,IAAI,oBAAoB,CAAC,0BAA0B;AAAA,IAC7F,EAAE,MAAM,sBAAsB,IAAI,gBAAgB,CAAC,8BAA8B;AAAA,EACnF;AACA,MAAI,CAAC,aAAa;AAChB,SAAK,KAAK,EAAE,MAAM,+BAA+B,IAAI,qCAAqC,CAAC,IAAI,CAAC;AAAA,EAClG;AACA,SAAO;AACT;AAEO,SAAS,QAAQ,KAAiB,MAA8B;AACrE,MAAI;AAEJ,UAAQ,IAAI,SAAS;AAAA,IACnB,KAAK;AAAY,aAAO,SAAS,GAAG;AAAO;AAAA,IAC3C,KAAK;AAAY,aAAO,UAAU,GAAG;AAAM;AAAA,IAC3C,KAAK;AAAY,aAAO,aAAa,GAAG;AAAG;AAAA,IAC3C,KAAK;AAAY,aAAO,YAAY,GAAG;AAAI;AAAA,IAC3C;AAAiB,aAAO,CAAC;AAAA,EAC3B;AAGA,MAAI,KAAK,WAAW,EAAG,QAAO;AAI9B,MAAI,KAAK,SAAS,KAAK,aAAa,SAAS,GAAG;AAC9C,UAAM,cAAc,QAAQ,KAAK,IAAI,KAAK,aAAa;AACvD,WAAO,CAAC,GAAG,MAAM,aAAa,UAAU,CAAC;AAAA,EAC3C;AAEA,QAAM,OAAO,QAAQ,KAAK,IAAI,KAAK,KAAK;AACxC,QAAM,MAAM,KAAK,GAAG;AACpB,SAAO;AAAA,EAAK,IAAI,MAAM,CAAC,IAAI,IAAI,IAAI;AACrC;AAGO,SAAS,UAAU,KAAyB;AACjD,SAAO,QAAQ,GAAG,KAAK;AACzB;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/strings.ts"],"sourcesContent":["/**\n * Shared string manipulation utilities.\n */\n\n/** Maximum length for generated slugs. */\nconst MAX_SLUG_LENGTH = 60\n\n/**\n * Convert a human-readable string to a filename-safe slug.\n * Lowercases, replaces non-alphanumeric chars with separator, trims edges.\n */\nexport function slugify(name: string, separator = '_'): string {\n const pattern = new RegExp(`[^a-z0-9]+`, 'g')\n const edgePattern = new RegExp(`^${escapeRegex(separator)}|${escapeRegex(separator)}$`, 'g')\n return name\n .toLowerCase()\n .replace(pattern, separator)\n .replace(edgePattern, '')\n .slice(0, MAX_SLUG_LENGTH)\n}\n\n/** Escape every regex metacharacter, so a value can be matched literally. */\nexport function escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Split a repeatable CLI flag into individual values.\n *\n * `--x=a,b --x=c` and `--x=a --x=b --x=c` mean the same thing; oclif hands over\n * the raw strings, and a comma is the natural separator for the lists these\n * flags take — table names, issue ids — none of which can contain one.\n */\nexport function parseFlagList(values?: string[]): string[] {\n if (!Array.isArray(values)) return []\n return values\n .flatMap(v => String(v).split(','))\n .map(v => v.trim())\n .filter(v => v.length > 0)\n}\n\n/**\n * Compile a `*`/`?` glob to an anchored regular expression.\n *\n * The same two wildcards `@dbdiff/cli` supports, so a pattern means one thing\n * whether it reaches dbdiff or is matched here. Every other character is\n * escaped, so a value containing regex metacharacters cannot turn a filter into\n * a different pattern. Both are linear: the pattern is anchored and has no\n * nested quantifiers.\n */\nexport function globToRegExp(pattern: string): RegExp {\n let out = '^'\n for (const ch of pattern) {\n if (ch === '*') out += '.*'\n else if (ch === '?') out += '.'\n else out += escapeRegex(ch)\n }\n return new RegExp(out + '$')\n}\n\n/** Does `value` match a `*`/`?` glob? Case-insensitive. */\nexport function matchesGlob(value: string, pattern: string): boolean {\n return globToRegExp(pattern.toLowerCase()).test(value.toLowerCase())\n}\n\n/**\n * Parse Postgres name[] which may arrive as a JS array or Postgres literal `{a,b}`.\n * Returns a sorted, deduplicated array of role names.\n *\n * An element with a space, comma or quote in it is double-quoted in the\n * literal, with `\\\\` escaping a quote or backslash: `{\"Admins \\\\\"A\\\\\"\",anon}`.\n * Split on commas, such a role kept its literal quoting and was then quoted\n * again as a name, so the policy went to a role that did not exist.\n */\nexport function normalizeRoles(roles: string[] | string): string[] {\n const arr = Array.isArray(roles) ? roles : [roles]\n return [...new Set(\n arr\n .flatMap(r => /^\\{.*\\}$/s.test(r) ? arrayLiteralElements(r) : [r])\n .map(r => r.trim())\n .filter(Boolean),\n )].sort()\n}\n\n/** The elements of a one-dimensional PostgreSQL array literal. */\nfunction arrayLiteralElements(literal: string): string[] {\n const inner = literal.slice(1, -1)\n const out: string[] = []\n let i = 0\n while (i < inner.length) {\n let value = ''\n if (inner[i] === '\"') {\n for (i++; i < inner.length && inner[i] !== '\"'; i++) {\n if (inner[i] === '\\\\') i++\n value += inner[i]\n }\n i++\n } else {\n const end = inner.indexOf(',', i)\n value = inner.slice(i, end === -1 ? inner.length : end)\n i = end === -1 ? inner.length : end\n }\n out.push(value)\n if (inner[i] === ',') i++\n }\n return out\n}\n"],"mappings":";AAKA,IAAM,kBAAkB;AAMjB,SAAS,QAAQ,MAAc,YAAY,KAAa;AAC7D,QAAM,UAAU,IAAI,OAAO,cAAc,GAAG;AAC5C,QAAM,cAAc,IAAI,OAAO,IAAI,YAAY,SAAS,CAAC,IAAI,YAAY,SAAS,CAAC,KAAK,GAAG;AAC3F,SAAO,KACJ,YAAY,EACZ,QAAQ,SAAS,SAAS,EAC1B,QAAQ,aAAa,EAAE,EACvB,MAAM,GAAG,eAAe;AAC7B;AAGO,SAAS,YAAY,GAAmB;AAC7C,SAAO,EAAE,QAAQ,uBAAuB,MAAM;AAChD;AASO,SAAS,cAAc,QAA6B;AACzD,MAAI,CAAC,MAAM,QAAQ,MAAM,EAAG,QAAO,CAAC;AACpC,SAAO,OACJ,QAAQ,OAAK,OAAO,CAAC,EAAE,MAAM,GAAG,CAAC,EACjC,IAAI,OAAK,EAAE,KAAK,CAAC,EACjB,OAAO,OAAK,EAAE,SAAS,CAAC;AAC7B;AAWO,SAAS,aAAa,SAAyB;AACpD,MAAI,MAAM;AACV,aAAW,MAAM,SAAS;AACxB,QAAI,OAAO,IAAK,QAAO;AAAA,aACd,OAAO,IAAK,QAAO;AAAA,QACvB,QAAO,YAAY,EAAE;AAAA,EAC5B;AACA,SAAO,IAAI,OAAO,MAAM,GAAG;AAC7B;AAGO,SAAS,YAAY,OAAe,SAA0B;AACnE,SAAO,aAAa,QAAQ,YAAY,CAAC,EAAE,KAAK,MAAM,YAAY,CAAC;AACrE;AAWO,SAAS,eAAe,OAAoC;AACjE,QAAM,MAAM,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;AACjD,SAAO,CAAC,GAAG,IAAI;AAAA,IACb,IACG,QAAQ,OAAK,YAAY,KAAK,CAAC,IAAI,qBAAqB,CAAC,IAAI,CAAC,CAAC,CAAC,EAChE,IAAI,OAAK,EAAE,KAAK,CAAC,EACjB,OAAO,OAAO;AAAA,EACnB,CAAC,EAAE,KAAK;AACV;AAGA,SAAS,qBAAqB,SAA2B;AACvD,QAAM,QAAQ,QAAQ,MAAM,GAAG,EAAE;AACjC,QAAM,MAAgB,CAAC;AACvB,MAAI,IAAI;AACR,SAAO,IAAI,MAAM,QAAQ;AACvB,QAAI,QAAQ;AACZ,QAAI,MAAM,CAAC,MAAM,KAAK;AACpB,WAAK,KAAK,IAAI,MAAM,UAAU,MAAM,CAAC,MAAM,KAAK,KAAK;AACnD,YAAI,MAAM,CAAC,MAAM,KAAM;AACvB,iBAAS,MAAM,CAAC;AAAA,MAClB;AACA;AAAA,IACF,OAAO;AACL,YAAM,MAAM,MAAM,QAAQ,KAAK,CAAC;AAChC,cAAQ,MAAM,MAAM,GAAG,QAAQ,KAAK,MAAM,SAAS,GAAG;AACtD,UAAI,QAAQ,KAAK,MAAM,SAAS;AAAA,IAClC;AACA,QAAI,KAAK,KAAK;AACd,QAAI,MAAM,CAAC,MAAM,IAAK;AAAA,EACxB;AACA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/sql-split.ts"],"sourcesContent":["/**\n * Splitting SQL text into statements.\n *\n * Kept apart from the quoting helpers in `sql.ts` because this is a scanner\n * rather than an escaper, and it is only needed where SQL arrives from outside\n * — a pg_dump, a migration file — rather than being generated here.\n */\n\n/** `$$` or `$tag$`, anchored at the current position. */\nconst DOLLAR_TAG = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/\n\n/**\n * Split SQL into individual statements.\n *\n * Splitting on `;` alone breaks the moment the SQL contains a routine body: a\n * `CREATE FUNCTION ... AS $$ BEGIN ... ; ... END; $$;` is shredded into three\n * fragments, none of which parse, and whatever depends on the function fails\n * after them. That is what `restore` did to a pg_dump's functions and their\n * triggers (issue #80).\n *\n * The text is walked once, tracking the four things that can hold a semicolon\n * without ending a statement:\n *\n * - `'single quoted'`, where `''` is an escaped quote and not a close\n * - `\"quoted identifiers\"`, same doubling rule\n * - `$tag$ dollar quoted $tag$`, which is how routine bodies arrive\n * - line comments, and block comments, which nest in PostgreSQL\n *\n * Statements come back trimmed with the trailing `;` removed, and empty\n * fragments dropped. Comments are left in place: they are part of the\n * statement's text, and a caller wanting a bare statement can say so.\n */\nexport function splitSqlStatements(sql: string): string[] {\n const statements: string[] = []\n let start = 0\n let i = 0\n let blockDepth = 0\n\n const push = (end: number) => {\n const piece = sql.slice(start, end).trim()\n if (piece.length > 0) statements.push(piece)\n }\n\n while (i < sql.length) {\n if (blockDepth > 0) {\n if (sql.startsWith('/*', i)) { blockDepth++; i += 2; continue }\n if (sql.startsWith('*/', i)) { blockDepth--; i += 2; continue }\n i++\n continue\n }\n\n if (sql.startsWith('/*', i)) { blockDepth = 1; i += 2; continue }\n\n if (sql.startsWith('--', i)) {\n const newline = sql.indexOf('\\n', i)\n i = newline === -1 ? sql.length : newline + 1\n continue\n }\n\n const ch = sql[i]\n\n if (ch === \"'\" || ch === '\"') {\n i++\n while (i < sql.length) {\n if (sql[i] !== ch) { i++; continue }\n // A doubled quote is an escape, not the end of the run.\n if (sql[i + 1] === ch) { i += 2; continue }\n i++\n break\n }\n continue\n }\n\n if (ch === '$') {\n const tag = DOLLAR_TAG.exec(sql.slice(i))\n if (tag) {\n const close = sql.indexOf(tag[0], i + tag[0].length)\n i = close === -1 ? sql.length : close + tag[0].length\n continue\n }\n i++\n continue\n }\n\n if (ch === ';') {\n push(i)\n i++\n start = i\n continue\n }\n\n i++\n }\n\n push(sql.length)\n return statements\n}\n\n/** Whether a statement is nothing but comments and whitespace. */\nexport function isCommentOnly(statement: string): boolean {\n const meaningful = statement\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0 && !line.startsWith('--'))\n return meaningful.length === 0\n}\n\n/**\n * The `\\restrict` / `\\unrestrict` wrappers pg_dump 16 and later emit.\n *\n * Matched as whole lines, and only these two commands rather than anything\n * beginning with a backslash: a line inside a dollar-quoted routine body could\n * start with one, and rewriting a function's body would be worse than the\n * problem being solved.\n */\nconst PSQL_WRAPPER_LINE = /^[ \\t]*\\\\(?:un)?restrict\\b[^\\n]*$/gm\n\n/**\n * Remove psql meta-commands, which only psql understands.\n *\n * Done to the text *before* it is split, because these commands are terminated\n * by the end of the line rather than by a semicolon. Dropping them afterwards\n * as whole statements took the following statement with them — `\\restrict abc`\n * and the `CREATE TABLE` under it are one fragment when nothing separates them\n * (issue #80). Sent to the server they fail with `syntax error at or near \"\\\"`.\n */\nexport function stripPsqlMetaCommands(sql: string): string {\n return sql.replace(PSQL_WRAPPER_LINE, '')\n}\n\n/**\n * Whether a statement is nothing but psql meta-commands and comments.\n *\n * A safety net for anything `stripPsqlMetaCommands` does not cover. It\n * deliberately requires *every* meaningful line to be a meta-command, so a\n * statement that also carries SQL is never discarded wholesale.\n */\nexport function isPsqlMetaCommand(statement: string): boolean {\n const meaningful = statement\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0 && !line.startsWith('--'))\n\n return meaningful.length > 0 && meaningful.every(line => line.startsWith('\\\\'))\n}\n"],"mappings":";AASA,IAAM,aAAa;AAuBZ,SAAS,mBAAmB,KAAuB;AACxD,QAAM,aAAuB,CAAC;AAC9B,MAAI,QAAQ;AACZ,MAAI,IAAI;AACR,MAAI,aAAa;AAEjB,QAAM,OAAO,CAAC,Q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F;AAEA,OAAK,IAAI,MAAM;AACf,SAAO;AACT;AAGO,SAAS,cAAc,WAA4B;AACxD,QAAM,aAAa,UAChB,MAAM,IAAI,EACV,IAAI,UAAQ,KAAK,KAAK,CAAC,EACvB,OAAO,UAAQ,KAAK,SAAS,KAAK,CAAC,KAAK,WAAW,IAAI,CAAC;AAC3D,SAAO,WAAW,WAAW;AAC/B;AAUA,IAAM,oBAAoB;AAWnB,SAAS,sBAAsB,KAAqB;AACzD,SAAO,IAAI,QAAQ,mBAAmB,EAAE;AAC1C;AASO,SAAS,kBAAkB,WAA4B;AAC5D,QAAM,aAAa,UAChB,MAAM,IAAI,EACV,IAAI,UAAQ,KAAK,KAAK,CAAC,EACvB,OAAO,UAAQ,KAAK,SAAS,KAAK,CAAC,KAAK,WAAW,IAAI,CAAC;AAE3D,SAAO,WAAW,SAAS,KAAK,WAAW,MAAM,UAAQ,KAAK,WAAW,IAAI,CAAC;AAChF;","names":[]}
@@ -1,16 +0,0 @@
1
- // src/pg-errors.ts
2
- var ABSENT_ON_TARGET = /* @__PURE__ */ new Set(["42P01", "42883", "3F000", "42704"]);
3
- var UNDEFINED_COLUMN = "42703";
4
- var EXTENSION_UNAVAILABLE = /* @__PURE__ */ new Set(["0A000", "58P01"]);
5
- function sqlState(err) {
6
- const code = err?.code;
7
- return typeof code === "string" ? code : void 0;
8
- }
9
-
10
- export {
11
- ABSENT_ON_TARGET,
12
- UNDEFINED_COLUMN,
13
- EXTENSION_UNAVAILABLE,
14
- sqlState
15
- };
16
- //# sourceMappingURL=chunk-H5MJ5DFX.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/pg-errors.ts"],"sourcesContent":["/**\n * SQLSTATEs for \"that does not exist here\": a relation, function, schema or\n * other object the statement names is missing from the database it ran on.\n */\nexport const ABSENT_ON_TARGET: ReadonlySet<string> = new Set(['42P01', '42883', '3F000', '42704'])\n\n/** A column the statement names is missing. */\nexport const UNDEFINED_COLUMN = '42703'\n\n/** SQLSTATEs for an extension the server does not ship. */\nexport const EXTENSION_UNAVAILABLE: ReadonlySet<string> = new Set(['0A000', '58P01'])\n\n/** The SQLSTATE of a PostgreSQL error, if it is one. */\nexport function sqlState(err: unknown): string | undefined {\n const code = (err as { code?: unknown } | null)?.code\n return typeof code === 'string' ? code : undefined\n}\n"],"mappings":";AAIO,IAAM,mBAAwC,oBAAI,IAAI,CAAC,SAAS,SAAS,SAAS,OAAO,CAAC;AAG1F,IAAM,mBAAmB;AAGzB,IAAM,wBAA6C,oBAAI,IAAI,CAAC,SAAS,OAAO,CAAC;AAG7E,SAAS,SAAS,KAAkC;AACzD,QAAM,OAAQ,KAAmC;AACjD,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/migration.ts"],"sourcesContent":["import { mkdir, writeFile, readFile, readdir } from 'node:fs/promises'\nimport { join, resolve } from 'node:path'\nimport type { MigrationFile, MigrationAction, SnapshotManifest } from './types/config'\nimport { loadSnapshot, findLatestSnapshot, captureSnapshot, generateTimestamp, type SnapshotOptions, type SnapshotResult } from './snapshot'\nimport { SUPAFORGE_DIR, MIGRATIONS_SUBDIR } from './constants'\nimport { splitSqlStatements, isCommentOnly } from './utils/sql-split.js'\nimport { slugify } from './utils/strings'\n\nexport interface BackupOptions extends Omit<SnapshotOptions, 'cwd'> {\n cwd?: string\n description?: string\n}\n\nexport interface BackupResult {\n snapshot: SnapshotResult\n migration: MigrationFile | null\n migrationFile: string | null\n /** True if this is the first snapshot (baseline, no diff possible). */\n isBaseline: boolean\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction migrationsDir(cwd: string): string {\n return resolve(cwd, SUPAFORGE_DIR, MIGRATIONS_SUBDIR)\n}\n\n// ─── Backup: Snapshot + Diff ─────────────────────────────────────────────────\n\n/**\n * Create a backup: capture a new snapshot and generate a migration file\n * containing the diff against the previous snapshot.\n *\n * If no previous snapshot exists, the migration is a \"baseline\" containing\n * the full state.\n */\nexport async function backup(options: BackupOptions): Promise<BackupResult> {\n const cwd = options.cwd ?? process.cwd()\n\n // Find previous snapshot for diffing\n const previousDir = await findLatestSnapshot(cwd)\n const previousManifest = previousDir ? await loadSnapshot(previousDir) : null\n\n // Capture new snapshot\n const snapshot = await captureSnapshot({ ...options, cwd })\n\n // Generate migration\n const description = options.description ?? 'auto-backup'\n const isBaseline = !previousManifest\n\n const migration = isBaseline\n ? await generateBaselineMigration(snapshot, cwd, description)\n : await generateDiffMigration(previousDir!, snapshot, cwd, description)\n\n let migrationFile: string | null = null\n if (migration) {\n const mDir = migrationsDir(cwd)\n await mkdir(mDir, { recursive: true })\n const filename = `${snapshot.timestamp}_${slugify(description, '-')}.json`\n migrationFile = join(mDir, filename)\n await writeFile(migrationFile, JSON.stringify(migration, null, 2) + '\\n')\n }\n\n return { snapshot, migration, migrationFile, isBaseline }\n}\n\n// ─── Migration Generation ────────────────────────────────────────────────────\n\nasync function generateBaselineMigration(\n snapshot: SnapshotResult,\n cwd: string,\n description: string,\n): Promise<MigrationFile> {\n const sqlUp: string[] = []\n const sqlDown: string[] = []\n const apiUp: MigrationAction[] = []\n const layers: string[] = []\n\n // Read each captured layer and add to migration\n for (const [layer, info] of Object.entries(snapshot.manifest.layers)) {\n if (!info.captured) continue\n layers.push(layer)\n\n if (layer === 'auth' || layer === 'edge-functions') {\n // API-based layers store JSON — convert to actions\n continue // Auth/edge-functions require project ref at apply time; stored in snapshot\n }\n\n if (layer === 'storage' && info.file === 'storage-buckets.json') {\n // Storage buckets — API-based, stored in snapshot\n continue\n }\n\n // SQL-based layers\n if (info.file.endsWith('.sql')) {\n try {\n const content = await readFile(join(snapshot.dir, info.file), 'utf-8')\n const statements = extractStatements(content)\n if (statements.length > 0) {\n sqlUp.push(...statements)\n }\n } catch { /* skip */ }\n }\n }\n\n return {\n version: snapshot.timestamp,\n description: `baseline: ${description}`,\n parent: null,\n layers,\n up: { sql: sqlUp, api: apiUp },\n down: { sql: sqlDown, api: [] },\n }\n}\n\nasync function generateDiffMigration(\n previousDir: string,\n snapshot: SnapshotResult,\n _cwd: string,\n description: string,\n): Promise<MigrationFile | null> {\n const previousManifest = await loadSnapshot(previousDir)\n const sqlUp: string[] = []\n const sqlDown: string[] = []\n const apiUp: MigrationAction[] = []\n const apiDown: MigrationAction[] = []\n const layers: string[] = []\n\n // Compare SQL-based layers\n for (const layer of ['rls', 'cron', 'webhooks', 'extensions', 'storage-policies'] as const) {\n const file = layerToFile(layer)\n const prevFile = layerToFile(layer)\n\n try {\n const prevContent = await readFile(join(previousDir, prevFile), 'utf-8').catch(() => '')\n const newContent = await readFile(join(snapshot.dir, file), 'utf-8').catch(() => '')\n\n if (prevContent === newContent) continue\n\n const prevStatements = new Set(extractStatements(prevContent))\n const newStatements = new Set(extractStatements(newContent))\n\n const added = [...newStatements].filter(s => !prevStatements.has(s))\n const removed = [...prevStatements].filter(s => !newStatements.has(s))\n\n if (added.length > 0 || removed.length > 0) {\n layers.push(layer === 'storage-policies' ? 'storage' : layer)\n\n // Both directions get the inverse of the other's changes.\n //\n // `up` was the added statements alone and `down` the removed ones, so\n // each direction only did half its job: applying a migration that\n // *removed* a policy did not drop it, and reverting one that *added*\n // a policy left it in place (issue #92). Undoing either is mechanical\n // for these layers — a cron job is unscheduled, a policy, trigger or\n // extension is dropped — and `inverseStatement` returns null rather\n // than guessing for anything else.\n sqlUp.push(...added)\n for (const statement of removed) {\n const inverse = inverseStatement(statement)\n if (inverse) sqlUp.push(inverse)\n }\n\n sqlDown.push(...removed)\n for (const statement of added) {\n const inverse = inverseStatement(statement)\n if (inverse) sqlDown.push(inverse)\n }\n }\n } catch { /* skip */ }\n }\n\n // Compare JSON-based layers (auth, storage buckets, edge functions)\n for (const layer of ['auth', 'storage-buckets', 'edge-functions'] as const) {\n const file = layerToFile(layer)\n try {\n const prevContent = await readFile(join(previousDir, file), 'utf-8').catch(() => '{}')\n const newContent = await readFile(join(snapshot.dir, file), 'utf-8').catch(() => '{}')\n\n if (prevContent === newContent) continue\n layers.push(layer === 'storage-buckets' ? 'storage' : layer)\n // Store the full new state as an API action — detailed diffing happens at apply time\n } catch { /* skip */ }\n }\n\n // Compare schema.json (diff by content change)\n try {\n const prevSchema = await readFile(join(previousDir, 'schema.json'), 'utf-8').catch(() => '')\n const newSchema = await readFile(join(snapshot.dir, 'schema.json'), 'utf-8').catch(() => '')\n if (prevSchema !== newSchema) {\n layers.push('schema')\n // No DDL here, and this says so rather than looking like a statement.\n //\n // Deriving a migration from two introspection documents means writing a\n // schema differ, which is what @dbdiff/cli already is — and it wants two\n // live databases, not two JSON files. What this *can* do is say which\n // objects moved, so the reader knows where to look instead of being told\n // only that something changed (issue #92).\n sqlUp.push(...schemaChangeNotes(prevSchema, newSchema))\n }\n } catch { /* skip */ }\n\n return {\n version: snapshot.timestamp,\n description,\n parent: previousManifest.timestamp,\n layers: [...new Set(layers)],\n up: { sql: sqlUp, api: apiUp },\n down: { sql: sqlDown, api: apiDown },\n }\n}\n\n// ─── Migration Reading ───────────────────────────────────────────────────────\n\n/** Load all migration files in timestamp order. */\nexport async function loadMigrations(cwd = process.cwd()): Promise<MigrationFile[]> {\n const dir = migrationsDir(cwd)\n try {\n const entries = await readdir(dir)\n const jsonFiles = entries.filter(e => e.endsWith('.json')).sort()\n const migrations: MigrationFile[] = []\n for (const file of jsonFiles) {\n const raw = await readFile(join(dir, file), 'utf-8')\n migrations.push(JSON.parse(raw) as MigrationFile)\n }\n return migrations\n } catch {\n return []\n }\n}\n\n/** List migration files with metadata. */\nexport async function listMigrationFiles(cwd = process.cwd()): Promise<{ file: string; version: string; description: string; layers: string[] }[]> {\n const dir = migrationsDir(cwd)\n try {\n const entries = await readdir(dir)\n const jsonFiles = entries.filter(e => e.endsWith('.json')).sort()\n const results: { file: string; version: string; description: string; layers: string[] }[] = []\n for (const file of jsonFiles) {\n const raw = await readFile(join(dir, file), 'utf-8')\n const m = JSON.parse(raw) as MigrationFile\n results.push({ file, version: m.version, description: m.description, layers: m.layers })\n }\n return results\n } catch {\n return []\n }\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction layerToFile(layer: string): string {\n switch (layer) {\n case 'rls': return 'rls.sql'\n case 'cron': return 'cron.sql'\n case 'webhooks': return 'webhooks.sql'\n case 'extensions': return 'extensions.sql'\n case 'storage-policies': return 'storage-policies.sql'\n case 'auth': return 'auth.json'\n case 'storage-buckets': return 'storage-buckets.json'\n case 'edge-functions': return 'edge-functions.json'\n default: return `${layer}.sql`\n }\n}\n\n/** Extract executable SQL statements from a snapshot file (skips comments). */\n/**\n * The statements in a snapshot layer file.\n *\n * Split on `;\\n` and then discarded any chunk beginning with `--`. Every layer\n * file opens with a `-- SupaForge … Snapshot` header, and that header lands in\n * the same chunk as the *first* statement — so the first statement of every\n * layer was thrown away with it (issue #92). Adding or removing the\n * alphabetically-first cron job, policy, webhook or extension was invisible,\n * and the previous first statement then appeared as newly added.\n *\n * Uses the same scanner `restore` does: it respects dollar-quoted bodies and\n * drops only chunks that are genuinely nothing but comments.\n */\nfunction extractStatements(content: string): string[] {\n if (!content) return []\n\n return splitSqlStatements(content)\n .filter(statement => !isCommentOnly(statement))\n .map(stripLeadingComments)\n .filter(statement => statement.length > 0)\n .map(statement => statement.endsWith(';') ? statement : `${statement};`)\n}\n\n/**\n * A statement without the comment lines above it.\n *\n * The header a layer file opens with carries a count — `-- 2 policies` — and\n * the splitter keeps a comment attached to the statement that follows it. So\n * the first statement of every file would differ between two snapshots\n * whenever the count changed, and be reported as both added and removed even\n * though nothing about it moved. Comparing the SQL alone is what makes the\n * diff mean anything.\n */\nfunction stripLeadingComments(statement: string): string {\n const lines = statement.split('\\n')\n let start = 0\n\n while (start < lines.length) {\n const line = lines[start].trim()\n if (line === '' || line.startsWith('--')) {\n start++\n continue\n }\n break\n }\n\n return lines.slice(start).join('\\n').trim()\n}\n\n/**\n * The statement that undoes `statement`, where that is mechanical.\n *\n * Only for the shapes a snapshot layer emits: a scheduled cron job, a policy,\n * a trigger, an extension. Anything else returns null rather than a guess —\n * a wrong inverse in a `down` is worse than an absent one, because it looks\n * like a revert and is not.\n */\nexport function inverseStatement(statement: string): string | null {\n const sql = statement.trim()\n\n const cron = /\\bcron\\.schedule\\s*\\(\\s*('(?:[^']|'')*')/i.exec(sql)\n if (cron) return `SELECT cron.unschedule(${cron[1]});`\n\n const policy = /\\bCREATE\\s+POLICY\\s+(\"[^\"]+\"|[\\w$]+)\\s+ON\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\s*\\.\\s*(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (policy) return `DROP POLICY IF EXISTS ${policy[1]} ON ${policy[2]};`\n\n const trigger = /\\bCREATE\\s+TRIGGER\\s+(\"[^\"]+\"|[\\w$]+)[\\s\\S]*?\\bON\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\s*\\.\\s*(?:\"[^\"]+\"|[\\w$]+))?)/i.exec(sql)\n if (trigger) return `DROP TRIGGER IF EXISTS ${trigger[1]} ON ${trigger[2]};`\n\n const extension = /\\bCREATE\\s+EXTENSION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\"[^\"]+\"|[\\w$]+)/i.exec(sql)\n if (extension) return `DROP EXTENSION IF EXISTS ${extension[1]};`\n\n return null\n}\n\n/**\n * What changed between two schema introspections, as comment lines.\n *\n * Not SQL, and shaped so it cannot be mistaken for any: the migration's schema\n * layer carries no DDL, and the previous single line — \"Schema changed. Use\n * @dbdiff/cli to generate migration SQL.\" — told the reader nothing about\n * *what* changed (issue #92).\n */\nexport function schemaChangeNotes(previousJson: string, currentJson: string): string[] {\n const notes = [\n '-- The schema changed. This migration carries no DDL for it: deriving one',\n '-- from two introspection documents is what @dbdiff/cli does, and it needs',\n '-- two live databases. Generate it with `supaforge migrate create`.',\n ]\n\n try {\n const before = JSON.parse(previousJson) as Record<string, Array<{ schema?: string; name?: string }>>\n const after = JSON.parse(currentJson) as Record<string, Array<{ schema?: string; name?: string }>>\n\n for (const kind of ['tables', 'views', 'functions', 'triggers', 'sequences', 'enums']) {\n const names = (list?: Array<{ schema?: string; name?: string }>) =>\n new Set((list ?? []).map(o => `${o.schema ?? 'public'}.${o.name ?? '?'}`))\n\n const from = names(before[kind])\n const to = names(after[kind])\n\n const added = [...to].filter(n => !from.has(n)).sort()\n const removed = [...from].filter(n => !to.has(n)).sort()\n\n if (added.length > 0) notes.push(`-- ${kind} added: ${added.join(', ')}`)\n if (removed.length > 0) notes.push(`-- ${kind} removed: ${removed.join(', ')}`)\n }\n } catch {\n // An unreadable document just means no detail to add.\n }\n\n return notes\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,WAAW,UAAU,eAAe;AACpD,SAAS,MAAM,eAAe;AAsB9B,SAAS,cAAc,KAAqB;AAC1C,SAAO,QAAQ,KAAK,eAAe,iBAAiB;AACtD;AAWA,eAAsB,OAAO,SAA+C;AAC1E,QAAM,MAAM,QAAQ,OAAO,QAAQ,IAAI;AAGvC,QAAM,cAAc,MAAM,mBAAmB,GAAG;AAChD,QAAM,mBAAmB,cAAc,MAAM,aAAa,WAAW,IAAI;AAGzE,QAAM,WAAW,MAAM,gBAAgB,EAAE,GAAG,SAAS,IAAI,CAAC;AAG1D,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,aAAa,CAAC;AAEpB,QAAM,YAAY,aACd,MAAM,0BAA0B,UAAU,KAAK,WAAW,IAC1D,MAAM,sBAAsB,aAAc,UAAU,KAAK,WAAW;AAExE,MAAI,gBAA+B;AACnC,MAAI,WAAW;AACb,UAAM,OAAO,cAAc,GAAG;AAC9B,UAAM,MAAM,MAAM,EAAE,WAAW,KAAK,CAAC;AACrC,UAAM,WAAW,GAAG,SAAS,SAAS,IAAI,QAAQ,aAAa,GAAG,CAAC;AACnE,oBAAgB,KAAK,MAAM,QAAQ;AACnC,UAAM,UAAU,eAAe,KAAK,UAAU,WAAW,MAAM,CAAC,IAAI,IAAI;AAAA,EAC1E;AAEA,SAA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CAAC,CAAC,EAAE,KAAK;AAEvD,UAAI,MAAM,SAAS,EAAG,OAAM,KAAK,QAAQ,IAAI,aAAa,MAAM,KAAK,IAAI,CAAC,EAAE;AAC5E,UAAI,QAAQ,SAAS,EAAG,OAAM,KAAK,QAAQ,IAAI,aAAa,QAAQ,KAAK,IAAI,CAAC,EAAE;AAAA,IAClF;AAAA,EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/render.ts"],"sourcesContent":["import type { ScanResult, CheckResult, DriftIssue } from './types/drift'\nimport { CHECK_META, isComparisonCheck } from './types/drift'\nimport { CHECK_LINE_PADDING } from './constants'\nimport { ok, warn, dim, bold, c } from './ui'\n\n/**\n * Number of checks that failed to run.\n *\n * Defensive against a malformed or partial ScanResult — an older cached\n * report, or a hand-built object in a hook — where `checks` may be missing\n * or not an array. Reporting zero errored checks is the safe fallback for\n * rendering; it never invents an error that is not there.\n */\nexport function countErrored(result: Pick<ScanResult, 'checks'>): number {\n if (!Array.isArray(result?.checks)) return 0\n return result.checks.filter(c => c?.status === 'error').length\n}\n\n/**\n * Number of checks that declined to run.\n *\n * A skipped layer was rendered identically to a clean one, so fourteen green\n * ticks could mean eleven comparisons and three layers that never opened a\n * connection (issue #42). Same defensive handling as countErrored.\n */\nexport function countSkipped(result: Pick<ScanResult, 'checks'>): number {\n if (!Array.isArray(result?.checks)) return 0\n return result.checks.filter(c => c?.status === 'skipped').length\n}\n\n/**\n * How many checks actually compared the two environments, over how many were\n * attempted.\n *\n * Printed alongside the score so a perfect number cannot be read as full\n * coverage. Skipped and errored layers both measured nothing, so neither\n * counts toward the numerator.\n */\nexport function coverage(result: Pick<ScanResult, 'checks'>): { compared: number; total: number } {\n if (!Array.isArray(result?.checks)) return { compared: 0, total: 0 }\n const total = result.checks.length\n const compared = result.checks.filter(c => c?.status === 'clean' || c?.status === 'drifted').length\n return { compared, total }\n}\n\n/**\n * Split the issue counts by whether they represent drift between the two\n * environments or the target's own posture.\n *\n * RLS Coverage and Migration History fire identically whichever pair you diff,\n * so counting them as drift made \"9 drift issues found\" the headline for a\n * comparison that found none (issue #40).\n */\nexport function splitCounts(result: Pick<ScanResult, 'checks'>): { drift: number; posture: number } {\n if (!Array.isArray(result?.checks)) return { drift: 0, posture: 0 }\n let drift = 0\n let posture = 0\n for (const check of result.checks) {\n const count = check?.issues?.length ?? 0\n if (isComparisonCheck(check?.check)) drift += count\n else posture += count\n }\n return { drift, posture }\n}\n\n/** Colour a 0–100 score green / amber / red. */\nfunction colorScore(score: number): string {\n let style: Parameters<typeof c>[0] = 'red'\n if (score >= 80) style = 'green'\n else if (score >= 50) style = 'yellow'\n return c(style, `${score}/100`)\n}\n\ninterface HeadlineCounts {\n drift: number\n noun: string\n driftedCount: number\n checkNoun: string\n erroredCount: number\n erroredNoun: string\n}\n\n/**\n * The one-line verdict.\n *\n * Drift wins over an error, and an error wins over silence: a check that could\n * not run measured nothing, so \"no drift detected\" would be a claim the scan\n * never earned (issue #29).\n */\nfunction formatHeadline(counts: HeadlineCounts): string {\n const prefix = bold('SupaForge scan complete:')\n if (counts.drift > 0) {\n return `${prefix} ${warn(`${counts.drift} drift ${counts.noun}`)} found across ${counts.driftedCount} ${counts.checkNoun}.`\n }\n if (counts.erroredCount > 0) {\n return `${prefix} ${warn(`${counts.erroredCount} ${counts.erroredNoun} could not complete`)} — drift is unknown.`\n }\n return `${prefix} ${ok('no drift detected. ✓')}`\n}\n\nexport function renderSummary(result: ScanResult): string {\n const lines: string[] = ['']\n\n // Counted separately: a posture finding is real but is not a difference\n // between the two environments (issue #40).\n const { drift, posture } = splitCounts(result)\n const noun = drift === 1 ? 'issue' : 'issues'\n const postureNoun = posture === 1 ? 'finding' : 'findings'\n const driftedCount = result.checks.filter(l => l.status === 'drifted' && isComparisonCheck(l.check)).length\n const checkNoun = driftedCount === 1 ? 'check' : 'checks'\n\n // A check that errored measured nothing. Reporting that as \"no drift\n // detected\" told users the environments matched when in truth the\n // comparison never ran (issue #29).\n const erroredCount = countErrored(result)\n const erroredNoun = erroredCount === 1 ? 'check' : 'checks'\n\n // A skipped check measured nothing either. It is a normal outcome rather\n // than a failure, so it is reported separately from an error — but it must\n // never read as a comparison that passed (issue #42).\n const skippedCount = countSkipped(result)\n const skippedNoun = skippedCount === 1 ? 'check was' : 'checks were'\n\n lines.push(formatHeadline({ drift, noun, driftedCount, checkNoun, erroredCount, erroredNoun }))\n\n // Named as what they are, so they cannot be read as the environments having\n // diverged. They are reported and scored, just not as drift.\n if (posture > 0) {\n lines.push(dim(`${posture} posture ${postureNoun} (RLS coverage / migration history) — present regardless of which pair you diff.`))\n }\n\n if (skippedCount > 0) {\n lines.push(dim(`${skippedCount} ${skippedNoun} skipped — coverage is partial.`))\n }\n\n // Drift was found *and* something failed: say so, or the count reads as the\n // whole picture.\n if (drift > 0 && erroredCount > 0) {\n lines.push(warn(`${erroredCount} further ${erroredNoun} could not complete — drift may be understated.`))\n }\n lines.push(`${dim('Source:')} ${result.source} ${dim('→')} ${dim('Target:')} ${result.target}`)\n lines.push('')\n\n for (const lr of result.checks) {\n lines.push(formatCheckLine(lr))\n }\n\n lines.push('')\n // The denominator the score was computed over, so 100/100 across a partial\n // run cannot be mistaken for a full comparison (issue #42).\n const { compared, total } = coverage(result)\n const coverageNote = compared === total ? '' : dim(` (${compared} of ${total} checks compared)`)\n lines.push(`${dim('Drift score:')} ${colorScore(result.score)}${coverageNote}`)\n\n if (result.postureScore !== null && result.postureScore !== undefined) {\n lines.push(`${dim('Posture score:')} ${colorScore(result.postureScore)}${dim(' (target only — RLS coverage, migration history)')}`)\n }\n lines.push('')\n\n return lines.join('\\n')\n}\n\nexport function renderDetailed(result: ScanResult): string {\n const lines = [renderSummary(result)]\n\n // Surface errored checks first — a check that couldn't run is more important\n // to see than the drift it failed to measure. Without this they only appeared\n // as a one-line \"(error: ...)\" in the summary with no detail or remediation.\n for (const lr of result.checks) {\n if (lr.status !== 'error') continue\n lines.push(formatErroredCheck(lr))\n }\n\n for (const lr of result.checks) {\n if (lr.issues.length === 0) continue\n const meta = CHECK_META[lr.check]\n lines.push(dim(`${'─'.repeat(2)} Layer ${meta.number}: ${meta.label} ${'─'.repeat(40)}`))\n lines.push('')\n\n for (const issue of lr.issues) {\n lines.push(formatIssue(issue))\n }\n }\n\n return lines.join('\\n')\n}\n\nfunction formatErroredCheck(lr: CheckResult): string {\n const meta = CHECK_META[lr.check]\n const lines: string[] = []\n lines.push(c('red', `── Layer ${meta.number}: ${meta.label} — could not run ${'─'.repeat(28)}`))\n lines.push('')\n lines.push(` ${c('red', '✖')} ${bold('Check failed — drift for this layer is unknown')}`)\n const errText = lr.error || 'check failed (no error message captured)'\n for (const line of errText.split('\\n')) {\n lines.push(` ${dim(line)}`)\n }\n lines.push('')\n lines.push(` ${dim('This layer was skipped in the totals above. Fix the error and re-run to')}`)\n lines.push(` ${dim('measure its drift; the score treats an errored check as unverified.')}`)\n lines.push('')\n return lines.join('\\n')\n}\n\nfunction formatCheckLine(lr: CheckResult): string {\n const meta = CHECK_META[lr.check]\n const icon = statusIcon(lr.status)\n const prefix = ` ${icon} Layer ${meta.number} (${meta.label}):`\n\n // \"0 issues\" is the wrong thing to print for a layer that never ran — it is\n // the exact text a clean comparison produces (issue #42). Reuses the\n // `skipped — reason` form `snapshot` already uses for the same situation.\n if (lr.status === 'skipped') {\n const reason = lr.skipReason ? ` — ${lr.skipReason}` : ''\n return `${prefix.padEnd(CHECK_LINE_PADDING)}${dim(`skipped${reason}`)}`\n }\n\n const count = lr.issues.length\n const noun = count === 1 ? 'issue' : 'issues'\n const severity = highestSeverity(lr)\n const sevLabel = severity ? colorSeverity(severity) : ''\n const errText = lr.error || (lr.status === 'error' ? 'check failed' : '')\n const errLabel = errText ? ` ${warn(`(error: ${errText})`)}` : ''\n // The live progress line counted these before they were folded; saying so\n // keeps the two numbers from looking inconsistent (issue #97).\n const folded = (lr.folded ?? [])\n .map(f => ` ${dim(`(+${f.count} reported under ${CHECK_META[f.into].label})`)}`)\n .join('')\n return `${prefix.padEnd(CHECK_LINE_PADDING)}${count} ${noun}${sevLabel}${folded}${errLabel}`\n}\n\n/** Glyph for an issue's severity. */\nfunction severityIcon(severity: DriftIssue['severity']): string {\n switch (severity) {\n case 'critical': return c('red', '✖')\n case 'warning': return warn('⚠')\n default: return c('blue', 'ℹ')\n }\n}\n\nfunction formatIssue(issue: DriftIssue): string {\n const lines: string[] = []\n lines.push(` ${severityIcon(issue.severity)} ${colorSeverity(issue.severity)} ${bold(issue.title)}`)\n lines.push(` ${dim(issue.description)}`)\n\n if (issue.sql) {\n lines.push('')\n lines.push(` ${dim('SQL fix (UP):')}`)\n for (const line of issue.sql.up.split('\\n')) {\n lines.push(` ${c('cyan', line)}`)\n }\n } else if (issue.action) {\n lines.push('')\n lines.push(` ${dim('API action:')} ${c('cyan', issue.action.label)}`)\n }\n\n lines.push('')\n return lines.join('\\n')\n}\n\nfunction statusIcon(status: CheckResult['status']): string {\n switch (status) {\n case 'clean': return ok('✓')\n case 'drifted': return warn('●')\n case 'error': return c('red', '✖')\n case 'skipped': return dim('○')\n }\n}\n\nfunction colorSeverity(severity: string): string {\n switch (severity) {\n case 'critical': return c('red', `[${severity.toUpperCase()}]`)\n case 'warning': return warn(`[${severity.toUpperCase()}]`)\n case 'info': return c('blue', `[${severity.toUpperCase()}]`)\n default: return `[${severity.toUpperCase()}]`\n }\n}\n\nfunction highestSeverity(lr: CheckResult): string | null {\n if (lr.issues.some(i => i.severity === 'critical')) return 'critical'\n if (lr.issues.some(i => i.severity === 'warning')) return 'warning'\n if (lr.issues.some(i => i.severity === 'info')) return 'info'\n return null\n}\n\n/** One skipped fix, as `promote` reports it. */\nexport interface SkippedFix {\n check: string\n issueId: string\n reason: string\n}\n\n/** Skipped fixes sharing a check and a reason. */\nexport interface SkipGroup {\n check: string\n reason: string\n issueIds: string[]\n}\n\n/**\n * Collapse skipped fixes that share a check and a reason (issue #84).\n *\n * The reason is a property of the *rule*, not of the issue, so a rule that\n * declines a whole check repeated itself once per issue. A posture check on a\n * project with 47 tables lacking RLS printed the same 150-character sentence\n * 47 times, and the result of the apply — the thing being looked for —\n * scrolled off the top.\n *\n * Grouped by reason rather than by check alone: one check can skip different\n * issues for different reasons, and merging those would misreport why.\n *\n * Insertion-ordered, so the output still follows the order the fixes were\n * planned in.\n */\nexport function groupSkips(skipped: readonly SkippedFix[]): SkipGroup[] {\n const groups = new Map<string, SkipGroup>()\n\n for (const item of skipped) {\n const key = `${item.check} ${item.reason}`\n const existing = groups.get(key)\n if (existing) existing.issueIds.push(item.issueId)\n else groups.set(key, { check: item.check, reason: item.reason, issueIds: [item.issueId] })\n }\n\n return [...groups.values()]\n}\n\n/** How many issue ids a collapsed group names before saying \"and N more\". */\nexport const SKIP_IDS_SHOWN = 6\n\n/**\n * An issue id with its leading check name removed.\n *\n * Only when the whole segment matches, so an id that merely begins with the\n * same letters keeps all of it, and never down to nothing.\n */\nfunction shortIssueId(issueId: string, check: string): string {\n for (const separator of ['-', ':']) {\n const prefix = `${check}${separator}`\n if (issueId.startsWith(prefix) && issueId.length > prefix.length) {\n return issueId.slice(prefix.length)\n }\n }\n return issueId\n}\n\n/**\n * Render collapsed skips, without colour so it can be asserted on.\n *\n * A group of one renders exactly as it always did — `id: reason` — so the\n * common case reads unchanged and only the repetitive case is collapsed.\n */\nexport function formatSkips(skipped: readonly SkippedFix[]): string[] {\n const lines: string[] = []\n\n for (const group of groupSkips(skipped)) {\n if (group.issueIds.length === 1) {\n lines.push(`○ [${group.check}] ${group.issueIds[0]}: ${group.reason}`)\n continue\n }\n\n // Count first: it is the part that changes between runs, and the reason\n // after it is the part that does not.\n lines.push(`○ [${group.check}] ${group.issueIds.length} issues: ${group.reason}`)\n\n // Issue ids are prefixed with their check, which is already in brackets on\n // the line above; dropping it keeps the list readable at terminal width.\n const shown = group.issueIds.slice(0, SKIP_IDS_SHOWN).map(id => shortIssueId(id, group.check))\n const rest = group.issueIds.length - shown.length\n lines.push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AClC,UAAM,SAAS,GAAG,KAAK,GAAG,SAAS;AACnC,QAAI,QAAQ,WAAW,MAAM,KAAK,QAAQ,SAAS,OAAO,QAAQ;AAChE,aAAO,QAAQ,MAAM,OAAO,MAAM;AAAA,IACpC;AAAA,EACF;AACA,SAAO;AACT;AAQO,SAAS,YAAY,SAA0C;AACpE,QAAM,QAAkB,CAAC;AAEzB,aAAW,SAAS,WAAW,OAAO,GAAG;AACvC,QAAI,MAAM,SAAS,WAAW,GAAG;AAC/B,YAAM,KAAK,WAAM,MAAM,KAAK,KAAK,MAAM,SAAS,CAAC,CAAC,KAAK,MAAM,MAAM,EAAE;AACrE;AAAA,IACF;AAIA,UAAM,KAAK,WAAM,MAAM,KAAK,KAAK,MAAM,SAAS,MAAM,YAAY,MAAM,MAAM,EAAE;AAIhF,UAAM,QAAQ,MAAM,SAAS,MAAM,GAAG,cAAc,EAAE,IAAI,QAAM,aAAa,IAAI,MAAM,KAAK,CAAC;AAC7F,UAAM,OAAO,MAAM,SAAS,SAAS,MAAM;AAC3C,UAAM,KAAK,OAAO,MAAM,KAAK,IAAI,CAAC,GAAG,OAAO,IAAI,eAAU,IAAI,UAAU,EAAE,EAAE;AAAA,EAC9E;AAEA,SAAO;AACT;","names":["c"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/mcp/state.ts","../src/mcp/server.ts"],"sourcesContent":["import type { ScanResult } from '../types/drift.js'\n\n/** In-memory store for the most recent scan result (per-process). */\nlet lastScanResult: ScanResult | null = null\n\nexport function setLastScanResult(result: ScanResult): void {\n lastScanResult = result\n}\n\nexport function getLastScanResult(): ScanResult | null {\n return lastScanResult\n}\n\nexport function clearLastScanResult(): void {\n lastScanResult = null\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { z } from 'zod'\nimport { readFile, readdir } from 'node:fs/promises'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { resolve, join, dirname } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { resolveConfig, validateConfig } from '../config.js'\nimport { createDefaultRegistry } from '../checks/index.js'\nimport { scan } from '../scanner.js'\nimport { promote } from '../promote.js'\nimport { captureSnapshot } from '../snapshot.js'\nimport { backup } from '../migration.js'\nimport { CHECK_NAMES } from '../types/drift.js'\nimport type { ScanResult, CheckName } from '../types/drift.js'\nimport { setLastScanResult, getLastScanResult } from './state.js'\n\nconst SERVER_NAME = 'supaforge'\n\n/**\n * The package's own version.\n *\n * Was a hardcoded '0.0.4' and had drifted fifteen releases behind (issue #82).\n * An MCP client has no other way to know which SupaForge it is talking to, so\n * an agent deciding whether a tool or argument exists was working from a\n * version that had not been true for months. Read from package.json, with a\n * fallback that says so rather than asserting a number.\n */\nconst SERVER_VERSION = resolveVersion()\n\nfunction resolveVersion(): string {\n try {\n const here = dirname(fileURLToPath(import.meta.url))\n // dist/ at runtime, src/mcp/ from source: walk up until package.json.\n for (const relative of ['../package.json', '../../package.json', '../../../package.json']) {\n const candidate = resolve(here, relative)\n if (!existsSync(candidate)) continue\n const pkg = JSON.parse(readFileSync(candidate, 'utf-8'))\n if (typeof pkg.version === 'string' && pkg.name?.includes('supaforge')) {\n return pkg.version\n }\n }\n } catch {\n // Fall through.\n }\n return '0.0.0-unknown'\n}\n\n/** Masks sensitive fields (dbUrl, accessToken) in config output. */\nfunction maskConfig(config: unknown): unknown {\n if (typeof config !== 'object' || config === null) return config\n const result: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(config as Record<string, unknown>)) {\n if (key === 'dbUrl' || key === 'accessToken') {\n result[key] = typeof value === 'string' && value.length > 0 ? '***' : value\n } else if (typeof value === 'object' && value !== null) {\n result[key] = maskConfig(value)\n } else {\n result[key] = value\n }\n }\n return result\n}\n\n/**\n * Create and configure the SupaForge MCP server.\n *\n * @param cwd - Working directory to resolve config files from (defaults to process.cwd())\n */\nexport interface ServerOptions {\n /**\n * Honour a `configPath` argument from the client.\n *\n * Off by default. Every tool accepted an arbitrary path and resolved its\n * working directory from it, so a tool call — or a prompt injected into one —\n * could point the server at any `supaforge.config.json` on disk, including\n * one holding production credentials, bypassing the config the server was\n * started with (issue #96). Enabled with `supaforge mcp --allow-config-path`\n * for the case where an agent legitimately manages several projects.\n */\n allowConfigPath?: boolean\n}\n\nexport function createServer(cwd = process.cwd(), options: ServerOptions = {}): McpServer {\n const allowConfigPath = options.allowConfigPath ?? false\n\n /**\n * The directory to load the config from.\n *\n * Refuses a `configPath` unless the server was started with\n * --allow-config-path, rather than ignoring it silently: a client that asked\n * for a different project should be told it did not get one.\n */\n const resolveCwd = (configPath?: string): string => {\n if (!configPath) return cwd\n if (!allowConfigPath) {\n throw new Error(\n 'configPath is not accepted by this server. It was started without '\n + '--allow-config-path, so it reads only the config in its own working '\n + `directory (${cwd}). Restart it with --allow-config-path to permit `\n + 'other projects.',\n )\n }\n return resolve(configPath, '..')\n }\n\n const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION })\n\n // ── Tools ──────────────────────────────────────────────────────────────────\n\n /**\n * scan_drift: Scan for environment drift and return a structured report.\n */\n server.registerTool(\n 'scan_drift',\n {\n // Reads both databases and writes nothing. Without annotations a client\n // could not tell this from apply_fixes, so it could not ask for\n // confirmation on the one that writes (issue #96).\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },\n\n description:\n 'Scan for drift between Supabase environments and return a structured report. ' +\n 'Results include per-check status, issues with SQL fixes, and a health score.',\n inputSchema: {\n configPath: z\n .string()\n .optional()\n .describe(\n 'Absolute path to supaforge.config.json. Rejected unless the server was '\n + 'started with --allow-config-path; otherwise the config in the server\\'s '\n + 'own working directory is used.',\n ),\n source: z\n .string()\n .optional()\n .describe('Source environment name (overrides config default).'),\n target: z\n .string()\n .optional()\n .describe('Target environment name (overrides config default).'),\n checks: z\n .array(z.enum(CHECK_NAMES))\n .optional()\n .describe('Limit scan to specific checks (e.g. [\"rls\", \"rls-coverage\"]).'),\n skip: z\n .array(z.enum(CHECK_NAMES))\n .optional()\n .describe(\n 'Skip specific checks, the equivalent of the CLI --skip flag. ' +\n 'Unioned with checks.exclude from the config file. Use this to avoid ' +\n 'a slow or failing layer without editing the project config.',\n ),\n },\n },\n async ({ configPath, source, target, checks, skip }) => {\n try {\n const effectiveCwd = resolveCwd(configPath)\n const raw = JSON.parse(await readFile(resolve(effectiveCwd, 'supaforge.config.json'), 'utf-8'))\n const config = resolveConfig({\n ...raw,\n ...(source ? { source } : {}),\n ...(target ? { target } : {}),\n })\n\n const errors = validateConfig(config)\n if (errors.length > 0) {\n return { content: [{ type: 'text' as const, text: `Config errors:\\n${errors.join('\\n')}` }], isError: true }\n }\n\n const registry = createDefaultRegistry()\n const result: ScanResult = await scan(registry, {\n config,\n checks: checks as CheckName[] | undefined,\n skip: skip as CheckName[] | undefined,\n })\n setLastScanResult(result)\n\n return { content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }] }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text' as const, text: `Error: ${msg}` }], isError: true }\n }\n },\n )\n\n /**\n * apply_fixes: Apply SQL fixes to resolve drift in the target environment.\n */\n server.registerTool(\n 'apply_fixes',\n {\n // Writes to the target database, and destructively when\n // allowDestructive is set. This is the one a client should confirm.\n annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false },\n\n description:\n 'Apply SQL fixes to resolve drift detected by scan_drift. ' +\n 'Previews by default — pass dryRun=false to actually write to the target database.',\n inputSchema: {\n configPath: z\n .string()\n .optional()\n .describe(\n 'Absolute path to supaforge.config.json. Rejected unless the server was '\n + 'started with --allow-config-path; otherwise the config in the server\\'s '\n + 'own working directory is used.',\n ),\n source: z.string().optional().describe('Source environment name.'),\n target: z.string().optional().describe('Target environment name.'),\n checks: z\n .array(z.enum(CHECK_NAMES))\n .optional()\n .describe('Apply fixes only for specific checks.'),\n dryRun: z\n .boolean()\n .optional()\n .default(true)\n .describe(\n 'Preview SQL without executing it. Defaults to true: writing is opt-in '\n + 'here as it is everywhere else in supaforge, where it needs --apply. '\n + 'Pass dryRun=false to actually apply the fixes.',\n ),\n },\n },\n async ({ configPath, source, target, checks, dryRun }) => {\n try {\n const effectiveCwd = resolveCwd(configPath)\n const raw = JSON.parse(await readFile(resolve(effectiveCwd, 'supaforge.config.json'), 'utf-8'))\n const config = resolveConfig({\n ...raw,\n ...(source ? { source } : {}),\n ...(target ? { target } : {}),\n })\n\n const errors = validateConfig(config)\n if (errors.length > 0) {\n return { content: [{ type: 'text' as const, text: `Config errors:\\n${errors.join('\\n')}` }], isError: true }\n }\n\n const registry = createDefaultRegistry()\n const scanResult: ScanResult = await scan(registry, {\n config,\n checks: checks as CheckName[] | undefined,\n })\n setLastScanResult(scanResult)\n\n const targetEnv = config.environments[config.target!]\n const promoteResult = await promote({\n dbUrl: targetEnv.dbUrl,\n scanResult,\n checks: checks as string[] | undefined,\n dryRun,\n })\n\n return { content: [{ type: 'text' as const, text: JSON.stringify(promoteResult, null, 2) }] }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text' as const, text: `Error: ${msg}` }], isError: true }\n }\n },\n )\n\n /**\n * take_snapshot: Capture a point-in-time snapshot of a Supabase environment.\n */\n server.registerTool(\n 'take_snapshot',\n {\n // Reads the database and writes local files only — nothing in any\n // database changes.\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },\n\n description:\n 'Capture a point-in-time snapshot of a Supabase environment. ' +\n 'Snapshots are stored under .supaforge/snapshots/ and can be used to restore state.',\n inputSchema: {\n configPath: z\n .string()\n .optional()\n .describe(\n 'Absolute path to supaforge.config.json. Rejected unless the server was '\n + 'started with --allow-config-path; otherwise the config in the server\\'s '\n + 'own working directory is used.',\n ),\n environment: z\n .string()\n .optional()\n .describe('Environment to snapshot (defaults to config source).'),\n },\n },\n async ({ configPath, environment }) => {\n try {\n const effectiveCwd = resolveCwd(configPath)\n const raw = JSON.parse(await readFile(resolve(effectiveCwd, 'supaforge.config.json'), 'utf-8'))\n const config = resolveConfig(raw)\n\n const envName = environment ?? config.source ?? Object.keys(config.environments)[0]\n const env = config.environments[envName]\n if (!env) {\n return {\n content: [{ type: 'text' as const, text: `Environment \"${envName}\" not found in config.` }],\n isError: true,\n }\n }\n\n const result = await captureSnapshot({ envName, env, config, cwd: effectiveCwd })\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify({ timestamp: result.timestamp, dir: result.dir, manifest: result.manifest }, null, 2),\n },\n ],\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text' as const, text: `Error: ${msg}` }], isError: true }\n }\n },\n )\n\n /**\n * create_migration: Create a migration file from snapshot diff.\n */\n server.registerTool(\n 'create_migration',\n {\n // Local files only, as with take_snapshot.\n annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false },\n\n description:\n 'Capture a snapshot and generate a migration file containing the diff against the previous snapshot. ' +\n 'Migration files are stored under .supaforge/migrations/.',\n inputSchema: {\n configPath: z\n .string()\n .optional()\n .describe(\n 'Absolute path to supaforge.config.json. Rejected unless the server was '\n + 'started with --allow-config-path; otherwise the config in the server\\'s '\n + 'own working directory is used.',\n ),\n environment: z\n .string()\n .optional()\n .describe('Environment to snapshot (defaults to config source).'),\n description: z\n .string()\n .optional()\n .describe('Human-readable description for the migration (e.g. \"add-rls-to-orders\").'),\n },\n },\n async ({ configPath, environment, description }) => {\n try {\n const effectiveCwd = resolveCwd(configPath)\n const raw = JSON.parse(await readFile(resolve(effectiveCwd, 'supaforge.config.json'), 'utf-8'))\n const config = resolveConfig(raw)\n\n const envName = environment ?? config.source ?? Object.keys(config.environments)[0]\n const env = config.environments[envName]\n if (!env) {\n return {\n content: [{ type: 'text' as const, text: `Environment \"${envName}\" not found in config.` }],\n isError: true,\n }\n }\n\n const result = await backup({\n envName,\n env,\n config,\n cwd: effectiveCwd,\n description,\n })\n\n return {\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n {\n isBaseline: result.isBaseline,\n migrationFile: result.migrationFile,\n snapshotDir: result.snapshot.dir,\n timestamp: result.snapshot.timestamp,\n },\n null,\n 2,\n ),\n },\n ],\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err)\n return { content: [{ type: 'text' as const, text: `Error: ${msg}` }], isError: true }\n }\n },\n )\n\n /**\n * get_check_result: Retrieve the result for a specific check from the last scan.\n */\n server.registerTool(\n 'get_check_result',\n {\n // Reads the last scan held in memory.\n annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },\n\n description:\n 'Retrieve the result for a specific check from the most recent scan_drift call. ' +\n 'Returns issues, status, and duration for the named check.',\n inputSchema: {\n check: z.enum(CHECK_NAMES).describe('The check name to retrieve (e.g. \"rls-coverage\").'),\n },\n },\n async ({ check }) => {\n const result = getLastScanResult()\n if (!result) {\n return {\n content: [{ type: 'text' as const, text: 'No scan result available. Run scan_drift first.' }],\n isError: true,\n }\n }\n const checkResult = result.checks.find(c => c.check === check)\n if (!checkResult) {\n return {\n content: [\n { type: 'text' as const, text: `Check \"${check}\" not found in last scan. Was it included in the scan?` },\n ],\n isError: true,\n }\n }\n return { content: [{ type: 'text' as const, text: JSON.stringify(checkResult, null, 2) }] }\n },\n )\n\n // ── Resources ──────────────────────────────────────────────────────────────\n\n /** Current SupaForge config (sensitive fields masked). */\n server.registerResource(\n 'config',\n 'supaforge://config',\n {\n title: 'SupaForge Config',\n description: 'Current supaforge.config.json (sensitive fields masked)',\n mimeType: 'application/json',\n },\n async (uri) => {\n try {\n const raw = JSON.parse(await readFile(resolve(cwd, 'supaforge.config.json'), 'utf-8'))\n const masked = maskConfig(raw)\n return {\n contents: [{ uri: uri.href, text: JSON.stringify(masked, null, 2), mimeType: 'application/json' }],\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err)\n return { contents: [{ uri: uri.href, text: `Error loading config: ${msg}`, mimeType: 'text/plain' }] }\n }\n },\n )\n\n /** Last scan result (updated after each scan_drift or apply_fixes call). */\n server.registerResource(\n 'last-scan',\n 'supaforge://last-scan',\n {\n title: 'Last Scan Result',\n description: 'The most recent drift scan result',\n mimeType: 'application/json',\n },\n async (uri) => {\n const result = getLastScanResult()\n if (!result) {\n return {\n contents: [\n {\n uri: uri.href,\n text: JSON.stringify({ message: 'No scan result yet. Run scan_drift first.' }),\n mimeType: 'application/json',\n },\n ],\n }\n }\n return { contents: [{ uri: uri.href, text: JSON.stringify(result, null, 2), mimeType: 'application/json' }] }\n },\n )\n\n /** List of migration files under .supaforge/migrations/. */\n server.registerResource(\n 'migrations',\n 'supaforge://migrations',\n {\n title: 'Migration Files',\n description: 'Migration files under .supaforge/migrations/',\n mimeType: 'application/json',\n },\n async (uri) => {\n try {\n const migrationsDir = join(cwd, '.supaforge', 'migrations')\n const files = await readdir(migrationsDir).catch(() => [] as string[])\n const jsonFiles = files.filter(f => f.endsWith('.json')).sort()\n return {\n contents: [\n {\n uri: uri.href,\n text: JSON.stringify({ directory: migrationsDir, files: jsonFiles }, null, 2),\n mimeType: 'application/json',\n },\n ],\n }\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err)\n return { contents: [{ uri: uri.href, text: `Error: ${msg}`, mimeType: 'text/plain' }] }\n }\n },\n )\n\n // ── Prompts ────────────────────────────────────────────────────────────────\n\n /** Prompt: review drift before deploying. */\n server.registerPrompt(\n 'review_drift_before_deploy',\n {\n description: 'Generate a drift review context to share with an AI agent before deploying.',\n argsSchema: {\n environment: z\n .string()\n .optional()\n .describe('Target environment name (e.g. \"production\")'),\n },\n },\n ({ environment }) => {\n const envNote = environment ? ` to **${environment}**` : ''\n const lastScan = getLastScanResult()\n const scanContext = lastScan\n ? `\\n\\nLast scan result (${lastScan.timestamp}):\\n- Score: ${lastScan.score}\\n- Total issues: ${lastScan.summary.total} (${lastScan.summary.critical} critical, ${lastScan.summary.warning} warnings)\\n- Checks: ${lastScan.checks.filter(c => c.status === 'drifted').map(c => c.check).join(', ') || 'none drifted'}`\n : '\\n\\nNo recent scan found — run scan_drift first for a current drift report.'\n\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: [\n `Before deploying${envNote}, please review the current SupaForge drift report.`,\n scanContext,\n '',\n 'Steps:',\n '1. Call scan_drift to get the latest drift report.',\n '2. Review critical issues (especially rls-coverage and rls checks).',\n '3. Confirm all SQL fixes look correct before applying.',\n '4. If safe, run apply_fixes with dryRun=true first, then dryRun=false.',\n ].join('\\n'),\n },\n },\n ],\n }\n },\n )\n\n /** Prompt: fix all critical issues. */\n server.registerPrompt(\n 'fix_critical_issues',\n {\n description: 'Generate a step-by-step plan to fix all critical drift issues.',\n argsSchema: {},\n },\n () => {\n const lastScan = getLastScanResult()\n let criticalSummary = 'No recent scan — run scan_drift first.'\n if (lastScan) {\n const criticalIssues = lastScan.checks\n .flatMap(c => c.issues)\n .filter(i => i.severity === 'critical')\n if (criticalIssues.length === 0) {\n criticalSummary = 'No critical issues found in the last scan. The target environment looks healthy.'\n } else {\n criticalSummary = [\n `Found ${criticalIssues.length} critical issue(s) in last scan (${lastScan.timestamp}):`,\n ...criticalIssues.map(i => `- [${i.check}] ${i.title}`),\n ].join('\\n')\n }\n }\n\n return {\n messages: [\n {\n role: 'user' as const,\n content: {\n type: 'text' as const,\n text: [\n 'Fix all critical drift issues in the target Supabase environment.',\n '',\n criticalSummary,\n '',\n 'Recommended steps:',\n '1. Run scan_drift to confirm the current state.',\n '2. Review each critical issue and its sql.up fix.',\n '3. Run apply_fixes with dryRun=true to preview the SQL.',\n '4. Confirm the SQL is safe, then run apply_fixes with dryRun=false.',\n '5. Run scan_drift again to confirm all critical issues are resolved.',\n '',\n 'Pay special attention to rls-coverage issues — tables without RLS enabled',\n 'are the CVE-2025-48757 vulnerability pattern.',\n ].join('\\n'),\n },\n },\n ],\n }\n },\n )\n\n return server\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAGA,IAAI,iBAAoC;AAEjC,SAAS,kBAAkB,QAA0B;AAC1D,mBAAiB;AACnB;AAEO,SAAS,oBAAuC;AACrD,SAAO;A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