@akal/supaforge 0.0.0-stage → 0.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/README.md +350 -2
  2. package/bin/dev.js +10 -0
  3. package/bin/run.js +18 -0
  4. package/dist/base-command.d.ts +134 -0
  5. package/dist/base-command.js +9 -0
  6. package/dist/base-command.js.map +1 -0
  7. package/dist/branch-C4ndfoj5.d.ts +58 -0
  8. package/dist/chunk-4OU7KO5Y.js +13 -0
  9. package/dist/chunk-4OU7KO5Y.js.map +1 -0
  10. package/dist/chunk-5QQBTLWO.js +642 -0
  11. package/dist/chunk-5QQBTLWO.js.map +1 -0
  12. package/dist/chunk-5Z3SAIQS.js +2807 -0
  13. package/dist/chunk-5Z3SAIQS.js.map +1 -0
  14. package/dist/chunk-6WAMNZLO.js +336 -0
  15. package/dist/chunk-6WAMNZLO.js.map +1 -0
  16. package/dist/chunk-BHYLBKYD.js +156 -0
  17. package/dist/chunk-BHYLBKYD.js.map +1 -0
  18. package/dist/chunk-BLKJWDTL.js +153 -0
  19. package/dist/chunk-BLKJWDTL.js.map +1 -0
  20. package/dist/chunk-DQQ5E563.js +64 -0
  21. package/dist/chunk-DQQ5E563.js.map +1 -0
  22. package/dist/chunk-G2DIPIYU.js +94 -0
  23. package/dist/chunk-G2DIPIYU.js.map +1 -0
  24. package/dist/chunk-H5MJ5DFX.js +16 -0
  25. package/dist/chunk-H5MJ5DFX.js.map +1 -0
  26. package/dist/chunk-KIFJGON5.js +248 -0
  27. package/dist/chunk-KIFJGON5.js.map +1 -0
  28. package/dist/chunk-LQXF65MC.js +240 -0
  29. package/dist/chunk-LQXF65MC.js.map +1 -0
  30. package/dist/chunk-NXRSAVRU.js +478 -0
  31. package/dist/chunk-NXRSAVRU.js.map +1 -0
  32. package/dist/chunk-PARSNTBD.js +837 -0
  33. package/dist/chunk-PARSNTBD.js.map +1 -0
  34. package/dist/chunk-RRMI5CZD.js +376 -0
  35. package/dist/chunk-RRMI5CZD.js.map +1 -0
  36. package/dist/chunk-SF3YA42C.js +506 -0
  37. package/dist/chunk-SF3YA42C.js.map +1 -0
  38. package/dist/chunk-TQJSQLWA.js +574 -0
  39. package/dist/chunk-TQJSQLWA.js.map +1 -0
  40. package/dist/chunk-VMTBLHN2.js +122 -0
  41. package/dist/chunk-VMTBLHN2.js.map +1 -0
  42. package/dist/chunk-VOXZWQ3N.js +948 -0
  43. package/dist/chunk-VOXZWQ3N.js.map +1 -0
  44. package/dist/chunk-X6V2GGDZ.js +333 -0
  45. package/dist/chunk-X6V2GGDZ.js.map +1 -0
  46. package/dist/chunk-XMYMIURR.js +552 -0
  47. package/dist/chunk-XMYMIURR.js.map +1 -0
  48. package/dist/chunk-YVDSR4GM.js +1264 -0
  49. package/dist/chunk-YVDSR4GM.js.map +1 -0
  50. package/dist/commands/clone.d.ts +66 -0
  51. package/dist/commands/clone.js +416 -0
  52. package/dist/commands/clone.js.map +1 -0
  53. package/dist/commands/diff.d.ts +65 -0
  54. package/dist/commands/diff.js +24 -0
  55. package/dist/commands/diff.js.map +1 -0
  56. package/dist/commands/help.d.ts +32 -0
  57. package/dist/commands/help.js +36 -0
  58. package/dist/commands/help.js.map +1 -0
  59. package/dist/commands/hukam.d.ts +13 -0
  60. package/dist/commands/hukam.js +29 -0
  61. package/dist/commands/hukam.js.map +1 -0
  62. package/dist/commands/init.d.ts +47 -0
  63. package/dist/commands/init.js +388 -0
  64. package/dist/commands/init.js.map +1 -0
  65. package/dist/commands/mcp.d.ts +13 -0
  66. package/dist/commands/mcp.js +44 -0
  67. package/dist/commands/mcp.js.map +1 -0
  68. package/dist/commands/migrate/baseline.d.ts +24 -0
  69. package/dist/commands/migrate/baseline.js +69 -0
  70. package/dist/commands/migrate/baseline.js.map +1 -0
  71. package/dist/commands/migrate/create.d.ts +36 -0
  72. package/dist/commands/migrate/create.js +128 -0
  73. package/dist/commands/migrate/create.js.map +1 -0
  74. package/dist/commands/migrate/list.d.ts +23 -0
  75. package/dist/commands/migrate/list.js +110 -0
  76. package/dist/commands/migrate/list.js.map +1 -0
  77. package/dist/commands/migrate/run.d.ts +61 -0
  78. package/dist/commands/migrate/run.js +19 -0
  79. package/dist/commands/migrate/run.js.map +1 -0
  80. package/dist/commands/report.d.ts +27 -0
  81. package/dist/commands/report.js +210 -0
  82. package/dist/commands/report.js.map +1 -0
  83. package/dist/commands/restore.d.ts +26 -0
  84. package/dist/commands/restore.js +268 -0
  85. package/dist/commands/restore.js.map +1 -0
  86. package/dist/commands/snapshot.d.ts +33 -0
  87. package/dist/commands/snapshot.js +251 -0
  88. package/dist/commands/snapshot.js.map +1 -0
  89. package/dist/commands/sync.d.ts +16 -0
  90. package/dist/commands/sync.js +39 -0
  91. package/dist/commands/sync.js.map +1 -0
  92. package/dist/config-CTbeRlJk.d.ts +134 -0
  93. package/dist/help.d.ts +28 -0
  94. package/dist/help.js +64 -0
  95. package/dist/help.js.map +1 -0
  96. package/dist/index.d.ts +493 -0
  97. package/dist/index.js +147 -0
  98. package/dist/index.js.map +1 -0
  99. package/package.json +74 -4
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sql-ast.ts","../src/sql-deps.ts"],"sourcesContent":["/**\n * SQL read by PostgreSQL's own parser, rather than by regular expressions.\n *\n * SupaForge has to understand statements it did not write — DBDiff's fixes, a\n * snapshot's files, migrations — to order them, hold back the destructive\n * ones, and find what they name. Reading that from the text with patterns\n * meant guessing: a role named inside a function body, `TRUNCATE` as a\n * privilege rather than a statement, a quoted name with a dot in it. Each\n * guess that went wrong was a bug, fixed by blanking out more of the text\n * first (sqlSkeleton) and adding another pattern.\n *\n * libpg_query is the parser PostgreSQL itself uses, compiled to WebAssembly.\n * It returns each statement as a tree, so a function body is a string in a\n * field rather than text that might look like DDL, and a name is a list of\n * identifiers rather than something to split on dots.\n *\n * The module is loaded once, when this file is first imported, so every\n * function here is synchronous.\n */\nimport { loadModule, parseSync } from 'libpg-query'\n\nawait loadModule()\n\n/** One parsed statement: its node type, and the node itself. */\nexport interface Statement {\n /** `DropStmt`, `AlterTableStmt`, `CreatePolicyStmt`… */\n kind: string\n // The parser's tree is untyped JSON; accessors below give it shape.\n node: Record<string, any>\n}\n\n/**\n * The statements in `sql`, or undefined when PostgreSQL would not accept it.\n *\n * Undefined rather than an exception: a caller can then fall back to what it\n * did before, which matters while SupaForge is moved over piece by piece.\n */\nexport function parseStatements(sql: string): Statement[] | undefined {\n try {\n const tree = parseSync(sql) as { stmts?: Array<{ stmt: Record<string, any> }> }\n return (tree.stmts ?? []).map(({ stmt }) => {\n const kind = Object.keys(stmt)[0]\n return { kind, node: stmt[kind] }\n })\n } catch {\n return undefined\n }\n}\n\n/** The plain name list of a `List` of `String` nodes, as the parser gives one. */\nexport function names(list: Array<Record<string, any>> | undefined): string[] {\n return (list ?? []).map(item => item.String?.sval ?? '').filter(Boolean)\n}\n\n/** The bare name of a `RangeVar` (a table reference), without its schema. */\nexport function relationName(rangeVar: Record<string, any> | undefined): string {\n return rangeVar?.relname ?? ''\n}\n","import { splitSqlStatements } from './utils/sql-split.js'\nimport { parseStatements, type Statement } from './sql-ast.js'\nimport { escapeRegex } from './utils/strings.js'\n\n/**\n * Dependency analysis for the SQL statements a diff produces.\n *\n * `@dbdiff/cli` emits one statement per difference, in the order it walked the\n * catalogue. That order carries no meaning for execution: a trigger can sort\n * ahead of the function it calls, and applying the set top-to-bottom then fails\n * on a sync that was perfectly valid (issue #48).\n *\n * Everything here works on the SQL text alone, because that is all a fix set\n * is. Two views of a statement are used, and the distinction matters:\n *\n * - the **skeleton** (`sqlSkeleton`), with string and dollar-quoted bodies\n * removed, for deciding *what a statement is*. A function body containing\n * the words `CREATE TABLE` must not make its statement look like a table.\n * - the **full text**, for deciding *what a statement mentions*. A view or\n * function body is exactly where the references to other objects live.\n */\n\n// ─── Execution phases ────────────────────────────────────────────────────────\n\n/**\n * Coarse ordering by object kind, ascending.\n *\n * Postgres requires an object to exist before anything referencing it is\n * created, and requires dependants to be gone before their base object is\n * dropped. Both directions are captured here: dependants are dropped first,\n * base objects are created first, and the destructive drops land at the end.\n *\n * Gaps between the values leave room to slot a kind in later without\n * renumbering the rest.\n */\nexport const PHASE = {\n /** Triggers, policies, views, indexes — dropped before what they depend on. */\n DROP_DEPENDANT: 10,\n /** A schema, before anything is made in it. */\n CREATE_SCHEMA: 15,\n /**\n * An extension, before the types and tables that may use it — an exclusion\n * constraint's btree_gist operator class. Read as OTHER it came after the\n * table, which failed (`no default operator class for access method gist`).\n */\n CREATE_EXTENSION: 20,\n /** Types, domains, sequences: no dependencies of their own. */\n CREATE_BASE: 30,\n CREATE_TABLE: 40,\n /** Columns and constraints, needing every table to exist first. */\n ALTER_TABLE: 50,\n /** Before the triggers that execute them and the views that call them. */\n CREATE_ROUTINE: 60,\n CREATE_INDEX: 70,\n CREATE_VIEW: 80,\n /** Anything unrecognised — grants, comments, ownership. */\n OTHER: 85,\n /** Triggers and policies: the last things to be created. */\n CREATE_DEPENDANT: 90,\n /**\n * Comments, once what they name exists: a policy or trigger is created at\n * CREATE_DEPENDANT, and a COMMENT ON it read as OTHER ran before it.\n */\n COMMENT: 95,\n /** Row changes, once the structure holding them is in place. */\n DATA: 100,\n DROP_TABLE: 110,\n /**\n * Routines, dropped once nothing calls them: the triggers, views and\n * policies come off first, and so do the column defaults, CHECK constraints,\n * expression indexes and tables — all of which can call one, and were still\n * in place when routines were dropped at the start (`cannot drop function\n * ... because other objects depend on it`). Before the types a routine's\n * signature can use.\n */\n DROP_ROUTINE: 115,\n DROP_BASE: 120,\n /** Once nothing that used it is left. */\n DROP_EXTENSION: 125,\n} as const\n\n/** The phases that take something away rather than make it. */\nconst DROP_PHASES: ReadonlySet<number> = new Set([\n PHASE.DROP_DEPENDANT, PHASE.DROP_TABLE, PHASE.DROP_ROUTINE, PHASE.DROP_BASE, PHASE.DROP_EXTENSION,\n])\n\n/**\n * Phase rules, first match wins.\n *\n * Order is deliberate in two places. The `CREATE` rules precede the `DROP`\n * ones so a merged `DROP FUNCTION` + `CREATE OR REPLACE FUNCTION` pair — how\n * `mergeRoutineReplacements` represents a modified routine — is phased by the\n * object it leaves behind rather than by the drop that opens it. And the\n * dependant kinds precede `FUNCTION` and `TABLE` so `CREATE TRIGGER ... EXECUTE\n * FUNCTION f()` is read as a trigger.\n */\nconst PHASE_RULES: Array<[RegExp, number]> = [\n // A column type change grouped with the dependants dbdiff drops and\n // recreates around it (see groupColumnTypeChanges) runs as the column change\n // it is — before a foreign key that needs the new type, for one — not as the\n // view or policy it happens to recreate.\n [/^\\s*DROP\\s+(?:POLICY|TRIGGER|(?:MATERIALIZED\\s+)?VIEW)\\b[\\s\\S]*\\bALTER\\s+TABLE\\s+\\S+\\s+ALTER\\s+COLUMN\\s+\\S+\\s+(?:SET\\s+DATA\\s+)?TYPE\\b/i, PHASE.ALTER_TABLE],\n [/\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\b/i, PHASE.CREATE_DEPENDANT],\n [/\\bCREATE\\s+POLICY\\b/i, PHASE.CREATE_DEPENDANT],\n [/\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:MATERIALIZED\\s+)?VIEW\\b/i, PHASE.CREATE_VIEW],\n [/\\bCREATE\\s+(?:UNIQUE\\s+)?INDEX\\b/i, PHASE.CREATE_INDEX],\n [/\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:FUNCTION|PROCEDURE)\\b/i, PHASE.CREATE_ROUTINE],\n [/^\\s*COMMENT\\s+ON\\b/i, PHASE.COMMENT],\n [/^\\s*CREATE\\s+SCHEMA\\b/i, PHASE.CREATE_SCHEMA],\n [/^\\s*CREATE\\s+EXTENSION\\b/i, PHASE.CREATE_EXTENSION],\n [/^\\s*DROP\\s+EXTENSION\\b/i, PHASE.DROP_EXTENSION],\n [/\\bCREATE\\s+(?:TYPE|DOMAIN|SEQUENCE)\\b/i, PHASE.CREATE_BASE],\n [/\\bCREATE\\s+TABLE\\b/i, PHASE.CREATE_TABLE],\n [/^\\s*ALTER\\s+TABLE\\b/i, PHASE.ALTER_TABLE],\n [/^\\s*DROP\\s+(?:TRIGGER|POLICY|INDEX)\\b/i, PHASE.DROP_DEPENDANT],\n [/^\\s*DROP\\s+(?:MATERIALIZED\\s+)?VIEW\\b/i, PHASE.DROP_DEPENDANT],\n [/^\\s*DROP\\s+(?:FUNCTION|PROCEDURE)\\b/i, PHASE.DROP_ROUTINE],\n [/^\\s*DROP\\s+TABLE\\b/i, PHASE.DROP_TABLE],\n [/^\\s*DROP\\s+(?:TYPE|DOMAIN|SEQUENCE)\\b/i, PHASE.DROP_BASE],\n [/^\\s*(?:INSERT|UPDATE|DELETE)\\b/i, PHASE.DATA],\n]\n\n/** Which execution phase a statement belongs to. */\nexport function statementPhase(sql: string): number {\n const skeleton = sqlSkeleton(sql)\n for (const [pattern, phase] of PHASE_RULES) {\n if (pattern.test(skeleton)) return phase\n }\n return PHASE.OTHER\n}\n\n// ─── Text views ──────────────────────────────────────────────────────────────\n\n/** Dollar-quoted routine bodies: `$$ ... $$`, `$fn$ ... $fn$`. */\nconst DOLLAR_BODY = /\\$([A-Za-z0-9_]*)\\$[\\s\\S]*?\\$\\1\\$/g\n\n/**\n * Single-quoted literals, doubled quotes included.\n *\n * Written as the unrolled `'[^']*(?:''[^']*)*'` rather than the equivalent\n * `'(?:[^']|'')*'`: only one alternative can match at any position either way,\n * but the unrolled form has no alternation to backtrack through at all, which\n * matters for a pattern run over SQL from an external process.\n */\nconst STRING_LITERAL = /'[^']*(?:''[^']*)*'/g\n\n/** `-- to end of line`, and `/* ... *\\/` across lines. */\nconst LINE_COMMENT = /--[^\\n]*/g\nconst BLOCK_COMMENT = /\\/\\*[\\s\\S]*?\\*\\//g\n\n/**\n * A statement with its literals and routine bodies blanked out.\n *\n * Used wherever the *shape* of a statement is being read rather than its\n * contents, so a body that happens to contain DDL keywords cannot be mistaken\n * for the statement's own kind.\n */\nexport function sqlSkeleton(sql: string): string {\n return sql\n .replace(DOLLAR_BODY, ' ')\n .replace(STRING_LITERAL, \" '' \")\n // Comments last, so a `--` inside a literal has already been blanked and\n // cannot swallow the rest of the line. dbdiff's own migrations are full of\n // `-- Recreate trigger` lines, and a commented-out CREATE would otherwise\n // read as a real one: enough to make the duplicate-fix check believe an\n // object exists and drop the statement that genuinely creates it.\n .replace(LINE_COMMENT, ' ')\n .replace(BLOCK_COMMENT, ' ')\n}\n\n// ─── Identifiers ─────────────────────────────────────────────────────────────\n\n/** One name, quoted (its own quotes doubled) or not. */\nconst NAME_PART = String.raw`\"(?:[^\"]|\"\")+\"|[\\w$]+`\n\n/** An optionally schema-qualified, optionally quoted identifier. */\nconst IDENT = String.raw`(?:${NAME_PART})(?:\\s*\\.\\s*(?:${NAME_PART}))?`\n\n/** Strip quoting and any schema qualifier, leaving a comparable bare name. */\nexport function bareName(identifier: string): string {\n const parts = identifier.match(new RegExp(NAME_PART, 'g')) ?? [identifier]\n return unquote(parts[parts.length - 1]).toLowerCase()\n}\n/** A quoted identifier as the name it is, its doubled quotes made single. */\nconst unquote = (part: string) => {\n const p = part.trim()\n return p.startsWith('\"') ? p.slice(1, -1).replace(/\"\"/g, '\"') : p\n}\n\n/** `schema.table.object`, lowercased, `public` where no schema is named: how policies are keyed. */\nconst objectKey = (schema: string | undefined, table: string | undefined, name: string | undefined) =>\n `${(schema || 'public').toLowerCase()}.${(table ?? '').toLowerCase()}.${(name ?? '').toLowerCase()}`\n\n/**\n * A relation's name with its schema, `public` where it names none:\n * `\"app\".\"accounts\"` → `app.accounts`, `users` → `public.users`. Folded the\n * way bareName folds, so the same relation written either way agrees.\n */\nexport function schemaQualified(identifier: string): string {\n const parts = identifier.match(new RegExp(NAME_PART, 'g')) ?? [identifier]\n const fold = (part: string) => unquote(part).toLowerCase()\n return `${parts.length > 1 ? fold(parts[0]) : 'public'}.${fold(parts[parts.length - 1])}`\n}\n\n/** `CREATE [OR REPLACE] [UNIQUE|MATERIALIZED|TEMP] <kind> [IF NOT EXISTS] <name>` */\nconst CREATES = new RegExp(\n String.raw`\\bCREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:UNIQUE\\s+|MATERIALIZED\\s+|TEMP(?:ORARY)?\\s+|CONSTRAINT\\s+){0,2}` +\n String.raw`(?:TABLE|VIEW|FUNCTION|PROCEDURE|TYPE|DOMAIN|SEQUENCE|INDEX|TRIGGER|POLICY)\\s+` +\n String.raw`(?:IF\\s+NOT\\s+EXISTS\\s+)?(${IDENT})`,\n 'gi',\n)\n\n/**\n * The bare names of every object a statement creates.\n *\n * Read off the skeleton so a routine body that creates something locally does\n * not advertise it to the rest of the batch. A merged DROP + CREATE pair\n * reports the name it recreates, which is what other statements need.\n */\nexport function providedNames(sql: string): string[] {\n const names = new Set<string>()\n for (const match of sqlSkeleton(sql).matchAll(CREATES)) {\n names.add(bareName(match[1]))\n }\n return [...names]\n}\n\n/**\n * A statement that only removes things.\n *\n * These take no \"must run after a CREATE\" edges: `DROP TABLE orders` mentions\n * `orders` but has to run *after* everything using it, not after its creation —\n * an ordering the phases already express. Recognised by creating nothing rather\n * than by the leading keyword alone, so a merged DROP + CREATE pair is\n * correctly excluded.\n */\nfunction isDropOnly(sql: string, provides: string[]): boolean {\n return provides.length === 0 && /^\\s*DROP\\b/i.test(sql)\n}\n\n// ─── Table references ────────────────────────────────────────────────────────\n\n/** `FROM`/`JOIN`/`INTO`/`UPDATE`/`REFERENCES` each introduce a table name. */\nconst BODY_TABLE_REF = new RegExp(String.raw`\\b(?:FROM|JOIN|INTO|UPDATE|REFERENCES)\\s+(?:ONLY\\s+)?(${IDENT})`, 'gi')\n\n/**\n * The `ON <table>` of an index, trigger or policy.\n *\n * Anchored on what follows the name so a join condition (`ON a.id = b.id`) is\n * not read as a table reference — the trailing keyword or punctuation is what\n * separates the two forms.\n */\nconst ON_TABLE_REF = new RegExp(String.raw`\\bON\\s+(?:ONLY\\s+)?(${IDENT})\\s*(?:USING\\b|FOR\\b|AS\\b|TO\\b|\\(|;|$)`, 'gi')\n\n/** The table an `ALTER`/`DROP TABLE` acts on. */\nconst TARGET_TABLE_REF = new RegExp(\n String.raw`^\\s*(?:ALTER|DROP)\\s+TABLE\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${IDENT})`,\n 'gi',\n)\n\n/**\n * Keywords that can follow a reference keyword without naming a table.\n *\n * `UPDATE ON public.orders` in a trigger definition is the one that matters:\n * without this, the word `ON` would be collected as a table called \"on\".\n */\nconst NOT_A_TABLE = new Set([\n 'on', 'of', 'from', 'join', 'into', 'select', 'lateral', 'only', 'conflict',\n 'delete', 'update', 'insert', 'constraint', 'each', 'row', 'statement', 'values',\n])\n\n/**\n * The tables a statement reads, writes or hangs off, as bare lowercase names.\n *\n * Deliberately over-inclusive: it reads the full text, bodies included, so a\n * view or function that touches an out-of-scope table is caught. A false\n * positive costs a fix that is skipped with a reason the user can read, which\n * is the safer direction — a false negative is a statement that runs and fails\n * (issue #48).\n */\n/**\n * The policies a statement creates, as `table.policy` in lower case.\n *\n * Two layers can now legitimately produce the same `CREATE POLICY`. The schema\n * check gets its SQL from `@dbdiff/cli`, which models RLS policies as of\n * 3.0.0-rc.10, and the rls check has always written its own. Applied together\n * the second fails with \"policy ... already exists\" and takes the whole\n * transaction with it, so the duplicate has to be recognised before it runs.\n *\n * Matched on the pair that identifies a policy in Postgres — its name and its\n * table — because the two layers spell the same policy differently: one emits\n * `ON \"t\"`, the other `ON \"public\".\"t\"` across several lines. The schema\n * qualifier is dropped for the same reason `referencedTables` drops it.\n */\nexport function createdPolicies(sql: string): string[] {\n const tree = parseStatements(sql)\n if (tree) {\n return tree.filter(s => s.kind === 'CreatePolicyStmt')\n .map(({ node }) => objectKey(node.table?.schemaname, node.table?.relname, node.policy_name))\n }\n const out: string[] = []\n const re = new RegExp(String.raw`CREATE\\s+POLICY\\s+(${NAME_PART})\\s+ON\\s+(${IDENT})`, 'gi')\n for (const m of sqlSkeleton(sql).matchAll(re)) {\n out.push(`${schemaQualified(m[2])}.${bareName(m[1])}`)\n }\n return out\n}\n\n/**\n * True when creating policies is all this statement does.\n *\n * The schema check bundles its policy alongside the table and the ENABLE ROW\n * LEVEL SECURITY that makes it mean anything, so that statement must never be\n * dropped as a duplicate — only a statement whose sole purpose is the policy can\n * be. Anything left once the CREATE POLICY statements are removed counts, which\n * errs towards keeping a statement rather than losing DDL.\n */\n/**\n * The policies a statement drops, keyed as `createdPolicies` keys them.\n *\n * Needed to tell a policy being *removed* from one being *replaced*: the RLS\n * check renders a modified policy as `DROP POLICY` + `CREATE POLICY` for the\n * same name, and that is not a loss of access control (issue #88).\n */\nexport function droppedPolicies(sql: string): string[] {\n const tree = parseStatements(sql)\n if (tree) {\n return tree.filter(s => s.kind === 'DropStmt' && s.node.removeType === 'OBJECT_POLICY')\n .flatMap(({ node }) => (node.objects as Array<Record<string, any>>)\n .map(o => (o.List?.items ?? []).map((i: Record<string, any>) => i.String?.sval as string))\n .map((parts: string[]) => objectKey(parts.at(-3), parts.at(-2), parts.at(-1))))\n }\n const out: string[] = []\n const re = new RegExp(String.raw`DROP\\s+POLICY\\s+(?:IF\\s+EXISTS\\s+)?(${NAME_PART})\\s+ON\\s+(${IDENT})`, 'gi')\n for (const m of sqlSkeleton(sql).matchAll(re)) {\n out.push(`${schemaQualified(m[2])}.${bareName(m[1])}`)\n }\n return out\n}\n\n/**\n * Policies this statement drops without putting back.\n *\n * Dropping a policy is not recoverable from the schema the way dropping a view\n * or a function is, and a dropped RESTRICTIVE policy *grants* access rather\n * than removing it — so it belongs behind the same gate as losing rows.\n */\nexport function policiesRemoved(sql: string): string[] {\n const recreated = new Set(createdPolicies(sql))\n return droppedPolicies(sql).filter(key => !recreated.has(key))\n}\n\nexport function createsOnlyPolicies(sql: string): boolean {\n if (createdPolicies(sql).length === 0) return false\n const withoutPolicies = sqlSkeleton(sql)\n .replace(/CREATE\\s+POLICY[\\s\\S]*?(?=;|$)/gi, '')\n .replace(/DROP\\s+POLICY[\\s\\S]*?(?=;|$)/gi, '')\n return !/[A-Za-z]/.test(withoutPolicies)\n}\n\n/**\n * The triggers a statement creates, keyed the way Postgres identifies one.\n *\n * Same collision as policies, one layer along. The schema check's SQL creates\n * webhook triggers — they are ordinary triggers as far as dbdiff is concerned —\n * and since issue #77 the webhooks check emits the server's own\n * `pg_get_triggerdef()` for the same trigger. Applied together the second fails\n * with `trigger \"x\" for relation \"y\" already exists`, and the transactional\n * apply discards every other fix with it: the reported symptom was a full\n * `diff --apply` rolling back six correct schema fixes.\n *\n * A trigger name is unique per table, not per schema, so the table belongs in\n * the key — which is also why the webhooks check now keys its own entries that\n * way. The schema qualifier is dropped for the same reason `referencedTables`\n * drops it: the two layers spell the same table differently.\n */\nexport function createdTriggers(sql: string): string[] {\n const tree = parseStatements(sql)\n if (tree) {\n return tree.filter(s => s.kind === 'CreateTrigStmt')\n .map(({ node }) => `${(node.relation?.relname ?? '').toLowerCase()}.${String(node.trigname).toLowerCase()}`)\n }\n const out: string[] = []\n const re = new RegExp(String.raw`CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER\\s+(${NAME_PART})[\\s\\S]*?\\sON\\s+(${IDENT})`, 'gi')\n for (const m of sqlSkeleton(sql).matchAll(re)) {\n out.push(`${bareName(m[2])}.${bareName(m[1])}`)\n }\n return out\n}\n\n/**\n * True when creating triggers is all this statement does.\n *\n * The same guard as `createsOnlyPolicies`: the schema check bundles a trigger\n * with the table and function it needs, and dropping that as a duplicate would\n * lose the DDL around it. A leading DROP TRIGGER is expected — the webhooks\n * check emits one before recreating a modified webhook — so it does not count\n * as doing something else.\n */\nexport function createsOnlyTriggers(sql: string): boolean {\n if (createdTriggers(sql).length === 0) return false\n const withoutTriggers = sqlSkeleton(sql)\n .replace(/CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?TRIGGER[\\s\\S]*?(?=;|$)/gi, '')\n .replace(/DROP\\s+TRIGGER[\\s\\S]*?(?=;|$)/gi, '')\n return !/[A-Za-z]/.test(withoutTriggers)\n}\n\nexport function referencedTables(sql: string): string[] {\n const names = new Set<string>()\n for (const pattern of [BODY_TABLE_REF, ON_TABLE_REF, TARGET_TABLE_REF]) {\n for (const match of sql.matchAll(pattern)) {\n const name = bareName(match[1])\n if (!NOT_A_TABLE.has(name)) names.add(name)\n }\n }\n return [...names]\n}\n\n// ─── Ordering ────────────────────────────────────────────────────────────────\n\n/** One statement, with everything the sort needs precomputed. */\ninterface Node {\n /** The fix's position in the order its producer wrote it, when that order is to be kept. */\n rank?: number\n phase: number\n /** Indices that must execute before this one. */\n after: Set<number>\n}\n\n/**\n * Match `name` used as a whole identifier, quoted or not, schema-qualified or\n * not. Built once per name rather than per comparison — a large fix set is\n * thousands of pairings.\n */\n/** Matches `name` as a whole identifier, quoted or not. */\nexport function identifierMatcher(name: string): RegExp {\n return new RegExp(String.raw`(?<![\\w$])\"?${escapeRegex(name)}\"?(?![\\w$])`, 'i')\n}\n\n/**\n * Build the \"must run after\" edges between statements.\n *\n * One rule covers every object kind: if a statement creates something named\n * `n`, any other statement mentioning `n` is assumed to need it. That catches\n * the reported trigger-before-function case, and equally a view over a new\n * table, an index on one, or a column default that calls a new function.\n */\nfunction linkDependencies(nodes: Node[], texts: string[], provides: string[][]): void {\n const droppers = texts.map((sql, i) => isDropOnly(sql, provides[i]))\n // What a statement *uses* is what it mentions outside its DROPs. A column\n // type change grouped with the dependants it drops and recreates mentions\n // the policy it drops, and was made to wait for the fix that creates that\n // policy — which then ran first, against the column's old type.\n const uses = texts.map(withoutDropStatements)\n\n for (let provider = 0; provider < nodes.length; provider++) {\n for (const name of provides[provider]) {\n const matcher = identifierMatcher(name)\n for (let consumer = 0; consumer < nodes.length; consumer++) {\n if (consumer === provider || droppers[consumer]) continue\n // A statement that creates `name` itself does not need another's:\n // two column changes under one view each recreate it, and linking\n // them both ways made a cycle, which the fallback resolves by\n // report order rather than by phase.\n if (provides[consumer].includes(name)) continue\n if (matcher.test(uses[consumer])) nodes[consumer].after.add(provider)\n }\n }\n }\n}\n\n/** A statement batch with its DROP statements taken out. */\nfunction withoutDropStatements(sql: string): string {\n if (!/\\bDROP\\b/i.test(sql)) return sql\n return splitSqlStatements(sql).filter(s => !/^\\s*DROP\\b/i.test(sqlSkeleton(s))).join('\\n')\n}\n\n/**\n * Pick the next statement to run: the one whose dependencies are all satisfied,\n * earliest by phase, then by the order the diff reported it.\n *\n * Falls back to the lowest remaining index when nothing is ready, which happens\n * only if the edges form a cycle — mutually referencing tables, or a name that\n * reads like two different objects. Emitting those in their original order is\n * no worse than the behaviour this replaces.\n */\nfunction nextReady(remaining: number[], nodes: Node[], done: Set<number>): number {\n const ready = remaining.filter(i => isSatisfied(nodes[i].after, done))\n const first = (from: number[], key: (n: Node) => number) =>\n from.reduce<number | undefined>((best, i) => best === undefined || key(nodes[i]) < key(nodes[best]) ? i : best, undefined)\n\n const head = first(ready.filter(i => nodes[i].rank !== undefined), n => n.rank as number)\n const free = first(ready.filter(i => nodes[i].rank === undefined), n => n.phase)\n if (head === undefined || free === undefined) return head ?? free ?? remaining[0]\n\n // DBDiff's fixes are one sequence, in DBDiff's order. Another check's fix\n // goes ahead of it only when it belongs before everything the sequence\n // still has to do — the earliest phase left in it, not the phase of the\n // fix at its head. Compared with the head alone, an RLS policy jumped ahead\n // of a column change it needed whenever a late-phase fix happened to come\n // first: \"operator does not exist: text = uuid\".\n //\n // What it has left to make, that is: a drop provides nothing another fix\n // could need. Counted, a DROP INDEX DBDiff sequences after its tables held\n // CREATE EXTENSION back until after the table whose exclusion constraint\n // needs it.\n const sequence = Math.min(...remaining\n .filter(i => nodes[i].rank !== undefined && !DROP_PHASES.has(nodes[i].phase))\n .map(i => nodes[i].phase))\n return nodes[free].phase < sequence ? free : head\n}\n/** Have all of `after` already run? Iterated rather than spread — this is the\n * inner loop of the sort, and a large fix set runs it thousands of times. */\nfunction isSatisfied(after: Set<number>, done: Set<number>): boolean {\n for (const dep of after) {\n if (!done.has(dep)) return false\n }\n return true\n}\n\n/**\n * Sort a fix set into an order Postgres can execute in a single pass.\n *\n * Stable within a phase: statements that neither depend on one another nor\n * differ in kind come out in the order the diff reported them, so the plan\n * stays recognisable against `--detail`.\n */\nexport function orderStatements<T>(\n items: T[],\n sqlOf: (item: T) => string,\n rankOf: (item: T) => number | undefined = () => undefined,\n): T[] {\n if (items.length < 2) return [...items]\n\n const texts = items.map(sqlOf)\n const provides = texts.map(providedNames)\n const nodes: Node[] = texts.map((sql, i) => ({ phase: statementPhase(sql), rank: rankOf(items[i]), after: new Set<number>() }))\n\n linkDependencies(nodes, texts, provides)\n\n const done = new Set<number>()\n let remaining = texts.map((_, i) => i)\n const ordered: T[] = []\n\n while (remaining.length > 0) {\n const next = nextReady(remaining, nodes, done)\n ordered.push(items[next])\n done.add(next)\n remaining = remaining.filter(i => i !== next)\n }\n\n return ordered\n}\n\n// ─── Statement subject ───────────────────────────────────────────────────────\n\n/** A schema-qualified object name, unquoted. `schema` is null when unqualified. */\nexport interface QualifiedName {\n schema: string | null\n name: string\n}\n\nfunction splitQualified(identifier: string): QualifiedName {\n const parts = identifier.match(/\"[^\"]+\"|[\\w$]+/g) ?? []\n const clean = parts.map(p => p.replace(/^\"|\"$/g, ''))\n if (clean.length >= 2) return { schema: clean[clean.length - 2], name: clean[clean.length - 1] }\n return { schema: null, name: clean[0] ?? '' }\n}\n\n/** A possibly three-part name (`schema.table.column`), as COMMENT ON COLUMN takes. */\nconst IDENT3 = String.raw`(?:\"[^\"]+\"|[\\w$]+)(?:\\s*\\.\\s*(?:\"[^\"]+\"|[\\w$]+)){0,2}`\n\nconst OBJECT_KIND = String.raw`(?:TABLE|VIEW|MATERIALIZED\\s+VIEW|FOREIGN\\s+TABLE|FUNCTION|PROCEDURE|ROUTINE|AGGREGATE|SEQUENCE|TYPE|DOMAIN|INDEX|SCHEMA)`\n\n/**\n * Subject patterns, most specific first, each with what its capture names:\n * an object, a schema, or a `schema.table.column`. For a trigger, policy,\n * rule or index the object is the table it belongs to rather than its own\n * name, since that is what owns it.\n */\nconst SUBJECT_RULES: Array<[RegExp, 'object' | 'schema' | 'column']> = [\n // CREATE/DROP/ALTER TRIGGER|POLICY name ... ON <table>\n [new RegExp(String.raw`^\\s*(?:CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:CONSTRAINT\\s+)?|DROP\\s+|ALTER\\s+)(?:TRIGGER|POLICY)\\s+(?:IF\\s+EXISTS\\s+)?(?:\"[^\"]+\"|[\\w$]+)[\\s\\S]*?\\bON\\s+(?:ONLY\\s+)?(${IDENT})`, 'i'), 'object'],\n // CREATE RULE name AS ON <event> TO <table>\n [new RegExp(String.raw`^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?RULE\\s+(?:\"[^\"]+\"|[\\w$]+)\\s+AS\\s+ON\\s+\\w+\\s+TO\\s+(${IDENT})`, 'i'), 'object'],\n // CREATE [UNIQUE] INDEX [CONCURRENTLY] [IF NOT EXISTS] [name] ON [ONLY] <table>\n [new RegExp(String.raw`^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX\\b[\\s\\S]*?\\bON\\s+(?:ONLY\\s+)?(${IDENT})`, 'i'), 'object'],\n // COMMENT ON TRIGGER|POLICY|RULE|CONSTRAINT name ON <table>\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+(?:TRIGGER|POLICY|RULE|CONSTRAINT)\\s+(?:\"[^\"]+\"|[\\w$]+)\\s+ON\\s+(?:DOMAIN\\s+)?(${IDENT})`, 'i'), 'object'],\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+COLUMN\\s+(${IDENT3})`, 'i'), 'column'],\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n [new RegExp(String.raw`^\\s*COMMENT\\s+ON\\s+${OBJECT_KIND}\\s+(${IDENT})`, 'i'), 'object'],\n // GRANT/REVOKE ... ON SCHEMA <schema> | ON ALL <kind> IN SCHEMA <schema> | ON [kind] <name>\n [new RegExp(String.raw`^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n [new RegExp(String.raw`^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+ALL\\s+\\w+\\s+IN\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n [new RegExp(String.raw`^\\s*(?:GRANT|REVOKE)\\b[\\s\\S]*?\\bON\\s+(?:${OBJECT_KIND}\\s+)?(${IDENT})`, 'i'), 'object'],\n // ALTER DEFAULT PRIVILEGES ... IN SCHEMA <schema>\n [new RegExp(String.raw`^\\s*ALTER\\s+DEFAULT\\s+PRIVILEGES\\b[\\s\\S]*?\\bIN\\s+SCHEMA\\s+((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n // CREATE|ALTER|DROP SCHEMA <schema>\n [new RegExp(String.raw`^\\s*(?:CREATE|ALTER|DROP)\\s+SCHEMA\\s+(?:IF\\s+(?:NOT\\s+)?EXISTS\\s+)?((?:\"[^\"]+\"|[\\w$]+))`, 'i'), 'schema'],\n // CREATE [OR REPLACE] [modifiers] <kind> [IF NOT EXISTS] <name>\n [new RegExp(String.raw`^\\s*CREATE\\s+(?:OR\\s+REPLACE\\s+)?(?:(?:TEMP|TEMPORARY|UNLOGGED|RECURSIVE)\\s+)*${OBJECT_KIND}\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(${IDENT})`, 'i'), 'object'],\n // ALTER|DROP <kind> [IF EXISTS] [ONLY] <name>\n [new RegExp(String.raw`^\\s*(?:ALTER|DROP)\\s+${OBJECT_KIND}\\s+(?:IF\\s+EXISTS\\s+)?(?:ONLY\\s+)?(${IDENT})`, 'i'), 'object'],\n]\n\n/**\n * The object a statement acts on — its *subject*, not every name it mentions.\n *\n * `CREATE TRIGGER t ... ON public.orders EXECUTE FUNCTION\n * supabase_functions.http_request(...)` acts on `public.orders`: it mentions a\n * platform schema, but what it creates belongs to the project. Deciding\n * ownership by mention skipped every Database Webhook on restore, and every\n * view reading `cron` or `vault`. The subject is what decides who owns a\n * statement's result.\n *\n * For `COMMENT ON COLUMN s.t.c` the subject is the table `s.t`; for a\n * schema-level statement (`CREATE SCHEMA x`, `GRANT ... ON SCHEMA x`,\n * `... IN SCHEMA x`) it is `{ schema: x, name: x }`. Undefined when the\n * statement's shape is not one of these.\n */\nexport function statementSubject(sql: string): QualifiedName | undefined {\n const skeleton = sqlSkeleton(sql)\n\n for (const [rule, captures] of SUBJECT_RULES) {\n const match = rule.exec(skeleton)\n if (!match) continue\n\n const parts = (match[1].match(/\"[^\"]+\"|[\\w$]+/g) ?? []).map(p => p.replace(/^\"|\"$/g, ''))\n if (captures === 'schema') return { schema: parts[0], name: parts[0] }\n if (captures === 'column') {\n return parts.length >= 3\n ? { schema: parts[parts.length - 3], name: parts[parts.length - 2] }\n : { schema: null, name: parts[0] ?? '' }\n }\n return splitQualified(match[1])\n }\n\n return undefined\n}\n\n/**\n * The policies (`schema.table.policy`) a fix consists of, when it is nothing but\n * CREATE and DROP POLICY statements; otherwise null.\n */\nexport function policyOnlyKeys(sql: string | undefined): string[] | null {\n if (!sql) return null\n const statements = splitSqlStatements(sql).filter(s => sqlSkeleton(s).trim() !== '')\n if (statements.length === 0) return null\n if (!statements.every(s => /^\\s*(?:CREATE|DROP)\\s+POLICY\\b/i.test(sqlSkeleton(s)))) return null\n return [...new Set([...createdPolicies(sql), ...droppedPolicies(sql)])]\n}\n\n/** The roles one parsed statement grants to or scopes a policy to. */\nfunction rolesOf({ kind, node }: Statement): string[] {\n const specs: Array<Record<string, any>> =\n (kind === 'GrantStmt' && node.is_grant) ? node.grantees ?? []\n : (kind === 'GrantRoleStmt' && node.is_grant) ? node.grantee_roles ?? []\n : (kind === 'CreatePolicyStmt' || kind === 'AlterPolicyStmt') ? node.roles ?? []\n : []\n return specs\n .map(spec => spec.RoleSpec)\n // PUBLIC, CURRENT_USER and the like are not role names.\n .filter(role => role?.roletype === 'ROLESPEC_CSTRING' && typeof role.rolename === 'string')\n .map(role => role.rolename as string)\n .filter(name => !name.startsWith('pg_'))\n}\n\n/** Role specifications that are keywords rather than roles, so never created. */\nconst ROLE_KEYWORDS = new Set(['public', 'current_user', 'current_role', 'session_user'])\n\n/**\n * Every role a statement grants to or scopes a policy to.\n *\n * A restore creates them first where the target lacks them, and `--prove`\n * declines to run when the server lacks them, since creating a role is never\n * confined to a throwaway database.\n *\n * A snapshot's `roles.sql` grants to Supabase's Data API roles — `anon`,\n * `authenticated`, `service_role` — and the usual restore target is plain\n * PostgreSQL, where none of them exist. A policy names roles too, and the\n * schema dump and the RLS layer both replay policies long before the roles\n * layer's grants: `CREATE POLICY … TO service_role` into plain PostgreSQL\n * failed with `role \"service_role\" does not exist` and, in one transaction,\n * rolled the whole restore back. Every role in the list is returned, not just\n * the first, since a policy for `authenticated, service_role` needs both.\n *\n * Read off the skeleton, so a role named inside a function body or a string\n * literal is not mistaken for one. `PUBLIC` and `CURRENT_USER` are keywords,\n * not roles, and a `pg_` role is built in: none of them can be created.\n * `ALTER POLICY … RENAME TO` names a policy, not a role.\n */\nexport function rolesNamedBy(sql: string): string[] {\n // Read from the parse tree: the regex below took TO inside a quoted policy\n // name for the role list — \"Allow users to read items\" named the roles\n // read, items, on and for, and a restore went looking for them — and read\n // only the first statement of a fix.\n const statements = parseStatements(sql)\n if (statements) return [...new Set(statements.flatMap(rolesOf))]\n\n const skeleton = sqlSkeleton(sql)\n const list =\n /^\\s*GRANT\\b[\\s\\S]*?\\bTO\\s+([\\s\\S]*?)(?=\\s+WITH\\b|\\s+GRANTED\\s+BY\\b|\\s*;|\\s*$)/i.exec(skeleton)\n ?? /^\\s*(?:CREATE|ALTER)\\s+POLICY\\b(?![\\s\\S]*\\bRENAME\\s+TO\\b)[\\s\\S]*?\\bTO\\s+([\\s\\S]*?)(?=\\s+USING\\b|\\s+WITH\\s+CHECK\\b|\\s*;|\\s*$)/i.exec(skeleton)\n if (!list) return []\n\n const roles = (list[1].match(/\"(?:[^\"]|\"\")+\"|[\\w$]+/g) ?? [])\n // Unquoted, PostgreSQL folds the name to lower case.\n .map(r => r.startsWith('\"') ? r.slice(1, -1).replace(/\"\"/g, '\"') : r.toLowerCase())\n .filter(r => !ROLE_KEYWORDS.has(r.toLowerCase()) && !r.startsWith('pg_'))\n return [...new Set(roles)]\n}\n"],"mappings":";;;;;;;;AAmBA,SAAS,YAAY,iBAAiB;AAEtC,MAAM,WAAW;AAgBV,SAAS,gBAAgB,KAAsC;AACpE,MAAI;AACF,UAAM,OAAO,UAAU,GAAG;AAC1B,YAAQ,KAAK,SAAS,CAAC,GAAG,IAAI,CAAC,EAAE,KAAK,MAAM;AAC1C,YAAM,OAAO,OAAO,KAAK,IAAI,EAAE,CAAC;AAChC,aAAO,EAAE,MAAM,MAAM,KAAK,IAAI,EAAE;AAAA,IAClC,CAAC;AAAA,EACH,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,MAAM,MAAwD;AAC5E,UAAQ,QAAQ,CAAC,GAAG,IAAI,UAAQ,KAAK,QAAQ,QAAQ,EAAE,EAAE,OAAO,OAAO;AACzE;AAGO,SAAS,aAAa,UAAmD;AAC9E,SAAO,UAAU,WAAW;AAC9B;;;ACtBO,IAAM,QAAQ;AAAA;AAAA,EAEnB,gBAAgB;AAAA;AAAA,EAEhB,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMf,kBAAkB;AAAA;AAAA,EAElB,aAAa;AAAA,EACb,cAAc;AAAA;AAAA,EAEd,aAAa;AAAA;AAAA,EAEb,gBAAgB;AAAA,EAChB,cAAc;AAAA,EACd,aAAa;AAAA;AAAA,EAEb,OAAO;AAAA;AAAA,EAEP,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlB,SAAS;AAAA;AAAA,EAET,MAAM;AAAA,EACN,YAAY;AAAA;AAAA;AAAA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,
20
+ ok,
21
+ validateConfig,
22
+ validateSingleEnvConfig,
23
+ warn
24
+ } from "./chunk-6WAMNZLO.js";
25
+
26
+ // src/base-command.ts
27
+ import { formatWithOptions } from "util";
28
+ import { Command } from "@oclif/core";
29
+
30
+ // src/preflight.ts
31
+ import pg2 from "pg";
32
+
33
+ // src/local-pg.ts
34
+ import { execFile } from "child_process";
35
+ import { promisify } from "util";
36
+ import pg from "pg";
37
+ var defaultExecFile = promisify(execFile);
38
+ var PG_IMAGE = "docker.io/library/postgres:17";
39
+ var DEFAULT_LOCAL_PORT = 5432;
40
+ var CONTAINER_NAME = "supaforge-local-pg";
41
+ var LOCAL_PG_USER = "postgres";
42
+ var LOCAL_PG_PASSWORD = "postgres";
43
+ var READINESS_RETRIES = 30;
44
+ var READINESS_INTERVAL_MS = 2e3;
45
+ async function defaultConnectFn(url) {
46
+ const client = new pg.Client(pgClientConfig(url));
47
+ await client.connect();
48
+ await client.end();
49
+ }
50
+ async function detectRuntime(execFn = defaultExecFile) {
51
+ for (const rt of ["podman", "docker"]) {
52
+ try {
53
+ await execFn(rt, ["--version"], { timeout: RUNTIME_DETECT_TIMEOUT_MS });
54
+ return rt;
55
+ } catch {
56
+ continue;
57
+ }
58
+ }
59
+ return null;
60
+ }
61
+ async function startLocalPg(options = {}) {
62
+ const exec = options.execFn ?? defaultExecFile;
63
+ const connect = options.connectFn ?? defaultConnectFn;
64
+ const runtime = options.runtime ?? await detectRuntime(exec);
65
+ if (!runtime) {
66
+ throw new Error(
67
+ "No container runtime found. Install Podman (recommended) or Docker.\n Podman: https://podman.io/docs/installation\n Docker: https://docs.docker.com/engine/install/"
68
+ );
69
+ }
70
+ const port = options.port ?? DEFAULT_LOCAL_PORT;
71
+ const password = options.password ?? LOCAL_PG_PASSWORD;
72
+ const name = options.name ?? CONTAINER_NAME;
73
+ const image = options.image ?? PG_IMAGE;
74
+ const existing = await getContainerStatus(runtime, name, exec);
75
+ if (existing === "running") {
76
+ return {
77
+ runtime,
78
+ containerName: name,
79
+ port,
80
+ url: buildLocalUrl(port, password)
81
+ };
82
+ }
83
+ if (existing === "stopped") {
84
+ await exec(runtime, ["rm", "-f", name], { timeout: CONTAINER_RM_TIMEOUT_MS });
85
+ }
86
+ const args = [
87
+ "run",
88
+ "-d",
89
+ "--name",
90
+ name,
91
+ "-p",
92
+ `${port}:5432`,
93
+ "-e",
94
+ `POSTGRES_PASSWORD=${password}`,
95
+ "-e",
96
+ `POSTGRES_USER=${LOCAL_PG_USER}`,
97
+ "--tmpfs",
98
+ "/var/lib/postgresql/data",
99
+ "--health-cmd",
100
+ `pg_isready -U ${LOCAL_PG_USER}`,
101
+ "--health-interval",
102
+ "5s",
103
+ "--health-timeout",
104
+ "5s",
105
+ "--health-retries",
106
+ "20",
107
+ "--health-start-period",
108
+ "10s",
109
+ image
110
+ ];
111
+ try {
112
+ await exec(runtime, args, { timeout: CONTAINER_START_TIMEOUT_MS });
113
+ } catch (err) {
114
+ throw new Error(
115
+ `Failed to start PostgreSQL container via ${runtime}: ${err.message}`
116
+ );
117
+ }
118
+ const url = buildLocalUrl(port, password);
119
+ await waitForPg(url, connect);
120
+ return { runtime, containerName: name, port, url };
121
+ }
122
+ async function getContainerStatus(runtime, name, execFn) {
123
+ try {
124
+ const { stdout } = await execFn(
125
+ runtime,
126
+ ["inspect", "--format", "{{.State.Running}}", name],
127
+ { timeout: RUNTIME_DETECT_TIMEOUT_MS }
128
+ );
129
+ return stdout.trim() === "true" ? "running" : "stopped";
130
+ } catch {
131
+ return "none";
132
+ }
133
+ }
134
+ function buildLocalUrl(port, password) {
135
+ return `postgres://${LOCAL_PG_USER}:${password}@localhost:${port}/postgres`;
136
+ }
137
+ async function waitForPg(url, connectFn) {
138
+ for (let i = 0; i < READINESS_RETRIES; i++) {
139
+ try {
140
+ await connectFn(url);
141
+ return;
142
+ } catch {
143
+ await sleep(READINESS_INTERVAL_MS);
144
+ }
145
+ }
146
+ throw new Error(
147
+ `PostgreSQL at ${url} did not become ready within ${READINESS_RETRIES * READINESS_INTERVAL_MS / 1e3}s`
148
+ );
149
+ }
150
+ function sleep(ms) {
151
+ return new Promise((resolve) => setTimeout(resolve, ms));
152
+ }
153
+
154
+ // src/preflight.ts
155
+ var SUPABASE_LOCAL_PORT = "54322";
156
+ var DEFAULT_PG_PORT = "5432";
157
+ var CONNECT_TIMEOUT_RE = /timeout expired|connection timeout/i;
158
+ var QUERY_TIMEOUT_RE = /query read timeout/i;
159
+ function describeTimeout(message, connectTimeoutMs, probeTimeoutMs) {
160
+ if (CONNECT_TIMEOUT_RE.test(message)) {
161
+ return `timed out after ${Math.round(connectTimeoutMs / 1e3)}s connecting \u2014 the host accepted the connection but never completed the handshake`;
162
+ }
163
+ if (QUERY_TIMEOUT_RE.test(message)) {
164
+ return `timed out after ${Math.round(probeTimeoutMs / 1e3)}s waiting for server response \u2014 connected, but the server did not answer`;
165
+ }
166
+ return message;
167
+ }
168
+ async function checkConnection(dbUrl) {
169
+ const connectTimeoutMs = resolveConnectTimeoutMs();
170
+ let client;
171
+ try {
172
+ client = new pg2.Client(pgClientConfig(dbUrl, DB_PROBE_TIMEOUT_MS));
173
+ await client.connect();
174
+ const { rows } = await client.query("SHOW server_version");
175
+ const version = rows[0].server_version;
176
+ return { reachable: true, version };
177
+ } catch (err) {
178
+ return {
179
+ reachable: false,
180
+ error: describeTimeout(describeFailure(err), connectTimeoutMs, DB_PROBE_TIMEOUT_MS)
181
+ };
182
+ } finally {
183
+ try {
184
+ await client?.end();
185
+ } catch {
186
+ }
187
+ }
188
+ }
189
+ var SERVER_REACHABLE_RE = /password authentication failed|does not exist|database .* does not exist|SSL.*required|no pg_hba\.conf entry/i;
190
+ async function buildLocalHints(dbUrl, error) {
191
+ const hints = [];
192
+ try {
193
+ const urlObj = new URL(dbUrl);
194
+ const isSupabasePort = urlObj.port === SUPABASE_LOCAL_PORT;
195
+ const isLocal = ["localhost", "127.0.0.1", "::1", ""].includes(urlObj.hostname);
196
+ if (!isLocal) return hints;
197
+ if (error && SERVER_REACHABLE_RE.test(error)) {
198
+ hints.push(`Check the username and password in your database URL.`);
199
+ if (isSupabasePort) {
200
+ hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. The default password is "postgres".`);
201
+ }
202
+ return hints;
203
+ }
204
+ if (isSupabasePort) {
205
+ hints.push(`Port ${SUPABASE_LOCAL_PORT} is the Supabase CLI default. Run ${cmd('"supabase start"')} to start your local Supabase instance.`);
206
+ }
207
+ const runtime = await detectRuntime();
208
+ if (runtime) {
209
+ hints.push(`${bold(runtime)} detected \u2014 you can start a PostgreSQL container manually.`);
210
+ }
211
+ if (!isSupabasePort) {
212
+ hints.push(`Start PostgreSQL manually on port ${urlObj.port || DEFAULT_PG_PORT}.`);
213
+ }
214
+ } catch {
215
+ }
216
+ return hints;
217
+ }
218
+ function buildTimeoutHints() {
219
+ return [
220
+ "The host is listening but the database did not answer.",
221
+ "Check the database process is running and not paused, restarting, or overloaded.",
222
+ "Over a VPN or tunnel, check the connection is still up.",
223
+ `Raise the bound with ${cmd("SUPAFORGE_CONNECT_TIMEOUT")} (in seconds) if the link is simply slow.`
224
+ ];
225
+ }
226
+ async function buildConnectionHints(dbUrl, error) {
227
+ if (error && /timed out after \d+s/.test(error)) return buildTimeoutHints();
228
+ return buildLocalHints(dbUrl, error);
229
+ }
230
+ var defaultPending = (msg) => {
231
+ if (!process.stdout.isTTY) return;
232
+ process.stdout.write(msg === null ? "\r\x1B[2K" : `\r\x1B[2K${msg}`);
233
+ };
234
+ var Preflight = class {
235
+ title;
236
+ log;
237
+ pending;
238
+ databases = [];
239
+ customs = [];
240
+ infoLines = [];
241
+ constructor(title, log, pending = defaultPending) {
242
+ this.title = title;
243
+ this.log = log;
244
+ this.pending = pending;
245
+ }
246
+ /** Register a database connectivity check. */
247
+ addDatabase(label, envName, dbUrl) {
248
+ this.databases.push({ label, envName, dbUrl });
249
+ return this;
250
+ }
251
+ /** Add an informational line to the header (displayed after database lines). */
252
+ addInfo(label, value) {
253
+ this.infoLines.push({ label, value });
254
+ return this;
255
+ }
256
+ /** Register a custom check (runs after all DB connectivity checks). */
257
+ addCheck(label, fn) {
258
+ this.customs.push({ label, fn });
259
+ return this;
260
+ }
261
+ /** Execute all registered checks, render results, and return the report. */
262
+ async run() {
263
+ const entries = [];
264
+ const log = this.log;
265
+ log(`
266
+ ${bold(this.title)}
267
+ `);
268
+ for (const db of this.databases) {
269
+ log(` ${db.label}: ${db.envName} ${dim(`(${redactUrls(db.dbUrl)})`)}`);
270
+ }
271
+ for (const info of this.infoLines) {
272
+ log(` ${info.label}: ${info.value}`);
273
+ }
274
+ log("");
275
+ log(" Checks:");
276
+ for (const db of this.databases) {
277
+ this.pending(` ${dim(`\u2026 connecting to ${db.label.toLowerCase()}`)}`);
278
+ const result = await checkConnection(db.dbUrl);
279
+ this.pending(null);
280
+ if (result.reachable) {
281
+ log(` ${ok("\u2713")} ${db.label} reachable ${dim(`(PostgreSQL ${result.version})`)}`);
282
+ entries.push({ label: db.label, passed: true, detail: `PostgreSQL ${result.version}` });
283
+ } else {
284
+ log(` ${warn("\u2717")} ${db.label} not reachable: ${redactUrls(describeFailure(result.error))}`);
285
+ const hints = await buildConnectionHints(db.dbUrl, result.error);
286
+ if (hints.length > 0) {
287
+ log(`
288
+ ${dim("Hints:")}`);
289
+ for (const h of hints) log(` ${dim("\u2022")} ${h}`);
290
+ }
291
+ entries.push({ label: db.label, passed: false, error: result.error, hints });
292
+ }
293
+ }
294
+ for (const custom of this.customs) {
295
+ this.pending(` ${dim(`\u2026 ${custom.label}`)}`);
296
+ const result = await custom.fn();
297
+ this.pending(null);
298
+ if (!result.error) {
299
+ const suffix = result.detail ? ` ${dim(result.detail)}` : "";
300
+ log(` ${ok("\u2713")} ${custom.label}${suffix}`);
301
+ entries.push({ label: custom.label, passed: true, detail: result.detail });
302
+ } else {
303
+ log(` ${warn("\u2717")} ${custom.label}: ${redactUrls(describeFailure(result.error))}`);
304
+ if (result.hints?.length) {
305
+ log(`
306
+ ${dim("Hints:")}`);
307
+ for (const h of result.hints) log(` ${dim("\u2022")} ${h}`);
308
+ }
309
+ entries.push({ label: custom.label, passed: false, error: result.error, hints: result.hints });
310
+ }
311
+ }
312
+ const passed = entries.every((e) => e.passed);
313
+ log("");
314
+ if (!passed) {
315
+ log(` ${warn("Some checks failed.")} Fix the issues above first.
316
+ `);
317
+ } else {
318
+ log(` ${ok("All checks passed.")}
319
+ `);
320
+ }
321
+ return { passed, checks: entries };
322
+ }
323
+ };
324
+
325
+ // src/run-log.ts
326
+ import { readFile, writeFile, mkdir, appendFile } from "fs/promises";
327
+ import { homedir } from "os";
328
+ import { join } from "path";
329
+ function runLogPath() {
330
+ return join(homedir(), RUN_LOG_DIR, RUN_LOG_FILE);
331
+ }
332
+ function runLogDir() {
333
+ return join(homedir(), RUN_LOG_DIR);
334
+ }
335
+ async function appendRunLog(entry) {
336
+ const dir = runLogDir();
337
+ await mkdir(dir, { recursive: true });
338
+ const path = runLogPath();
339
+ const line = JSON.stringify(entry) + "\n";
340
+ await appendFile(path, line, "utf8");
341
+ pruneRunLog(path).catch(() => {
342
+ });
343
+ }
344
+ async function readRunLog() {
345
+ try {
346
+ const raw = await readFile(runLogPath(), "utf8");
347
+ return raw.split("\n").filter(Boolean).map((line) => {
348
+ try {
349
+ return JSON.parse(line);
350
+ } catch {
351
+ return null;
352
+ }
353
+ }).filter((e) => e !== null);
354
+ } catch {
355
+ return [];
356
+ }
357
+ }
358
+ async function pruneRunLog(path) {
359
+ try {
360
+ const raw = await readFile(path, "utf8");
361
+ const lines = raw.split("\n").filter(Boolean);
362
+ if (lines.length <= RUN_LOG_MAX_ENTRIES) return;
363
+ const trimmed = lines.slice(lines.length - RUN_LOG_MAX_ENTRIES);
364
+ await writeFile(path, trimmed.join("\n") + "\n", "utf8");
365
+ } catch {
366
+ }
367
+ }
368
+ function redactArgs(argv) {
369
+ return argv.map(redactUrls);
370
+ }
371
+
372
+ // src/base-command.ts
373
+ var BaseCommand = class extends Command {
374
+ _startTime = 0;
375
+ _logWritten = false;
376
+ _checkSummaries;
377
+ /**
378
+ * Under --json, stdout carries the JSON and nothing else: every other line a
379
+ * command prints — preflight checks, progress — goes to stderr. Before, the
380
+ * text came first and the output did not parse.
381
+ */
382
+ log(message = "", ...args) {
383
+ if (this.argv.includes("--json")) {
384
+ process.stderr.write(formatWithOptions({ colors: false }, message, ...args) + "\n");
385
+ return;
386
+ }
387
+ super.log(message, ...args);
388
+ }
389
+ /** The command's result as JSON, on stdout. */
390
+ json(value) {
391
+ process.stdout.write(JSON.stringify(value, null, 2) + "\n");
392
+ }
393
+ /** Call after scan() to attach per-check metadata to the run log entry. */
394
+ setCheckSummaries(summaries) {
395
+ this._checkSummaries = summaries;
396
+ }
397
+ async init() {
398
+ await super.init();
399
+ this._startTime = Date.now();
400
+ }
401
+ async catch(err) {
402
+ this._logWritten = true;
403
+ await this._writeRunLog("error", err.message);
404
+ return super.catch(err);
405
+ }
406
+ async finally(err) {
407
+ if (!this._logWritten) {
408
+ await this._writeRunLog(err ? "error" : "success", err?.message);
409
+ }
410
+ return super.finally(err);
411
+ }
412
+ async _writeRunLog(exitStatus, error) {
413
+ try {
414
+ const version = this.config?.version;
415
+ const argv = this.argv ?? [];
416
+ await appendRunLog({
417
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
418
+ command: this.id ?? "unknown",
419
+ args: redactArgs(argv),
420
+ durationMs: Date.now() - this._startTime,
421
+ exitStatus,
422
+ error,
423
+ version,
424
+ checkSummaries: this._checkSummaries
425
+ });
426
+ } catch {
427
+ }
428
+ }
429
+ /** Load config or exit with a helpful error. */
430
+ async loadConfigOrFail() {
431
+ try {
432
+ return await loadConfig();
433
+ } catch {
434
+ this.error(
435
+ 'Could not load supaforge.config.json. Run "supaforge init" first.'
436
+ );
437
+ }
438
+ }
439
+ /**
440
+ * Resolve a single environment by name.
441
+ * Accepts an explicit flag value or falls back to config.source.
442
+ */
443
+ resolveEnv(config, envFlag) {
444
+ const envName = envFlag ?? config.source;
445
+ if (!envName) {
446
+ this.error('No environment specified. Use --env=<name> or set "source" in your config.');
447
+ }
448
+ const errors = validateSingleEnvConfig(config, envName);
449
+ if (errors.length > 0) {
450
+ this.error(`Invalid configuration:
451
+ ${errors.join("\n ")}`);
452
+ }
453
+ return { envName, env: config.environments[envName] };
454
+ }
455
+ /**
456
+ * Validate a two-env (source + target) config.
457
+ * Applies flag overrides before validation.
458
+ */
459
+ validateDualEnvConfig(config, sourceFlag, targetFlag) {
460
+ if (sourceFlag) config.source = sourceFlag;
461
+ if (targetFlag) config.target = targetFlag;
462
+ const errors = validateConfig(config);
463
+ if (errors.length > 0) {
464
+ this.error(`Invalid configuration:
465
+ ${errors.join("\n ")}`);
466
+ }
467
+ }
468
+ /** Redact password from a database URL for display. */
469
+ redactUrl(url) {
470
+ return url.replace(/:([^@/]{1,})@/, ":***@");
471
+ }
472
+ /** Resolve the migrations directory from config (with default fallback). */
473
+ resolveMigrationsDir(config) {
474
+ return config.checks?.migrations?.dir ?? DEFAULT_MIGRATIONS_DIR;
475
+ }
476
+ /**
477
+ * Create, run, and enforce a preflight check.
478
+ * Returns the Preflight instance for commands that need to add custom checks.
479
+ * When `abortMessage` is provided, exits with an error if checks fail.
480
+ */
481
+ createPreflight(title) {
482
+ return new Preflight(title, (m) => this.log(m));
483
+ }
484
+ /**
485
+ * Run a preflight and abort with a user-friendly message if it fails.
486
+ * Returns the report for commands that inspect individual check results.
487
+ */
488
+ async runPreflight(preflight, commandName) {
489
+ const report = await preflight.run();
490
+ if (!report.passed) {
491
+ this.error(`${commandName} aborted \u2014 fix the issues above first.`, { exit: 1 });
492
+ }
493
+ return report;
494
+ }
495
+ };
496
+
497
+ export {
498
+ DEFAULT_LOCAL_PORT,
499
+ LOCAL_PG_USER,
500
+ LOCAL_PG_PASSWORD,
501
+ startLocalPg,
502
+ runLogPath,
503
+ readRunLog,
504
+ BaseCommand
505
+ };
506
+ //# sourceMappingURL=chunk-SF3YA42C.js.map