@akal/supaforge 0.0.32 → 0.0.34

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 +66 -11
  3. package/dist/base-command.js +4 -3
  4. package/dist/{chunk-DMIWAJRB.js → chunk-3WKWPSFN.js} +6 -6
  5. package/dist/{chunk-GZREXCQZ.js → chunk-5STH2A6K.js} +17 -10
  6. package/dist/{chunk-6LJERPUN.js → chunk-6ERVCWLY.js} +20 -12
  7. package/dist/{chunk-GEHPTPNZ.js → chunk-7DL63NWP.js} +3 -3
  8. package/dist/{chunk-UWAVXC57.js → chunk-DQJSSTIJ.js} +39 -15
  9. package/dist/{chunk-ORQJVE57.js → chunk-EFKQOQGG.js} +15 -16
  10. package/dist/{chunk-7NAZGZPV.js → chunk-F46FFUKC.js} +16 -17
  11. package/dist/chunk-GQPGH6YR.js +50 -0
  12. package/dist/{chunk-6Q7MHFBM.js → chunk-HNJ6BNNZ.js} +2 -2
  13. package/dist/{chunk-MIRLB5JM.js → chunk-ICSCHS72.js} +66 -14
  14. package/dist/{chunk-6WAMNZLO.js → chunk-KNXHLVF7.js} +126 -4
  15. package/dist/{chunk-SQPCWGQO.js → chunk-MG3SFV5J.js} +22 -121
  16. package/dist/{chunk-BUOWHE36.js → chunk-N5VNNOA2.js} +37 -52
  17. package/dist/{chunk-3HGAV5CC.js → chunk-OB5GP7UB.js} +19 -16
  18. package/dist/{chunk-4IVN7QVY.js → chunk-PYAGSMFB.js} +23 -15
  19. package/dist/{chunk-SC2XHGIS.js → chunk-S5L4A3UR.js} +3 -3
  20. package/dist/{chunk-2SELREHW.js → chunk-TPX2MAO4.js} +7 -9
  21. package/dist/{chunk-NTUASFQ3.js → chunk-V2SBZERO.js} +4 -4
  22. package/dist/{chunk-G2DIPIYU.js → chunk-WK5YTINL.js} +29 -2
  23. package/dist/{chunk-BLKJWDTL.js → chunk-ZI435CAU.js} +2 -2
  24. package/dist/commands/clone.js +11 -11
  25. package/dist/commands/diff.d.ts +13 -1
  26. package/dist/commands/diff.js +19 -16
  27. package/dist/commands/hukam.js +15 -14
  28. package/dist/commands/init.js +5 -1
  29. package/dist/commands/mcp.d.ts +1 -0
  30. package/dist/commands/mcp.js +26 -10
  31. package/dist/commands/migrate/baseline.js +5 -4
  32. package/dist/commands/migrate/create.js +8 -7
  33. package/dist/commands/migrate/list.js +6 -5
  34. package/dist/commands/migrate/run.js +8 -7
  35. package/dist/commands/report.js +5 -4
  36. package/dist/commands/restore.js +13 -12
  37. package/dist/commands/snapshot.d.ts +7 -0
  38. package/dist/commands/snapshot.js +36 -8
  39. package/dist/commands/sync.js +15 -14
  40. package/dist/index.js +14 -14
  41. package/package.json +10 -8
  42. package/bin/dev.js +0 -10
  43. package/dist/base-command.js.map +0 -1
  44. package/dist/chunk-2SELREHW.js.map +0 -1
  45. package/dist/chunk-3HGAV5CC.js.map +0 -1
  46. package/dist/chunk-4IVN7QVY.js.map +0 -1
  47. package/dist/chunk-6LJERPUN.js.map +0 -1
  48. package/dist/chunk-6Q7MHFBM.js.map +0 -1
  49. package/dist/chunk-6WAMNZLO.js.map +0 -1
  50. package/dist/chunk-7NAZGZPV.js.map +0 -1
  51. package/dist/chunk-BLKJWDTL.js.map +0 -1
  52. package/dist/chunk-BUOWHE36.js.map +0 -1
  53. package/dist/chunk-DMIWAJRB.js.map +0 -1
  54. package/dist/chunk-DQQ5E563.js.map +0 -1
  55. package/dist/chunk-G2DIPIYU.js.map +0 -1
  56. package/dist/chunk-GEHPTPNZ.js.map +0 -1
  57. package/dist/chunk-GZREXCQZ.js.map +0 -1
  58. package/dist/chunk-MIRLB5JM.js.map +0 -1
  59. package/dist/chunk-NTUASFQ3.js.map +0 -1
  60. package/dist/chunk-ORQJVE57.js.map +0 -1
  61. package/dist/chunk-SC2XHGIS.js.map +0 -1
  62. package/dist/chunk-SQPCWGQO.js.map +0 -1
  63. package/dist/chunk-UWAVXC57.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/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 { checkConnection } from '../preflight.js'\nimport { redactUrls, describeFailure } from '../utils/error.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 // Both databases must answer before anything is compared. Without\n // this, an unreadable source looked empty to the checks that treated a\n // failed read as \"nothing there\", and the target's webhooks were\n // dropped as extra.\n const unreachable: string[] = []\n for (const [label, name] of [['Source', config.source!], ['Target', config.target!]] as const) {\n const conn = await checkConnection(config.environments[name].dbUrl)\n if (!conn.reachable) unreachable.push(`${label} (${name}) not reachable: ${redactUrls(describeFailure(conn.error))}`)\n }\n if (unreachable.length > 0) {\n return { content: [{ type: 'text' as const, text: `Nothing compared or applied.\\n${unreachable.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 // A check that failed measured nothing, so none of its drift was\n // applied; the call is not a success.\n const unchecked = scanResult.checks\n .filter(c => c.status === 'error')\n .map(c => ({ check: c.check, error: c.error ?? 'check failed' }))\n const body = unchecked.length ? { ...promoteResult, unchecked } : promoteResult\n return {\n content: [{ type: 'text' as const, text: JSON.stringify(body, null, 2) }],\n ...(unchecked.length || promoteResult.errors.length ? { isError: true } : {}),\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 * 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;AACT;AAEO,SAAS,sBAA4B;AAC1C,mBAAiB;AACnB;;;ACfA,SAAS,iBAAiB;AAC1B,SAAS,SAAS;AAClB,SAAS,UAAU,eAAe;AAClC,SAAS,YAAY,oBAAoB;AACzC,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,qBAAqB;AAa9B,IAAM,cAAc;AAWpB,IAAM,iBAAiB,eAAe;AAEtC,SAAS,iBAAyB;AAChC,MAAI;AACF,UAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;AAEnD,eAAW,YAAY,CAAC,mBAAmB,sBAAsB,uBAAuB,GAAG;AACzF,YAAM,YAAY,QAAQ,MAAM,QAAQ;AACxC,UAAI,CAAC,WAAW,SAAS,EAAG;AAC5B,YAAM,MAAM,KAAK,MAAM,aAAa,WAAW,OAAO,CAAC;AACvD,UAAI,OAAO,IAAI,YAAY,YAAY,IAAI,MAAM,SAAS,WAAW,GAAG;AACtE,eAAO,IAAI;AAAA,MACb;AAAA,IACF;AAAA,EACF,QAAQ;AAAA,EAER;AACA,SAAO;AACT;AAGA,SAAS,WAAW,QAA0B;AAC5C,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;AAC1D,QAAM,SAAkC,CAAC;AACzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAiC,GAAG;AAC5E,QAAI,QAAQ,WAAW,QAAQ,eAAe;AAC5C,aAAO,GAAG,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AAAA,IACxE,WAAW,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AAA,UACxD,EAAE,KAAK,IAAI;AAAA,QACb;AAAA,MACF;AAEA,aAAO;AAAA,QACL,UAAU;AAAA,UACR;AAAA,YACE,MAAM;AAAA,YACN,SAAS;AAAA,cACP,MAAM;AAAA,cACN,MAAM;AAAA,gBACJ;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,cACF,EAAE,KAAK,IAAI;AAAA,YACb;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/sanitize.ts"],"sourcesContent":["import { redactUrls } from './error.js'\n\n/**\n * Strip PII from a string at source — before it ever leaves the user's machine.\n *\n * Covers the realistic surface area without over-engineering:\n * • DB credentials via redactUrls (postgres://user:PASSWORD@host)\n * • Local file-system paths (/Users/alice/... or /home/alice/...)\n * • Bare IPv4 addresses\n */\nexport function sanitizeForReport(text: string): string {\n return redactUrls(text)\n .replace(/\\/(?:Users|home)\\/[^/\\s\"'`]+/g, '~')\n .replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, '[ip]')\n}\n"],"mappings":";;;;;AAUO,SAAS,kBAAkB,MAAsB;AACtD,SAAO,WAAW,IAAI,EACnB,QAAQ,iCAAiC,GAAG,EAC5C,QAAQ,gCAAgC,MAAM;AACnD;","names":[]}
