@akal/supaforge 0.0.0-stage → 0.0.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +350 -2
- package/bin/dev.js +10 -0
- package/bin/run.js +18 -0
- package/dist/base-command.d.ts +135 -0
- package/dist/base-command.js +9 -0
- package/dist/base-command.js.map +1 -0
- package/dist/branch-C4ndfoj5.d.ts +58 -0
- package/dist/chunk-2SELREHW.js +156 -0
- package/dist/chunk-2SELREHW.js.map +1 -0
- package/dist/chunk-3HGAV5CC.js +2073 -0
- package/dist/chunk-3HGAV5CC.js.map +1 -0
- package/dist/chunk-4IVN7QVY.js +632 -0
- package/dist/chunk-4IVN7QVY.js.map +1 -0
- package/dist/chunk-6LJERPUN.js +499 -0
- package/dist/chunk-6LJERPUN.js.map +1 -0
- package/dist/chunk-6Q7MHFBM.js +13 -0
- package/dist/chunk-6Q7MHFBM.js.map +1 -0
- package/dist/chunk-6WAMNZLO.js +336 -0
- package/dist/chunk-6WAMNZLO.js.map +1 -0
- package/dist/chunk-7NAZGZPV.js +868 -0
- package/dist/chunk-7NAZGZPV.js.map +1 -0
- package/dist/chunk-BLKJWDTL.js +153 -0
- package/dist/chunk-BLKJWDTL.js.map +1 -0
- package/dist/chunk-BUOWHE36.js +1311 -0
- package/dist/chunk-BUOWHE36.js.map +1 -0
- package/dist/chunk-DMIWAJRB.js +602 -0
- package/dist/chunk-DMIWAJRB.js.map +1 -0
- package/dist/chunk-DQQ5E563.js +64 -0
- package/dist/chunk-DQQ5E563.js.map +1 -0
- package/dist/chunk-G2DIPIYU.js +94 -0
- package/dist/chunk-G2DIPIYU.js.map +1 -0
- package/dist/chunk-GEHPTPNZ.js +240 -0
- package/dist/chunk-GEHPTPNZ.js.map +1 -0
- package/dist/chunk-GZREXCQZ.js +207 -0
- package/dist/chunk-GZREXCQZ.js.map +1 -0
- package/dist/chunk-MIRLB5JM.js +1292 -0
- package/dist/chunk-MIRLB5JM.js.map +1 -0
- package/dist/chunk-NTUASFQ3.js +248 -0
- package/dist/chunk-NTUASFQ3.js.map +1 -0
- package/dist/chunk-ORQJVE57.js +642 -0
- package/dist/chunk-ORQJVE57.js.map +1 -0
- package/dist/chunk-SC2XHGIS.js +122 -0
- package/dist/chunk-SC2XHGIS.js.map +1 -0
- package/dist/chunk-SQPCWGQO.js +657 -0
- package/dist/chunk-SQPCWGQO.js.map +1 -0
- package/dist/chunk-UWAVXC57.js +916 -0
- package/dist/chunk-UWAVXC57.js.map +1 -0
- package/dist/commands/clone.d.ts +66 -0
- package/dist/commands/clone.js +416 -0
- package/dist/commands/clone.js.map +1 -0
- package/dist/commands/diff.d.ts +81 -0
- package/dist/commands/diff.js +23 -0
- package/dist/commands/diff.js.map +1 -0
- package/dist/commands/help.d.ts +32 -0
- package/dist/commands/help.js +36 -0
- package/dist/commands/help.js.map +1 -0
- package/dist/commands/hukam.d.ts +13 -0
- package/dist/commands/hukam.js +28 -0
- package/dist/commands/hukam.js.map +1 -0
- package/dist/commands/init.d.ts +47 -0
- package/dist/commands/init.js +388 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/mcp.d.ts +13 -0
- package/dist/commands/mcp.js +43 -0
- package/dist/commands/mcp.js.map +1 -0
- package/dist/commands/migrate/baseline.d.ts +24 -0
- package/dist/commands/migrate/baseline.js +69 -0
- package/dist/commands/migrate/baseline.js.map +1 -0
- package/dist/commands/migrate/create.d.ts +36 -0
- package/dist/commands/migrate/create.js +127 -0
- package/dist/commands/migrate/create.js.map +1 -0
- package/dist/commands/migrate/list.d.ts +23 -0
- package/dist/commands/migrate/list.js +110 -0
- package/dist/commands/migrate/list.js.map +1 -0
- package/dist/commands/migrate/run.d.ts +61 -0
- package/dist/commands/migrate/run.js +18 -0
- package/dist/commands/migrate/run.js.map +1 -0
- package/dist/commands/report.d.ts +27 -0
- package/dist/commands/report.js +210 -0
- package/dist/commands/report.js.map +1 -0
- package/dist/commands/restore.d.ts +26 -0
- package/dist/commands/restore.js +266 -0
- package/dist/commands/restore.js.map +1 -0
- package/dist/commands/snapshot.d.ts +33 -0
- package/dist/commands/snapshot.js +249 -0
- package/dist/commands/snapshot.js.map +1 -0
- package/dist/commands/sync.d.ts +16 -0
- package/dist/commands/sync.js +38 -0
- package/dist/commands/sync.js.map +1 -0
- package/dist/config-CTbeRlJk.d.ts +134 -0
- package/dist/help.d.ts +28 -0
- package/dist/help.js +64 -0
- package/dist/help.js.map +1 -0
- package/dist/index.d.ts +498 -0
- package/dist/index.js +147 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/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;AACF;AAGA,eAAsB,kBAAkB,QAAmB,SAAoC;AAC7F,SAAO,kBAAkB,QAAQ,MAAM,aAAa,OAAO,CAAC;AAC9D;AAUA,eAAsB,iBAAiB,QAAmB,SAAiB,OAAgC;AACzG,QAAM,OAAO,MAAM,SAAS,KAAK,SAAS,GAAG,KAAK,OAAO,GAAG,OAAO;AACnE,QAAM,WAAW,MAAM,WAAW,QAAQ,WAAW,KAAK,GAAG,IAAI;AACjE,QAAM,eAAe,QAAQ,WAAW,KAAK,CAAC;AAC9C,SAAO;AACT;AAOA,eAAsB,eAAe,QAAmB,MAA2C;AACjG,QAAM,EAAE,MAAM,CAAC,OAAO,EAAE,IAAI,MAAM,OAAO,MAAuB,yDAAyD;AACzH,MAAI,CAAC,SAAS,GAAI,QAAO;AACzB,SAAO,WAAW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AAW,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"]}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CLONE_SKIP_FLAGS,
|
|
3
|
+
cmd,
|
|
4
|
+
dim
|
|
5
|
+
} from "./chunk-6WAMNZLO.js";
|
|
6
|
+
|
|
7
|
+
// src/tips.ts
|
|
8
|
+
function applyTip(sourceIsClone, driftedChecks) {
|
|
9
|
+
if (!sourceIsClone) {
|
|
10
|
+
return { text: `Add ${cmd("--apply")} to push all fixes to the target in one shot.` };
|
|
11
|
+
}
|
|
12
|
+
const layer = driftedChecks[0] ?? "schema";
|
|
13
|
+
return {
|
|
14
|
+
text: `Source is a local clone \u2014 ${cmd("--apply")} would reshape the target to match it, including dropping roles, grants and policies the clone never had. Scope it first: ${cmd(`--check=${layer} --apply --dry-run`)}.`
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function diffTips(ctx) {
|
|
18
|
+
const tips = [];
|
|
19
|
+
const { driftTotal = 0, driftedChecks = [], detail, apply, singleCheck, skippedChecks = [], erroredChecks = [], sourceIsClone } = ctx;
|
|
20
|
+
if (apply) {
|
|
21
|
+
if (driftTotal > 0) {
|
|
22
|
+
tips.push({ text: `Re-run ${cmd("supaforge diff")} to verify everything is clean.` });
|
|
23
|
+
tips.push({ text: `Take a snapshot after a successful sync: ${cmd("supaforge snapshot")}.` });
|
|
24
|
+
} else {
|
|
25
|
+
tips.push({ text: `No drift to apply \u2014 run ${cmd("supaforge snapshot")} to lock in this clean state.` });
|
|
26
|
+
}
|
|
27
|
+
return tips;
|
|
28
|
+
}
|
|
29
|
+
if (driftTotal > 0 && !detail) {
|
|
30
|
+
tips.push({ text: `Add ${cmd("--detail")} to see the full SQL for each issue.` });
|
|
31
|
+
tips.push(applyTip(sourceIsClone, driftedChecks));
|
|
32
|
+
if (driftedChecks.length > 1) {
|
|
33
|
+
tips.push({ text: `Focus on one layer: ${cmd(`--check=${driftedChecks[0]}`)} to see just that check.` });
|
|
34
|
+
}
|
|
35
|
+
if (skippedChecks.length === 0) {
|
|
36
|
+
tips.push({ text: `Post-clone? Use ${cmd(CLONE_SKIP_FLAGS)} to suppress clone-only noise, roles and grants included.` });
|
|
37
|
+
}
|
|
38
|
+
} else if (driftTotal > 0 && detail) {
|
|
39
|
+
tips.push(
|
|
40
|
+
sourceIsClone ? applyTip(sourceIsClone, driftedChecks) : { text: `Run ${cmd("supaforge diff --apply")} to execute all the SQL fixes above.` }
|
|
41
|
+
);
|
|
42
|
+
if (driftedChecks.length > 1) {
|
|
43
|
+
tips.push({ text: `Fix one layer at a time: ${cmd(`--check=${driftedChecks[0]} --apply`)}.` });
|
|
44
|
+
}
|
|
45
|
+
} else if (driftTotal === 0) {
|
|
46
|
+
tips.push(...noDriftTips(erroredChecks, singleCheck));
|
|
47
|
+
}
|
|
48
|
+
return tips;
|
|
49
|
+
}
|
|
50
|
+
function cloneTips(ctx) {
|
|
51
|
+
if (!ctx.cloneApplied) {
|
|
52
|
+
return [{ text: `Looks good? Add ${cmd("--apply")} to execute the clone.` }];
|
|
53
|
+
}
|
|
54
|
+
return [
|
|
55
|
+
{
|
|
56
|
+
text: `Diff against this clone with: ${cmd(`supaforge diff ${CLONE_SKIP_FLAGS}`)} \u2014 or add ${cmd('"checks": { "exclude": [...] }')} to config to make it permanent.`
|
|
57
|
+
},
|
|
58
|
+
{ text: `Restore from a snapshot any time: ${cmd("supaforge restore --env=local --from-snapshot=latest --apply")}.` },
|
|
59
|
+
{ text: `Run ${cmd("supaforge snapshot")} on the remote after a deploy to track incremental drift.` }
|
|
60
|
+
];
|
|
61
|
+
}
|
|
62
|
+
function snapshotTips(ctx) {
|
|
63
|
+
if (ctx.snapshotList) {
|
|
64
|
+
return [
|
|
65
|
+
{ text: `Clean up old snapshots with ${cmd("supaforge snapshot --prune")} (keeps last 7 by default).` },
|
|
66
|
+
{ text: `Restore into an environment: ${cmd("supaforge restore --env=local --from-snapshot=latest --apply")}.` }
|
|
67
|
+
];
|
|
68
|
+
}
|
|
69
|
+
if (ctx.snapshotMigration) {
|
|
70
|
+
return [
|
|
71
|
+
{ text: `Migration files live in ${cmd(".supaforge/migrations/")} \u2014 commit them to version-control.` },
|
|
72
|
+
{ text: `Replay all migrations: ${cmd("supaforge restore --env=local --from-migrations --apply")}.` }
|
|
73
|
+
];
|
|
74
|
+
}
|
|
75
|
+
return [
|
|
76
|
+
{ text: `Add ${cmd("--migration")} to also generate an incremental diff against the previous snapshot.` },
|
|
77
|
+
{ text: `List all snapshots: ${cmd("supaforge snapshot --list")}.` },
|
|
78
|
+
{ text: `Restore this snapshot: ${cmd("supaforge restore --env=local --from-snapshot=latest --apply")}.` }
|
|
79
|
+
];
|
|
80
|
+
}
|
|
81
|
+
function restoreTips(_ctx) {
|
|
82
|
+
return [
|
|
83
|
+
{ text: `After a restore, run ${cmd("supaforge diff")} to confirm the environment matches the source.` },
|
|
84
|
+
{ text: `Take a new snapshot to lock in the restored state: ${cmd("supaforge snapshot")}.` }
|
|
85
|
+
];
|
|
86
|
+
}
|
|
87
|
+
var GENERAL_TIPS = [
|
|
88
|
+
{ text: `${cmd("supaforge hukam")} is an alias for ${cmd("diff")} \u2014 same flags, different vibe \u{1F64F}` },
|
|
89
|
+
{ text: `Use ${cmd("--source=X --target=Y")} to compare any two environments without editing config.` },
|
|
90
|
+
{ text: `Store credentials in ${cmd(".env")} \u2014 SupaForge auto-loads it. Config supports ${cmd("$VAR")} references.` },
|
|
91
|
+
{ text: `Add ${cmd('"checks": { "exclude": ["storage","vault"] }')} to config to permanently skip noisy checks.` },
|
|
92
|
+
{ text: `Run ${cmd("supaforge diff --json")} for machine-readable output \u2014 useful in scripts and CI.` },
|
|
93
|
+
{ text: `Connect AI agents: add ${cmd("supaforge mcp")} to your Claude Desktop / Cursor MCP config.` },
|
|
94
|
+
{ text: `Enable row-level data drift: add ${cmd('"checks": { "data": { "tables": ["plans","flags"] } }')} to config.` },
|
|
95
|
+
{ text: `${cmd("supaforge diff --include-files")} also checks file-level storage drift (checksums).` },
|
|
96
|
+
{ text: `${cmd("supaforge sync")} is shorthand for ${cmd("diff --apply")} \u2014 detects and fixes drift in one step.` },
|
|
97
|
+
{ text: `Preview an apply in dependency order without running it: ${cmd("supaforge diff --apply --dry-run")}.` },
|
|
98
|
+
{ text: `Apply a reviewed subset by id: ${cmd("supaforge diff --apply --only='schema-create-*'")}.` }
|
|
99
|
+
];
|
|
100
|
+
function noDriftTips(erroredChecks, singleCheck) {
|
|
101
|
+
if (erroredChecks.length > 0) {
|
|
102
|
+
const noun = erroredChecks.length === 1 ? "check" : "checks";
|
|
103
|
+
const names = erroredChecks.join(", ");
|
|
104
|
+
return [
|
|
105
|
+
{ text: `${erroredChecks.length} ${noun} could not run (${names}) \u2014 drift is unknown, not zero.` },
|
|
106
|
+
{ text: `Re-run with ${cmd("--detail")} to see why, then fix the cause before trusting this result.` }
|
|
107
|
+
];
|
|
108
|
+
}
|
|
109
|
+
const tips = [
|
|
110
|
+
{ text: `Environments are in sync \u2014 run ${cmd("supaforge snapshot")} to capture this state.` },
|
|
111
|
+
{ text: `Wire this into CI: ${cmd("supaforge diff")} exits 1 on critical drift.` }
|
|
112
|
+
];
|
|
113
|
+
if (!singleCheck) {
|
|
114
|
+
tips.push({ text: `Deep-dive a specific layer: ${cmd("supaforge diff --check=rls --detail")}.` });
|
|
115
|
+
}
|
|
116
|
+
return tips;
|
|
117
|
+
}
|
|
118
|
+
function pickTip(ctx, seed) {
|
|
119
|
+
let pool;
|
|
120
|
+
switch (ctx.command) {
|
|
121
|
+
case "diff":
|
|
122
|
+
pool = diffTips(ctx);
|
|
123
|
+
break;
|
|
124
|
+
case "clone":
|
|
125
|
+
pool = cloneTips(ctx);
|
|
126
|
+
break;
|
|
127
|
+
case "snapshot":
|
|
128
|
+
pool = snapshotTips(ctx);
|
|
129
|
+
break;
|
|
130
|
+
case "restore":
|
|
131
|
+
pool = restoreTips(ctx);
|
|
132
|
+
break;
|
|
133
|
+
default:
|
|
134
|
+
pool = [];
|
|
135
|
+
}
|
|
136
|
+
if (pool.length === 0) pool = GENERAL_TIPS;
|
|
137
|
+
if (pool.length < 3 && GENERAL_TIPS.length > 0) {
|
|
138
|
+
const generalIdx = (seed ?? Date.now()) % GENERAL_TIPS.length;
|
|
139
|
+
pool = [...pool, GENERAL_TIPS[generalIdx]];
|
|
140
|
+
}
|
|
141
|
+
const idx = (seed ?? Date.now()) % pool.length;
|
|
142
|
+
const tip = pool[idx];
|
|
143
|
+
return `
|
|
144
|
+
${dim("tip:")} ${tip.text}`;
|
|
145
|
+
}
|
|
146
|
+
function renderTip(ctx) {
|
|
147
|
+
return pickTip(ctx) ?? "";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export {
|
|
151
|
+
renderTip
|
|
152
|
+
};
|
|
153
|
+
//# sourceMappingURL=chunk-BLKJWDTL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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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