@akal/supaforge 0.0.0-stage → 0.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +350 -2
- package/bin/dev.js +10 -0
- package/bin/run.js +18 -0
- package/dist/base-command.d.ts +134 -0
- package/dist/base-command.js +9 -0
- package/dist/base-command.js.map +1 -0
- package/dist/branch-C4ndfoj5.d.ts +58 -0
- package/dist/chunk-4OU7KO5Y.js +13 -0
- package/dist/chunk-4OU7KO5Y.js.map +1 -0
- package/dist/chunk-5QQBTLWO.js +642 -0
- package/dist/chunk-5QQBTLWO.js.map +1 -0
- package/dist/chunk-5Z3SAIQS.js +2807 -0
- package/dist/chunk-5Z3SAIQS.js.map +1 -0
- package/dist/chunk-6WAMNZLO.js +336 -0
- package/dist/chunk-6WAMNZLO.js.map +1 -0
- package/dist/chunk-BHYLBKYD.js +156 -0
- package/dist/chunk-BHYLBKYD.js.map +1 -0
- package/dist/chunk-BLKJWDTL.js +153 -0
- package/dist/chunk-BLKJWDTL.js.map +1 -0
- package/dist/chunk-DQQ5E563.js +64 -0
- package/dist/chunk-DQQ5E563.js.map +1 -0
- package/dist/chunk-G2DIPIYU.js +94 -0
- package/dist/chunk-G2DIPIYU.js.map +1 -0
- package/dist/chunk-H5MJ5DFX.js +16 -0
- package/dist/chunk-H5MJ5DFX.js.map +1 -0
- package/dist/chunk-KIFJGON5.js +248 -0
- package/dist/chunk-KIFJGON5.js.map +1 -0
- package/dist/chunk-LQXF65MC.js +240 -0
- package/dist/chunk-LQXF65MC.js.map +1 -0
- package/dist/chunk-NXRSAVRU.js +478 -0
- package/dist/chunk-NXRSAVRU.js.map +1 -0
- package/dist/chunk-PARSNTBD.js +837 -0
- package/dist/chunk-PARSNTBD.js.map +1 -0
- package/dist/chunk-RRMI5CZD.js +376 -0
- package/dist/chunk-RRMI5CZD.js.map +1 -0
- package/dist/chunk-SF3YA42C.js +506 -0
- package/dist/chunk-SF3YA42C.js.map +1 -0
- package/dist/chunk-TQJSQLWA.js +574 -0
- package/dist/chunk-TQJSQLWA.js.map +1 -0
- package/dist/chunk-VMTBLHN2.js +122 -0
- package/dist/chunk-VMTBLHN2.js.map +1 -0
- package/dist/chunk-VOXZWQ3N.js +948 -0
- package/dist/chunk-VOXZWQ3N.js.map +1 -0
- package/dist/chunk-X6V2GGDZ.js +333 -0
- package/dist/chunk-X6V2GGDZ.js.map +1 -0
- package/dist/chunk-XMYMIURR.js +552 -0
- package/dist/chunk-XMYMIURR.js.map +1 -0
- package/dist/chunk-YVDSR4GM.js +1264 -0
- package/dist/chunk-YVDSR4GM.js.map +1 -0
- package/dist/commands/clone.d.ts +66 -0
- package/dist/commands/clone.js +416 -0
- package/dist/commands/clone.js.map +1 -0
- package/dist/commands/diff.d.ts +65 -0
- package/dist/commands/diff.js +24 -0
- package/dist/commands/diff.js.map +1 -0
- package/dist/commands/help.d.ts +32 -0
- package/dist/commands/help.js +36 -0
- package/dist/commands/help.js.map +1 -0
- package/dist/commands/hukam.d.ts +13 -0
- package/dist/commands/hukam.js +29 -0
- package/dist/commands/hukam.js.map +1 -0
- package/dist/commands/init.d.ts +47 -0
- package/dist/commands/init.js +388 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/mcp.d.ts +13 -0
- package/dist/commands/mcp.js +44 -0
- package/dist/commands/mcp.js.map +1 -0
- package/dist/commands/migrate/baseline.d.ts +24 -0
- package/dist/commands/migrate/baseline.js +69 -0
- package/dist/commands/migrate/baseline.js.map +1 -0
- package/dist/commands/migrate/create.d.ts +36 -0
- package/dist/commands/migrate/create.js +128 -0
- package/dist/commands/migrate/create.js.map +1 -0
- package/dist/commands/migrate/list.d.ts +23 -0
- package/dist/commands/migrate/list.js +110 -0
- package/dist/commands/migrate/list.js.map +1 -0
- package/dist/commands/migrate/run.d.ts +61 -0
- package/dist/commands/migrate/run.js +19 -0
- package/dist/commands/migrate/run.js.map +1 -0
- package/dist/commands/report.d.ts +27 -0
- package/dist/commands/report.js +210 -0
- package/dist/commands/report.js.map +1 -0
- package/dist/commands/restore.d.ts +26 -0
- package/dist/commands/restore.js +268 -0
- package/dist/commands/restore.js.map +1 -0
- package/dist/commands/snapshot.d.ts +33 -0
- package/dist/commands/snapshot.js +251 -0
- package/dist/commands/snapshot.js.map +1 -0
- package/dist/commands/sync.d.ts +16 -0
- package/dist/commands/sync.js +39 -0
- package/dist/commands/sync.js.map +1 -0
- package/dist/config-CTbeRlJk.d.ts +134 -0
- package/dist/help.d.ts +28 -0
- package/dist/help.js +64 -0
- package/dist/help.js.map +1 -0
- package/dist/index.d.ts +493 -0
- package/dist/index.js +147 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -4
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
import {
|
|
2
|
+
captureSnapshot,
|
|
3
|
+
checkPgDumpCompat
|
|
4
|
+
} from "./chunk-YVDSR4GM.js";
|
|
5
|
+
import {
|
|
6
|
+
pgClientConfig,
|
|
7
|
+
pgQuery,
|
|
8
|
+
quoteName
|
|
9
|
+
} from "./chunk-X6V2GGDZ.js";
|
|
10
|
+
import {
|
|
11
|
+
BRANCHES_FILE,
|
|
12
|
+
CLONE_PROGRESS_INTERVAL_MS,
|
|
13
|
+
PG_PIPELINE_TIMEOUT_MS,
|
|
14
|
+
SUPABASE_PLATFORM_SCHEMAS
|
|
15
|
+
} from "./chunk-6WAMNZLO.js";
|
|
16
|
+
|
|
17
|
+
// src/branch.ts
|
|
18
|
+
import { spawn } from "child_process";
|
|
19
|
+
import { readFile, writeFile, mkdir } from "fs/promises";
|
|
20
|
+
import { resolve, dirname } from "path";
|
|
21
|
+
import pg from "pg";
|
|
22
|
+
|
|
23
|
+
// src/stubs.ts
|
|
24
|
+
var AUTH_STUBS_SQL = `
|
|
25
|
+
-- Minimal auth schema for FK constraints and RLS policies
|
|
26
|
+
CREATE SCHEMA IF NOT EXISTS auth;
|
|
27
|
+
|
|
28
|
+
CREATE TABLE IF NOT EXISTS auth.users (
|
|
29
|
+
id uuid NOT NULL PRIMARY KEY DEFAULT gen_random_uuid()
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
CREATE OR REPLACE FUNCTION auth.uid() RETURNS uuid
|
|
33
|
+
LANGUAGE sql STABLE
|
|
34
|
+
AS $$ SELECT COALESCE(
|
|
35
|
+
nullif(current_setting('request.jwt.claims', true), '')::jsonb->>'sub',
|
|
36
|
+
nullif(current_setting('request.jwt.claim.sub', true), '')
|
|
37
|
+
)::uuid $$;
|
|
38
|
+
|
|
39
|
+
CREATE OR REPLACE FUNCTION auth.role() RETURNS text
|
|
40
|
+
LANGUAGE sql STABLE
|
|
41
|
+
AS $$ SELECT COALESCE(
|
|
42
|
+
nullif(current_setting('request.jwt.claims', true), '')::jsonb->>'role',
|
|
43
|
+
nullif(current_setting('request.jwt.claim.role', true), '')
|
|
44
|
+
)::text $$;
|
|
45
|
+
|
|
46
|
+
CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb
|
|
47
|
+
LANGUAGE sql STABLE
|
|
48
|
+
AS $$ SELECT COALESCE(
|
|
49
|
+
nullif(current_setting('request.jwt.claims', true), ''),
|
|
50
|
+
nullif(current_setting('request.jwt.claim', true), ''),
|
|
51
|
+
'{}'
|
|
52
|
+
)::jsonb $$;
|
|
53
|
+
|
|
54
|
+
CREATE OR REPLACE FUNCTION auth.email() RETURNS text
|
|
55
|
+
LANGUAGE sql STABLE
|
|
56
|
+
AS $$ SELECT COALESCE(
|
|
57
|
+
nullif(current_setting('request.jwt.claims', true), '')::jsonb->>'email',
|
|
58
|
+
nullif(current_setting('request.jwt.claim.email', true), '')
|
|
59
|
+
)::text $$;
|
|
60
|
+
`;
|
|
61
|
+
var STORAGE_STUBS_SQL = `
|
|
62
|
+
-- Minimal storage schema for storage check compatibility
|
|
63
|
+
CREATE SCHEMA IF NOT EXISTS storage;
|
|
64
|
+
|
|
65
|
+
CREATE TABLE IF NOT EXISTS storage.buckets (
|
|
66
|
+
id text NOT NULL PRIMARY KEY,
|
|
67
|
+
name text NOT NULL UNIQUE,
|
|
68
|
+
owner uuid,
|
|
69
|
+
created_at timestamptz DEFAULT now(),
|
|
70
|
+
updated_at timestamptz DEFAULT now(),
|
|
71
|
+
public boolean DEFAULT false,
|
|
72
|
+
file_size_limit bigint,
|
|
73
|
+
allowed_mime_types text[]
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
CREATE TABLE IF NOT EXISTS storage.objects (
|
|
77
|
+
id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
|
|
78
|
+
bucket_id text REFERENCES storage.buckets(id),
|
|
79
|
+
name text,
|
|
80
|
+
owner uuid,
|
|
81
|
+
created_at timestamptz DEFAULT now(),
|
|
82
|
+
updated_at timestamptz DEFAULT now(),
|
|
83
|
+
last_accessed_at timestamptz DEFAULT now(),
|
|
84
|
+
metadata jsonb
|
|
85
|
+
);
|
|
86
|
+
`;
|
|
87
|
+
var CLONE_STUBS_SQL = [AUTH_STUBS_SQL, STORAGE_STUBS_SQL].join("\n");
|
|
88
|
+
|
|
89
|
+
// src/branch.ts
|
|
90
|
+
var BRANCH_DB_PREFIX = "supaforge_branch_";
|
|
91
|
+
function branchDbName(name) {
|
|
92
|
+
const safe = name.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
|
|
93
|
+
if (!safe) throw new Error(`Invalid branch name: "${name}"`);
|
|
94
|
+
return `${BRANCH_DB_PREFIX}${safe}`;
|
|
95
|
+
}
|
|
96
|
+
function replaceDbName(sourceUrl, dbName) {
|
|
97
|
+
const u = new URL(sourceUrl);
|
|
98
|
+
u.pathname = `/${dbName}`;
|
|
99
|
+
return u.toString();
|
|
100
|
+
}
|
|
101
|
+
function parseUrl(url) {
|
|
102
|
+
const u = new URL(url);
|
|
103
|
+
return {
|
|
104
|
+
host: u.hostname,
|
|
105
|
+
port: u.port || "5432",
|
|
106
|
+
user: u.username,
|
|
107
|
+
password: u.password,
|
|
108
|
+
database: u.pathname.replace(/^\//, "")
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
async function manifestPath(cwd) {
|
|
112
|
+
return resolve(cwd, BRANCHES_FILE);
|
|
113
|
+
}
|
|
114
|
+
async function loadManifest(cwd = process.cwd()) {
|
|
115
|
+
try {
|
|
116
|
+
const raw = await readFile(await manifestPath(cwd), "utf-8");
|
|
117
|
+
return JSON.parse(raw);
|
|
118
|
+
} catch {
|
|
119
|
+
return { branches: [] };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
async function saveManifest(manifest, cwd) {
|
|
123
|
+
const p = await manifestPath(cwd);
|
|
124
|
+
await mkdir(dirname(p), { recursive: true });
|
|
125
|
+
await writeFile(p, JSON.stringify(manifest, null, 2) + "\n");
|
|
126
|
+
}
|
|
127
|
+
async function createBranch(opts) {
|
|
128
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
129
|
+
const dbName = branchDbName(opts.name);
|
|
130
|
+
const branchUrl = replaceDbName(opts.sourceUrl, dbName);
|
|
131
|
+
const manifest = await loadManifest(cwd);
|
|
132
|
+
if (manifest.branches.some((b) => b.name === opts.name)) {
|
|
133
|
+
throw new Error(`Branch "${opts.name}" already exists.`);
|
|
134
|
+
}
|
|
135
|
+
const created = await tryTemplateCopy(opts.sourceUrl, dbName);
|
|
136
|
+
let pgDumpPath = "pg_dump";
|
|
137
|
+
let pgRestorePath = "pg_restore";
|
|
138
|
+
if (!created) {
|
|
139
|
+
const compat = await checkPgDumpCompat(opts.sourceUrl);
|
|
140
|
+
if (!compat.compatible) {
|
|
141
|
+
throw new Error(compat.message);
|
|
142
|
+
}
|
|
143
|
+
pgDumpPath = compat.pgDumpPath;
|
|
144
|
+
pgRestorePath = compat.pgRestorePath;
|
|
145
|
+
}
|
|
146
|
+
const dumpCreated = created || await tryDumpRestore(opts.sourceUrl, dbName, opts.schemaOnly ?? false, pgDumpPath, pgRestorePath);
|
|
147
|
+
if (!dumpCreated) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
"Failed to create branch. Ensure you have CREATE DATABASE privileges and that pg_dump + pg_restore are available in your PATH."
|
|
150
|
+
);
|
|
151
|
+
}
|
|
152
|
+
const meta = {
|
|
153
|
+
name: opts.name,
|
|
154
|
+
dbName,
|
|
155
|
+
dbUrl: branchUrl,
|
|
156
|
+
createdFrom: opts.sourceLabel,
|
|
157
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
158
|
+
schemaOnly: opts.schemaOnly ?? false
|
|
159
|
+
};
|
|
160
|
+
if (opts.env && opts.config) {
|
|
161
|
+
try {
|
|
162
|
+
const snapshot = await captureSnapshot({
|
|
163
|
+
envName: opts.sourceLabel,
|
|
164
|
+
env: opts.env,
|
|
165
|
+
config: opts.config,
|
|
166
|
+
cwd
|
|
167
|
+
});
|
|
168
|
+
meta.snapshotDir = snapshot.dir;
|
|
169
|
+
} catch {
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
manifest.branches.push(meta);
|
|
173
|
+
await saveManifest(manifest, cwd);
|
|
174
|
+
return meta;
|
|
175
|
+
}
|
|
176
|
+
async function tryTemplateCopy(sourceUrl, newDb) {
|
|
177
|
+
const { database } = parseUrl(sourceUrl);
|
|
178
|
+
const maintenanceUrl = replaceDbName(sourceUrl, "postgres");
|
|
179
|
+
const client = new pg.Client(pgClientConfig(maintenanceUrl));
|
|
180
|
+
try {
|
|
181
|
+
await client.connect();
|
|
182
|
+
await client.query(`CREATE DATABASE ${quoteName(newDb)} TEMPLATE ${quoteName(database)}`);
|
|
183
|
+
return true;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
} finally {
|
|
187
|
+
await client.end();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
async function tryDumpRestore(sourceUrl, newDb, schemaOnly, pgDumpPath = "pg_dump", pgRestorePath = "pg_restore") {
|
|
191
|
+
const maintenanceUrl = replaceDbName(sourceUrl, "postgres");
|
|
192
|
+
const client = new pg.Client(pgClientConfig(maintenanceUrl));
|
|
193
|
+
try {
|
|
194
|
+
await client.connect();
|
|
195
|
+
await client.query(`CREATE DATABASE ${quoteName(newDb)}`);
|
|
196
|
+
} catch {
|
|
197
|
+
return false;
|
|
198
|
+
} finally {
|
|
199
|
+
await client.end();
|
|
200
|
+
}
|
|
201
|
+
const dumpArgs = ["--format=custom", "--no-owner", "--no-acl", sourceUrl];
|
|
202
|
+
if (schemaOnly) dumpArgs.unshift("--schema-only");
|
|
203
|
+
const targetUrl = replaceDbName(sourceUrl, newDb);
|
|
204
|
+
const restoreArgs = [
|
|
205
|
+
"--format=custom",
|
|
206
|
+
"--no-owner",
|
|
207
|
+
"--no-acl",
|
|
208
|
+
`--dbname=${targetUrl}`
|
|
209
|
+
];
|
|
210
|
+
try {
|
|
211
|
+
await new Promise((resolve2, reject) => {
|
|
212
|
+
const dump = spawn(pgDumpPath, dumpArgs, { stdio: ["ignore", "pipe", "pipe"] });
|
|
213
|
+
const restore = spawn(pgRestorePath, restoreArgs, { stdio: [dump.stdout, "pipe", "pipe"] });
|
|
214
|
+
let restoreStderr = "";
|
|
215
|
+
restore.stderr?.on("data", (chunk) => {
|
|
216
|
+
restoreStderr += chunk.toString();
|
|
217
|
+
});
|
|
218
|
+
let dumpError = "";
|
|
219
|
+
dump.stderr?.on("data", (chunk) => {
|
|
220
|
+
dumpError += chunk.toString();
|
|
221
|
+
});
|
|
222
|
+
let dumpExit = null;
|
|
223
|
+
let restoreExit = null;
|
|
224
|
+
let settled = false;
|
|
225
|
+
function tryResolve() {
|
|
226
|
+
if (settled || dumpExit === null || restoreExit === null) return;
|
|
227
|
+
settled = true;
|
|
228
|
+
if (dumpExit !== 0) {
|
|
229
|
+
reject(new Error(`pg_dump failed (exit ${dumpExit}): ${dumpError}`));
|
|
230
|
+
} else if (restoreExit !== 0 && restoreExit !== 1) {
|
|
231
|
+
reject(new Error(`pg_restore failed (exit ${restoreExit}): ${restoreStderr}`));
|
|
232
|
+
} else {
|
|
233
|
+
resolve2();
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
dump.on("close", (code) => {
|
|
237
|
+
dumpExit = code ?? 1;
|
|
238
|
+
tryResolve();
|
|
239
|
+
});
|
|
240
|
+
restore.on("close", (code) => {
|
|
241
|
+
restoreExit = code ?? 1;
|
|
242
|
+
tryResolve();
|
|
243
|
+
});
|
|
244
|
+
dump.on("error", (err) => {
|
|
245
|
+
if (!settled) {
|
|
246
|
+
settled = true;
|
|
247
|
+
reject(err);
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
restore.on("error", (err) => {
|
|
251
|
+
if (!settled) {
|
|
252
|
+
settled = true;
|
|
253
|
+
reject(err);
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
});
|
|
257
|
+
return true;
|
|
258
|
+
} catch {
|
|
259
|
+
const cleanup = new pg.Client(pgClientConfig(maintenanceUrl));
|
|
260
|
+
try {
|
|
261
|
+
await cleanup.connect();
|
|
262
|
+
await cleanup.query(`DROP DATABASE IF EXISTS ${quoteName(newDb)}`);
|
|
263
|
+
} finally {
|
|
264
|
+
await cleanup.end();
|
|
265
|
+
}
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
async function listBranches(cwd = process.cwd()) {
|
|
270
|
+
const manifest = await loadManifest(cwd);
|
|
271
|
+
return manifest.branches;
|
|
272
|
+
}
|
|
273
|
+
async function listServerDatabases(serverUrl) {
|
|
274
|
+
const maintenanceUrl = replaceDbName(serverUrl, "postgres");
|
|
275
|
+
const client = new pg.Client(pgClientConfig(maintenanceUrl));
|
|
276
|
+
try {
|
|
277
|
+
await client.connect();
|
|
278
|
+
const { rows } = await client.query(
|
|
279
|
+
"SELECT datname FROM pg_database WHERE datistemplate = false"
|
|
280
|
+
);
|
|
281
|
+
return new Set(rows.map((r) => String(r.datname)));
|
|
282
|
+
} finally {
|
|
283
|
+
await client.end();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async function reconcileClones(opts) {
|
|
287
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
288
|
+
const manifest = await loadManifest(cwd);
|
|
289
|
+
const tracked = manifest.branches.map((b) => ({ ...b }));
|
|
290
|
+
if (!opts.localServerUrl) return tracked;
|
|
291
|
+
let existing;
|
|
292
|
+
try {
|
|
293
|
+
existing = await listServerDatabases(opts.localServerUrl);
|
|
294
|
+
} catch {
|
|
295
|
+
return tracked;
|
|
296
|
+
}
|
|
297
|
+
for (const clone of tracked) {
|
|
298
|
+
if (!existing.has(clone.dbName)) clone.missing = true;
|
|
299
|
+
}
|
|
300
|
+
const trackedNames = new Set(tracked.map((c) => c.dbName));
|
|
301
|
+
const discovered = [...existing].filter(
|
|
302
|
+
(db) => !trackedNames.has(db) && (db.startsWith(BRANCH_DB_PREFIX) || db === opts.configuredLocalDb)
|
|
303
|
+
).map((db) => ({
|
|
304
|
+
name: db,
|
|
305
|
+
dbName: db,
|
|
306
|
+
dbUrl: replaceDbName(opts.localServerUrl, db),
|
|
307
|
+
createdFrom: "unknown",
|
|
308
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
309
|
+
schemaOnly: false,
|
|
310
|
+
discovered: true
|
|
311
|
+
}));
|
|
312
|
+
if (discovered.length > 0) {
|
|
313
|
+
manifest.branches.push(
|
|
314
|
+
...discovered.map(({ missing: _m, discovered: _d, ...meta }) => meta)
|
|
315
|
+
);
|
|
316
|
+
await saveManifest(manifest, cwd).catch(() => {
|
|
317
|
+
});
|
|
318
|
+
}
|
|
319
|
+
return [...tracked, ...discovered];
|
|
320
|
+
}
|
|
321
|
+
async function addBranchToManifest(meta, cwd = process.cwd()) {
|
|
322
|
+
const manifest = await loadManifest(cwd);
|
|
323
|
+
const existing = manifest.branches.findIndex((b) => b.name === meta.name);
|
|
324
|
+
if (existing >= 0) {
|
|
325
|
+
manifest.branches[existing] = meta;
|
|
326
|
+
} else {
|
|
327
|
+
manifest.branches.push(meta);
|
|
328
|
+
}
|
|
329
|
+
await saveManifest(manifest, cwd);
|
|
330
|
+
}
|
|
331
|
+
async function deleteBranch(name, sourceUrl, cwd = process.cwd()) {
|
|
332
|
+
const manifest = await loadManifest(cwd);
|
|
333
|
+
const idx = manifest.branches.findIndex((b) => b.name === name);
|
|
334
|
+
if (idx === -1) throw new Error(`Branch "${name}" not found.`);
|
|
335
|
+
const branch = manifest.branches[idx];
|
|
336
|
+
const maintenanceUrl = replaceDbName(sourceUrl, "postgres");
|
|
337
|
+
const client = new pg.Client(pgClientConfig(maintenanceUrl));
|
|
338
|
+
try {
|
|
339
|
+
await client.connect();
|
|
340
|
+
await client.query(
|
|
341
|
+
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()`,
|
|
342
|
+
[branch.dbName]
|
|
343
|
+
);
|
|
344
|
+
await client.query(`DROP DATABASE IF EXISTS ${quoteName(branch.dbName)}`);
|
|
345
|
+
} finally {
|
|
346
|
+
await client.end();
|
|
347
|
+
}
|
|
348
|
+
manifest.branches.splice(idx, 1);
|
|
349
|
+
await saveManifest(manifest, cwd);
|
|
350
|
+
}
|
|
351
|
+
async function cloneRemoteToLocal(opts) {
|
|
352
|
+
const compat = await checkPgDumpCompat(opts.remoteUrl);
|
|
353
|
+
if (!compat.compatible) {
|
|
354
|
+
throw new Error(compat.message);
|
|
355
|
+
}
|
|
356
|
+
const localMaintenanceUrl = opts.localBaseUrl;
|
|
357
|
+
const localDbUrl = replaceDbName(opts.localBaseUrl, opts.localDbName);
|
|
358
|
+
const client = new pg.Client(pgClientConfig(localMaintenanceUrl));
|
|
359
|
+
try {
|
|
360
|
+
await client.connect();
|
|
361
|
+
if (opts.force) {
|
|
362
|
+
await client.query(
|
|
363
|
+
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1 AND pid <> pg_backend_pid()`,
|
|
364
|
+
[opts.localDbName]
|
|
365
|
+
);
|
|
366
|
+
await client.query(`DROP DATABASE IF EXISTS ${quoteName(opts.localDbName)}`);
|
|
367
|
+
}
|
|
368
|
+
await client.query(`CREATE DATABASE ${quoteName(opts.localDbName)}`);
|
|
369
|
+
} catch (err) {
|
|
370
|
+
const msg = err.message ?? "";
|
|
371
|
+
if (msg.includes("already exists")) {
|
|
372
|
+
throw new Error(
|
|
373
|
+
`Database "${opts.localDbName}" already exists on the local server. Drop it first with: psql "${localMaintenanceUrl}" -c 'DROP DATABASE "${opts.localDbName}"'`
|
|
374
|
+
);
|
|
375
|
+
}
|
|
376
|
+
throw new Error(`Failed to create local database: ${msg}`);
|
|
377
|
+
} finally {
|
|
378
|
+
await client.end();
|
|
379
|
+
}
|
|
380
|
+
if (opts.excludeSchemas?.length) {
|
|
381
|
+
const stubClient = new pg.Client(pgClientConfig(localDbUrl));
|
|
382
|
+
try {
|
|
383
|
+
await stubClient.connect();
|
|
384
|
+
await stubClient.query(CLONE_STUBS_SQL);
|
|
385
|
+
} finally {
|
|
386
|
+
await stubClient.end();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const extensions = await installRemoteExtensions(opts.remoteUrl, localDbUrl, opts.excludeSchemas ?? []);
|
|
390
|
+
const dumpArgs = ["--format=custom", "--no-owner", "--no-acl"];
|
|
391
|
+
if (opts.schemaOnly) dumpArgs.push("--schema-only");
|
|
392
|
+
if (opts.excludeSchemas?.length) {
|
|
393
|
+
for (const schema of opts.excludeSchemas) {
|
|
394
|
+
dumpArgs.push(`--exclude-schema=${schema}`);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
dumpArgs.push(opts.remoteUrl);
|
|
398
|
+
const restoreArgs = [
|
|
399
|
+
"--format=custom",
|
|
400
|
+
"--no-owner",
|
|
401
|
+
"--no-acl",
|
|
402
|
+
`--dbname=${localDbUrl}`
|
|
403
|
+
];
|
|
404
|
+
let restoreLog = "";
|
|
405
|
+
try {
|
|
406
|
+
restoreLog = await new Promise((resolve2, reject) => {
|
|
407
|
+
const dump = spawn(compat.pgDumpPath, dumpArgs, { stdio: ["ignore", "pipe", "pipe"] });
|
|
408
|
+
const restore = spawn(compat.pgRestorePath, restoreArgs, { stdio: ["pipe", "pipe", "pipe"] });
|
|
409
|
+
let bytesTransferred = 0;
|
|
410
|
+
dump.stdout.on("data", (chunk) => {
|
|
411
|
+
bytesTransferred += chunk.length;
|
|
412
|
+
});
|
|
413
|
+
dump.stdout.pipe(restore.stdin);
|
|
414
|
+
let restoreStderr = "";
|
|
415
|
+
let lastRestoreMessage = "";
|
|
416
|
+
restore.stderr?.on("data", (chunk) => {
|
|
417
|
+
restoreStderr += chunk.toString();
|
|
418
|
+
const lines = chunk.toString().split("\n").filter(Boolean);
|
|
419
|
+
if (lines.length > 0) {
|
|
420
|
+
lastRestoreMessage = lines[lines.length - 1].trim().slice(0, 120);
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
let dumpError = "";
|
|
424
|
+
dump.stderr?.on("data", (chunk) => {
|
|
425
|
+
dumpError += chunk.toString();
|
|
426
|
+
});
|
|
427
|
+
const startTime = Date.now();
|
|
428
|
+
const progressInterval = opts.onProgress ? setInterval(() => {
|
|
429
|
+
opts.onProgress({
|
|
430
|
+
bytesTransferred,
|
|
431
|
+
elapsedMs: Date.now() - startTime,
|
|
432
|
+
lastRestoreMessage: lastRestoreMessage || void 0
|
|
433
|
+
});
|
|
434
|
+
}, CLONE_PROGRESS_INTERVAL_MS) : null;
|
|
435
|
+
let dumpExit = null;
|
|
436
|
+
let restoreExit = null;
|
|
437
|
+
let settled = false;
|
|
438
|
+
const cleanup = () => {
|
|
439
|
+
if (progressInterval) clearInterval(progressInterval);
|
|
440
|
+
clearTimeout(timeout);
|
|
441
|
+
};
|
|
442
|
+
const trySettle = () => {
|
|
443
|
+
if (settled || dumpExit === null || restoreExit === null) return;
|
|
444
|
+
settled = true;
|
|
445
|
+
cleanup();
|
|
446
|
+
opts.onProgress?.({
|
|
447
|
+
bytesTransferred,
|
|
448
|
+
elapsedMs: Date.now() - startTime,
|
|
449
|
+
lastRestoreMessage: void 0
|
|
450
|
+
});
|
|
451
|
+
if (dumpExit !== 0) {
|
|
452
|
+
reject(new Error(`pg_dump failed (exit ${dumpExit}): ${dumpError}`));
|
|
453
|
+
} else if (restoreExit !== 0 && restoreExit !== 1) {
|
|
454
|
+
reject(new Error(`pg_restore failed (exit ${restoreExit}): ${restoreStderr}`));
|
|
455
|
+
} else {
|
|
456
|
+
resolve2(restoreStderr);
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
dump.on("close", (code) => {
|
|
460
|
+
dumpExit = code ?? 1;
|
|
461
|
+
trySettle();
|
|
462
|
+
});
|
|
463
|
+
restore.on("close", (code) => {
|
|
464
|
+
restoreExit = code ?? 1;
|
|
465
|
+
trySettle();
|
|
466
|
+
});
|
|
467
|
+
dump.on("error", (err) => {
|
|
468
|
+
if (!settled) {
|
|
469
|
+
settled = true;
|
|
470
|
+
cleanup();
|
|
471
|
+
reject(err);
|
|
472
|
+
}
|
|
473
|
+
});
|
|
474
|
+
restore.on("error", (err) => {
|
|
475
|
+
if (!settled) {
|
|
476
|
+
settled = true;
|
|
477
|
+
cleanup();
|
|
478
|
+
reject(err);
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
const timeout = setTimeout(() => {
|
|
482
|
+
if (!settled) {
|
|
483
|
+
settled = true;
|
|
484
|
+
cleanup();
|
|
485
|
+
dump.kill();
|
|
486
|
+
restore.kill();
|
|
487
|
+
reject(new Error(
|
|
488
|
+
"pg_dump | pg_restore timed out after 30 minutes.\n" + (dumpError ? ` pg_dump stderr: ${dumpError.slice(0, 500)}
|
|
489
|
+
` : "") + (restoreStderr ? ` pg_restore stderr: ${restoreStderr.slice(0, 500)}` : "")
|
|
490
|
+
));
|
|
491
|
+
}
|
|
492
|
+
}, PG_PIPELINE_TIMEOUT_MS);
|
|
493
|
+
});
|
|
494
|
+
} catch (err) {
|
|
495
|
+
const cleanup = new pg.Client(pgClientConfig(localMaintenanceUrl));
|
|
496
|
+
try {
|
|
497
|
+
await cleanup.connect();
|
|
498
|
+
await cleanup.query(`DROP DATABASE IF EXISTS ${quoteName(opts.localDbName)}`);
|
|
499
|
+
} catch {
|
|
500
|
+
} finally {
|
|
501
|
+
await cleanup.end();
|
|
502
|
+
}
|
|
503
|
+
throw err;
|
|
504
|
+
}
|
|
505
|
+
const { failures, unavailable } = restoreFailures(restoreLog);
|
|
506
|
+
return {
|
|
507
|
+
url: localDbUrl,
|
|
508
|
+
failures,
|
|
509
|
+
unavailable,
|
|
510
|
+
extensionsInstalled: extensions.installed
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
function restoreFailures(stderr, platformSchemas = SUPABASE_PLATFORM_SCHEMAS) {
|
|
514
|
+
const entries = [];
|
|
515
|
+
for (const block of stderr.split(/^pg_restore: (?:error|warning): /m).slice(1)) {
|
|
516
|
+
const error = /could not execute query: ERROR:\s+(.*)/.exec(block)?.[1]?.trim();
|
|
517
|
+
const command = /^Command was: ([\s\S]*?)(?:\n\s*\n|$)/m.exec(block)?.[1]?.trim();
|
|
518
|
+
if (error && command) entries.push({ error, command });
|
|
519
|
+
}
|
|
520
|
+
const notShipped = new Set(entries.filter((e) => / is not available$/.test(e.error) && /^CREATE\s+EXTENSION\b/i.test(e.command)).map((e) => extensionName(e.command)));
|
|
521
|
+
const inPlatformSchema = new RegExp(`\\b(?:${platformSchemas.map(escapeRegExp).join("|")})\\.`);
|
|
522
|
+
const failures = [];
|
|
523
|
+
const unavailable = [];
|
|
524
|
+
for (const { error, command } of entries) {
|
|
525
|
+
if (/ already exists$/.test(error)) continue;
|
|
526
|
+
if (/^SET\s+/i.test(command) && /^unrecognized configuration parameter/.test(error)) continue;
|
|
527
|
+
if (/^CREATE\s+EXTENSION\b/i.test(command)) {
|
|
528
|
+
const entry2 = { object: `extension ${extensionName(command)}`, error };
|
|
529
|
+
(notShipped.has(extensionName(command)) ? unavailable : failures).push(entry2);
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
const ext = /^COMMENT\s+ON\s+EXTENSION\s+("[^"]+"|[\w$]+)/i.exec(command)?.[1];
|
|
533
|
+
if (ext && notShipped.has(ext.replace(/"/g, ""))) continue;
|
|
534
|
+
const entry = { object: summariseCommand(command), error };
|
|
535
|
+
if (/^CREATE\s+EVENT\s+TRIGGER\b/i.test(command) && inPlatformSchema.test(error)) {
|
|
536
|
+
unavailable.push(entry);
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
failures.push(entry);
|
|
540
|
+
}
|
|
541
|
+
return { failures, unavailable };
|
|
542
|
+
}
|
|
543
|
+
var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
544
|
+
function extensionName(command) {
|
|
545
|
+
const m = /^CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?("[^"]+"|[\w$]+)/i.exec(command);
|
|
546
|
+
return (m?.[1] ?? "?").replace(/"/g, "");
|
|
547
|
+
}
|
|
548
|
+
function summariseCommand(command) {
|
|
549
|
+
const firstLine = command.split("\n")[0].replace(/\s*\($/, "").replace(/;$/, "");
|
|
550
|
+
if (/^COPY\s/i.test(firstLine)) return `data for ${firstLine.split(/\s+/)[1]}`;
|
|
551
|
+
return firstLine.length > 100 ? `${firstLine.slice(0, 97)}\u2026` : firstLine;
|
|
552
|
+
}
|
|
553
|
+
async function installRemoteExtensions(remoteUrl, localDbUrl, excludeSchemas) {
|
|
554
|
+
const installed = [];
|
|
555
|
+
if (excludeSchemas.length === 0) return { installed };
|
|
556
|
+
const remote = new pg.Client(pgClientConfig(remoteUrl));
|
|
557
|
+
let wanted = [];
|
|
558
|
+
try {
|
|
559
|
+
await remote.connect();
|
|
560
|
+
const { rows } = await remote.query(
|
|
561
|
+
`SELECT e.extname, n.nspname AS schema
|
|
562
|
+
FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace
|
|
563
|
+
WHERE n.nspname = ANY($1::text[])
|
|
564
|
+
AND n.nspname NOT LIKE 'pg\\_%' AND n.nspname <> 'information_schema'
|
|
565
|
+
ORDER BY e.extname`,
|
|
566
|
+
[excludeSchemas]
|
|
567
|
+
);
|
|
568
|
+
wanted = rows;
|
|
569
|
+
} catch {
|
|
570
|
+
return { installed };
|
|
571
|
+
} finally {
|
|
572
|
+
await remote.end();
|
|
573
|
+
}
|
|
574
|
+
const local = new pg.Client(pgClientConfig(localDbUrl));
|
|
575
|
+
try {
|
|
576
|
+
await local.connect();
|
|
577
|
+
const { rows } = await local.query("SELECT name FROM pg_available_extensions");
|
|
578
|
+
const available = new Set(rows.map((r) => r.name));
|
|
579
|
+
for (const { extname, schema } of wanted) {
|
|
580
|
+
if (!available.has(extname)) continue;
|
|
581
|
+
try {
|
|
582
|
+
await local.query(`CREATE SCHEMA IF NOT EXISTS ${quoteName(schema)}`);
|
|
583
|
+
await local.query(`CREATE EXTENSION IF NOT EXISTS ${quoteName(extname)} WITH SCHEMA ${quoteName(schema)} CASCADE`);
|
|
584
|
+
installed.push(extname);
|
|
585
|
+
} catch {
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
} finally {
|
|
589
|
+
await local.end();
|
|
590
|
+
}
|
|
591
|
+
return { installed };
|
|
592
|
+
}
|
|
593
|
+
async function isCloneDatabase(dbUrl, cwd = process.cwd()) {
|
|
594
|
+
if (!dbUrl) return false;
|
|
595
|
+
let dbName;
|
|
596
|
+
try {
|
|
597
|
+
dbName = new URL(dbUrl).pathname.replace(/^\//, "");
|
|
598
|
+
} catch {
|
|
599
|
+
return false;
|
|
600
|
+
}
|
|
601
|
+
if (!dbName) return false;
|
|
602
|
+
if (dbName.startsWith(BRANCH_DB_PREFIX)) return true;
|
|
603
|
+
try {
|
|
604
|
+
const manifest = await loadManifest(cwd);
|
|
605
|
+
return manifest.branches.some((b) => b.dbName === dbName);
|
|
606
|
+
} catch {
|
|
607
|
+
return false;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
var SUPABASE_SUBSTRATE_SCHEMAS = ["auth", "storage"];
|
|
611
|
+
async function sourceLooksLikeCloneOf(sourceUrl, targetUrl, queryFn = pgQuery) {
|
|
612
|
+
if (!sourceUrl || !targetUrl) return false;
|
|
613
|
+
const query = `SELECT count(*)::int AS n FROM information_schema.schemata
|
|
614
|
+
WHERE schema_name = ANY($1::text[])`;
|
|
615
|
+
try {
|
|
616
|
+
const [source, target] = await Promise.all([
|
|
617
|
+
queryFn(sourceUrl, query, [[...SUPABASE_SUBSTRATE_SCHEMAS]]),
|
|
618
|
+
queryFn(targetUrl, query, [[...SUPABASE_SUBSTRATE_SCHEMAS]])
|
|
619
|
+
]);
|
|
620
|
+
const sourceHas = source[0]?.n ?? 0;
|
|
621
|
+
const targetHas = target[0]?.n ?? 0;
|
|
622
|
+
return targetHas > 0 && sourceHas === 0;
|
|
623
|
+
} catch {
|
|
624
|
+
return false;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
export {
|
|
629
|
+
BRANCH_DB_PREFIX,
|
|
630
|
+
branchDbName,
|
|
631
|
+
replaceDbName,
|
|
632
|
+
loadManifest,
|
|
633
|
+
createBranch,
|
|
634
|
+
listBranches,
|
|
635
|
+
reconcileClones,
|
|
636
|
+
addBranchToManifest,
|
|
637
|
+
deleteBranch,
|
|
638
|
+
cloneRemoteToLocal,
|
|
639
|
+
isCloneDatabase,
|
|
640
|
+
sourceLooksLikeCloneOf
|
|
641
|
+
};
|
|
642
|
+
//# sourceMappingURL=chunk-5QQBTLWO.js.map
|