@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.
Files changed (97) 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 +135 -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-2SELREHW.js +156 -0
  9. package/dist/chunk-2SELREHW.js.map +1 -0
  10. package/dist/chunk-3HGAV5CC.js +2073 -0
  11. package/dist/chunk-3HGAV5CC.js.map +1 -0
  12. package/dist/chunk-4IVN7QVY.js +632 -0
  13. package/dist/chunk-4IVN7QVY.js.map +1 -0
  14. package/dist/chunk-6LJERPUN.js +499 -0
  15. package/dist/chunk-6LJERPUN.js.map +1 -0
  16. package/dist/chunk-6Q7MHFBM.js +13 -0
  17. package/dist/chunk-6Q7MHFBM.js.map +1 -0
  18. package/dist/chunk-6WAMNZLO.js +336 -0
  19. package/dist/chunk-6WAMNZLO.js.map +1 -0
  20. package/dist/chunk-7NAZGZPV.js +868 -0
  21. package/dist/chunk-7NAZGZPV.js.map +1 -0
  22. package/dist/chunk-BLKJWDTL.js +153 -0
  23. package/dist/chunk-BLKJWDTL.js.map +1 -0
  24. package/dist/chunk-BUOWHE36.js +1311 -0
  25. package/dist/chunk-BUOWHE36.js.map +1 -0
  26. package/dist/chunk-DMIWAJRB.js +602 -0
  27. package/dist/chunk-DMIWAJRB.js.map +1 -0
  28. package/dist/chunk-DQQ5E563.js +64 -0
  29. package/dist/chunk-DQQ5E563.js.map +1 -0
  30. package/dist/chunk-G2DIPIYU.js +94 -0
  31. package/dist/chunk-G2DIPIYU.js.map +1 -0
  32. package/dist/chunk-GEHPTPNZ.js +240 -0
  33. package/dist/chunk-GEHPTPNZ.js.map +1 -0
  34. package/dist/chunk-GZREXCQZ.js +207 -0
  35. package/dist/chunk-GZREXCQZ.js.map +1 -0
  36. package/dist/chunk-MIRLB5JM.js +1292 -0
  37. package/dist/chunk-MIRLB5JM.js.map +1 -0
  38. package/dist/chunk-NTUASFQ3.js +248 -0
  39. package/dist/chunk-NTUASFQ3.js.map +1 -0
  40. package/dist/chunk-ORQJVE57.js +642 -0
  41. package/dist/chunk-ORQJVE57.js.map +1 -0
  42. package/dist/chunk-SC2XHGIS.js +122 -0
  43. package/dist/chunk-SC2XHGIS.js.map +1 -0
  44. package/dist/chunk-SQPCWGQO.js +657 -0
  45. package/dist/chunk-SQPCWGQO.js.map +1 -0
  46. package/dist/chunk-UWAVXC57.js +916 -0
  47. package/dist/chunk-UWAVXC57.js.map +1 -0
  48. package/dist/commands/clone.d.ts +66 -0
  49. package/dist/commands/clone.js +416 -0
  50. package/dist/commands/clone.js.map +1 -0
  51. package/dist/commands/diff.d.ts +81 -0
  52. package/dist/commands/diff.js +23 -0
  53. package/dist/commands/diff.js.map +1 -0
  54. package/dist/commands/help.d.ts +32 -0
  55. package/dist/commands/help.js +36 -0
  56. package/dist/commands/help.js.map +1 -0
  57. package/dist/commands/hukam.d.ts +13 -0
  58. package/dist/commands/hukam.js +28 -0
  59. package/dist/commands/hukam.js.map +1 -0
  60. package/dist/commands/init.d.ts +47 -0
  61. package/dist/commands/init.js +388 -0
  62. package/dist/commands/init.js.map +1 -0
  63. package/dist/commands/mcp.d.ts +13 -0
  64. package/dist/commands/mcp.js +43 -0
  65. package/dist/commands/mcp.js.map +1 -0
  66. package/dist/commands/migrate/baseline.d.ts +24 -0
  67. package/dist/commands/migrate/baseline.js +69 -0
  68. package/dist/commands/migrate/baseline.js.map +1 -0
  69. package/dist/commands/migrate/create.d.ts +36 -0
  70. package/dist/commands/migrate/create.js +127 -0
  71. package/dist/commands/migrate/create.js.map +1 -0
  72. package/dist/commands/migrate/list.d.ts +23 -0
  73. package/dist/commands/migrate/list.js +110 -0
  74. package/dist/commands/migrate/list.js.map +1 -0
  75. package/dist/commands/migrate/run.d.ts +61 -0
  76. package/dist/commands/migrate/run.js +18 -0
  77. package/dist/commands/migrate/run.js.map +1 -0
  78. package/dist/commands/report.d.ts +27 -0
  79. package/dist/commands/report.js +210 -0
  80. package/dist/commands/report.js.map +1 -0
  81. package/dist/commands/restore.d.ts +26 -0
  82. package/dist/commands/restore.js +266 -0
  83. package/dist/commands/restore.js.map +1 -0
  84. package/dist/commands/snapshot.d.ts +33 -0
  85. package/dist/commands/snapshot.js +249 -0
  86. package/dist/commands/snapshot.js.map +1 -0
  87. package/dist/commands/sync.d.ts +16 -0
  88. package/dist/commands/sync.js +38 -0
  89. package/dist/commands/sync.js.map +1 -0
  90. package/dist/config-CTbeRlJk.d.ts +134 -0
  91. package/dist/help.d.ts +28 -0
  92. package/dist/help.js +64 -0
  93. package/dist/help.js.map +1 -0
  94. package/dist/index.d.ts +498 -0
  95. package/dist/index.js +147 -0
  96. package/dist/index.js.map +1 -0
  97. package/package.json +74 -4