@@ -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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAWO,IAAM,4BAA4B;AAAA,EACvC,GAAG;AAAA,EACH;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,kBAAkB,gBAAmC,wBAAkC;AACrG,SAAO,CAAC,GAAG,oBAAI,IAAI;AAAA,IAAC,GAAG;AAAA,IAAe,GAAG,0BAA0B,OAAO,OAAK,CAAC,uBAAuB,SAAS,CAAC,CAAC;AAAA,IAChH;AAAA,IAAa;AAAA,IAAc;AAAA,EAAgB,CAAC,CAAC;AACjD;AAGO,IAAM,aAAa;AAAA,EACxB,QAAQ;AAAA,IACN;AAAA,IACA;AAAA,EACF;AAAA,EACA,aAAa;AAAA,IACX;AAAA,EACF;AAAA,EACA,cAAc;AAAA,IACZ;AAAA,IACA;AAAA,EACF;AAAA,EACA,aAAa;AAAA,IACX;AAAA,IACA;AAAA,EACF;AACF;AAGO,IAAM,qBAAqB;AAgB3B,IAAM,qBA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AAS,gBAAgB;AAKlB,IAAM,IAAI,CAAC,OAAc,SAAyB,SAAS,OAAO,IAAI;AAGtE,IAAM,KAAK,CAAC,SAAyB,EAAE,SAAS,IAAI;AAGpD,IAAM,OAAO,CAAC,SAAyB,EAAE,UAAU,IAAI;AAGvD,IAAM,MAAM,CAAC,SAAyB,EAAE,OAAO,IAAI;AAGnD,IAAM,MAAM,CAAC,SAAyB,EAAE,QAAQ,IAAI;AAGpD,IAAM,OAAO,CAAC,SAAyB,EAAE,QAAQ,IAAI;AAGrD,SAAS,WAAW,OAA0B,KAAkC;AACrF,aAAW,QAAQ,OAAO;AACxB,QAAI,IAAI,IAAI,CAAC;AAAA,EACf;AACF;AAEA,IAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQf,IAAM,UAAU;AAChB,IAAM,SAAS;AAGf,IAAM,mBAAmB;AAGlB,SAAS,YAAY,KAAkC;AAC5D,QAAM,OAAO,QAAQ,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/restore.ts","../src/restore-data.ts","../src/restore-replace.ts"],"sourcesContent":["import { readFile, access } from 'node:fs/promises'\nimport { constants } from 'node:fs'\nimport { join } from 'node:path'\nimport pg from 'pg'\nimport { pgClientConfig } from './db.js'\nimport type { MigrationFile, SnapshotManifest } from './types/config'\nimport { loadMigrations } from './migration'\nimport { MIGRATIONS_TABLE } from './constants.js'\nimport { ensureMigrationsTable, getAppliedVersions } from './migrate.js'\nimport { loadSnapshot } from './snapshot'\nimport type { QueryFn } from './db'\nimport { pgQuery } from './db'\nimport { errMsg } from './utils/error'\nimport { DEFAULT_IGNORE_SCHEMAS, SUPABASE_PLATFORM_SCHEMAS } from './defaults'\nimport { dropUnsupportedSetStatements, knownParameters } from './prove'\nimport { splitSqlStatements, isCommentOnly, isPsqlMetaCommand, stripPsqlMetaCommands } from './utils/sql-split'\nimport { quoteIdent, quoteLiteral, quoteName } from './utils/sql.js'\nimport { sqlSkeleton, statementSubject, rolesNamedBy } from './sql-deps.js'\nimport { ABSENT_ON_TARGET, EXTENSION_UNAVAILABLE } from './pg-errors.js'\nimport { dataTablesInOrder, restoreBuckets, restoreTableRows } from './restore-data.js'\nimport {\n replaceableSchemas, findExternalDependents, dropSchemaContents, recreateExternalDependents,\n resetRelationGrants, type ExternalDependent,\n} from './restore-replace.js'\n\nexport type FetchFn = (url: string, init?: RequestInit) => Promise<Response>\n\nexport interface RestoreOptions {\n /** Target database URL to restore into. */\n targetUrl: string\n /** Project ref for API-based operations (auth, storage, edge functions). */\n targetProjectRef?: string\n /** Access token for Supabase Management API. */\n targetAccessToken?: string\n /** Restore from a specific snapshot directory. */\n snapshotDir?: string\n /** Or restore from migrations up to a specific version. */\n toVersion?: string\n /** Starting version (skip migrations before this). */\n fromVersion?: string\n /** Working directory for .supaforge/ */\n cwd?: string\n /** Query function for DB operations. */\n queryFn?: QueryFn\n /** Fetch function for API operations. */\n fetchFn?: FetchFn\n /**\n * Apply each statement on its own, keeping whatever succeeds.\n *\n * Off by default. A restore used to run this way always, so a failure part\n * way through left a half-restored database and the errors were listed only\n * at the end (issue #95). PostgreSQL has transactional DDL, so the whole\n * restore now succeeds or leaves the target exactly as it was.\n */\n noTransaction?: boolean\n /**\n * Drop the schemas the snapshot covers before replaying into them.\n *\n * What `--force` now means. It used to only skip the \"target is not empty\"\n * check, so restoring over an existing database failed on every object that\n * was already there and replaced nothing (issue #95).\n */\n replace?: boolean\n}\n\nexport interface RestoreResult {\n applied: { type: 'sql' | 'api'; label: string }[]\n skipped: { type: 'sql' | 'api'; label: string; reason: string }[]\n errors: { type: 'sql' | 'api'; label: string; error: string }[]\n mode: 'snapshot' | 'migrations'\n /**\n * Objects of the snapshot left out because they need something this target\n * cannot have — an extension it does not ship, a Supabase schema it lacks —\n * listed in `skipped`. The rest was restored; the copy is not complete.\n */\n incomplete?: boolean\n /**\n * Statements that ran and were then rolled back, when the restore was\n * transactional and something failed.\n *\n * Reported apart from `applied`, which is emptied: a restore that rolled\n * back applied nothing, and saying it applied 60 operations would be the\n * most misleading thing this command could tell anyone (issue #95).\n */\n rolledBack?: { type: 'sql' | 'api'; label: string }[]\n}\n\n// ─── Safety Check ────────────────────────────────────────────────────────────\n\n/**\n * Check whether the target database has user tables in the public schema.\n * Returns the table names if any exist — used to gate destructive restore.\n */\nexport async function getPublicTables(targetUrl: string): Promise<string[]> {\n const ignoreList = DEFAULT_IGNORE_SCHEMAS.map(s => `'${s}'`).join(', ')\n const client = new pg.Client(pgClientConfig(targetUrl))\n await client.connect()\n try {\n const { rows } = await client.query<{ tablename: string }>(\n `SELECT tablename FROM pg_tables\n WHERE schemaname = 'public'\n AND schemaname NOT IN (${ignoreList})\n ORDER BY tablename`,\n )\n return rows.map(r => r.tablename)\n } finally {\n await client.end()\n }\n}\n\n// ─── Restore from Snapshot ───────────────────────────────────────────────────\n\n/**\n * Restore a Supabase environment from a snapshot directory.\n * Applies all SQL files (schema, RLS, cron, webhooks, extensions, data).\n * API layers (auth, storage buckets, edge functions) log what would need manual action.\n */\nexport async function restoreFromSnapshot(options: RestoreOptions): Promise<RestoreResult> {\n if (!options.snapshotDir) throw new Error('snapshotDir is required for snapshot restore')\n\n const result: RestoreResult = { applied: [], skipped: [], errors: [], mode: 'snapshot' }\n const manifest = await loadSnapshot(options.snapshotDir)\n\n // Apply SQL layers in dependency order\n const sqlOrder = RESTORE_SQL_ORDER\n const client = new pg.Client(pgClientConfig(options.targetUrl))\n await client.connect()\n\n // One transaction for the lot, unless asked otherwise. A restore that fails\n // half way used to leave a database matching neither the snapshot nor its own\n // previous state, with the errors reported only at the end (issue #95).\n // PostgreSQL has transactional DDL, so this is the same guarantee `--apply`\n // gives in promote().\n const transactional = !options.noTransaction\n if (transactional) await client.query('BEGIN')\n\n /** What the target turned out to lack — see tolerableFailure. */\n const missing = new Set<string>()\n // Objects a skipped statement would have created, with why it was skipped.\n const leftOut = new Map<string, string>()\n\n /** Webhook triggers the schema dump creates, so the webhooks layer can skip them. */\n const createdBySchemaLayer = new Set<string>()\n\n /** Triggers and policies outside the cleared schemas, to put back — see restore-replace. */\n let external: ExternalDependent[] = []\n\n // schema.sql is a pg_dump, which empties search_path for the rest of the\n // session. Every later layer holds names as the catalog rendered them —\n // unqualified where they resolved through the default path — so a storage\n // policy calling `is_admin()` failed with \"function is_admin() does not\n // exist\" and, in one transaction, took the whole restore with it. The\n // session's own path is put back after each layer.\n const { rows: [{ search_path: sessionSearchPath }] } =\n await client.query<{ search_path: string }>('SHOW search_path')\n\n try {\n // `--force` means replace, not \"carry on regardless\". Skipping the\n // not-empty check and then failing on every object that already exists\n // replaced nothing at all. What it clears, and what it must not, is in\n // restore-replace.ts.\n if (options.replace) {\n const schemas = replaceableSchemas(await schemasInSnapshot(options.snapshotDir))\n const dependents = await findExternalDependents(client, schemas)\n if (dependents.blockers.length > 0) {\n result.errors.push({\n type: 'sql',\n label: 'Restore --force',\n error: `clearing ${schemas.join(', ')} would also drop objects outside them that `\n + `this restore cannot put back: ${dependents.blockers.join('; ')}. `\n + 'Nothing was changed. Remove or move those first, or restore into an empty database.',\n })\n throw new RestoreAborted()\n }\n external = dependents.recreate\n const dropped = await dropSchemaContents(client, schemas)\n result.applied.push({\n type: 'sql',\n label: `Cleared ${dropped} object(s) from ${schemas.join(', ')} (--force)`,\n })\n }\n\n for (const layer of sqlOrder) {\n const file = layerRestoreFile(layer)\n const info = manifest.layers[layer === 'storage-policies' ? 'storage' : layer]\n if (!info?.captured) {\n result.skipped.push({ type: 'sql', label: `Layer: ${layer}`, reason: 'Not captured in snapshot' })\n continue\n }\n\n // The schema layer's own file is introspection JSON, not DDL; `schema.sql`\n // is the replayable companion (issue #80). Say which it is and why when\n // it is not there, rather than reporting \"File not readable\" — that\n // sends the reader looking for a permissions problem, and the schema\n // silently not being restored is the whole of the bug.\n if (layer === 'schema' && !(await isReadable(join(options.snapshotDir, file)))) {\n result.skipped.push({\n type: 'sql',\n label: `Layer: ${layer}`,\n reason: info.sqlSkipReason\n ?? 'this snapshot has no schema.sql — it predates one being written, so the '\n + 'schema cannot be replayed. Use `supaforge clone`, or '\n + '`restore --from-migrations`.',\n })\n continue\n }\n\n try {\n const raw = await readFile(join(options.snapshotDir, file), 'utf-8')\n const content = layer === 'schema'\n ? await replayableSchemaSql(raw, options.targetUrl)\n : raw\n\n let statements = extractExecutableStatements(content)\n\n // Grants are restored exactly, not added to whatever default\n // privileges gave the recreated objects — see resetRelationGrants.\n if (layer === 'roles') {\n const reset = await resetRelationGrants(\n client, replaceableSchemas(await schemasInSnapshot(options.snapshotDir)))\n if (reset > 0) {\n result.applied.push({ type: 'sql', label: `Reset grants on ${reset} relation(s) before replaying the captured ones` })\n }\n }\n\n // Objects the platform owns cannot be recreated by `postgres`, and a\n // snapshot of a Supabase project carries several: `pgbouncer.get_auth`\n // in the schema dump, pg_cron's own policies on `cron.job` in the RLS\n // dump. They failed on every single restore (issue #95).\n statements = statements.filter(sql => {\n const owner = platformOwnedObject(sql)\n if (owner === undefined) return true\n result.skipped.push({\n type: 'sql',\n label: summarizeStatement(sql),\n reason: `${owner} is managed by the platform and cannot be recreated here`,\n })\n return false\n })\n\n // The webhooks layer re-creates triggers the schema dump already made\n // — the restore-side twin of the overlap #77 settled for `diff --apply`.\n if (layer === 'webhooks') {\n statements = statements.filter(sql => {\n if (!createdBySchemaLayer.has(webhookTriggerKey(sql) ?? '')) return true\n result.skipped.push({\n type: 'sql',\n label: summarizeStatement(sql),\n reason: 'already created by the schema layer',\n })\n return false\n })\n }\n\n if (layer === 'schema') {\n for (const sql of statements) {\n const key = webhookTriggerKey(sql)\n if (key) createdBySchemaLayer.add(key)\n }\n }\n\n for (const sql of statements) {\n await applyStatement(client, sql, transactional, result, missing, leftOut)\n }\n } catch (err) {\n if (err instanceof RestoreAborted) throw err\n result.skipped.push({ type: 'sql', label: `Layer: ${layer}`, reason: 'File not readable' })\n }\n await client.query(`SELECT set_config('search_path', $1, false)`, [sessionSearchPath])\n }\n\n // Rows last, once the tables, their keys and the roles exist: reference\n // data as captured, then the buckets the storage policies are about.\n await restoreRows(client, options.snapshotDir, manifest, result, transactional)\n\n // What clearing the schemas took with it from outside them — the auth\n // trigger that calls a public function, a storage policy that does —\n // goes back once everything it depends on exists again.\n for (const dep of await recreateExternalDependents(client, external)) {\n result.applied.push({\n type: 'sql',\n label: `Recreated ${dep.kind} ${dep.name} on ${dep.schema}.${dep.table} (outside the snapshot, dropped by --force)`,\n })\n }\n\n if (transactional) {\n if (result.errors.length > 0) {\n await client.query('ROLLBACK')\n // Nothing was written, so nothing was applied. Reporting otherwise\n // would be the most misleading thing this command could say.\n result.rolledBack = result.applied\n result.applied = []\n // Nothing was restored, so nothing was left out of a restore either.\n delete result.incomplete\n } else {\n await client.query('COMMIT')\n }\n }\n } catch (err) {\n if (transactional) {\n await client.query('ROLLBACK').catch(() => undefined)\n result.rolledBack = result.applied\n result.applied = []\n delete result.incomplete\n }\n // A RestoreAborted carries no message of its own: the statement that failed\n // has already been recorded, and adding a second entry for the same\n // failure would only make it harder to read.\n if (!(err instanceof RestoreAborted)) {\n result.errors.push({ type: 'sql', label: 'Restore', error: errMsg(err) })\n }\n } finally {\n await client.end()\n }\n\n // Layers that were captured and cannot be replayed as SQL. Named\n // individually rather than left out: a restore that lists what it did and\n // says nothing about four of the twelve layers reads as complete when it is\n // not, which is the thing a restore most needs to be honest about.\n for (const note of MANUAL_LAYERS) {\n if (manifest.layers[note.layer]?.captured) {\n result.skipped.push({ type: note.type, label: note.label, reason: note.reason })\n }\n }\n\n return result\n}\n\n/**\n * The snapshot's rows: `data/*.json` per table and `storage-buckets.json`.\n * Each table and the buckets apply on their own; a failure is an error like\n * any other, and in one transaction ends the restore.\n */\nasync function restoreRows(\n client: pg.Client,\n snapshotDir: string,\n manifest: SnapshotManifest,\n result: RestoreResult,\n transactional: boolean,\n): Promise<void> {\n const attempt = async (label: string, run: () => Promise<string | undefined>) => {\n if (transactional) await client.query('SAVEPOINT sf_restore_rows')\n try {\n const done = await run()\n if (done) result.applied.push({ type: 'sql', label: `${label}: ${done}` })\n } catch (err) {\n if (transactional) await client.query('ROLLBACK TO SAVEPOINT sf_restore_rows')\n result.errors.push({ type: 'sql', label, error: errMsg(err) })\n if (transactional) throw new RestoreAborted()\n }\n }\n\n if (manifest.layers.data?.captured) {\n const dataDir = join(snapshotDir, 'data')\n for (const table of await dataTablesInOrder(client, dataDir)) {\n await attempt(`Data: ${table}`, async () => `${await restoreTableRows(client, dataDir, table)} row(s)`)\n }\n }\n\n const buckets = join(snapshotDir, 'storage-buckets.json')\n if (manifest.layers.storage?.captured && await isReadable(buckets)) {\n await attempt('Storage buckets', async () => {\n const created = await restoreBuckets(client, buckets)\n if (created === undefined) {\n result.skipped.push({ type: 'api', label: 'Storage buckets', reason: 'this target has no storage schema to hold them' })\n return undefined\n }\n return `${created} created; objects are never transferred`\n })\n }\n}\n\n/** Captured layers a restore cannot replay, and what to do about each. */\nconst MANUAL_LAYERS: ReadonlyArray<{\n layer: string\n type: 'api' | 'sql'\n label: string\n reason: string\n}> = [\n {\n layer: 'auth',\n type: 'api',\n label: 'Auth config',\n reason: 'Requires --project-ref and --api-key to restore via Management API',\n },\n {\n layer: 'edge-functions',\n type: 'api',\n label: 'Edge Functions',\n reason: 'Deploy via \"supabase functions deploy\" from your local functions directory',\n },\n {\n layer: 'vault',\n type: 'sql',\n label: 'Vault secrets',\n reason: 'vault.sql lists the secret names only — a value cannot be read out of Vault, '\n + 'so each must be recreated by hand with vault.create_secret',\n },\n]\n\n// ─── Restore from Migrations ─────────────────────────────────────────────────\n\n/**\n * Restore by replaying migration files in order.\n * Tracks applied migrations in a `_supaforge_migrations` table.\n */\nexport async function restoreFromMigrations(options: RestoreOptions): Promise<RestoreResult> {\n const cwd = options.cwd ?? process.cwd()\n const result: RestoreResult = { applied: [], skipped: [], errors: [], mode: 'migrations' }\n const queryFn = options.queryFn ?? pgQuery\n\n const migrations = await loadMigrations(cwd)\n if (migrations.length === 0) {\n result.skipped.push({ type: 'sql', label: 'No migrations', reason: 'No migration files found in .supaforge/migrations/' })\n return result\n }\n\n // Filter by version range\n let filtered = migrations\n if (options.fromVersion) {\n filtered = filtered.filter(m => m.version >= options.fromVersion!)\n }\n if (options.toVersion) {\n filtered = filtered.filter(m => m.version <= options.toVersion!)\n }\n\n // Ensure tracking table exists\n const client = new pg.Client(pgClientConfig(options.targetUrl))\n await client.connect()\n\n try {\n // Tracked in `supabase_migrations.schema_migrations` — the same table\n // `migrate run` uses, in a schema the Data API does not expose.\n //\n // It used to be `public._supaforge_migrations`, created unqualified. On\n // Supabase a table in `public` receives the project's default grants to\n // `anon` and `authenticated`, and this one was created with RLS off — so\n // anyone holding the public anon key could read it, insert into it and\n // delete from it through the Data API, and thereby decide which migrations\n // a later restore believed were already applied (issue #93). It was also a\n // second, disagreeing record of the same thing.\n await ensureMigrationsTable(options.targetUrl, queryFn)\n\n const legacy = await findLegacyTrackingTable(client)\n if (legacy) {\n result.skipped.push({\n type: 'sql',\n label: 'public._supaforge_migrations',\n reason: 'left over from an earlier version and reachable with the anon key — '\n + 'tracking has moved to supabase_migrations.schema_migrations. '\n + 'Drop it: DROP TABLE public._supaforge_migrations;',\n })\n }\n\n const applied = await getAppliedVersions(options.targetUrl, queryFn)\n\n for (const migration of filtered) {\n if (applied.has(migration.version)) {\n result.skipped.push({ type: 'sql', label: `v${migration.version}`, reason: 'Already applied' })\n continue\n }\n\n // Apply SQL statements\n let ran = 0\n for (const sql of migration.up.sql) {\n if (isCommentOnly(sql)) continue // marker text, not a statement\n try {\n await client.query(sql)\n ran++\n result.applied.push({ type: 'sql', label: summarizeStatement(sql) })\n } catch (err) {\n result.errors.push({\n type: 'sql',\n label: summarizeStatement(sql),\n error: errMsg(err),\n })\n }\n }\n\n // A migration that applied nothing is not applied.\n //\n // `snapshot --migration` writes files whose schema layer is the comment\n // `-- Schema changed. Use @dbdiff/cli to generate migration SQL.`, and\n // the baseline `clone` writes has no statements at all. Recording those\n // as done meant a restore into an empty database built nothing and then\n // reported success — and left the tracking table asserting the schema\n // was in place (issue #93).\n if (ran === 0) {\n result.skipped.push({\n type: 'sql',\n label: `v${migration.version}`,\n reason: 'carries no SQL to apply, so it was not recorded as applied. '\n + 'Snapshot-derived migrations hold no schema DDL — use '\n + '`supaforge clone`, or restore from a snapshot, to build structure.',\n })\n continue\n }\n\n await queryFn(\n options.targetUrl,\n `INSERT INTO ${MIGRATIONS_TABLE} (version, name, statements)\n VALUES ($1, $2, '{}')\n ON CONFLICT (version) DO NOTHING`,\n [migration.version, migration.description],\n )\n }\n } finally {\n await client.end()\n }\n\n return result\n}\n\n// ─── Preview (Dry-Run) ──────────────────────────────────────────────────────\n\n/** Preview what a snapshot restore would apply (no DB connection required). */\nexport async function previewSnapshotRestore(snapshotDir: string): Promise<{ layer: string; statements: string[] }[]> {\n const manifest = await loadSnapshot(snapshotDir)\n const preview: { layer: string; statements: string[] }[] = []\n\n const sqlOrder = RESTORE_SQL_ORDER\n for (const layer of sqlOrder) {\n const file = layerRestoreFile(layer)\n const info = manifest.layers[layer === 'storage-policies' ? 'storage' : layer]\n if (!info?.captured) continue\n\n try {\n const content = await readFile(join(snapshotDir, file), 'utf-8')\n const statements = extractExecutableStatements(content)\n if (statements.length > 0) {\n preview.push({ layer, statements })\n }\n } catch { /* skip */ }\n }\n\n return preview\n}\n\n/** Preview what migration restore would apply. */\nexport async function previewMigrationRestore(cwd = process.cwd(), toVersion?: string, fromVersion?: string): Promise<MigrationFile[]> {\n let migrations = await loadMigrations(cwd)\n if (fromVersion) migrations = migrations.filter(m => m.version >= fromVersion)\n if (toVersion) migrations = migrations.filter(m => m.version <= toVersion)\n return migrations\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/** Whether a snapshot file exists and can be read. */\nasync function isReadable(path: string): Promise<boolean> {\n try {\n await access(path, constants.R_OK)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * The schema dump, with preamble settings the target does not have removed.\n *\n * pg_dump writes its preamble for its own version, so a snapshot taken with a\n * PostgreSQL 17 client carries `SET transaction_timeout = 0`, which a 15 or 16\n * server rejects — and the restore would fail on the first line of the schema.\n * The same filtering `--prove` applies for the same reason (issue #72).\n *\n * If the target cannot be asked what it supports, the dump is replayed as-is:\n * a failure there is a real failure, and guessing which settings to drop would\n * be worse than reporting it.\n */\nasync function replayableSchemaSql(sql: string, targetUrl: string): Promise<string> {\n try {\n return dropUnsupportedSetStatements(sql, await knownParameters(targetUrl)).sql\n } catch {\n return sql\n }\n}\n\n/**\n * The snapshot layers a restore replays, in dependency order.\n *\n * `realtime` and `roles` were captured as replayable SQL and then never\n * replayed: the two layers were added to `snapshot` without being added here,\n * so a restore silently dropped every publication membership and every table\n * grant the snapshot held. Both come after `schema`, because a publication can\n * only add a table that exists and a grant can only name one.\n *\n * `vault` is deliberately absent — its file is a comment-only list of secret\n * names, because a secret's value cannot be read out of Vault and inventing one\n * is worse than leaving it absent (issue #91). It is reported as needing manual\n * action instead, alongside the API layers.\n */\nconst RESTORE_SQL_ORDER = [\n 'extensions', 'schema', 'rls', 'cron', 'webhooks', 'storage-policies', 'realtime', 'roles',\n]\n\nfunction layerRestoreFile(layer: string): string {\n switch (layer) {\n case 'extensions': return 'extensions.sql'\n case 'schema': return 'schema.sql'\n case 'rls': return 'rls.sql'\n case 'cron': return 'cron.sql'\n case 'webhooks': return 'webhooks.sql'\n case 'storage-policies': return 'storage-policies.sql'\n default: return `${layer}.sql`\n }\n}\n\n/** Blank lines and comment lines ahead of the statement's first real token. */\nconst LEADING_NOISE = /^(?:[ \\t]*(?:--[^\\n]*)?\\n)*[ \\t]*/\n\n/** `CREATE SCHEMA x`, at the point the statement actually begins. */\nconst OPENS_CREATE_SCHEMA = /^CREATE\\s+SCHEMA\\s+(?!IF\\s+NOT\\s+EXISTS\\b)/i\n\n/**\n * Make a `CREATE SCHEMA` conditional, if that is what this statement is.\n *\n * Both the test and the rewrite are anchored past pg_dump's comment header\n * rather than applied to the statement as a whole. Matching anywhere reaches\n * into routine bodies — a function running `EXECUTE 'CREATE SCHEMA x'` would\n * have had its body rewritten, changing what the function does.\n */\nfunction makeCreateSchemaConditional(statement: string): string {\n const lead = LEADING_NOISE.exec(statement)?.[0] ?? ''\n const body = statement.slice(lead.length)\n\n if (!OPENS_CREATE_SCHEMA.test(body)) return statement\n return lead + body.replace(/^CREATE\\s+SCHEMA\\s+/i, 'CREATE SCHEMA IF NOT EXISTS ')\n}\n\nfunction extractExecutableStatements(content: string): string[] {\n if (!content) return []\n\n // `\\restrict` / `\\unrestrict` go first: they end at the newline, not at a\n // semicolon, so removing them after splitting would take the statement they\n // are sitting above with them.\n const sql = stripPsqlMetaCommands(content)\n\n // A real pg_dump cannot be split on `;` — routine bodies are dollar-quoted\n // and contain their own semicolons (issue #80).\n return splitSqlStatements(sql)\n .filter(s => !isCommentOnly(s))\n .filter(s => !isPsqlMetaCommand(s))\n // A dump scoped to `--schema=public` recreates the schema, and every\n // database already has `public`. Making it conditional keeps a genuinely\n // new schema (`CREATE SCHEMA reporting`) working while restoring into an\n // existing database stops failing on line one.\n .map(makeCreateSchemaConditional)\n .map(s => s.endsWith(';') ? s : `${s};`)\n}\n\nexport function summarizeStatement(sql: string): string {\n // Blank lines are not the statement. Skipping only comment lines meant a\n // dump's `-- header\\n-- 2 extensions\\n\\nCREATE EXTENSION …` summarised as the\n // empty line between them, so restore reported `✓ [sql]` with nothing after\n // it and, worse, `✗ [sql] : policy … already exists` — an error with no\n // indication of which statement produced it (issue #80).\n const first = sql\n .split('\\n')\n .map(l => l.trim())\n .find(l => l.length > 0 && !l.startsWith('--'))\n ?? sql.trim()\n return first.length > 80 ? `${first.slice(0, 77)}...` : first\n}\n\n/**\n * The `public._supaforge_migrations` table an earlier version created.\n *\n * Worth naming rather than ignoring: it is reachable with the project's anon\n * key, so it should be dropped rather than merely abandoned (issue #93).\n */\nasync function findLegacyTrackingTable(client: pg.Client): Promise<boolean> {\n try {\n const { rows } = await client.query(\n `SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = '_supaforge_migrations'`,\n )\n return rows.length > 0\n } catch {\n return false\n }\n}\n\n/**\n * The schemas a snapshot's `schema.sql` creates.\n *\n * Used by `--force` to clear the ground before replaying. Read from the dump\n * rather than assumed to be `public`, so a snapshot covering `reporting` as\n * well does not leave half of it behind — and so nothing outside the snapshot\n * is touched.\n */\nasync function schemasInSnapshot(snapshotDir: string): Promise<string[]> {\n try {\n const sql = await readFile(join(snapshotDir, 'schema.sql'), 'utf-8')\n const found = new Set<string>()\n\n for (const match of sql.matchAll(/^\\s*CREATE SCHEMA (?:IF NOT EXISTS )?(\"[^\"]+\"|[A-Za-z_][\\w$]*)/gim)) {\n found.add(match[1].replace(/\"/g, ''))\n }\n\n // A dump scoped to public may not carry a CREATE SCHEMA for it at all.\n found.add('public')\n return [...found]\n } catch {\n return ['public']\n }\n}\n\n\n/**\n * Schemas whose contents belong to the platform, not the project.\n *\n * A Supabase snapshot captures objects in these that `postgres` cannot\n * recreate — `pgbouncer.get_auth()` needs the `pgbouncer` role, and pg_cron\n * owns its own policies on `cron.job` — so every restore failed on them\n * (issue #95). They are the project's to read, never to rebuild.\n */\nconst PLATFORM_OWNED_SCHEMAS = ['pgbouncer', 'cron', 'pgsodium', 'vault', '_realtime', 'supabase_functions']\n\n/**\n * The platform-owned object a statement creates or changes, if any.\n *\n * Decided by the statement's *subject* — what it acts on — not by every schema\n * it mentions. `CREATE TRIGGER ... ON public.orders EXECUTE FUNCTION\n * supabase_functions.http_request(...)` is a Database Webhook, the project's\n * own, and matching by mention skipped every one of them on restore, along\n * with any view that reads `cron.job_run_details` or `vault.decrypted_secrets`.\n *\n * Returns the schema so the skip can say which it was.\n */\nexport function platformOwnedObject(sql: string): string | undefined {\n const subject = statementSubject(sql)\n if (!subject?.schema) return undefined\n return PLATFORM_OWNED_SCHEMAS.includes(subject.schema) ? subject.schema : undefined\n}\n\n/**\n * Schemas only a Supabase instance has. A statement naming one of them can\n * fail on plain PostgreSQL for no reason but that — see `tolerableFailure`.\n */\nconst SUPABASE_ONLY_SCHEMAS = [\n ...new Set([...SUPABASE_PLATFORM_SCHEMAS, ...PLATFORM_OWNED_SCHEMAS]),\n].filter(s => s !== 'pg_catalog' && s !== 'information_schema')\n\n/**\n * The Supabase-only schema a statement names that the target lacks, if any.\n */\nexport function mentionedPlatformSchema(\n sql: string,\n targetSchemas: ReadonlySet<string>,\n): string | undefined {\n const skeleton = sqlSkeleton(sql)\n return SUPABASE_ONLY_SCHEMAS.find(schema =>\n !targetSchemas.has(schema)\n && new RegExp(String.raw`(?:\"${schema}\"|\\b${schema})\\s*\\.`, 'i').test(skeleton))\n}\n\n/**\n * Statements that attach to an object rather than define one: a grant, a\n * policy, a trigger, a view, a comment, a foreign key, publication\n * membership, a cron call. Only these may be skipped — a table or a column\n * that cannot be created fails the restore, however it fails.\n */\nconst ATTACHMENT = new RegExp(String.raw`^\\s*(?:`\n + String.raw`GRANT|REVOKE|COMMENT\\s+ON|SELECT|ALTER\\s+PUBLICATION|ALTER\\s+DEFAULT\\s+PRIVILEGES|`\n + String.raw`ALTER\\s+POLICY|ALTER\\s+TABLE\\s+(?:ONLY\\s+)?\\S+\\s+ADD\\s+CONSTRAINT\\b[\\s\\S]*\\bFOREIGN\\s+KEY|`\n + String.raw`CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:POLICY|(?:CONSTRAINT\\s+)?TRIGGER|VIEW|MATERIALIZED\\s+VIEW|RULE)`\n + String.raw`)\\b`, 'i')\n\n/**\n * Why a failed statement can be skipped instead of failing the restore, or\n * undefined when it cannot.\n *\n * A Supabase snapshot restored into plain PostgreSQL carries things that\n * cannot exist there: `pg_graphql`, a Database Webhook calling\n * `supabase_functions.http_request`, a grant on `storage.objects`, a policy\n * calling `auth.uid()`, a foreign key to `auth.users`. In one transaction the\n * first of them rolled back the whole restore — nothing applied at all.\n *\n * So they are skipped by name, under three conditions together: the\n * statement only attaches to something (ATTACHMENT), PostgreSQL's error says\n * something is missing, and the Supabase schema it names does not exist on\n * this target at all. On a Supabase target every such schema exists, so\n * nothing there is ever skipped this way; and a table that cannot be created\n * fails the restore wherever it is. An extension the server does not ship is\n * skipped on its own terms.\n *\n * @param targetSchemas the schemas the target has, read after the failure\n */\nexport function tolerableFailure(\n sql: string,\n err: unknown,\n targetSchemas: ReadonlySet<string>,\n missing: ReadonlySet<string> = new Set(),\n leftOut: ReadonlyMap<string, string> = new Map(),\n): string | undefined {\n const code = (err as { code?: string } | null)?.code\n if (!code) return undefined\n const skeleton = sqlSkeleton(sql)\n\n if (/^\\s*CREATE\\s+EXTENSION\\b/i.test(skeleton)) {\n return EXTENSION_UNAVAILABLE.has(code)\n ? `extension not available on this server: ${errMsg(err)}`\n : undefined\n }\n // A snapshot of PostgreSQL 17 grants MAINTAIN, which an older server has no\n // word for: restoring it into 15 rolled back everything.\n if (/^\\s*GRANT\\s+MAINTAIN\\b/i.test(skeleton) && /unrecognized privilege type/i.test(errMsg(err))) {\n return 'MAINTAIN is a PostgreSQL 17 privilege this server does not have'\n }\n if (!ABSENT_ON_TARGET.has(code)) return undefined\n\n const schema = mentionedPlatformSchema(sql, targetSchemas)\n if (schema && (ATTACHMENT.test(skeleton) || ROUTINE.test(skeleton))) {\n return `depends on ${schema}, which this target does not have (${errMsg(err)})`\n }\n // Once the target has turned out to lack something the snapshot needs, what\n // needs it fails in turn: the table typed by the extension, then its\n // indexes, keys and rows. Each is left out and named, and the rest is\n // restored — one missing extension rolled back everything before.\n if (missing.size > 0) {\n const message = errMsg(err)\n // An object that was itself left out, named by the error: its own cause,\n // not every extension the target lacks. An index on a table typed by\n // pgvector listed pg_cron and pg_net too.\n const absent = /^(?:relation|type|function) \"([^\"]+)\" does not exist/i.exec(message)?.[1]\n const key = absent && (absent.includes('.') ? absent : `public.${absent}`)\n const cause = key ? leftOut.get(key) ?? leftOut.get(key.toLowerCase()) : undefined\n if (cause) return `${message}, as ${key} was left out: ${cause}`\n\n // The ones the error is about, when it names any: every missing extension\n // listed against every failure said nothing about which one was needed.\n // The statement counts as well as the error: `CREATE TABLE … extensions.vector(3)`\n // fails on the schema, but it is pgvector that it needs.\n const named = [...missing].filter(what => {\n const name = /^the (.+) (?:extension|schema)$/.exec(what)?.[1]\n const word = name !== undefined && new RegExp(`\\\\b${name.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\b`, 'i')\n return word !== false && (word.test(message) || word.test(sqlSkeleton(sql)))\n })\n return `${message}, as this target lacks ${(named.length > 0 ? named : [...missing]).join(', ')}`\n }\n return undefined\n}\n\n/**\n * A routine, which fails when its signature names a type or table in a schema\n * the target lacks. Its body is not checked: the schema dump turns\n * check_function_bodies off.\n */\nconst ROUTINE = /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:FUNCTION|PROCEDURE)\\b/i\n\n/** `CREATE … TABLE|VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE [schema.]name`. */\nconst CREATED = /^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:(?:UNLOGGED|TEMP|TEMPORARY)\\s+)?(?:TABLE|VIEW|MATERIALIZED\\s+VIEW|TYPE|DOMAIN|SEQUENCE|FUNCTION|PROCEDURE)\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(?:(\"[^\"]+\"|[\\w$]+)\\s*\\.\\s*)?(\"[^\"]+\"|[\\w$]+)/i\n\n/** The objects a statement creates, as `schema.name` (`public` when unqualified). */\nexport function createdObjects(sql: string): string[] {\n const m = CREATED.exec(sqlSkeleton(sql))\n if (!m) return []\n const bare = (n: string) => n.replace(/^\"|\"$/g, '')\n return [`${m[1] ? bare(m[1]) : 'public'}.${bare(m[2])}`]\n}\n\n/**\n * Run one restore statement, with what it needs prepared first.\n *\n * In a transaction each statement runs under a savepoint, so a failure that\n * `tolerableFailure` accepts is undone on its own and the restore continues;\n * any other failure aborts the lot.\n */\nasync function applyStatement(\n client: pg.Client,\n sql: string,\n transactional: boolean,\n result: RestoreResult,\n missing: Set<string>,\n leftOut: Map<string, string> = new Map(),\n): Promise<void> {\n if (transactional) await client.query('SAVEPOINT sf_restore_statement')\n try {\n // `CREATE EXTENSION ... WITH SCHEMA \"extensions\"` needs that schema to\n // exist, and on plain PostgreSQL it does not (issue #95).\n const needed = extensionTargetSchema(sql)\n if (needed) await client.query(`CREATE SCHEMA IF NOT EXISTS ${quoteName(needed)}`)\n\n // `GRANT … TO anon` and `CREATE POLICY … TO service_role` need the role to\n // exist, and on plain PostgreSQL none of Supabase's Data API roles do.\n for (const role of rolesNamedBy(sql)) await client.query(createRoleIfMissing(role))\n\n await client.query(conditionalPublicationMembership(sql))\n if (transactional) await client.query('RELEASE SAVEPOINT sf_restore_statement')\n result.applied.push({ type: 'sql', label: summarizeStatement(sql) })\n } catch (err) {\n // Back to the savepoint first: until then the transaction accepts no\n // query, and deciding needs one.\n if (transactional) await client.query('ROLLBACK TO SAVEPOINT sf_restore_statement')\n const { rows } = await client.query<{ nspname: string }>('SELECT nspname FROM pg_namespace')\n const targetSchemas = new Set(rows.map(r => r.nspname))\n const tolerated = tolerableFailure(sql, err, targetSchemas, missing, leftOut)\n if (tolerated) {\n result.skipped.push({ type: 'sql', label: summarizeStatement(sql), reason: tolerated })\n // What this would have created, and why it is not there, for whatever\n // fails on its absence later.\n const cause = /(this target lacks .+)$/.exec(tolerated)?.[1] ?? tolerated\n for (const name of createdObjects(sql)) leftOut.set(name, cause)\n // What the target lacks, for what fails after it; and whether this was\n // one of the snapshot's own objects rather than something the platform\n // or the server is missing.\n const extension = /^\\s*CREATE\\s+EXTENSION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\"[^\"]+\"|[\\w$-]+)/i.exec(sqlSkeleton(sql))\n const schema = mentionedPlatformSchema(sql, targetSchemas)\n if (extension) missing.add(`the ${extension[1].replace(/\"/g, '')} extension`)\n else if (schema && tolerated.startsWith('depends on')) missing.add(`the ${schema} schema`)\n else result.incomplete = true\n return\n }\n result.errors.push({ type: 'sql', label: summarizeStatement(sql), error: errMsg(err) })\n // In a transaction, stop at the first real failure and let the rollback\n // handle it: everything after would only report the transaction aborted.\n if (transactional) throw new RestoreAborted()\n }\n}\n\n/**\n * `schema.table.trigger` for a statement creating a webhook trigger, else null.\n *\n * A trigger name is unique only per table, which is the same keying the\n * webhooks check settled on in #77.\n */\nexport function webhookTriggerKey(sql: string): string | null {\n const match = /CREATE\\s+TRIGGER\\s+(\"[^\"]+\"|[\\w$]+)[\\s\\S]*?\\bON\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\s*\\.\\s*(?:\"[^\"]+\"|[\\w$]+))?)/i\n .exec(sqlSkeleton(sql))\n if (!match) return null\n\n const bare = (s: string) => s.replace(/\"/g, '').trim()\n return `${bare(match[2])}.${bare(match[1])}`.toLowerCase()\n}\n\n/**\n * A schema that already exists everywhere and cannot be created.\n *\n * PostgreSQL rejects a name beginning with `pg_` before it even evaluates\n * `IF NOT EXISTS`, so asking for one is an error rather than a no-op — the\n * same trap as issue #94, which is where `--prove` used to abort.\n */\nexport function isSystemSchema(schema: string): boolean {\n return schema === 'pg_catalog' || schema === 'information_schema' || schema.startsWith('pg_')\n}\n\n/**\n * The schema a `CREATE EXTENSION ... WITH SCHEMA x` needs creating first, if any.\n *\n * A Supabase snapshot puts its extensions in `extensions`, which plain\n * PostgreSQL has never heard of, so every one of them failed there with\n * `schema \"extensions\" does not exist` (issue #95).\n *\n * System schemas are excluded. `plpgsql` lives in `pg_catalog`, and asking for\n * that one aborts the transaction and takes the whole restore with it — which\n * is what a first attempt at this fix did.\n */\nexport function extensionTargetSchema(sql: string): string | undefined {\n const match = /CREATE\\s+EXTENSION\\b[\\s\\S]*?\\bWITH\\s+SCHEMA\\s+(\"[^\"]+\"|[\\w$]+)/i\n .exec(sqlSkeleton(sql))\n if (!match) return undefined\n\n const schema = match[1].replace(/\"/g, '')\n return isSystemSchema(schema) ? undefined : schema\n}\n\n/**\n * `CREATE ROLE` guarded on the role not already existing.\n *\n * PostgreSQL has no `CREATE ROLE IF NOT EXISTS`, so this is the DO-block form.\n * `NOLOGIN`, deliberately: these are grant targets, and a restore quietly\n * creating a role that can log in would be a worse outcome than a failed grant.\n */\nexport function createRoleIfMissing(role: string): string {\n return `DO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${quoteLiteral(role)}) THEN\n CREATE ROLE ${quoteName(role)} NOLOGIN;\n END IF;\nEND $$;`\n}\n\n/**\n * `ALTER PUBLICATION … ADD TABLE` guarded on the table not already being in it.\n *\n * Adding a table twice is an error — `relation \"orders\" is already member of\n * publication` — so restoring the realtime layer into a database that already\n * has the publication populated aborted the whole transaction. Every other\n * statement a restore replays is either idempotent or made so (the same reason\n * `CREATE SCHEMA` is rewritten), and this is the one that was not.\n *\n * Anything that is not such a statement is returned unchanged.\n */\nexport function conditionalPublicationMembership(sql: string): string {\n const match = /^\\s*ALTER\\s+PUBLICATION\\s+(\"[^\"]+\"|[\\w$]+)\\s+ADD\\s+TABLE\\s+(?:ONLY\\s+)?([^;]+?)\\s*;?\\s*$/i\n .exec(sql)\n if (!match) return sql\n\n const [, publication, table] = match\n const parts = table.split('.').map(p => p.replace(/\"/g, '').trim())\n if (parts.length !== 2) return sql\n\n const [schema, name] = parts\n return `DO $$ BEGIN\n IF NOT EXISTS (\n SELECT 1 FROM pg_publication_tables\n WHERE pubname = ${quoteLiteral(publication.replace(/\"/g, ''))}\n AND schemaname = ${quoteLiteral(schema)}\n AND tablename = ${quoteLiteral(name)}\n ) THEN\n EXECUTE ${quoteLiteral(`ALTER PUBLICATION ${quoteIdent(publication.replace(/\"/g, ''))} ADD TABLE ${quoteName(schema)}.${quoteName(name)}`)};\n END IF;\nEND $$;`\n}\n\n/** Thrown to unwind out of the layer loop once a transaction has aborted. */\nclass RestoreAborted extends Error {}\n","/**\n * Replaying a snapshot's rows: reference data (`data/*.json`) and storage\n * buckets (`storage-buckets.json`).\n *\n * Both were captured and never restored — the data loop looked for `.sql`\n * files the snapshot does not write, and buckets were left to the Storage API.\n * Rows go in through `json_populate_recordset`, so PostgreSQL converts each\n * value to its column's type itself, exactly as it rendered it.\n */\nimport { readdir, readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport type pg from 'pg'\nimport { quoteIdent, quoteLiteral, quoteName } from './utils/sql'\n\n/** The tables a snapshot holds rows for, by file name. */\nexport async function dataTablesIn(dataDir: string): Promise<string[]> {\n try {\n return (await readdir(dataDir)).filter(f => f.endsWith('.json')).map(f => f.slice(0, -'.json'.length)).sort()\n } catch {\n return []\n }\n}\n\n/** The snapshot's data tables, parents before children so foreign keys hold. */\nexport async function dataTablesInOrder(client: pg.Client, dataDir: string): Promise<string[]> {\n return inDependencyOrder(client, await dataTablesIn(dataDir))\n}\n\n/**\n * Insert one table's rows, and move each serial or identity sequence past the\n * ids restored.\n *\n * A row already there is kept (`ON CONFLICT DO NOTHING`), so a restore can be\n * run twice. Generated columns are left to compute; identity columns keep\n * their captured values.\n */\nexport async function restoreTableRows(client: pg.Client, dataDir: string, table: string): Promise<number> {\n const rows = await readFile(join(dataDir, `${table}.json`), 'utf-8')\n const inserted = await insertRows(client, quoteIdent(table), rows)\n await resetSequences(client, quoteIdent(table))\n return inserted\n}\n\n/**\n * Create the buckets the target does not have. A bucket is a row in\n * `storage.buckets` — the Storage API writes the same row — so the target\n * needs that table, and nothing else; objects are never transferred.\n */\nexport async function restoreBuckets(client: pg.Client, file: string): Promise<number | undefined> {\n const { rows: [present] } = await client.query<{ ok: boolean }>(`SELECT to_regclass('storage.buckets') IS NOT NULL AS ok`)\n if (!present?.ok) return undefined\n return insertRows(client, 'storage.buckets', await readFile(file, 'utf-8'))\n}\n\n/**\n * `rows` is the file's JSON as written, handed to the server untouched:\n * parsed and serialised again here, a bigint past 2^53 or a long numeric\n * came back rounded.\n */\nasync function insertRows(client: pg.Client, table: string, rows: string): Promise<number> {\n // Each column's text, which the column's type reads back exactly (see\n // capturedRows) — or, from a snapshot taken before that, JSON values.\n const asText = rows.trimStart().startsWith('{')\n const elements = asText ? `json_array_elements($1::json -> 'rows')` : `json_array_elements($1::json)`\n const { rows: keys } = await client.query<{ key: string }>(\n `SELECT DISTINCT json_object_keys(e) AS key FROM ${elements} e`, [rows])\n if (keys.length === 0) return 0\n const { rows: columns } = await client.query<{ name: string; identity: string; generated: string; type: string }>(\n `SELECT attname AS name, attidentity AS identity, attgenerated AS generated, format_type(atttypid, atttypmod) AS type\n FROM pg_attribute WHERE attrelid = $1::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`,\n [table])\n // The columns both the rows and the table have: a column added since the\n // snapshot takes its default, one dropped since is left behind.\n const captured = new Set(keys.map(k => k.key))\n const usable = columns.filter(c => c.generated === '' && captured.has(c.name))\n const list = usable.map(c => quoteName(c.name)).join(', ')\n const overriding = usable.some(c => c.identity === 'a') ? ' OVERRIDING SYSTEM VALUE' : ''\n const select = asText\n ? `SELECT ${usable.map(c => `(e ->> ${quoteLiteral(c.name)})::${c.type}`).join(', ')} FROM ${elements} e`\n : `SELECT ${list} FROM json_populate_recordset(NULL::${table}, $1::json)`\n const { rowCount } = await client.query(\n `INSERT INTO ${table} (${list})${overriding} ${select} ON CONFLICT DO NOTHING`, [rows])\n return rowCount ?? 0\n}\n\nasync function resetSequences(client: pg.Client, table: string): Promise<void> {\n const { rows } = await client.query<{ seq: string; col: string }>(\n `SELECT pg_get_serial_sequence($1, attname) AS seq, attname AS col\n FROM pg_attribute WHERE attrelid = $1::regclass AND attnum > 0 AND NOT attisdropped\n AND pg_get_serial_sequence($1, attname) IS NOT NULL`,\n [table])\n for (const { seq, col } of rows) {\n await client.query(\n `SELECT setval($1, coalesce((SELECT max(${quoteName(col)}) FROM ${table}), 1),\n (SELECT max(${quoteName(col)}) FROM ${table}) IS NOT NULL)`,\n [seq])\n }\n}\n\n/**\n * Parents first, by the foreign keys between the tables being restored. A\n * cycle cannot be ordered and keeps the order the files came in; a table the\n * target lacks is left for the insert to report.\n */\nasync function inDependencyOrder(client: pg.Client, tables: string[]): Promise<string[]> {\n const { rows: oids } = await client.query<{ name: string; oid: string | null }>(\n `SELECT t AS name, to_regclass(q)::oid::text AS oid FROM unnest($1::text[], $2::text[]) AS u(t, q)`,\n [tables, tables.map(quoteIdent)])\n const byOid = new Map(oids.filter(r => r.oid).map(r => [r.oid as string, r.name]))\n const { rows: keys } = await client.query<{ child: string; parent: string }>(\n `SELECT conrelid::text AS child, confrelid::text AS parent FROM pg_constraint\n WHERE contype = 'f' AND conrelid::text = ANY($1) AND confrelid::text = ANY($1) AND conrelid <> confrelid`,\n [[...byOid.keys()]])\n const parents = new Map<string, Set<string>>(tables.map(t => [t, new Set()]))\n for (const { child, parent } of keys) parents.get(byOid.get(child)!)?.add(byOid.get(parent)!)\n\n const ordered: string[] = []\n const placed = new Set<string>()\n while (ordered.length < tables.length) {\n const ready = tables.filter(t => !placed.has(t) && [...parents.get(t)!].every(p => placed.has(p)))\n // A cycle: take the rest as they are.\n for (const t of ready.length > 0 ? ready : tables.filter(t => !placed.has(t))) {\n ordered.push(t)\n placed.add(t)\n }\n }\n return ordered\n}\n","import type pg from 'pg'\nimport { PLATFORM_ROLES } from './checks/roles.js'\nimport { SUPABASE_PLATFORM_SCHEMAS } from './defaults'\n\n/**\n * What `restore --force` clears, and what it must put back.\n *\n * `--force` replaces the snapshot's objects in the target. It used to do that\n * with `DROP SCHEMA ... CASCADE` on every schema the dump mentioned, which was\n * wrong three ways:\n *\n * - The dump mentions platform schemas — a Supabase dump carries\n * `CREATE SCHEMA graphql` and `CREATE SCHEMA pgbouncer` — so they were\n * dropped too. As `postgres` that fails (\"must be owner of schema\n * graphql\"), so `--force` never worked against Supabase; as a superuser it\n * would have removed `pgbouncer.get_auth`, which the restore then skips as\n * platform-owned and never puts back.\n * - CASCADE reaches out of the schema. `on_auth_user_created`, the trigger\n * on `auth.users` that calls `public.handle_new_user()`, is dropped with\n * `public` — and no snapshot layer captures `auth`, so it was lost for\n * good, silently. Storage policies calling a `public` function go the\n * same way.\n * - Dropping the schema itself drops its grants and default privileges. On\n * Supabase those are what give `anon` and `authenticated` USAGE on\n * `public` and their privileges on every new table.\n *\n * So the schemas stay and only their contents go; platform schemas are never\n * touched; and whatever outside them depends on what is dropped is captured\n * first and recreated afterwards — or, where it is something that cannot be\n * put back faithfully, the restore refuses before changing anything.\n */\n\n/** Schemas `--force` never clears, whatever the dump mentions. */\nconst NEVER_CLEARED = new Set(SUPABASE_PLATFORM_SCHEMAS)\n\n/** The schemas `--force` may clear: the snapshot's own, never the platform's. */\nexport function replaceableSchemas(snapshotSchemas: string[]): string[] {\n return snapshotSchemas.filter(s => !NEVER_CLEARED.has(s) && !s.startsWith('pg_'))\n}\n\n/** An object outside the cleared schemas that depends on something inside them. */\nexport interface ExternalDependent {\n kind: 'trigger' | 'policy'\n schema: string\n table: string\n name: string\n /** The DDL that puts it back. */\n ddl: string\n}\n\nexport interface ExternalDependents {\n /** Triggers and policies, captured so they can be recreated. */\n recreate: ExternalDependent[]\n /** Anything else — a column, a constraint, a view — described for the refusal. */\n blockers: string[]\n}\n\n/**\n * Objects outside `schemas` that a CASCADE of their contents would drop.\n *\n * Read from pg_depend: every normal dependency whose referenced object lives in\n * one of `schemas` and whose dependent does not. Triggers and policies can be\n * reproduced exactly from the catalog, so they are captured; anything else is\n * reported as a blocker, because dropping it would lose data (a column of an\n * enum type) or structure this restore does not own (a view in another\n * schema).\n *\n * Captured with an empty search_path so every name in the DDL is qualified:\n * `public.handle_new_user()`, not a bare name that happens to resolve today.\n */\nexport async function findExternalDependents(\n client: pg.Client,\n schemas: string[],\n): Promise<ExternalDependents> {\n if (schemas.length === 0) return { recreate: [], blockers: [] }\n\n const { rows: [{ search_path: previous }] } = await client.query<{ search_path: string }>(\n 'SHOW search_path',\n )\n await client.query(`SELECT set_config('search_path', '', false)`)\n try {\n const { rows } = await client.query<{\n kind: string; identity: string; schema: string | null\n trigger_ddl: string | null; policy_ddl: string | null\n table_schema: string | null; table_name: string | null; object_name: string | null\n }>(EXTERNAL_DEPENDENTS_SQL, [schemas])\n\n const recreate: ExternalDependent[] = []\n const blockers: string[] = []\n const seen = new Set<string>()\n\n for (const row of rows) {\n if (seen.has(row.identity)) continue\n seen.add(row.identity)\n\n if (row.kind === 'trigger' && row.trigger_ddl) {\n recreate.push({\n kind: 'trigger', schema: row.table_schema!, table: row.table_name!,\n name: row.object_name!, ddl: `${row.trigger_ddl};`,\n })\n } else if (row.kind === 'policy' && row.policy_ddl) {\n recreate.push({\n kind: 'policy', schema: row.table_schema!, table: row.table_name!,\n name: row.object_name!, ddl: `${row.policy_ddl};`,\n })\n } else {\n blockers.push(`${row.kind} ${row.identity}`)\n }\n }\n\n return { recreate, blockers }\n } finally {\n await client.query(`SELECT set_config('search_path', $1, false)`, [previous])\n }\n}\n\nconst EXTERNAL_DEPENDENTS_SQL = `\n -- What clearing drops: everything in the schemas except extension members,\n -- which dropSchemaContents leaves in place. Counting those would refuse a\n -- --force over, say, an auth default calling public.uuid_generate_v4()\n -- from an extension installed in public, which is never dropped.\n WITH members AS (\n SELECT objid FROM pg_depend WHERE deptype = 'e'\n ),\n inside AS (\n SELECT c.oid, 'pg_class'::regclass AS classid\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY($1) AND c.oid NOT IN (SELECT objid FROM members)\n UNION ALL\n SELECT p.oid, 'pg_proc'::regclass\n FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = ANY($1) AND p.oid NOT IN (SELECT objid FROM members)\n UNION ALL\n SELECT t.oid, 'pg_type'::regclass\n FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace\n WHERE n.nspname = ANY($1) AND t.oid NOT IN (SELECT objid FROM members)\n ),\n dependents AS (\n SELECT DISTINCT d.classid, d.objid, d.objsubid\n FROM pg_depend d\n JOIN inside i ON i.oid = d.refobjid AND i.classid = d.refclassid\n WHERE d.deptype = 'n'\n )\n SELECT o.type AS kind, o.identity, o.schema,\n CASE WHEN dep.classid = 'pg_trigger'::regclass\n THEN pg_get_triggerdef(dep.objid) END AS trigger_ddl,\n CASE WHEN dep.classid = 'pg_policy'::regclass THEN (\n SELECT format('CREATE POLICY %I ON %I.%I AS %s FOR %s TO %s%s%s',\n p.polname, pn.nspname, pc.relname,\n CASE WHEN p.polpermissive THEN 'PERMISSIVE' ELSE 'RESTRICTIVE' END,\n CASE p.polcmd WHEN 'r' THEN 'SELECT' WHEN 'a' THEN 'INSERT'\n WHEN 'w' THEN 'UPDATE' WHEN 'd' THEN 'DELETE' ELSE 'ALL' END,\n CASE WHEN p.polroles = '{0}' THEN 'PUBLIC'\n ELSE (SELECT string_agg(quote_ident(r.rolname), ', ' ORDER BY r.rolname)\n FROM pg_roles r WHERE r.oid = ANY (p.polroles)) END,\n CASE WHEN p.polqual IS NOT NULL\n THEN ' USING (' || pg_get_expr(p.polqual, p.polrelid) || ')' ELSE '' END,\n CASE WHEN p.polwithcheck IS NOT NULL\n THEN ' WITH CHECK (' || pg_get_expr(p.polwithcheck, p.polrelid) || ')' ELSE '' END)\n FROM pg_policy p\n JOIN pg_class pc ON pc.oid = p.polrelid\n JOIN pg_namespace pn ON pn.oid = pc.relnamespace\n WHERE p.oid = dep.objid) END AS policy_ddl,\n COALESCE(tn.nspname, pn.nspname) AS table_schema,\n COALESCE(tc.relname, pc.relname) AS table_name,\n COALESCE(t.tgname, p.polname) AS object_name\n FROM dependents dep\n CROSS JOIN LATERAL pg_identify_object(dep.classid, dep.objid, dep.objsubid) o\n LEFT JOIN pg_trigger t ON dep.classid = 'pg_trigger'::regclass AND t.oid = dep.objid\n LEFT JOIN pg_class tc ON tc.oid = t.tgrelid\n LEFT JOIN pg_namespace tn ON tn.oid = tc.relnamespace\n LEFT JOIN pg_policy p ON dep.classid = 'pg_policy'::regclass AND p.oid = dep.objid\n LEFT JOIN pg_class pc ON pc.oid = p.polrelid\n LEFT JOIN pg_namespace pn ON pn.oid = pc.relnamespace\n -- The schema an object lives in. pg_identify_object reports none for a\n -- trigger, policy, rule or column default, which belong to their\n -- relation's schema: read as \"no schema\", every view, default, policy and\n -- trigger inside the cleared schemas looked like an outside dependent —\n -- refusing a --force over any table with a serial column, and putting\n -- back policies the snapshot had removed.\n CROSS JOIN LATERAL (\n SELECT COALESCE(\n tn.nspname,\n pn.nspname,\n (SELECT n.nspname FROM pg_attrdef ad JOIN pg_class c ON c.oid = ad.adrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE dep.classid = 'pg_attrdef'::regclass AND ad.oid = dep.objid),\n (SELECT n.nspname FROM pg_rewrite r JOIN pg_class c ON c.oid = r.ev_class\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE dep.classid = 'pg_rewrite'::regclass AND r.oid = dep.objid),\n (SELECT n.nspname FROM pg_constraint k\n LEFT JOIN pg_class c ON c.oid = k.conrelid\n LEFT JOIN pg_type ty ON ty.oid = k.contypid\n JOIN pg_namespace n ON n.oid = COALESCE(c.relnamespace, ty.typnamespace)\n WHERE dep.classid = 'pg_constraint'::regclass AND k.oid = dep.objid),\n o.schema\n ) AS schema\n ) owner\n WHERE owner.schema IS NULL OR NOT (owner.schema = ANY($1))\n ORDER BY o.type, o.identity\n`\n\n/**\n * Drop every object in `schemas`, keeping the schemas themselves.\n *\n * Keeping the schema keeps its grants and default privileges, which the dump\n * does not carry (it is taken with --no-privileges). Extension members are\n * left alone: the extension owns them, DROP refuses them, and the extensions\n * layer puts the extension back if it is missing.\n *\n * @returns how many objects were dropped\n */\nexport async function dropSchemaContents(client: pg.Client, schemas: string[]): Promise<number> {\n if (schemas.length === 0) return 0\n\n const { rows } = await client.query<{ statement: string }>(DROP_CONTENTS_SQL, [schemas])\n for (const { statement } of rows) {\n await client.query(statement)\n }\n return rows.length\n}\n\n// Views before tables before routines before types, so most drops find their\n// object still there; IF EXISTS covers what an earlier CASCADE already took.\nconst DROP_CONTENTS_SQL = `\n WITH members AS (\n SELECT objid FROM pg_depend WHERE deptype = 'e'\n )\n SELECT statement FROM (\n SELECT 1 AS phase, format('DROP %s IF EXISTS %I.%I CASCADE',\n CASE c.relkind WHEN 'v' THEN 'VIEW' WHEN 'm' THEN 'MATERIALIZED VIEW'\n WHEN 'f' THEN 'FOREIGN TABLE' WHEN 'S' THEN 'SEQUENCE'\n ELSE 'TABLE' END,\n n.nspname, c.relname) AS statement,\n n.nspname || '.' || c.relname AS sort_key\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = ANY($1)\n AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')\n AND c.oid NOT IN (SELECT objid FROM members)\n UNION ALL\n SELECT 2, format('DROP %s IF EXISTS %s CASCADE',\n CASE p.prokind WHEN 'a' THEN 'AGGREGATE' WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END,\n p.oid::regprocedure::text),\n p.oid::regprocedure::text\n FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace\n WHERE n.nspname = ANY($1)\n AND p.oid NOT IN (SELECT objid FROM members)\n UNION ALL\n SELECT 3, format('DROP %s IF EXISTS %I.%I CASCADE',\n CASE t.typtype WHEN 'd' THEN 'DOMAIN' ELSE 'TYPE' END, n.nspname, t.typname),\n n.nspname || '.' || t.typname\n FROM pg_type t JOIN pg_namespace n ON n.oid = t.typnamespace\n WHERE n.nspname = ANY($1)\n AND t.typtype IN ('e', 'd', 'r', 'm', 'c')\n AND (t.typtype <> 'c' OR (SELECT relkind FROM pg_class WHERE oid = t.typrelid) = 'c')\n AND t.oid NOT IN (SELECT objid FROM members)\n ) s\n ORDER BY phase, sort_key\n`\n\n/**\n * Put back the captured dependents the restore did not recreate itself.\n *\n * A storage policy may well be in the snapshot's storage-policies layer and\n * already be back; creating it again would fail. So each is checked first.\n */\nexport async function recreateExternalDependents(\n client: pg.Client,\n dependents: ExternalDependent[],\n): Promise<ExternalDependent[]> {\n const recreated: ExternalDependent[] = []\n\n for (const dep of dependents) {\n const exists = dep.kind === 'trigger'\n ? `SELECT 1 FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname = $1 AND c.relname = $2 AND t.tgname = $3`\n : `SELECT 1 FROM pg_policies WHERE schemaname = $1 AND tablename = $2 AND policyname = $3`\n const { rows } = await client.query(exists, [dep.schema, dep.table, dep.name])\n if (rows.length > 0) continue\n\n await client.query(dep.ddl)\n recreated.push(dep)\n }\n\n return recreated\n}\n\n/**\n * Strip every grant but the owner's from the objects in `schemas` whose\n * grants the roles layer captures — tables, views, materialized views,\n * foreign tables, sequences and routines — so the layer that follows leaves\n * exactly the grants it captured.\n *\n * The schema layer is a dump taken with --no-privileges, so each object it\n * creates starts with whatever the target's default privileges give — on\n * Supabase, everything to `anon` and `authenticated` — and the roles layer\n * only ever *adds* grants. A view whose grants had been narrowed (`REVOKE ALL\n * ON v FROM anon`, the usual way to keep a view off the public API) came back\n * wide open, and so did a SECURITY DEFINER function the source kept from the\n * API: a routine is executable by PUBLIC unless that is revoked.\n *\n * Grants to the platform's roles are left alone, since the roles layer does\n * not capture them and could not put them back; so are objects an extension\n * owns, whose grants are the extension's.\n *\n * @returns how many objects were reset\n */\nexport async function resetRelationGrants(client: pg.Client, schemas: string[]): Promise<number> {\n if (schemas.length === 0) return 0\n const { rows } = await client.query<{ statement: string }>(`\n WITH acl AS (\n SELECT CASE c.relkind WHEN 'S' THEN 'SEQUENCE ' ELSE '' END || c.oid::regclass::text AS object, a.grantee\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n CROSS JOIN LATERAL aclexplode(c.relacl) a\n WHERE n.nspname = ANY($1)\n AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')\n AND a.grantee <> c.relowner\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype = 'e')\n UNION ALL\n SELECT CASE p.prokind WHEN 'p' THEN 'PROCEDURE ' ELSE 'FUNCTION ' END || p.oid::regprocedure::text, a.grantee\n FROM pg_proc p\n JOIN pg_namespace n ON n.oid = p.pronamespace\n CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a\n WHERE n.nspname = ANY($1)\n AND a.grantee <> p.proowner\n AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')\n )\n SELECT format('REVOKE ALL ON %s FROM %s', object,\n string_agg(DISTINCT CASE WHEN grantee = 0 THEN 'PUBLIC'\n ELSE quote_ident(pg_get_userbyid(grantee)) END, ', ')) AS statement\n FROM acl\n WHERE grantee = 0\n OR (pg_get_userbyid(grantee) <> ALL ($2::text[]) AND pg_get_userbyid(grantee) NOT LIKE 'pg\\\\_%')\n GROUP BY object\n `, [schemas, PLATFORM_ROLES])\n for (const { statement } of rows) await client.query(statement)\n return rows.length\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAAA,WAAU,cAAc;AACjC,SAAS,iBAAiB;AAC1B,SAAS,QAAAC,aAAY;AACrB,OAAO,QAAQ;;;ACMf,SAAS,SAAS,gBAAgB;AAClC,SAAS,YAAY;AAKrB,eAAsB,aAAa,SAAoC;AACrE,MAAI;AACF,YAAQ,MAAM,QAAQ,OAAO,GAAG,OAAO,OAAK,EAAE,SAAS,OAAO,CAAC,EAAE,IAAI,OAAK,EAAE,MAAM,GAAG,CAAC,QAAQ,MAAM,CAAC,EAAE,KAAK;AAAA,EAC9G,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AAC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AI,CAAC,MAAO,QAAO;AAEnB,QAAM,SAAS,MAAM,CAAC,EAAE,QAAQ,MAAM,EAAE;AACxC,SAAO,eAAe,MAAM,IAAI,SAAY;AAC9C;AASO,SAAS,oBAAoB,MAAsB;AACxD,SAAO;AAAA,0DACiD,aAAa,IAAI,CAAC;AAAA,kBAC1D,UAAU,IAAI,CAAC;AAAA;AAAA;AAGjC;AAaO,SAAS,iCAAiC,KAAqB;AACpE,QAAM,QAAQ,4FACX,KAAK,GAAG;AACX,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,CAAC,EAAE,aAAa,KAAK,IAAI;AAC/B,QAAM,QAAQ,MAAM,MAAM,GAAG,EAAE,IAAI,OAAK,EAAE,QAAQ,MAAM,EAAE,EAAE,KAAK,CAAC;AAClE,MAAI,MAAM,WAAW,EAAG,QAAO;AAE/B,QAAM,CAAC,QAAQ,IAAI,IAAI;AACvB,SAAO;AAAA;AAAA;AAAA,sBAGa,aAAa,YAAY,QAAQ,MAAM,EAAE,CAAC,CAAC;AAAA,yBACxC,aAAa,MAAM,CAAC;AAAA,wBACrB,aAAa,IAAI,CAAC;AAAA;AAAA,cAE5B,aAAa,qBAAqB,WAAW,YAAY,QAAQ,MAAM,EAAE,CAAC,CAAC,cAAc,UAAU,MAAM,CAAC,IAAI,UAAU,IAAI,CAAC,EAAE,CAAC;AAAA;AAAA;AAG9I;AAGA,IAAM,iBAAN,cAA6B,MAAM;AAAC;","names":["readFile","join","t","join","readFile"]}
@@ -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;AAAA,EACtF;AACA,QAAM,QAAQ,cAAc,CAAC,KAAK;AAClC,SAAO;AAAA,IACL,MACE,kCAA6B,IAAI,SAAS,CAAC,6HAExB,IAAI,WAAW,KAAK,oBAAoB,CAAC;AAAA,EAChE;AACF;AAEA,SAAS,SAAS,KAAwB;AACxC,QAAM,OAAc,CAAC;AACrB,QAAM,EAAE,aAAa,GAAG,gBAAgB,CAAC,GAAG,QAAQ,OAAO,aAAa,gBAAgB,CAAC,GAAG,gBAAgB,CAAC,GAAG,cAAc,IAAI;AAElI,MAAI,OAAO;AAET,QAAI,aAAa,GAAG;AAClB,WAAK,KAAK,EAAE,MAAM,UAAU,IAAI,gBAAgB,CAAC,kCAAkC,CAAC;AACpF,WAAK,KAAK,EAAE,MAAM,4CAA4C,IAAI,oBAAoB,CAAC,IAAI,CAAC;AAAA,IAC9F,OAAO;AACL,WAAK,KAAK,EAAE,MAAM,gCAA2B,IAAI,oBAAoB,CAAC,gCAAgC,CAAC;AAAA,IACzG;AACA,WAAO;AAAA,EACT;AAEA,MAAI,aAAa,KAAK,CAAC,QAAQ;AAE7B,SAAK,KAAK,EAAE,MAAM,OAAO,IAAI,UAAU,CAAC,uCAAuC,CAAC;AAChF,SAAK,KAAK,SAAS,eAAe,aAAa,CAAC;AAChD,QAAI,cAAc,SAAS,GAAG;AAC5B,WAAK,KAAK,EAAE,MAAM,uBAAuB,IAAI,WAAW,cAAc,CAAC,CAAC,EAAE,CAAC,2BAA2B,CAAC;AAAA,IACzG;AACA,QAAI,cAAc,WAAW,GAA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