@akal/supaforge 0.0.0-stage → 0.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +350 -2
- package/bin/dev.js +10 -0
- package/bin/run.js +18 -0
- package/dist/base-command.d.ts +134 -0
- package/dist/base-command.js +9 -0
- package/dist/base-command.js.map +1 -0
- package/dist/branch-C4ndfoj5.d.ts +58 -0
- package/dist/chunk-4OU7KO5Y.js +13 -0
- package/dist/chunk-4OU7KO5Y.js.map +1 -0
- package/dist/chunk-5QQBTLWO.js +642 -0
- package/dist/chunk-5QQBTLWO.js.map +1 -0
- package/dist/chunk-5Z3SAIQS.js +2807 -0
- package/dist/chunk-5Z3SAIQS.js.map +1 -0
- package/dist/chunk-6WAMNZLO.js +336 -0
- package/dist/chunk-6WAMNZLO.js.map +1 -0
- package/dist/chunk-BHYLBKYD.js +156 -0
- package/dist/chunk-BHYLBKYD.js.map +1 -0
- package/dist/chunk-BLKJWDTL.js +153 -0
- package/dist/chunk-BLKJWDTL.js.map +1 -0
- package/dist/chunk-DQQ5E563.js +64 -0
- package/dist/chunk-DQQ5E563.js.map +1 -0
- package/dist/chunk-G2DIPIYU.js +94 -0
- package/dist/chunk-G2DIPIYU.js.map +1 -0
- package/dist/chunk-H5MJ5DFX.js +16 -0
- package/dist/chunk-H5MJ5DFX.js.map +1 -0
- package/dist/chunk-KIFJGON5.js +248 -0
- package/dist/chunk-KIFJGON5.js.map +1 -0
- package/dist/chunk-LQXF65MC.js +240 -0
- package/dist/chunk-LQXF65MC.js.map +1 -0
- package/dist/chunk-NXRSAVRU.js +478 -0
- package/dist/chunk-NXRSAVRU.js.map +1 -0
- package/dist/chunk-PARSNTBD.js +837 -0
- package/dist/chunk-PARSNTBD.js.map +1 -0
- package/dist/chunk-RRMI5CZD.js +376 -0
- package/dist/chunk-RRMI5CZD.js.map +1 -0
- package/dist/chunk-SF3YA42C.js +506 -0
- package/dist/chunk-SF3YA42C.js.map +1 -0
- package/dist/chunk-TQJSQLWA.js +574 -0
- package/dist/chunk-TQJSQLWA.js.map +1 -0
- package/dist/chunk-VMTBLHN2.js +122 -0
- package/dist/chunk-VMTBLHN2.js.map +1 -0
- package/dist/chunk-VOXZWQ3N.js +948 -0
- package/dist/chunk-VOXZWQ3N.js.map +1 -0
- package/dist/chunk-X6V2GGDZ.js +333 -0
- package/dist/chunk-X6V2GGDZ.js.map +1 -0
- package/dist/chunk-XMYMIURR.js +552 -0
- package/dist/chunk-XMYMIURR.js.map +1 -0
- package/dist/chunk-YVDSR4GM.js +1264 -0
- package/dist/chunk-YVDSR4GM.js.map +1 -0
- package/dist/commands/clone.d.ts +66 -0
- package/dist/commands/clone.js +416 -0
- package/dist/commands/clone.js.map +1 -0
- package/dist/commands/diff.d.ts +65 -0
- package/dist/commands/diff.js +24 -0
- package/dist/commands/diff.js.map +1 -0
- package/dist/commands/help.d.ts +32 -0
- package/dist/commands/help.js +36 -0
- package/dist/commands/help.js.map +1 -0
- package/dist/commands/hukam.d.ts +13 -0
- package/dist/commands/hukam.js +29 -0
- package/dist/commands/hukam.js.map +1 -0
- package/dist/commands/init.d.ts +47 -0
- package/dist/commands/init.js +388 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/mcp.d.ts +13 -0
- package/dist/commands/mcp.js +44 -0
- package/dist/commands/mcp.js.map +1 -0
- package/dist/commands/migrate/baseline.d.ts +24 -0
- package/dist/commands/migrate/baseline.js +69 -0
- package/dist/commands/migrate/baseline.js.map +1 -0
- package/dist/commands/migrate/create.d.ts +36 -0
- package/dist/commands/migrate/create.js +128 -0
- package/dist/commands/migrate/create.js.map +1 -0
- package/dist/commands/migrate/list.d.ts +23 -0
- package/dist/commands/migrate/list.js +110 -0
- package/dist/commands/migrate/list.js.map +1 -0
- package/dist/commands/migrate/run.d.ts +61 -0
- package/dist/commands/migrate/run.js +19 -0
- package/dist/commands/migrate/run.js.map +1 -0
- package/dist/commands/report.d.ts +27 -0
- package/dist/commands/report.js +210 -0
- package/dist/commands/report.js.map +1 -0
- package/dist/commands/restore.d.ts +26 -0
- package/dist/commands/restore.js +268 -0
- package/dist/commands/restore.js.map +1 -0
- package/dist/commands/snapshot.d.ts +33 -0
- package/dist/commands/snapshot.js +251 -0
- package/dist/commands/snapshot.js.map +1 -0
- package/dist/commands/sync.d.ts +16 -0
- package/dist/commands/sync.js +39 -0
- package/dist/commands/sync.js.map +1 -0
- package/dist/config-CTbeRlJk.d.ts +134 -0
- package/dist/help.d.ts +28 -0
- package/dist/help.js +64 -0
- package/dist/help.js.map +1 -0
- package/dist/index.d.ts +493 -0
- package/dist/index.js +147 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/db.ts","../src/utils/error.ts","../src/checks/base.ts","../src/checks/migrations.ts","../src/utils/sql.ts"],"sourcesContent":["import pg from 'pg'\nimport { DB_CONNECT_TIMEOUT_MS } from './constants.js'\n\nexport type QueryFn = (dbUrl: string, sql: string, params?: unknown[]) => Promise<Record<string, unknown>[]>\n\n/**\n * Resolve the bound on establishing a connection (ms).\n *\n * SUPAFORGE_CONNECT_TIMEOUT is in seconds, so a network that legitimately\n * needs longer than the default can raise it without a code change. A\n * malformed or non-positive value falls back to the default rather than\n * forwarding something `pg` would treat as \"wait forever\" — which is the very\n * failure this bound exists to prevent (issue #44).\n */\nexport function resolveConnectTimeoutMs(): number {\n const raw = process.env.SUPAFORGE_CONNECT_TIMEOUT\n if (raw) {\n const secs = Number(raw)\n if (Number.isFinite(secs) && secs > 0) return Math.round(secs * 1000)\n }\n return DB_CONNECT_TIMEOUT_MS\n}\n\n/**\n * Build `pg.Client` config with a connection bound always applied.\n *\n * Every client in the codebase goes through here so none can be constructed\n * without one. `queryTimeoutMs` is opt-in: it belongs on short probes, not on\n * a migration or restore that is legitimately slow.\n */\nexport function pgClientConfig(dbUrl: string, queryTimeoutMs?: number): pg.ClientConfig {\n const config: pg.ClientConfig = {\n connectionString: dbUrl,\n connectionTimeoutMillis: resolveConnectTimeoutMs(),\n }\n if (queryTimeoutMs !== undefined) {\n config.query_timeout = queryTimeoutMs\n }\n return config\n}\n\n/**\n * One pool per database, shared by every query in a run.\n *\n * `pgQuery` used to open and close a `pg.Client` per query, and each connection\n * costs several round trips before the query itself runs: TCP, startup, then\n * SCRAM authentication. Over a link with latency that dominated a diff — a full\n * run opened 47 connections for 574 round trips, and the storage check alone\n * opened 14 (issue #78). `schema-introspect.ts` already shared a pool for\n * snapshots; the diff path did not.\n *\n * `allowExitOnIdle` is what makes this safe to do without lifecycle plumbing\n * through every command: an idle pool does not hold the process open, so a CLI\n * that forgets to close one still exits. `closePgPools()` exists for tests and\n * for anywhere that wants the sockets gone at a known moment.\n */\nconst pools = new Map<string, pg.Pool>()\n\n/**\n * Concurrent checks share these, so a pool needs more than one connection —\n * but a diff is not a web server, and a Supabase pooler counts every one.\n */\nconst POOL_MAX = 4\n\nfunction poolFor(dbUrl: string): pg.Pool {\n const existing = pools.get(dbUrl)\n if (existing) return existing\n\n const pool = new pg.Pool({\n ...pgClientConfig(dbUrl),\n max: POOL_MAX,\n allowExitOnIdle: true,\n })\n // A pool emits 'error' for an idle client dropped by the server, and an\n // unhandled 'error' event would take the process down. Queries still reject\n // through their own promise, so this only has to stop the crash.\n pool.on('error', () => undefined)\n\n pools.set(dbUrl, pool)\n return pool\n}\n\nexport const pgQuery: QueryFn = async (dbUrl, sql, params) => {\n const { rows } = await poolFor(dbUrl).query(sql, params)\n return rows\n}\n\n/**\n * Run `fn` on one pooled connection inside a transaction that is always\n * rolled back — for reading what the server makes of something by creating it\n * as a temporary object, without leaving anything behind.\n */\nexport async function inRolledBackTransaction<T>(\n dbUrl: string,\n fn: (client: pg.PoolClient) => Promise<T>,\n): Promise<T> {\n const client = await poolFor(dbUrl).connect()\n try {\n await client.query('BEGIN')\n try {\n return await fn(client)\n } finally {\n await client.query('ROLLBACK').catch(() => undefined)\n }\n } finally {\n client.release()\n }\n}\n\n/** Close every pool this process opened. Safe to call more than once. */\nexport async function closePgPools(): Promise<void> {\n const open = [...pools.values()]\n pools.clear()\n await Promise.all(open.map(pool => pool.end().catch(() => undefined)))\n}\n","/**\n * Regex matching database connection URL schemes (postgres, mysql, etc.).\n * Captures the scheme + `://` and the rest of the URL up to the next whitespace.\n */\nconst DB_URL_RE = /\\b((?:postgres(?:ql)?|mysql|mariadb):\\/\\/)(\\S+)/g\n\n/**\n * Redact passwords from database connection URLs in a string.\n *\n * Replaces `://user:PASSWORD@host` with `://user:***@host` to prevent\n * credentials from leaking into logs, error messages, or terminal output.\n * Handles passwords containing special characters including `@`.\n */\nexport function redactUrls(message: string): string {\n return message.replace(DB_URL_RE, (_, scheme: string, rest: string) => {\n const lastAt = rest.lastIndexOf('@')\n if (lastAt === -1) return scheme + rest\n const creds = rest.slice(0, lastAt)\n const hostPart = rest.slice(lastAt)\n const colonIdx = creds.indexOf(':')\n if (colonIdx === -1) return scheme + rest\n return scheme + creds.slice(0, colonIdx) + ':***' + hostPart\n })\n}\n\n/** Shown when a failure carries nothing at all that could name it. */\nexport const UNDESCRIBED_ERROR = 'unknown error — no message reported'\n\n/**\n * Get something printable out of a thrown value.\n *\n * Not every failure arrives as an `Error` with a populated `message`. One did\n * not — observed when a container runtime's daemon stopped while a port mapping\n * was still registered — and every renderer downstream printed its label, a\n * colon, and nothing: `✗ Source database not reachable:` (issue #47).\n *\n * Falls back through what a driver error still carries when its message is\n * empty: the `code` (`ECONNRESET`, `EPIPE`) is the most useful, then the error\n * type, then a fixed string. The return value is never empty, which is the\n * whole point — a reason a user cannot read is worse than a generic one.\n */\nexport function describeFailure(err: unknown): string {\n if (typeof err === 'string') return err.trim() || UNDESCRIBED_ERROR\n\n const candidate = err as { message?: unknown; code?: unknown; name?: unknown } | null | undefined\n const message = typeof candidate?.message === 'string' ? candidate.message.trim() : ''\n if (message) return message\n\n const code = typeof candidate?.code === 'string' ? candidate.code.trim() : ''\n if (code) return `${code} (no further detail reported)`\n\n const name = typeof candidate?.name === 'string' ? candidate.name.trim() : ''\n if (name && name !== 'Error') return `${name} (no further detail reported)`\n\n if (err !== null && err !== undefined && !(err instanceof Error)) {\n const rendered = String(err).trim()\n if (rendered && rendered !== '[object Object]') return rendered\n }\n\n return UNDESCRIBED_ERROR\n}\n\n/**\n * Extract a concise error message from an unknown caught value.\n *\n * Safely handles Error instances, strings, and other thrown types, and never\n * returns an empty string — see describeFailure. Used across the codebase in\n * catch blocks to normalise error output. Automatically redacts database\n * credentials from the message.\n */\nexport function errMsg(err: unknown): string {\n return redactUrls(describeFailure(err))\n}\n\n/**\n * An error whose message is already written for the user — it has been\n * diagnosed, and usually carries remediation steps.\n *\n * friendlyDbError() passes these through untouched instead of pattern-matching\n * them into a generic connection error. Without this, any accurate message that\n * happens to mention a timeout (including one telling the user which timeout\n * env var to raise) got rewritten into advice to check their host and port.\n */\nexport class DiagnosticError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'DiagnosticError'\n }\n}\n\n/**\n * Structural check rather than `instanceof`.\n *\n * The CLI and its tests can load a module through more than one path (src vs\n * dist, ESM vs CJS interop), which yields two distinct class identities and\n * makes `instanceof` silently false. Matching on the name keeps the guard\n * working across those boundaries.\n */\nexport function isDiagnosticError(err: unknown): boolean {\n return err instanceof DiagnosticError || (err instanceof Error && err.name === 'DiagnosticError')\n}\n\n// ─── Connection Error Patterns ───────────────────────────────────────────────\n\n/** Known patterns matched against error messages, checked in order. */\nconst CONNECTION_ERROR_PATTERNS: Array<{ test: (msg: string) => boolean; build: (host: string) => string }> = [\n {\n test: (m) => /ECONNREFUSED|Connection refused/i.test(m),\n build: (host) => `Cannot connect to PostgreSQL at ${host} — the server does not appear to be running. Start it and try again.`,\n },\n {\n test: (m) => /ENOTFOUND|getaddrinfo/i.test(m),\n build: (host) => `Cannot resolve hostname ${host} — check the database URL in your config.`,\n },\n {\n // Deliberately narrow. A bare /timeout/i also matches our own remediation\n // text — \"set SUPAFORGE_DBDIFF_TIMEOUT=600\" contains \"TIMEOUT\" — which is\n // how an accurate \"Schema diff timed out after Ns\" message was being\n // rewritten into a wrong \"check the host and port\" one (issue #29).\n // DiagnosticError below is the primary guard; this is defence in depth.\n test: (m) => /ETIMEDOUT|connection timed out|timeout expired|statement timeout/i.test(m),\n build: (host) => `Connection to ${host} timed out — verify the host and port are correct and that the server is reachable.`,\n },\n {\n test: (m) => /password authentication failed/i.test(m),\n build: (host) => `Authentication failed for ${host} — check the username and password in your database URL.`,\n },\n {\n // Must stay anchored to \"database ... does not exist\" (Postgres SQLSTATE\n // 3D000). A bare /does not exist/ is the same trap as the timeout pattern\n // above: it matched dbdiff's own CLI complaint — The \"--allow-destructive\"\n // option does not exist — and rewrote it into \"Database does not exist on\n // 127.0.0.1:5432\", sending you off to check a database name that was fine\n // while the real cause (an outdated @dbdiff/cli) went unmentioned.\n test: (m) => /database\\s+\"[^\"]*\"\\s+does not exist|3D000/i.test(m),\n build: (host) => `Database does not exist on ${host} — verify the database name in your config.`,\n },\n {\n test: (m) => /SSL.*required|no pg_hba.conf entry/i.test(m),\n build: (host) => `Connection rejected by ${host} — the server requires SSL or your IP is not allowed. Check pg_hba.conf and SSL settings.`,\n },\n]\n\n/**\n * Extract host:port from a PostgreSQL connection URL.\n * Returns just the host portion with the port for display.\n */\nfunction extractHost(dbUrl: string): string {\n try {\n const url = new URL(dbUrl)\n return url.port ? `${url.hostname}:${url.port}` : url.hostname\n } catch {\n return 'the configured host'\n }\n}\n\n/**\n * Translate a raw database error into a user-friendly message.\n *\n * Matches known pg error patterns and returns an actionable message\n * with the host identified. Returns the original (redacted) message\n * if no pattern matches.\n */\nexport function friendlyDbError(err: unknown, dbUrl?: string): string {\n const raw = errMsg(err)\n\n // Already a message written for the user, with its own diagnosis and\n // remediation — translating it again can only make it worse, and did:\n // the schema-diff timeout message was being replaced by a connection\n // error naming a host that was demonstrably reachable (issue #29).\n if (isDiagnosticError(err)) return raw\n\n const host = dbUrl ? extractHost(dbUrl) : 'the configured host'\n\n for (const pattern of CONNECTION_ERROR_PATTERNS) {\n try {\n if (pattern.test(raw)) {\n return pattern.build(host)\n }\n } catch {\n // A malformed host or an unexpected pattern failure must never turn a\n // reportable error into a crash — fall through to the raw message.\n }\n }\n\n return raw\n}\n","import type { EnvironmentConfig, SupaForgeConfig } from '../types/config'\nimport type { TableFilter } from '../utils/table-filter'\nimport type { DriftIssue, CheckName } from '../types/drift'\n\nexport interface CheckContext {\n /**\n * Which tables this run is scoped to, resolved from `checks.tables` /\n * `checks.excludeTables` and the `--tables` / `--exclude-tables` flags.\n *\n * Only the schema and data layers act on it — they are the ones backed by\n * @dbdiff/cli, which is where the table concept exists (issue #43). Absent\n * or empty means every table, which is the default.\n */\n tableFilter?: TableFilter\n /**\n * Optional sink for sub-check progress, e.g. the table counter emitted\n * during a long schema diff (issue #29). Checks that have nothing\n * fine-grained to report simply ignore it.\n */\n onDetail?: (detail: string) => void\n source: EnvironmentConfig\n target: EnvironmentConfig\n config: SupaForgeConfig\n}\n\n/**\n * Thrown by a check that cannot run — missing credentials, an absent\n * extension, nothing configured to compare.\n *\n * Checks used to signal this by returning `[]`, which is the same value a\n * genuinely clean scan returns. The distinction was lost before it reached the\n * scanner, so a layer that never ran rendered as a green zero-issue pass\n * (issue #42). Throwing keeps `scan()` returning plain issues while giving the\n * scanner something it cannot mistake for a result.\n *\n * A skip is a normal outcome, not a failure: it carries no stack for the user\n * and is reported separately from errored checks.\n */\nexport class CheckSkipped extends Error {\n /** Distinguishes a skip from a genuine error across module boundaries. */\n override readonly name = 'CheckSkipped'\n\n constructor(reason: string) {\n super(reason)\n }\n}\n\n/**\n * Name-based rather than `instanceof`, which fails when two copies of the\n * module are loaded — a real possibility with bundled output and linked\n * packages.\n */\nexport function isCheckSkipped(err: unknown): err is CheckSkipped {\n return err instanceof Error && err.name === 'CheckSkipped'\n}\n\nexport abstract class Check {\n abstract readonly name: CheckName\n abstract scan(ctx: CheckContext): Promise<DriftIssue[]>\n}\n","import { readdir as fsReaddir } from 'node:fs/promises'\nimport type { QueryFn } from '../db.js'\nimport { pgQuery } from '../db.js'\nimport type { DriftIssue } from '../types/drift.js'\nimport { MIGRATIONS_TABLE } from '../constants.js'\nimport { quoteLiteral } from '../utils/sql.js'\nimport { Check, CheckSkipped, type CheckContext } from './base.js'\nimport type { MigrationsMode } from '../types/config.js'\n\nexport const DEFAULT_MIGRATIONS_DIR = 'supabase/migrations'\n\nconst MIGRATIONS_SQL = `\n SELECT version, name\n FROM ${MIGRATIONS_TABLE}\n ORDER BY version\n`\n\ninterface MigrationRecord {\n version: string\n name: string | null\n}\n\nexport interface LocalMigration {\n version: string\n name: string\n filename: string\n}\n\nexport type ReadDirFn = (dir: string) => Promise<string[]>\n\nconst defaultReadDir: ReadDirFn = async (dir) => {\n const entries = await fsReaddir(dir)\n return entries as string[]\n}\n\nexport class MigrationsCheck extends Check {\n readonly name = 'migrations' as const\n\n constructor(\n private queryFn: QueryFn = pgQuery,\n private readDirFn: ReadDirFn = defaultReadDir,\n ) {\n super()\n }\n\n async scan(ctx: CheckContext): Promise<DriftIssue[]> {\n const dir = ctx.config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR\n const mode = resolveMigrationsMode(ctx.config.checks?.migrations?.mode)\n\n // Nothing to read or query when the check is switched off entirely. It is\n // still reported as skipped rather than clean, so turning it off does not\n // look like a layer that passed (issue #42).\n if (mode === 'ignore') throw new CheckSkipped(\"checks.migrations.mode is 'ignore'\")\n\n const [local, db] = await Promise.all([\n readLocalMigrations(dir, this.readDirFn),\n this.fetchDbMigrations(ctx.target.dbUrl),\n ])\n\n return diffMigrations(local, db, mode)\n }\n\n private async fetchDbMigrations(dbUrl: string): Promise<MigrationRecord[]> {\n try {\n return await this.queryFn(dbUrl, MIGRATIONS_SQL) as unknown as MigrationRecord[]\n } catch {\n // schema_migrations table doesn't exist — no records to compare\n return []\n }\n }\n}\n\n/**\n * Parse a migration filename into version + name.\n * Handles both `20240101000000_create_users.sql` and `001_initial_schema.sql`.\n */\nexport function parseFilename(filename: string): { version: string; name: string } | null {\n if (!filename.endsWith('.sql')) return null\n const match = filename.replace(/\\.sql$/, '').match(/^(\\d+)_(.+)$/)\n if (!match) return null\n return { version: match[1], name: match[2] }\n}\n\nexport async function readLocalMigrations(\n dir: string,\n readDirFn: ReadDirFn = defaultReadDir,\n): Promise<LocalMigration[]> {\n let files: string[]\n try {\n files = (await readDirFn(dir)).filter(f => f.endsWith('.sql')).sort()\n } catch {\n return []\n }\n\n const migrations: LocalMigration[] = []\n for (const filename of files) {\n const parsed = parseFilename(filename)\n if (!parsed) continue\n migrations.push({ ...parsed, filename })\n }\n return migrations\n}\n\nconst MIGRATIONS_MODES: MigrationsMode[] = ['auto', 'warn', 'ignore']\n\n/**\n * Normalise the configured mode.\n *\n * An unrecognised value falls back to 'auto' rather than throwing — a typo in\n * a config file should not take the whole scan down, and 'auto' is the least\n * surprising default.\n */\nexport function resolveMigrationsMode(raw: unknown): MigrationsMode {\n return MIGRATIONS_MODES.includes(raw as MigrationsMode) ? (raw as MigrationsMode) : 'auto'\n}\n\n/**\n * One INFO describing a project that applies migrations outside the Supabase\n * CLI, instead of one warning per file.\n *\n * schema_migrations is a Supabase CLI convention, not a database requirement.\n * Projects that apply migrations via psql or the SQL editor never populate it,\n * so every local file was reported as \"unapplied\" on every scan — all false\n * positives, and enough of them to drown the rest of the layer (issue #31).\n */\nfunction untrackedWorkflowIssue(local: LocalMigration[]): DriftIssue {\n const noun = local.length === 1 ? 'file' : 'files'\n return {\n id: 'migration-workflow-untracked',\n check: 'migrations',\n severity: 'info',\n title: `Untracked migration workflow: ${local.length} local ${noun}, none recorded`,\n description:\n `${MIGRATIONS_TABLE} is empty while ${local.length} migration ${noun} exist locally. ` +\n 'That is the normal shape for a project applying migrations outside the Supabase CLI ' +\n '(psql, the SQL editor, or another tool), so each file is not reported separately. ' +\n 'Run `supaforge migrate baseline` to record them as applied, or set ' +\n 'checks.migrations.mode to \"warn\" to report every file, or \"ignore\" to disable this check.',\n sourceValue: `${local.length} local migration ${noun}`,\n }\n}\n\nexport function diffMigrations(\n local: LocalMigration[],\n db: MigrationRecord[],\n mode: MigrationsMode = 'auto',\n): DriftIssue[] {\n if (mode === 'ignore') return []\n\n const issues: DriftIssue[] = []\n const dbMap = new Map(db.map(r => [r.version, r]))\n const localMap = new Map(local.map(m => [m.version, m]))\n const unapplied = local.filter(m => !dbMap.has(m.version))\n\n // Nothing tracked at all, but files on disk: report the workflow once\n // rather than each file. Requires db to be *entirely* empty — a project\n // that tracks some migrations and missed others has genuine drift.\n if (mode === 'auto' && db.length === 0 && unapplied.length > 0) {\n issues.push(untrackedWorkflowIssue(local))\n } else {\n for (const migration of unapplied) {\n issues.push({\n id: `migration-unapplied-${migration.version}`,\n check: 'migrations',\n severity: 'warning',\n title: `Unapplied migration: ${migration.filename}`,\n description: `Migration file \"${migration.filename}\" exists locally but is not recorded in ${MIGRATIONS_TABLE}.`,\n sourceValue: migration.filename,\n sql: {\n up: markAppliedSql(migration.version, migration.name),\n down: `DELETE FROM ${MIGRATIONS_TABLE} WHERE version = ${quoteLiteral(migration.version)};`,\n },\n })\n }\n }\n\n // DB records without local files (untracked)\n for (const [version, record] of dbMap) {\n if (!localMap.has(version)) {\n issues.push({\n id: `migration-untracked-${version}`,\n check: 'migrations',\n severity: 'info',\n title: `Untracked migration: ${version}`,\n description: `Migration version \"${version}\"${record.name ? ` (${record.name})` : ''} is recorded in the database but has no corresponding local file.`,\n targetValue: record,\n })\n }\n }\n\n return issues\n}\n\n/** SQL to insert a migration record into schema_migrations (mark as applied). */\nfunction markAppliedSql(version: string, name: string): string {\n return [\n `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)`,\n `VALUES (${quoteLiteral(version)}, ${quoteLiteral(name)}, '{}')`,\n `ON CONFLICT (version) DO NOTHING;`,\n ].join('\\n')\n}\n","/**\n * Shared SQL escaping utilities for generating safe SQL strings.\n *\n * Used across checks, snapshots, and migration layers to avoid\n * duplicating quoting logic.\n */\n\n/**\n * Quote a schema-qualified or bare identifier for safe inclusion in SQL.\n * Handles `schema.table` → `\"schema\".\"table\"` and bare `table` → `\"table\"`.\n */\nexport function quoteIdent(name: string): string {\n return name.split('.').map(p => `\"${p.replace(/\"/g, '\"\"')}\"`).join('.')\n}\n\n/**\n * Quote a bare identifier (single name, no dot-splitting).\n * Use for column/table names that should never be schema-qualified.\n */\nexport function quoteName(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`\n}\n\n/**\n * Quote a string value for safe inclusion as a SQL literal.\n * Escapes single quotes by doubling them.\n */\nexport function quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`\n}\n\n/**\n * Convert a JavaScript value to a SQL literal representation.\n * Handles null, boolean, number, array, and string types.\n */\nexport function sqlLiteral(val: unknown): string {\n if (val === null || val === undefined) return 'NULL'\n if (typeof val === 'boolean') return val ? 'true' : 'false'\n if (typeof val === 'number') return String(val)\n if (Array.isArray(val)) return `ARRAY[${val.map(v => quoteLiteral(String(v))).join(', ')}]`\n return quoteLiteral(String(val))\n}\n"],"mappings":";;;;;;AAAA,OAAO,QAAQ;AAcR,SAAS,0BAAkC;AAChD,QAAM,MAAM,QAAQ,IAAI;AACxB,MAAI,KAAK;AACP,UAAM,OAAO,OAAO,GAAG;AACvB,QAAI,OAAO,SAAS,IAAI,KAAK,OAAO,EAAG,QAAO,KAAK,MAAM,OAAO,GAAI;AAAA,EACtE;AACA,SAAO;AACT;AASO,SAAS,eAAe,OAAe,gBAA0C;AACtF,QAAM,SAA0B;AAAA,IAC9B,kBAAkB;AAAA,IAClB,yBAAyB,wBAAwB;AAAA,EACnD;AACA,MAAI,mBAAmB,QAAW;AAChC,WAAO,gBAAgB;AAAA,EACzB;AACA,SAAO;AACT;AAiBA,IAAM,QAAQ,oBAAI,IAAqB;AAMvC,IAAM,WAAW;AAEjB,SAAS,QAAQ,OAAwB;AACvC,QAAM,WAAW,MAAM,IAAI,KAAK;AAChC,MAAI,SAAU,QA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AK,aAAa,IAAI,CAAC;AAAA,IACvD;AAAA,EACF,EAAE,KAAK,IAAI;AACb;","names":[]}
|
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
import {
|
|
2
|
+
sanitizeForReport
|
|
3
|
+
} from "./chunk-4OU7KO5Y.js";
|
|
4
|
+
import {
|
|
5
|
+
coverage,
|
|
6
|
+
formatSkips,
|
|
7
|
+
renderDetailed,
|
|
8
|
+
renderSummary
|
|
9
|
+
} from "./chunk-LQXF65MC.js";
|
|
10
|
+
import {
|
|
11
|
+
CHECK_META,
|
|
12
|
+
CHECK_NAMES,
|
|
13
|
+
createDefaultRegistry,
|
|
14
|
+
describeTableFilter,
|
|
15
|
+
isFiltered,
|
|
16
|
+
planWork,
|
|
17
|
+
promote,
|
|
18
|
+
resolveTableFilter,
|
|
19
|
+
scan,
|
|
20
|
+
summarizeByKind
|
|
21
|
+
} from "./chunk-5Z3SAIQS.js";
|
|
22
|
+
import {
|
|
23
|
+
comparedSchemas,
|
|
24
|
+
proofScope,
|
|
25
|
+
proveConvergence,
|
|
26
|
+
residualHeldBack
|
|
27
|
+
} from "./chunk-TQJSQLWA.js";
|
|
28
|
+
import {
|
|
29
|
+
renderTip
|
|
30
|
+
} from "./chunk-BLKJWDTL.js";
|
|
31
|
+
import {
|
|
32
|
+
BaseCommand
|
|
33
|
+
} from "./chunk-SF3YA42C.js";
|
|
34
|
+
import {
|
|
35
|
+
isCloneDatabase,
|
|
36
|
+
sourceLooksLikeCloneOf
|
|
37
|
+
} from "./chunk-5QQBTLWO.js";
|
|
38
|
+
import {
|
|
39
|
+
parseFlagList
|
|
40
|
+
} from "./chunk-DQQ5E563.js";
|
|
41
|
+
import {
|
|
42
|
+
CLONE_SKIP_FLAGS,
|
|
43
|
+
DEFAULT_IGNORE_SCHEMAS,
|
|
44
|
+
bold,
|
|
45
|
+
cmd,
|
|
46
|
+
dim,
|
|
47
|
+
ok,
|
|
48
|
+
schemaDiffIgnores,
|
|
49
|
+
warn
|
|
50
|
+
} from "./chunk-6WAMNZLO.js";
|
|
51
|
+
|
|
52
|
+
// src/commands/diff.ts
|
|
53
|
+
import { Flags } from "@oclif/core";
|
|
54
|
+
|
|
55
|
+
// src/ci.ts
|
|
56
|
+
function escapeData(value) {
|
|
57
|
+
return value.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
|
|
58
|
+
}
|
|
59
|
+
function escapeProperty(value) {
|
|
60
|
+
return escapeData(value).replace(/:/g, "%3A").replace(/,/g, "%2C");
|
|
61
|
+
}
|
|
62
|
+
function formatAnnotation(issue) {
|
|
63
|
+
const level = issue.severity === "critical" ? "error" : "warning";
|
|
64
|
+
const title = escapeProperty(issue.title);
|
|
65
|
+
const message = escapeData(issue.description);
|
|
66
|
+
return `::${level} title=${title}::${message}`;
|
|
67
|
+
}
|
|
68
|
+
function formatGitHubAnnotations(result) {
|
|
69
|
+
const lines = [];
|
|
70
|
+
for (const check of result.checks) {
|
|
71
|
+
for (const issue of check.issues) {
|
|
72
|
+
lines.push(formatAnnotation(issue));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return lines;
|
|
76
|
+
}
|
|
77
|
+
function exceeds(counts, failOn) {
|
|
78
|
+
if (failOn === "critical") return counts.critical > 0;
|
|
79
|
+
if (failOn === "warning") return counts.critical > 0 || counts.warning > 0;
|
|
80
|
+
return counts.total > 0;
|
|
81
|
+
}
|
|
82
|
+
function computeCiExitCode(result, failOn = "critical", opts = {}) {
|
|
83
|
+
const hasError = result.checks.some((c) => c.status === "error");
|
|
84
|
+
if (hasError) return 2;
|
|
85
|
+
const { drift, posture } = summarizeByKind(result.checks);
|
|
86
|
+
if (exceeds(drift, failOn)) return 1;
|
|
87
|
+
if (opts.failOnPosture && exceeds(posture, failOn)) return 1;
|
|
88
|
+
return 0;
|
|
89
|
+
}
|
|
90
|
+
function formatCiSummary(result) {
|
|
91
|
+
const criticalIssues = [];
|
|
92
|
+
const warningIssues = [];
|
|
93
|
+
const errors = [];
|
|
94
|
+
const skipped = [];
|
|
95
|
+
for (const check of result.checks ?? []) {
|
|
96
|
+
if (check?.status === "error") {
|
|
97
|
+
errors.push({ check: check.check, message: check.error ?? "Check failed with no error message" });
|
|
98
|
+
}
|
|
99
|
+
if (check?.status === "skipped") {
|
|
100
|
+
skipped.push({ check: check.check, reason: check.skipReason ?? "no reason given" });
|
|
101
|
+
}
|
|
102
|
+
for (const issue of check?.issues ?? []) {
|
|
103
|
+
const entry = { check: check.check, id: issue.id, title: issue.title };
|
|
104
|
+
if (issue.severity === "critical") {
|
|
105
|
+
criticalIssues.push(entry);
|
|
106
|
+
} else if (issue.severity === "warning") {
|
|
107
|
+
warningIssues.push(entry);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
timestamp: result.timestamp,
|
|
113
|
+
score: result.score,
|
|
114
|
+
postureScore: result.postureScore ?? null,
|
|
115
|
+
summary: result.summary,
|
|
116
|
+
errors,
|
|
117
|
+
skipped,
|
|
118
|
+
coverage: coverage(result),
|
|
119
|
+
criticalIssues,
|
|
120
|
+
warningIssues
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// src/commands/diff.ts
|
|
125
|
+
function describeCheckOutcome(status, issueCount, skipReason) {
|
|
126
|
+
if (status === "error") return { glyph: warn("\u2717"), text: warn("error") };
|
|
127
|
+
if (status === "skipped") {
|
|
128
|
+
return { glyph: dim("\u25CB"), text: dim(`skipped \u2014 ${skipReason ?? "no reason given"}`) };
|
|
129
|
+
}
|
|
130
|
+
return { glyph: ok("\u2713"), text: `${issueCount} issues` };
|
|
131
|
+
}
|
|
132
|
+
var APPLY_ONLY_FLAGS = [
|
|
133
|
+
{ flag: "prove", shapesThePlan: false },
|
|
134
|
+
{ flag: "no-transaction", shapesThePlan: false },
|
|
135
|
+
{ flag: "only", shapesThePlan: true },
|
|
136
|
+
{ flag: "apply-posture", shapesThePlan: true },
|
|
137
|
+
{ flag: "allow-destructive", shapesThePlan: true }
|
|
138
|
+
];
|
|
139
|
+
function inertApplyFlags(flags) {
|
|
140
|
+
if (flags["apply"]) return [];
|
|
141
|
+
const dryRun = Boolean(flags["dry-run"]);
|
|
142
|
+
return APPLY_ONLY_FLAGS.filter(({ flag, shapesThePlan }) => {
|
|
143
|
+
const given = flags[flag];
|
|
144
|
+
const passed = Array.isArray(given) ? given.length > 0 : Boolean(given);
|
|
145
|
+
if (!passed) return false;
|
|
146
|
+
return !(dryRun && shapesThePlan);
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
var Diff = class _Diff extends BaseCommand {
|
|
150
|
+
static description = "Detect drift between Supabase environments and optionally fix it";
|
|
151
|
+
static examples = [
|
|
152
|
+
"<%= config.bin %> diff",
|
|
153
|
+
"<%= config.bin %> diff --detail",
|
|
154
|
+
"<%= config.bin %> diff --apply",
|
|
155
|
+
"<%= config.bin %> diff --check=rls",
|
|
156
|
+
"<%= config.bin %> diff --check=rls --apply",
|
|
157
|
+
"<%= config.bin %> diff --source=staging --target=production",
|
|
158
|
+
"<%= config.bin %> diff --skip=storage --skip=vault",
|
|
159
|
+
"<%= config.bin %> diff --tables=orders,order_items",
|
|
160
|
+
"<%= config.bin %> diff --tables='billing_*' --exclude-tables='*_audit'",
|
|
161
|
+
"<%= config.bin %> diff --tables=orders --detail",
|
|
162
|
+
// Built from the same constant the tips and the post-clone output use, so
|
|
163
|
+
// the advice cannot fall behind the check list again: this example predated
|
|
164
|
+
// Layer 14 and omitted `roles`, which on a real clone → remote diff is 227
|
|
165
|
+
// of the findings someone following it was left to puzzle over (issue #70).
|
|
166
|
+
`<%= config.bin %> diff ${CLONE_SKIP_FLAGS}`,
|
|
167
|
+
"<%= config.bin %> diff --ci",
|
|
168
|
+
"<%= config.bin %> diff --ci --fail-on=warning"
|
|
169
|
+
];
|
|
170
|
+
/**
|
|
171
|
+
* Read from the environment rather than passed as flags, because they tune
|
|
172
|
+
* limits rather than select behaviour. Rendered as their own `--help`
|
|
173
|
+
* section (issue #40); the README carries the same table plus the timeout
|
|
174
|
+
* precedence chain.
|
|
175
|
+
*/
|
|
176
|
+
static envVars = [
|
|
177
|
+
{ name: "SUPAFORGE_CONNECT_TIMEOUT", description: "Seconds before a database connection attempt is abandoned (default 15)." },
|
|
178
|
+
{ name: "SUPAFORGE_DBDIFF_TIMEOUT", description: "Seconds before the schema/data diff is abandoned. Overrides checks.schema.timeout (default 600)." },
|
|
179
|
+
{ name: "SUPAFORGE_DBDIFF_MEMORY", description: "PHP memory limit for @dbdiff/cli \u2014 512M, 2G, or -1 for unlimited (default dbdiff's own 1G)." }
|
|
180
|
+
];
|
|
181
|
+
static flags = {
|
|
182
|
+
check: Flags.string({
|
|
183
|
+
char: "l",
|
|
184
|
+
description: "Limit to a specific check",
|
|
185
|
+
options: [...CHECK_NAMES]
|
|
186
|
+
}),
|
|
187
|
+
skip: Flags.string({
|
|
188
|
+
char: "x",
|
|
189
|
+
description: "Skip a specific check (repeatable). Also configurable via checks.exclude in supaforge.config.json.",
|
|
190
|
+
options: [...CHECK_NAMES],
|
|
191
|
+
multiple: true
|
|
192
|
+
}),
|
|
193
|
+
detail: Flags.boolean({
|
|
194
|
+
description: "Show detailed SQL diffs (default: summary)",
|
|
195
|
+
default: false
|
|
196
|
+
}),
|
|
197
|
+
apply: Flags.boolean({
|
|
198
|
+
description: "Apply SQL fixes to resolve drift in the target environment",
|
|
199
|
+
default: false
|
|
200
|
+
}),
|
|
201
|
+
"allow-destructive": Flags.boolean({
|
|
202
|
+
description: "With --apply, also run fixes that drop tables or columns (destroys data)",
|
|
203
|
+
default: false
|
|
204
|
+
}),
|
|
205
|
+
"dry-run": Flags.boolean({
|
|
206
|
+
description: "With --apply, print the fixes in the order they would run without executing any of them",
|
|
207
|
+
default: false
|
|
208
|
+
}),
|
|
209
|
+
"no-transaction": Flags.boolean({
|
|
210
|
+
description: "With --apply, run each fix on its own instead of rolling the whole set back on the first failure",
|
|
211
|
+
aliases: ["continue-on-error"],
|
|
212
|
+
default: false
|
|
213
|
+
}),
|
|
214
|
+
only: Flags.string({
|
|
215
|
+
description: "With --apply, only apply these issue ids (repeatable, comma-separated, globs allowed). Ids come from --json.",
|
|
216
|
+
multiple: true
|
|
217
|
+
}),
|
|
218
|
+
"include-files": Flags.boolean({
|
|
219
|
+
description: "Include file-level drift detection in storage check",
|
|
220
|
+
default: false
|
|
221
|
+
}),
|
|
222
|
+
tables: Flags.string({
|
|
223
|
+
description: "Only compare these tables in the schema and data checks (repeatable, comma-separated, globs allowed). Overrides checks.tables.",
|
|
224
|
+
multiple: true
|
|
225
|
+
}),
|
|
226
|
+
"exclude-tables": Flags.string({
|
|
227
|
+
description: "Never compare these tables (repeatable, comma-separated, globs allowed). Merged with checks.excludeTables.",
|
|
228
|
+
multiple: true
|
|
229
|
+
}),
|
|
230
|
+
json: Flags.boolean({ description: "Output results as JSON" }),
|
|
231
|
+
source: Flags.string({ char: "s", description: "Source environment name" }),
|
|
232
|
+
target: Flags.string({ char: "t", description: "Target environment name" }),
|
|
233
|
+
ci: Flags.boolean({
|
|
234
|
+
description: "CI mode: emit GitHub Actions annotations and use semantic exit codes (0=clean, 1=drift, 2=error)",
|
|
235
|
+
default: false
|
|
236
|
+
}),
|
|
237
|
+
prove: Flags.boolean({
|
|
238
|
+
description: "Before applying, replay the migration on a throwaway clone of the target and verify it reproduces the source exactly. Refuses to apply if it does not.",
|
|
239
|
+
default: false
|
|
240
|
+
}),
|
|
241
|
+
"apply-posture": Flags.boolean({
|
|
242
|
+
description: "With --apply, also apply fixes from checks that judge the target on its own (RLS coverage, migration history). Off by default: those fixes move the target away from the source and so create drift.",
|
|
243
|
+
default: false
|
|
244
|
+
}),
|
|
245
|
+
"fail-on": Flags.string({
|
|
246
|
+
description: "Threshold for a non-zero exit in CI mode",
|
|
247
|
+
options: ["critical", "warning", "any"],
|
|
248
|
+
default: "critical"
|
|
249
|
+
}),
|
|
250
|
+
"fail-on-posture": Flags.boolean({
|
|
251
|
+
description: "Let findings from the target-only checks (RLS coverage, migration history) affect the exit code too. Off by default: they fire identically whichever pair you diff, so they cannot indicate that the environments have diverged.",
|
|
252
|
+
default: false
|
|
253
|
+
})
|
|
254
|
+
};
|
|
255
|
+
/**
|
|
256
|
+
* Report what `--apply` did, or — under `--dry-run` — what it would do.
|
|
257
|
+
*
|
|
258
|
+
* The applied list is printed in execution order, which is now dependency
|
|
259
|
+
* order rather than the order the checks reported the issues. That ordering
|
|
260
|
+
* is the whole point of the dry run: it is what makes the outcome of a real
|
|
261
|
+
* apply predictable before running it (issue #48).
|
|
262
|
+
*/
|
|
263
|
+
renderApplyResult(result, dryRun) {
|
|
264
|
+
const verb = dryRun ? "Would apply" : "Applied";
|
|
265
|
+
if (result.applied.length > 0) {
|
|
266
|
+
const heading = `${verb} ${result.applied.length} fix(es)${dryRun ? ", in this order" : ""}:`;
|
|
267
|
+
this.log(dryRun ? bold(heading) : ok(heading));
|
|
268
|
+
result.applied.forEach((stmt, i) => {
|
|
269
|
+
const glyph = dryRun ? dim(`${i + 1}.`) : ok("\u2713");
|
|
270
|
+
this.log(` ${glyph} ${dim(`[${stmt.check}]`)} ${stmt.issueId}`);
|
|
271
|
+
if (dryRun && stmt.sql) this.log(` ${dim(stmt.sql.replace(/\s*\n\s*/g, " "))}`);
|
|
272
|
+
if (dryRun && stmt.action) this.log(` ${dim(stmt.action)}`);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
if (result.skipped.length > 0) {
|
|
276
|
+
this.log(`
|
|
277
|
+
${dim(`Skipped ${result.skipped.length} issue(s):`)}`);
|
|
278
|
+
for (const line of formatSkips(result.skipped)) this.log(` ${dim(line)}`);
|
|
279
|
+
}
|
|
280
|
+
if (result.rolledBack?.length) {
|
|
281
|
+
this.log(`
|
|
282
|
+
${warn(`Rolled back ${result.rolledBack.length} fix(es)`)} \u2014 the target is unchanged:`);
|
|
283
|
+
for (const item of result.rolledBack) {
|
|
284
|
+
this.log(` ${dim("\u21A9")} ${dim(`[${item.check}]`)} ${item.issueId}`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (result.errors.length > 0) {
|
|
288
|
+
this.log(`
|
|
289
|
+
${warn(`${result.errors.length} error(s):`)}`);
|
|
290
|
+
for (const item of result.errors) {
|
|
291
|
+
this.log(` ${warn("\u2717")} ${dim(`[${item.check}]`)} ${item.issueId}: ${item.error}`);
|
|
292
|
+
}
|
|
293
|
+
if (result.rolledBack) {
|
|
294
|
+
this.log(`
|
|
295
|
+
${dim(`Nothing was written. Re-run with ${cmd("--no-transaction")} to apply the fixes that do work.`)}`);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (dryRun) {
|
|
299
|
+
this.log(`
|
|
300
|
+
${dim(`Nothing was executed. Drop ${cmd("--dry-run")} to apply.`)}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
async run() {
|
|
304
|
+
const { flags } = await this.parse(_Diff);
|
|
305
|
+
for (const { flag, shapesThePlan } of inertApplyFlags(flags)) {
|
|
306
|
+
const suggestion = shapesThePlan ? `Add ${cmd("--apply")} (or ${cmd("--dry-run")} to preview) for it to take effect.` : `Add ${cmd("--apply")} for it to take effect.`;
|
|
307
|
+
process.stderr.write(` ${warn(`--${flag} has no effect without --apply.`)} ${suggestion}
|
|
308
|
+
`);
|
|
309
|
+
}
|
|
310
|
+
const config = await this.loadConfigOrFail();
|
|
311
|
+
this.validateDualEnvConfig(config, flags.source, flags.target);
|
|
312
|
+
const registry = createDefaultRegistry({ includeFiles: flags["include-files"] });
|
|
313
|
+
const checks = flags.check ? [flags.check] : void 0;
|
|
314
|
+
const skip = flags.skip?.length ? flags.skip : void 0;
|
|
315
|
+
const tableFilter = resolveTableFilter(config, {
|
|
316
|
+
tables: flags.tables,
|
|
317
|
+
excludeTables: flags["exclude-tables"]
|
|
318
|
+
});
|
|
319
|
+
if (isFiltered(tableFilter) && !flags.json && !flags.ci) {
|
|
320
|
+
this.log(`
|
|
321
|
+
${dim(describeTableFilter(tableFilter))}`);
|
|
322
|
+
}
|
|
323
|
+
if (!flags.json && !flags.ci) {
|
|
324
|
+
const sourceEnv = config.environments[config.source];
|
|
325
|
+
const targetEnv = config.environments[config.target];
|
|
326
|
+
const pre = this.createPreflight("Diff preflight checks").addDatabase("Source", config.source, sourceEnv.dbUrl).addDatabase("Target", config.target, targetEnv.dbUrl);
|
|
327
|
+
await this.runPreflight(pre, "Diff");
|
|
328
|
+
}
|
|
329
|
+
const makeProgress = () => {
|
|
330
|
+
if (flags.json || flags.ci) return void 0;
|
|
331
|
+
process.stdout.write("\n Scanning...\n");
|
|
332
|
+
return (event) => {
|
|
333
|
+
const meta = CHECK_META[event.check];
|
|
334
|
+
const label = meta?.label ?? event.check;
|
|
335
|
+
const idx = `[${event.index + 1}/${event.total}]`;
|
|
336
|
+
if (event.phase === "check:start") {
|
|
337
|
+
process.stdout.write(` \u25B6 ${idx} ${label}...
|
|
338
|
+
`);
|
|
339
|
+
} else {
|
|
340
|
+
if (process.stdout.isTTY) process.stdout.write("\r\x1B[2K");
|
|
341
|
+
const dur = `${(event.durationMs / 1e3).toFixed(1)}s`;
|
|
342
|
+
const { glyph, text } = describeCheckOutcome(event.status, event.issueCount, event.skipReason);
|
|
343
|
+
process.stdout.write(` ${glyph} ${idx} ${label.padEnd(24)} ${text} (${dur})
|
|
344
|
+
`);
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
};
|
|
348
|
+
const makeDetail = () => {
|
|
349
|
+
if (flags.json || flags.ci || !process.stdout.isTTY) return void 0;
|
|
350
|
+
return (_check, detail) => {
|
|
351
|
+
process.stdout.write(`\r\x1B[2K ${dim(detail)}`);
|
|
352
|
+
};
|
|
353
|
+
};
|
|
354
|
+
if (flags.apply || flags["dry-run"]) {
|
|
355
|
+
const onProgress2 = makeProgress();
|
|
356
|
+
const scanResult = await scan(registry, { config, checks, skip, tableFilter, onProgress: onProgress2, onDetail: makeDetail() });
|
|
357
|
+
this.setCheckSummaries(scanResult.checks.map((c) => ({
|
|
358
|
+
check: c.check,
|
|
359
|
+
status: c.status,
|
|
360
|
+
issueCount: c.issues.length,
|
|
361
|
+
durationMs: c.durationMs,
|
|
362
|
+
...c.error ? { error: sanitizeForReport(c.error) } : {}
|
|
363
|
+
})));
|
|
364
|
+
if (scanResult.summary.total === 0) {
|
|
365
|
+
if (flags.json) {
|
|
366
|
+
const empty = { applied: [], skipped: [], errors: [] };
|
|
367
|
+
this.json(empty);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
this.log(`${ok("No drift detected.")} Nothing to apply. \u2713`);
|
|
371
|
+
this.log(renderTip({ command: "diff", apply: true, driftTotal: 0 }));
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const targetEnv = config.environments[config.target];
|
|
375
|
+
const dryRun = flags["dry-run"];
|
|
376
|
+
if (flags.prove && !dryRun) {
|
|
377
|
+
const sourceEnv = config.environments[config.source];
|
|
378
|
+
const planned = planWork(scanResult, {
|
|
379
|
+
checks,
|
|
380
|
+
only: parseFlagList(flags.only),
|
|
381
|
+
allowDestructive: flags["allow-destructive"],
|
|
382
|
+
tableFilter,
|
|
383
|
+
applyPosture: flags["apply-posture"]
|
|
384
|
+
});
|
|
385
|
+
const { replay, unproved } = proofScope(planned.sqlStatements);
|
|
386
|
+
const migrationSql = replay.map((s) => s.sql).join("\n");
|
|
387
|
+
this.log(`
|
|
388
|
+
${dim("Proving convergence on a throwaway clone\u2026")}`);
|
|
389
|
+
if (unproved.length > 0) {
|
|
390
|
+
const byCheck = [...new Set(unproved.map((s) => s.check))].map((c) => `${c} \xD7${unproved.filter((s) => s.check === c).length}`).join(", ");
|
|
391
|
+
this.log(` ${dim(`Not proved \u2014 act outside the proved schemas or on the whole server: ${byCheck}`)}`);
|
|
392
|
+
}
|
|
393
|
+
const proof = replay.length === 0 ? { converged: false, residual: [], cloneName: "", skipped: "none of the planned fixes is one the proof can replay" } : await proveConvergence({
|
|
394
|
+
sourceUrl: sourceEnv.dbUrl,
|
|
395
|
+
targetUrl: targetEnv.dbUrl,
|
|
396
|
+
migrationSql,
|
|
397
|
+
// Every schema the schema diff compares, not `public` alone: a
|
|
398
|
+
// migration dropping a schema the source lacks runs against it.
|
|
399
|
+
schemas: await comparedSchemas(
|
|
400
|
+
sourceEnv.dbUrl,
|
|
401
|
+
targetEnv.dbUrl,
|
|
402
|
+
schemaDiffIgnores(config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS)
|
|
403
|
+
),
|
|
404
|
+
// The checks this run compares: without the schema check, what the
|
|
405
|
+
// target already lacks elsewhere is not this migration's to fix.
|
|
406
|
+
checks: scanResult.checks.map((c) => c.check)
|
|
407
|
+
});
|
|
408
|
+
if (proof.skipped) {
|
|
409
|
+
this.log(` ${warn("Convergence not proven")}: ${proof.skipped}`);
|
|
410
|
+
this.log(` ${dim("Continuing \u2014 re-run without --prove to silence this.")}
|
|
411
|
+
`);
|
|
412
|
+
} else if (!proof.converged && residualHeldBack(proof.residual, heldBackSql(scanResult, planned)).unexplained.length === 0) {
|
|
413
|
+
this.log(` ${ok("Converged")}, apart from what is held back and stays on the target:`);
|
|
414
|
+
for (const line of proof.residual.slice(0, 15)) this.log(` ${dim(line)}`);
|
|
415
|
+
this.log("");
|
|
416
|
+
} else if (!proof.converged) {
|
|
417
|
+
this.log(` ${warn("Migration does not reproduce the source.")} Nothing was applied.
|
|
418
|
+
`);
|
|
419
|
+
const { unexplained } = residualHeldBack(proof.residual, heldBackSql(scanResult, planned));
|
|
420
|
+
for (const line of unexplained.slice(0, 15)) this.log(` ${line}`);
|
|
421
|
+
if (unexplained.length > 15) {
|
|
422
|
+
this.log(` ${dim(`\u2026and ${unexplained.length - 15} more`)}`);
|
|
423
|
+
}
|
|
424
|
+
this.log(`
|
|
425
|
+
${dim("These objects would still differ after applying.")}`);
|
|
426
|
+
this.exit(1);
|
|
427
|
+
} else {
|
|
428
|
+
if (proof.outOfScope?.length) {
|
|
429
|
+
this.log(` ${ok("Converged")} on what this run compares. Outside it, and already different before:`);
|
|
430
|
+
for (const line of proof.outOfScope.slice(0, 15)) this.log(` ${dim(line)}`);
|
|
431
|
+
if (proof.outOfScope.length > 15) this.log(` ${dim(`\u2026and ${proof.outOfScope.length - 15} more`)}`);
|
|
432
|
+
this.log("");
|
|
433
|
+
} else {
|
|
434
|
+
this.log(` ${ok("Converged")} \u2014 the migration reproduces the source exactly.
|
|
435
|
+
`);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
const result2 = await promote({
|
|
440
|
+
dbUrl: targetEnv.dbUrl,
|
|
441
|
+
scanResult,
|
|
442
|
+
checks,
|
|
443
|
+
dryRun,
|
|
444
|
+
allowDestructive: flags["allow-destructive"],
|
|
445
|
+
tableFilter,
|
|
446
|
+
only: parseFlagList(flags.only),
|
|
447
|
+
applyPosture: flags["apply-posture"],
|
|
448
|
+
transactional: !flags["no-transaction"]
|
|
449
|
+
});
|
|
450
|
+
if (flags.json) {
|
|
451
|
+
this.json(result2);
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
this.renderApplyResult(result2, dryRun);
|
|
455
|
+
if (result2.errors.length > 0) {
|
|
456
|
+
this.exit(1);
|
|
457
|
+
}
|
|
458
|
+
this.log(renderTip({
|
|
459
|
+
command: "diff",
|
|
460
|
+
apply: true,
|
|
461
|
+
driftTotal: scanResult.summary.total,
|
|
462
|
+
driftedChecks: scanResult.checks.filter((c) => c.status === "drifted").map((c) => c.check)
|
|
463
|
+
}));
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const onProgress = makeProgress();
|
|
467
|
+
const result = await scan(registry, { config, checks, skip, tableFilter, onProgress, onDetail: makeDetail() });
|
|
468
|
+
this.setCheckSummaries(result.checks.map((c) => ({
|
|
469
|
+
check: c.check,
|
|
470
|
+
status: c.status,
|
|
471
|
+
issueCount: c.issues.length,
|
|
472
|
+
durationMs: c.durationMs,
|
|
473
|
+
...c.error ? { error: sanitizeForReport(c.error) } : {}
|
|
474
|
+
})));
|
|
475
|
+
const sourceUrl = config.environments[config.source]?.dbUrl;
|
|
476
|
+
const sourceIsClone = await isCloneDatabase(sourceUrl) || await sourceLooksLikeCloneOf(sourceUrl, config.environments[config.target]?.dbUrl);
|
|
477
|
+
const driftedChecks = result.checks.filter((c) => c.status === "drifted").map((c) => c.check);
|
|
478
|
+
const skippedChecks = result.checks.filter((c) => c.status === "skipped").map((c) => c.check);
|
|
479
|
+
const erroredChecks = result.checks.filter((c) => c.status === "error").map((c) => c.check);
|
|
480
|
+
if (flags.ci) {
|
|
481
|
+
const failOn = flags["fail-on"] ?? "critical";
|
|
482
|
+
const annotations = formatGitHubAnnotations(result);
|
|
483
|
+
for (const line of annotations) {
|
|
484
|
+
process.stderr.write(line + "\n");
|
|
485
|
+
}
|
|
486
|
+
const summary = formatCiSummary(result);
|
|
487
|
+
process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
|
|
488
|
+
const exitCode = computeCiExitCode(result, failOn, {
|
|
489
|
+
failOnPosture: flags["fail-on-posture"]
|
|
490
|
+
});
|
|
491
|
+
if (exitCode !== 0) {
|
|
492
|
+
this.exit(exitCode);
|
|
493
|
+
}
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
if (flags.json) {
|
|
497
|
+
this.json(result);
|
|
498
|
+
} else if (flags.detail) {
|
|
499
|
+
this.log(renderDetailed(result));
|
|
500
|
+
this.log(renderTip({
|
|
501
|
+
command: "diff",
|
|
502
|
+
detail: true,
|
|
503
|
+
driftTotal: result.summary.total,
|
|
504
|
+
driftedChecks,
|
|
505
|
+
skippedChecks,
|
|
506
|
+
erroredChecks,
|
|
507
|
+
singleCheck: checks?.[0],
|
|
508
|
+
sourceIsClone
|
|
509
|
+
}));
|
|
510
|
+
} else {
|
|
511
|
+
this.log(renderSummary(result));
|
|
512
|
+
if (result.summary.total > 0) {
|
|
513
|
+
this.log(` \u2192 Run with ${cmd("--detail")} to see SQL diffs`);
|
|
514
|
+
this.log(
|
|
515
|
+
sourceIsClone ? ` \u2192 ${cmd("--apply")} would push this clone's shape onto the target, absences included \u2014 preview it first with ${cmd("--apply --dry-run")}
|
|
516
|
+
` : ` \u2192 Run with ${cmd("--apply")} to fix drift
|
|
517
|
+
`
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
this.log(renderTip({
|
|
521
|
+
command: "diff",
|
|
522
|
+
detail: false,
|
|
523
|
+
driftTotal: result.summary.total,
|
|
524
|
+
driftedChecks,
|
|
525
|
+
skippedChecks,
|
|
526
|
+
erroredChecks,
|
|
527
|
+
singleCheck: checks?.[0],
|
|
528
|
+
sourceIsClone
|
|
529
|
+
}));
|
|
530
|
+
}
|
|
531
|
+
const { drift, posture } = summarizeByKind(result.checks);
|
|
532
|
+
if (drift.critical === 0 && posture.critical > 0 && !flags.json) {
|
|
533
|
+
this.log(
|
|
534
|
+
` ${dim("Posture findings do not affect the exit code \u2014 they describe the target, not drift from the source. Add")} ${cmd("--fail-on-posture")} ${dim("to gate on them.")}
|
|
535
|
+
`
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
if (drift.critical > 0 || flags["fail-on-posture"] && posture.critical > 0) {
|
|
539
|
+
this.exit(1);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
function heldBackSql(scanResult, planned) {
|
|
544
|
+
const skipped = new Set(planned.skipped.map((s) => s.issueId));
|
|
545
|
+
return scanResult.checks.flatMap((c) => c.issues).filter((i) => skipped.has(i.id) && i.sql?.up).map((i) => i.sql.up);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export {
|
|
549
|
+
inertApplyFlags,
|
|
550
|
+
Diff
|
|
551
|
+
};
|
|
552
|
+
//# sourceMappingURL=chunk-XMYMIURR.js.map
|