package/README.md CHANGED
@@ -1,3 +1,351 @@
1
- # Temporary Holding Version
1
+ # supaforge
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Diff and sync your Supabase environments.
4
+
5
+ SupaForge compares two Supabase projects (dev and prod, say) across
6
+ everything that makes up a project, not just the schema. It reports every
7
+ difference and makes the target match the source. Fixes run in dependency
8
+ order, in one transaction, and can be proved on a throwaway copy before
9
+ anything changes. With a single project, it snapshots, restores and clones it.
10
+
11
+ - **The whole project.** It covers schema, RLS, storage, auth, Edge Functions,
12
+ cron, webhooks, Realtime, Vault, extensions, grants, reference data and
13
+ migration history.
14
+ - **Safe by default.** Every write needs `--apply`, and anything that loses
15
+ data or opens up access also needs `--allow-destructive`. A failed apply
16
+ leaves the target exactly as it was.
17
+ - **Provable.** `--prove` rehearses the migration and refuses to apply one
18
+ that wouldn't reproduce the source.
19
+ - **Anywhere.** It works with Supabase Cloud, self-hosted stacks, plain
20
+ PostgreSQL targets, CI pipelines and AI agents (MCP).
21
+
22
+ Built by [Akal](https://github.com/akalsoftware).
23
+
24
+ ## Quick start
25
+
26
+ ```bash
27
+ npm install -g @akal/supaforge
28
+
29
+ supaforge init # create supaforge.config.json
30
+ supaforge diff # what has drifted?
31
+ supaforge diff --detail # with the SQL
32
+ supaforge diff --apply # fix the target
33
+ ```
34
+
35
+ Everything that writes previews first. Add `--apply` to make it happen.
36
+
37
+ ## What it compares
38
+
39
+ | Check | What it reads | Fixed with |
40
+ | --- | --- | --- |
41
+ | Schema | [`@dbdiff/cli`](https://github.com/DBDiff/DBDiff): every schema you own | SQL |
42
+ | Reference data | Rows of the tables in `checks.data.tables` | SQL |
43
+ | RLS policies | `pg_policies`, compared by meaning, not text | SQL |
44
+ | RLS coverage | Tables in the target with RLS off (target only) | SQL, opt-in |
45
+ | Edge Functions | Management API, Studio, or a functions directory | Deploy command |
46
+ | Storage | Buckets and their policies (objects are never copied) | API and SQL |
47
+ | Auth config | Management API, or GoTrue on self-hosted | API (hosted) |
48
+ | Cron jobs | `cron.job` | SQL |
49
+ | Webhooks | Triggers calling `supabase_functions.http_request` | SQL |
50
+ | Realtime | Publications, and policies on `realtime.messages` | SQL |
51
+ | Vault | Secret names and descriptions (values can't be read) | Command to run |
52
+ | Extensions | `pg_extension` | SQL |
53
+ | Migration history | Local migration files against `supabase_migrations` (target only) | SQL, opt-in |
54
+ | Roles and grants | Custom roles, and grants including `anon`, `authenticated`, `service_role` | SQL |
55
+
56
+ The schema check covers tables, columns, keys, indexes, partitions, views,
57
+ materialized views, functions, triggers, sequences, enums, composite types,
58
+ domains, policies, extensions and comments. It runs in every schema except
59
+ Supabase's own (`auth`, `storage`, and so on) and those in `ignoreSchemas`.
60
+ Objects owned by an extension belong to it and aren't compared.
61
+
62
+ A check that can't run, for example without API credentials, says so and why.
63
+ It's never reported as a clean pass.
64
+
65
+ ## Commands
66
+
67
+ ```
68
+ supaforge init Create a config interactively
69
+ supaforge diff Report drift (alias: hukam)
70
+ supaforge sync Alias for diff --apply
71
+
72
+ supaforge snapshot --apply Capture an environment's structure and configuration
73
+ supaforge restore --apply Rebuild a database from a snapshot or migrations
74
+ supaforge clone --apply Copy a remote database to a local one
75
+
76
+ supaforge migrate create Write a migration file from the current drift
77
+ supaforge migrate list Local migrations, applied and pending
78
+ supaforge migrate run --apply Run pending migrations
79
+ supaforge migrate baseline --apply Mark migrations applied without running them
80
+
81
+ supaforge report Recent runs, from a local log
82
+ supaforge mcp MCP server for AI agents
83
+ supaforge help <command> Every flag, e.g. help diff
84
+ ```
85
+
86
+ Useful `diff` flags:
87
+
88
+ | Flag | Does |
89
+ | --- | --- |
90
+ | `--check=rls` / `--skip=storage` | One check, or all but some (`--skip` repeats) |
91
+ | `--tables=orders,items` / `--exclude-tables='*_log'` | Scope the schema and data checks |
92
+ | `--only=<id,...>` | Apply only these findings (ids come from `--json`, globs allowed) |
93
+ | `--dry-run` | Print the fixes in the order they'd run, run nothing |
94
+ | `--prove` | Rehearse the fixes on a throwaway copy first |
95
+ | `--allow-destructive` | Also apply drops and deletes |
96
+ | `--apply-posture` | Also apply the target-only checks' fixes |
97
+ | `--no-transaction` | Apply fix by fix, keeping what works |
98
+ | `--json` / `--ci` | Machine-readable output; CI annotations and exit codes |
99
+
100
+ ## Applying fixes safely
101
+
102
+ - **Preview first.** `diff`, `snapshot`, `restore`, `clone` and `migrate run`
103
+ write nothing without `--apply`.
104
+ - **Destructive fixes need a second flag.** Dropping a schema, table or
105
+ column, deleting or truncating rows, and removing an RLS policy are reported
106
+ but skipped until you add `--allow-destructive`. `migrate run` uses the same
107
+ gate.
108
+ - **Dependency order.** Fixes run in dependency order: functions before the
109
+ triggers that call them, columns before their indexes, drops last. A changed
110
+ object that has to be dropped and recreated is a single fix.
111
+ - **One transaction.** If a fix fails, the whole set rolls back and the target
112
+ is unchanged. A fix the target can't hold, because it needs an extension or
113
+ a Supabase schema the target lacks, is skipped with the reason, and the rest
114
+ still applies.
115
+ - **`--prove`.** The fixes are replayed on a structure-only copy of the target,
116
+ made on the target's own server. Nothing is applied unless the result matches
117
+ the source. Changes a copy can't hold, such as cron jobs (pg_cron lives in
118
+ one database per server), are listed as not proved.
119
+
120
+ ```bash
121
+ supaforge diff --dry-run # the plan, in order
122
+ supaforge diff --apply --prove # rehearse, then apply
123
+ supaforge diff --apply --only='schema-create-*'
124
+ ```
125
+
126
+ ### Posture checks
127
+
128
+ RLS coverage and migration history look at the target alone, so they report
129
+ the same findings whichever pair you diff. They're scored separately
130
+ (`Posture score`), don't set the exit code unless you pass
131
+ `--fail-on-posture`, and their fixes apply only with `--apply-posture`, or
132
+ when you name the check, as in `--check=rls-coverage --apply`. Applying them
133
+ blindly would move the target away from the source.
134
+
135
+ ## Snapshot, restore and clone
136
+
137
+ ```bash
138
+ supaforge snapshot --env=prod --apply # capture
139
+ supaforge snapshot --env=prod --migration --apply # and write what changed since the last one
140
+ supaforge restore --env=local --from-snapshot=latest --apply
141
+ supaforge clone --env=prod --apply # local copy, data included
142
+ ```
143
+
144
+ A snapshot records a project's structure and configuration: schema, RLS
145
+ policies, cron, webhooks, extensions, storage, auth, Edge Functions,
146
+ reference data, Realtime, Vault names and grants. **It is not a
147
+ backup.** It holds no rows beyond `checks.data.tables`, and no stored files.
148
+
149
+ `restore --from-snapshot` puts back:
150
+
151
+ | Restored | Notes |
152
+ | --- | --- |
153
+ | Extensions, schema, RLS policies, cron jobs, webhooks, Realtime publications, grants | As SQL, in dependency order. Roles a policy or grant names are created first |
154
+ | Storage policies and buckets | Bucket rows are created when the target has a `storage` schema; files never are |
155
+ | Reference data | The rows of `checks.data.tables`, parents before children, sequences moved past the restored ids |
156
+
157
+ It can't put back auth config, Edge Functions (deploy them with
158
+ `supabase functions deploy`), or Vault secret values. Each of these is named in
159
+ the output.
160
+
161
+ - **Targets.** Restore runs as one transaction and expects an empty database.
162
+ `--force` clears the snapshot's own schemas first (never Supabase's) and
163
+ puts back the triggers and policies outside them that depended on what it
164
+ cleared.
165
+ - **Plain PostgreSQL.** Restoring into plain PostgreSQL works. What can't
166
+ exist there is skipped and named: a foreign key to `auth.users`, a webhook,
167
+ an extension the server doesn't ship, and everything that needs it.
168
+ - **Exit code.** A restore that left anything out exits 1. So does one that
169
+ refused to run.
170
+ - **JSON.** `--json` prints only JSON, for a preview too.
171
+
172
+ `clone` copies a remote database into a local server with `pg_dump` and
173
+ `pg_restore` (`--schema-only` to leave the rows behind). Extensions the local
174
+ server has are installed first. Objects it couldn't restore are listed by
175
+ cause. Afterwards the config's `target` points at the clone, so a bare
176
+ `diff --apply` writes there rather than to the remote.
177
+
178
+ ## Migrations
179
+
180
+ ```bash
181
+ supaforge migrate create --name=add_orders # from the drift between source and target
182
+ supaforge migrate run --env=prod # preview
183
+ supaforge migrate run --env=prod --apply
184
+ ```
185
+
186
+ - **Files and history.** Files live in `supabase/migrations` (set
187
+ `checks.migrations.dir` to change it). Applied versions are recorded in
188
+ `supabase_migrations.schema_migrations`, the Supabase CLI's table.
189
+ - **Destructive statements.** `migrate create` lists any it wrote, and
190
+ `migrate run` needs `--allow-destructive` to run them.
191
+ - **History table permissions.** On a self-hosted stack the history table can
192
+ belong to an admin role. SupaForge then says which `GRANT` is needed instead
193
+ of failing with a bare permission error.
194
+ - **Projects without a tracked history.** `checks.migrations.mode` decides
195
+ how the migration-history check reports them: `auto` (one note when nothing
196
+ is tracked), `warn` or `ignore`.
197
+
198
+ ## Configuration
199
+
200
+ ```json
201
+ {
202
+ "environments": {
203
+ "dev": { "dbUrl": "$DEV_DATABASE_URL", "projectRef": "abc123", "accessToken": "$SUPABASE_ACCESS_TOKEN" },
204
+ "prod": { "dbUrl": "$PROD_DATABASE_URL", "projectRef": "xyz789", "accessToken": "$SUPABASE_ACCESS_TOKEN" }
205
+ },
206
+ "source": "dev",
207
+ "target": "prod",
208
+ "checks": {
209
+ "data": { "tables": ["plans", "feature_flags"] },
210
+ "exclude": ["edge-functions"]
211
+ }
212
+ }
213
+ ```
214
+
215
+ | Field | Meaning |
216
+ | --- | --- |
217
+ | `dbUrl` | PostgreSQL connection string. `$VAR` and `${VAR}` are read from the environment |
218
+ | `projectRef`, `accessToken` | Enable the Management API checks (auth, Edge Functions) |
219
+ | `apiUrl` | A self-hosted API gateway, used instead of `projectRef` |
220
+ | `studioUrl`, `functionsPath` | Where self-hosted Edge Functions are read from |
221
+ | `source`, `target` | What to compare: the source is the truth, the target gets fixed |
222
+ | `ignoreSchemas` | Schemas of your own to leave out |
223
+ | `checks.data.tables` | Tables whose rows are compared and snapshotted |
224
+ | `checks.exclude` | Checks never to run (merged with `--skip`) |
225
+ | `checks.tables`, `checks.excludeTables` | Default scope for the schema and data checks |
226
+ | `checks.migrations.dir`, `checks.migrations.mode` | Where migrations live and how the history check reports |
227
+
228
+ - **Per environment.** `checks.exclude` and `checks.schema.timeout` can also
229
+ be set on an environment, and apply when it's the target.
230
+ - **`.env` files.** `.env` files are loaded the Next.js way:
231
+ `.env.{NODE_ENV}.local`, `.env.local`, `.env.{NODE_ENV}`, `.env`. Values
232
+ already in the environment win.
233
+ - **Single database.** A config with a single environment and no
234
+ `source`/`target` is fine. Use `snapshot`, `clone` and `restore`.
235
+
236
+ | Environment variable | Default | Purpose |
237
+ | --- | --- | --- |
238
+ | `SUPAFORGE_DBDIFF_TIMEOUT` | `600` | Seconds before the schema or data diff gives up |
239
+ | `SUPAFORGE_DBDIFF_MEMORY` | `1G` | Memory limit for `@dbdiff/cli` (`2G`, `-1` for none) |
240
+ | `SUPAFORGE_CONNECT_TIMEOUT` | `15` | Seconds to wait for a connection |
241
+ | `SUPAFORGE_CHECK_CONCURRENCY` | `4` | Checks run at once. Lower it behind a tight pooler |
242
+ | `SUPAFORGE_PG_BIN` | — | A directory of PostgreSQL client tools (`pg_dump`, `psql`) to use when the ones on `PATH` are too old for a server |
243
+
244
+ ## Self-hosted Supabase
245
+
246
+ Set `apiUrl` to the gateway and `accessToken` to the service-role key. All
247
+ checks run.
248
+
249
+ - **Edge Functions.** Self-hosted has no management endpoint for Edge
250
+ Functions, so set `studioUrl` (Studio's port, not the gateway's) or
251
+ `functionsPath` (the mounted functions directory). The two can be mixed
252
+ across environments. Studio's functions API is unauthenticated, so don't
253
+ expose it publicly.
254
+ - **Auth config.** On self-hosted, auth config is read from GoTrue's settings
255
+ endpoint, which carries fewer keys and can't be written. Change the
256
+ deployment's environment instead.
257
+
258
+ ## Diffing a clone
259
+
260
+ A local clone is plain PostgreSQL. Storage, auth, Edge Functions, Vault,
261
+ Realtime and Supabase's roles have nothing to compare there, so skip those
262
+ checks:
263
+
264
+ ```json
265
+ { "checks": { "exclude": ["storage", "auth", "edge-functions", "vault", "realtime", "roles"] } }
266
+ ```
267
+
268
+ When the source is a clone and the target isn't, `diff` warns that `--apply`
269
+ would push the clone's shape, absences included, onto the target.
270
+
271
+ ## CI and exit codes
272
+
273
+ ```yaml
274
+ - run: npx @akal/supaforge diff --ci
275
+ env:
276
+ DEV_DATABASE_URL: ${{ secrets.DEV_DATABASE_URL }}
277
+ PROD_DATABASE_URL: ${{ secrets.PROD_DATABASE_URL }}
278
+ ```
279
+
280
+ | Code | Meaning |
281
+ | --- | --- |
282
+ | `0` | Did what was asked, including when there was nothing to do |
283
+ | `1` | Found drift, declined to act, or something failed or was left out |
284
+ | `2` | Couldn't run: a usage error, or under `--ci` a check that couldn't finish |
285
+
286
+ `--ci` fails on critical drift by default. Set the threshold with
287
+ `--fail-on=warning` or `--fail-on=any`.
288
+
289
+ ## MCP (AI agents)
290
+
291
+ ```json
292
+ { "mcpServers": { "supaforge": { "command": "supaforge", "args": ["mcp"] } } }
293
+ ```
294
+
295
+ The server exposes these tools:
296
+
297
+ | Tool | Annotation |
298
+ | --- | --- |
299
+ | `scan_drift` | Read-only |
300
+ | `get_check_result` | Read-only |
301
+ | `apply_fixes` | Destructive. Previews unless `dryRun: false` |
302
+ | `take_snapshot` | Writes files |
303
+ | `create_migration` | Writes files |
304
+
305
+ It reads the config in its own directory, and refuses a `configPath` from a
306
+ client unless started with `--allow-config-path`.
307
+
308
+ ## Hooks
309
+
310
+ ```ts
311
+ import { HookBus, scan, createDefaultRegistry, loadConfig } from '@akal/supaforge'
312
+
313
+ const bus = new HookBus()
314
+ bus.on('supaforge.check.after', ({ check, result }) => {
315
+ if (result.status === 'drifted') console.log(`Drift in ${check}`)
316
+ })
317
+ await scan(createDefaultRegistry(), { config: await loadConfig() }, bus)
318
+ ```
319
+
320
+ ## Development
321
+
322
+ ```bash
323
+ cd packages/cli
324
+ npm install
325
+ npm test # unit tests
326
+ npm run lint # type-check
327
+ ./bin/dev.js diff # run from source
328
+ ```
329
+
330
+ | Suite | Command | Needs |
331
+ | --- | --- | --- |
332
+ | Integration | `npm run test:integration` | Docker or Podman |
333
+ | Database e2e | `npm run test:e2e` | Docker or Podman |
334
+ | Scenarios | `npx vitest run -c vitest.scenarios.config.ts` | Docker or Podman, `pg_dump` |
335
+ | Supabase e2e | `npm run test:e2e:supabase` | Supabase CLI |
336
+ | Release candidates | `scripts/test-release-candidates.sh --dbdiff ../DBDiff --pg-conformance ../pg-conformance` | Podman or Docker |
337
+
338
+ The release-candidates script builds DBDiff's binary and the npm packages
339
+ from local checkouts the way a release does, installs SupaForge against them
340
+ as a user would, and runs every suite above against that install. It tests
341
+ changes that span the three projects together, before any of them is
342
+ released.
343
+
344
+ The scenario suite migrates every case in the
345
+ [`@akal/pg-conformance`](https://www.npmjs.com/package/@akal/pg-conformance) corpus in both
346
+ directions. It checks the result against the corpus's own state oracle and
347
+ against `--prove`.
348
+
349
+ ## License
350
+
351
+ MIT
package/bin/dev.js ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env tsx
2
+ import {execute} from '@oclif/core'
3
+
4
+ await execute({development: true, dir: import.meta.url}).catch((err) => {
5
+ if (err && typeof err === 'object' && 'oclif' in err) return
6
+ process.stderr.write(`\nUnexpected error: ${err?.message ?? err}\n`)
7
+ process.stderr.write('If this looks like a bug, please report it:\n')
8
+ process.stderr.write(' https://github.com/akalsoftware/supaforge/issues/new\n\n')
9
+ process.exitCode = 1
10
+ })
package/bin/run.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ import {existsSync} from 'node:fs'
3
+ import {execute, settings} from '@oclif/core'
4
+
5
+ // The published package is compiled and ships no src/. Left on, oclif looks
6
+ // for TypeScript whenever NODE_ENV is development or test — as in many
7
+ // projects running npx supaforge — and warned on every command that it could
8
+ // not find it. A checkout keeps the lookup, which its tests rely on.
9
+ if (!existsSync(new URL('../src', import.meta.url))) settings.enableAutoTranspile = false
10
+
11
+ await execute({dir: import.meta.url}).catch((err) => {
12
+ // oclif handles CLIError internally — this catches truly unexpected errors.
13
+ if (err && typeof err === 'object' && 'oclif' in err) return
14
+ process.stderr.write(`\nUnexpected error: ${err?.message ?? err}\n`)
15
+ process.stderr.write('If this looks like a bug, please report it:\n')
16
+ process.stderr.write(' https://github.com/akalsoftware/supaforge/issues/new\n\n')
17
+ process.exitCode = 1
18
+ })
@@ -0,0 +1,135 @@
1
+ import { Command } from '@oclif/core';
2
+ import { S as SupaForgeConfig, E as EnvironmentConfig } from './config-CTbeRlJk.js';
3
+
4
+ /** Outcome of a single preflight check (DB connectivity or custom). */
5
+ interface CheckEntry {
6
+ label: string;
7
+ passed: boolean;
8
+ detail?: string;
9
+ error?: string;
10
+ hints?: string[];
11
+ }
12
+ /** Full report returned by Preflight.run(). */
13
+ interface PreflightReport {
14
+ passed: boolean;
15
+ checks: CheckEntry[];
16
+ }
17
+ type LogFn = (msg: string) => void;
18
+ /**
19
+ * Render a transient "in progress" line, or clear it when passed null.
20
+ *
21
+ * Separate from LogFn because these lines are overwritten rather than kept:
22
+ * on a TTY the finished result replaces them, and off a TTY they are dropped
23
+ * entirely so piped output and CI logs stay one line per check.
24
+ */
25
+ type PendingFn = (msg: string | null) => void;
26
+ /** Custom check callback. Return null on success, or an error string on failure. */
27
+ type CustomCheckFn = () => Promise<{
28
+ error?: string;
29
+ detail?: string;
30
+ hints?: string[];
31
+ }>;
32
+ /**
33
+ * Composable preflight check runner.
34
+ *
35
+ * Usage:
36
+ * ```ts
37
+ * const pre = new Preflight('Diff preflight checks', (m) => this.log(m))
38
+ * pre.addDatabase('Source', 'local', sourceUrl)
39
+ * pre.addDatabase('Target', 'prod', targetUrl)
40
+ * const report = await pre.run()
41
+ * if (!report.passed) this.error('Aborted.', { exit: 1 })
42
+ * ```
43
+ *
44
+ * For commands with extra checks (e.g. clone's pg_dump compat):
45
+ * ```ts
46
+ * pre.addCheck('pg_dump compatibility', async () => { ... })
47
+ * ```
48
+ */
49
+ declare class Preflight {
50
+ private readonly title;
51
+ private readonly log;
52
+ private readonly pending;
53
+ private readonly databases;
54
+ private readonly customs;
55
+ private readonly infoLines;
56
+ constructor(title: string, log: LogFn, pending?: PendingFn);
57
+ /** Register a database connectivity check. */
58
+ addDatabase(label: string, envName: string, dbUrl: string): this;
59
+ /** Add an informational line to the header (displayed after database lines). */
60
+ addInfo(label: string, value: string): this;
61
+ /** Register a custom check (runs after all DB connectivity checks). */
62
+ addCheck(label: string, fn: CustomCheckFn): this;
63
+ /** Execute all registered checks, render results, and return the report. */
64
+ run(): Promise<PreflightReport>;
65
+ }
66
+
67
+ /**
68
+ * Per-check summary attached to diff/apply run log entries.
69
+ * Contains only operational metadata — never SQL, table names, or data values.
70
+ * Error strings are sanitized (URLs and file paths stripped) before storage.
71
+ */
72
+ interface RunLogCheckSummary {
73
+ check: string;
74
+ status: string;
75
+ issueCount: number;
76
+ durationMs: number;
77
+ error?: string;
78
+ }
79
+
80
+ /**
81
+ * Shared base for all supaforge commands.
82
+ * Extracts config loading, env resolution, URL redaction, and run logging.
83
+ */
84
+ declare abstract class BaseCommand extends Command {
85
+ private _startTime;
86
+ private _logWritten;
87
+ private _checkSummaries?;
88
+ /**
89
+ * Under --json, stdout carries the JSON and nothing else: every other line a
90
+ * command prints — preflight checks, progress — goes to stderr. Before, the
91
+ * text came first and the output did not parse.
92
+ */
93
+ log(message?: string, ...args: unknown[]): void;
94
+ private _jsonWritten;
95
+ /** The command's result as JSON, on stdout. */
96
+ protected json(value: unknown): void;
97
+ /** Call after scan() to attach per-check metadata to the run log entry. */
98
+ protected setCheckSummaries(summaries: RunLogCheckSummary[]): void;
99
+ init(): Promise<void>;
100
+ catch(err: Error): Promise<void>;
101
+ finally(err: Error | undefined): Promise<void>;
102
+ private _writeRunLog;
103
+ /** Load config or exit with a helpful error. */
104
+ protected loadConfigOrFail(): Promise<SupaForgeConfig>;
105
+ /**
106
+ * Resolve a single environment by name.
107
+ * Accepts an explicit flag value or falls back to config.source.
108
+ */
109
+ protected resolveEnv(config: SupaForgeConfig, envFlag?: string): {
110
+ envName: string;
111
+ env: EnvironmentConfig;
112
+ };
113
+ /**
114
+ * Validate a two-env (source + target) config.
115
+ * Applies flag overrides before validation.
116
+ */
117
+ protected validateDualEnvConfig(config: SupaForgeConfig, sourceFlag?: string, targetFlag?: string): void;
118
+ /** Redact password from a database URL for display. */
119
+ protected redactUrl(url: string): string;
120
+ /** Resolve the migrations directory from config (with default fallback). */
121
+ protected resolveMigrationsDir(config: SupaForgeConfig): string;
122
+ /**
123
+ * Create, run, and enforce a preflight check.
124
+ * Returns the Preflight instance for commands that need to add custom checks.
125
+ * When `abortMessage` is provided, exits with an error if checks fail.
126
+ */
127
+ protected createPreflight(title: string): Preflight;
128
+ /**
129
+ * Run a preflight and abort with a user-friendly message if it fails.
130
+ * Returns the report for commands that inspect individual check results.
131
+ */
132
+ protected runPreflight(preflight: Preflight, commandName: string): Promise<PreflightReport>;
133
+ }
134
+
135
+ export { BaseCommand };
@@ -0,0 +1,9 @@
1
+ import {
2
+ BaseCommand
3
+ } from "./chunk-GZREXCQZ.js";
4
+ import "./chunk-SQPCWGQO.js";
5
+ import "./chunk-6WAMNZLO.js";
6
+ export {
7
+ BaseCommand
8
+ };
9
+ //# sourceMappingURL=base-command.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,58 @@
1
+ import { E as EnvironmentConfig, S as SupaForgeConfig } from './config-CTbeRlJk.js';
2
+
3
+ /** Prefix for branch database names created by SupaForge. */
4
+ declare const BRANCH_DB_PREFIX = "supaforge_branch_";
5
+ interface BranchMeta {
6
+ name: string;
7
+ dbName: string;
8
+ dbUrl: string;
9
+ createdFrom: string;
10
+ createdAt: string;
11
+ schemaOnly: boolean;
12
+ /** Directory containing the layer snapshot taken at branch creation time. */
13
+ snapshotDir?: string;
14
+ }
15
+ interface BranchesManifest {
16
+ branches: BranchMeta[];
17
+ }
18
+ interface CreateBranchOptions {
19
+ /** Branch name (must be unique). Converted to a safe DB identifier. */
20
+ name: string;
21
+ /** Connection URL of the database to branch from. */
22
+ sourceUrl: string;
23
+ /** Human-readable label for where we branched from (e.g. "production"). */
24
+ sourceLabel: string;
25
+ /** If true, copy schema only (no data). */
26
+ schemaOnly?: boolean;
27
+ /** Working directory for .supaforge/ metadata. */
28
+ cwd?: string;
29
+ /** Capture a full snapshot alongside the DB clone. */
30
+ env?: EnvironmentConfig;
31
+ /** Config needed for snapshot (ignore schemas, data tables, etc.). */
32
+ config?: SupaForgeConfig;
33
+ }
34
+ /** Sanitise a branch name into a valid Postgres identifier. */
35
+ declare function branchDbName(name: string): string;
36
+ /** Build a connection URL pointing at a different database on the same server. */
37
+ declare function replaceDbName(sourceUrl: string, dbName: string): string;
38
+ declare function loadManifest(cwd?: string): Promise<BranchesManifest>;
39
+ /**
40
+ * Create a branch by copying the source database.
41
+ *
42
+ * Strategy:
43
+ * 1. Try `CREATE DATABASE ... TEMPLATE` (instant, requires no other connections).
44
+ * 2. Fall back to `pg_dump | pg_restore` (works for remote / busy databases).
45
+ */
46
+ declare function createBranch(opts: CreateBranchOptions): Promise<BranchMeta>;
47
+ /** List all tracked branches. */
48
+ declare function listBranches(cwd?: string): Promise<BranchMeta[]>;
49
+ /** Delete a branch: drop the database and remove from manifest. */
50
+ declare function deleteBranch(name: string, sourceUrl: string, cwd?: string): Promise<void>;
51
+ interface RestoreFailure {
52
+ /** The statement, summarised: `CREATE TABLE public.docs`, `extension vector`. */
53
+ object: string;
54
+ /** PostgreSQL's error message. */
55
+ error: string;
56
+ }
57
+
58
+ export { BRANCH_DB_PREFIX as B, type CreateBranchOptions as C, type RestoreFailure as R, type BranchMeta as a, type BranchesManifest as b, branchDbName as c, createBranch as d, deleteBranch as e, loadManifest as f, listBranches as l, replaceDbName as r };