@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,336 @@
|
|
|
1
|
+
// src/defaults.ts
|
|
2
|
+
var DEFAULT_IGNORE_SCHEMAS = [
|
|
3
|
+
"auth",
|
|
4
|
+
"storage",
|
|
5
|
+
"realtime",
|
|
6
|
+
// Supabase's own realtime internals live in _realtime (underscore), a
|
|
7
|
+
// different schema from 'realtime'. Its tables are owned by supabase_admin,
|
|
8
|
+
// so reporting "RLS not enabled" on them is a finding nobody can act on —
|
|
9
|
+
// it dragged the posture score down with unfixable noise.
|
|
10
|
+
"_realtime",
|
|
11
|
+
"vault",
|
|
12
|
+
"net",
|
|
13
|
+
"graphql_public",
|
|
14
|
+
"supabase_migrations",
|
|
15
|
+
"pgsodium",
|
|
16
|
+
"pgtle",
|
|
17
|
+
"supabase_functions",
|
|
18
|
+
"extensions",
|
|
19
|
+
"pg_catalog",
|
|
20
|
+
"information_schema"
|
|
21
|
+
];
|
|
22
|
+
var SUPABASE_PLATFORM_SCHEMAS = [
|
|
23
|
+
...DEFAULT_IGNORE_SCHEMAS,
|
|
24
|
+
"cron",
|
|
25
|
+
"pgbouncer",
|
|
26
|
+
"graphql"
|
|
27
|
+
];
|
|
28
|
+
function schemaDiffIgnores(ignoreSchemas = DEFAULT_IGNORE_SCHEMAS) {
|
|
29
|
+
return [.../* @__PURE__ */ new Set([
|
|
30
|
+
...ignoreSchemas,
|
|
31
|
+
...SUPABASE_PLATFORM_SCHEMAS.filter((s) => !DEFAULT_IGNORE_SCHEMAS.includes(s)),
|
|
32
|
+
"_realtime",
|
|
33
|
+
"_analytics",
|
|
34
|
+
"pgsodium_masks"
|
|
35
|
+
])];
|
|
36
|
+
}
|
|
37
|
+
var INIT_HINTS = {
|
|
38
|
+
DB_URL: [
|
|
39
|
+
' In Supabase: click "Connect" (top bar) -> Direct -> Session pooler -> URI -> copy the Connection string.',
|
|
40
|
+
" Format: postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres\n"
|
|
41
|
+
],
|
|
42
|
+
PROJECT_URL: [
|
|
43
|
+
" Dashboard overview \u2192 click Copy \u2192 Project URL, or Project Settings \u2192 General \u2192 Project ID."
|
|
44
|
+
],
|
|
45
|
+
ACCESS_TOKEN: [
|
|
46
|
+
" supabase.com/dashboard/account/tokens \u2192 Generate new token.",
|
|
47
|
+
" This is a personal access token for the Supabase Management API (auth config, edge functions).\n"
|
|
48
|
+
],
|
|
49
|
+
DATA_TABLES: [
|
|
50
|
+
" Reference-data tables are rows that should be identical across environments",
|
|
51
|
+
" (e.g. countries, currencies, feature_flags, plans).\n"
|
|
52
|
+
]
|
|
53
|
+
};
|
|
54
|
+
var RELATION_NOT_FOUND = "does not exist";
|
|
55
|
+
var CLONE_NOISE_CHECKS = [
|
|
56
|
+
"storage",
|
|
57
|
+
"auth",
|
|
58
|
+
"edge-functions",
|
|
59
|
+
"vault",
|
|
60
|
+
"realtime",
|
|
61
|
+
// different schema from 'realtime'. Its tables are owned by supabase_admin,
|
|
62
|
+
// so reporting "RLS not enabled" on them is a finding nobody can act on —
|
|
63
|
+
// it dragged the posture score down with unfixable noise.
|
|
64
|
+
"roles"
|
|
65
|
+
];
|
|
66
|
+
var CLONE_SKIP_FLAGS = CLONE_NOISE_CHECKS.map((c2) => `--skip=${c2}`).join(" ");
|
|
67
|
+
|
|
68
|
+
// src/config.ts
|
|
69
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
70
|
+
import { resolve as resolve2 } from "path";
|
|
71
|
+
|
|
72
|
+
// src/env-loader.ts
|
|
73
|
+
import { readFile } from "fs/promises";
|
|
74
|
+
import { resolve } from "path";
|
|
75
|
+
import { existsSync } from "fs";
|
|
76
|
+
var ENV_FILE_PRIORITY = [
|
|
77
|
+
".env.local",
|
|
78
|
+
".env"
|
|
79
|
+
];
|
|
80
|
+
function buildEnvFilePriority(nodeEnv) {
|
|
81
|
+
if (!nodeEnv) return ENV_FILE_PRIORITY;
|
|
82
|
+
return [
|
|
83
|
+
`.env.${nodeEnv}.local`,
|
|
84
|
+
".env.local",
|
|
85
|
+
`.env.${nodeEnv}`,
|
|
86
|
+
".env"
|
|
87
|
+
];
|
|
88
|
+
}
|
|
89
|
+
function parseEnvContent(content) {
|
|
90
|
+
const result = /* @__PURE__ */ new Map();
|
|
91
|
+
for (const line of content.split("\n")) {
|
|
92
|
+
const trimmed = line.trim();
|
|
93
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
94
|
+
const eqIndex = trimmed.indexOf("=");
|
|
95
|
+
if (eqIndex < 1) continue;
|
|
96
|
+
const key = trimmed.slice(0, eqIndex).trim();
|
|
97
|
+
let value = trimmed.slice(eqIndex + 1).trim();
|
|
98
|
+
if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
|
|
99
|
+
value = value.slice(1, -1);
|
|
100
|
+
}
|
|
101
|
+
result.set(key, value);
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
async function loadEnvFiles(cwd = process.cwd()) {
|
|
106
|
+
const nodeEnv = process.env.NODE_ENV;
|
|
107
|
+
const candidates = buildEnvFilePriority(nodeEnv);
|
|
108
|
+
const loaded = [];
|
|
109
|
+
let injected = 0;
|
|
110
|
+
const seen = /* @__PURE__ */ new Set();
|
|
111
|
+
for (const candidate of candidates) {
|
|
112
|
+
const fullPath = resolve(cwd, candidate);
|
|
113
|
+
if (!existsSync(fullPath)) continue;
|
|
114
|
+
let content;
|
|
115
|
+
try {
|
|
116
|
+
content = await readFile(fullPath, "utf-8");
|
|
117
|
+
} catch {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
loaded.push(candidate);
|
|
121
|
+
const entries = parseEnvContent(content);
|
|
122
|
+
for (const [key, value] of entries) {
|
|
123
|
+
if (key in process.env || seen.has(key)) continue;
|
|
124
|
+
process.env[key] = value;
|
|
125
|
+
seen.add(key);
|
|
126
|
+
injected++;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return { loaded, injected };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/config.ts
|
|
133
|
+
var CONFIG_FILENAME = "supaforge.config.json";
|
|
134
|
+
var ENV_VAR_RE = /\$\{([^}]+)\}|\$([A-Z_][A-Z0-9_]*)/gi;
|
|
135
|
+
function expandEnvVars(value) {
|
|
136
|
+
return value.replace(ENV_VAR_RE, (match, braced, bare) => {
|
|
137
|
+
const name = braced ?? bare;
|
|
138
|
+
return process.env[name] ?? match;
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
function parseProjectRef(value) {
|
|
142
|
+
const trimmed = value.trim();
|
|
143
|
+
try {
|
|
144
|
+
const url = new URL(trimmed);
|
|
145
|
+
const match = url.hostname.match(/^([^.]+)\.supabase\.co$/);
|
|
146
|
+
if (match) return match[1];
|
|
147
|
+
} catch {
|
|
148
|
+
}
|
|
149
|
+
return trimmed;
|
|
150
|
+
}
|
|
151
|
+
function expandEnvironments(environments) {
|
|
152
|
+
const result = {};
|
|
153
|
+
for (const [name, env] of Object.entries(environments)) {
|
|
154
|
+
result[name] = {
|
|
155
|
+
...env,
|
|
156
|
+
dbUrl: expandEnvVars(env.dbUrl),
|
|
157
|
+
...env.accessToken ? { accessToken: expandEnvVars(env.accessToken) } : {},
|
|
158
|
+
...env.projectRef ? { projectRef: parseProjectRef(env.projectRef) } : {}
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
async function loadConfig(cwd = process.cwd()) {
|
|
164
|
+
await loadEnvFiles(cwd);
|
|
165
|
+
const configPath = resolve2(cwd, CONFIG_FILENAME);
|
|
166
|
+
const raw = await readFile2(configPath, "utf-8");
|
|
167
|
+
const config = JSON.parse(raw);
|
|
168
|
+
return resolveConfig(config);
|
|
169
|
+
}
|
|
170
|
+
function resolveConfig(config) {
|
|
171
|
+
return {
|
|
172
|
+
...config,
|
|
173
|
+
environments: expandEnvironments(config.environments),
|
|
174
|
+
ignoreSchemas: config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function validateConfig(config) {
|
|
178
|
+
const errors = [];
|
|
179
|
+
if (!config.environments || typeof config.environments !== "object") {
|
|
180
|
+
errors.push("environments is required and must be an object");
|
|
181
|
+
return errors;
|
|
182
|
+
}
|
|
183
|
+
if (Object.keys(config.environments).length < 2) {
|
|
184
|
+
errors.push("At least two environments are required");
|
|
185
|
+
}
|
|
186
|
+
if (!config.source) errors.push('"source" environment name is required');
|
|
187
|
+
if (!config.target) errors.push('"target" environment name is required');
|
|
188
|
+
if (config.source && !config.environments[config.source]) {
|
|
189
|
+
errors.push(`Source environment "${config.source}" not found in environments`);
|
|
190
|
+
}
|
|
191
|
+
if (config.target && !config.environments[config.target]) {
|
|
192
|
+
errors.push(`Target environment "${config.target}" not found in environments`);
|
|
193
|
+
}
|
|
194
|
+
if (config.source && config.target && config.source === config.target) {
|
|
195
|
+
errors.push("Source and target must be different environments");
|
|
196
|
+
}
|
|
197
|
+
for (const [name, env] of Object.entries(config.environments)) {
|
|
198
|
+
if (!env.dbUrl) errors.push(`Environment "${name}" is missing dbUrl`);
|
|
199
|
+
}
|
|
200
|
+
return errors;
|
|
201
|
+
}
|
|
202
|
+
function validateSingleEnvConfig(config, envName) {
|
|
203
|
+
const errors = [];
|
|
204
|
+
if (!config.environments || typeof config.environments !== "object") {
|
|
205
|
+
errors.push("environments is required and must be an object");
|
|
206
|
+
return errors;
|
|
207
|
+
}
|
|
208
|
+
if (!config.environments[envName]) {
|
|
209
|
+
errors.push(`Environment "${envName}" not found in environments`);
|
|
210
|
+
return errors;
|
|
211
|
+
}
|
|
212
|
+
if (!config.environments[envName].dbUrl) {
|
|
213
|
+
errors.push(`Environment "${envName}" is missing dbUrl`);
|
|
214
|
+
}
|
|
215
|
+
return errors;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// src/constants.ts
|
|
219
|
+
var SUPAFORGE_DIR = ".supaforge";
|
|
220
|
+
var SNAPSHOTS_SUBDIR = "snapshots";
|
|
221
|
+
var MIGRATIONS_SUBDIR = "migrations";
|
|
222
|
+
var BRANCHES_FILE = `${SUPAFORGE_DIR}/branches.json`;
|
|
223
|
+
var SUPABASE_MGMT_API = "https://api.supabase.com/v1/projects";
|
|
224
|
+
var DBDIFF_EXEC_TIMEOUT_MS = 6e5;
|
|
225
|
+
var DB_CONNECT_TIMEOUT_MS = 15e3;
|
|
226
|
+
var DB_PROBE_TIMEOUT_MS = 15e3;
|
|
227
|
+
var DBDIFF_MAX_BUFFER = 10 * 1024 * 1024;
|
|
228
|
+
var PG_PIPELINE_TIMEOUT_MS = 18e5;
|
|
229
|
+
var CLONE_PROGRESS_INTERVAL_MS = 1e3;
|
|
230
|
+
var RUNTIME_DETECT_TIMEOUT_MS = 5e3;
|
|
231
|
+
var CONTAINER_RM_TIMEOUT_MS = 1e4;
|
|
232
|
+
var CONTAINER_START_TIMEOUT_MS = 6e4;
|
|
233
|
+
var SCORE_PENALTY_CRITICAL = 15;
|
|
234
|
+
var SCORE_PENALTY_WARNING = 5;
|
|
235
|
+
var SCORE_PENALTY_INFO = 1;
|
|
236
|
+
var SCORE_PENALTY_ERROR = 3;
|
|
237
|
+
var SCORE_MAX = 100;
|
|
238
|
+
var CHECK_LINE_PADDING = 40;
|
|
239
|
+
var CLONE_EXTRA_EXCLUDE_SCHEMAS = [
|
|
240
|
+
"graphql",
|
|
241
|
+
"_realtime",
|
|
242
|
+
"_analytics",
|
|
243
|
+
"pgsodium_masks"
|
|
244
|
+
];
|
|
245
|
+
var MIGRATIONS_SCHEMA = "supabase_migrations";
|
|
246
|
+
var MIGRATIONS_TABLE_NAME = "schema_migrations";
|
|
247
|
+
var MIGRATIONS_TABLE = `${MIGRATIONS_SCHEMA}.${MIGRATIONS_TABLE_NAME}`;
|
|
248
|
+
var STORAGE_LIST_LIMIT = 1e3;
|
|
249
|
+
var RUN_LOG_DIR = ".supaforge";
|
|
250
|
+
var RUN_LOG_FILE = "run-log.jsonl";
|
|
251
|
+
var RUN_LOG_MAX_ENTRIES = 500;
|
|
252
|
+
|
|
253
|
+
// src/ui.ts
|
|
254
|
+
import { colorize } from "@oclif/core/ux";
|
|
255
|
+
var c = (style, text) => colorize(style, text);
|
|
256
|
+
var ok = (text) => c("green", text);
|
|
257
|
+
var warn = (text) => c("yellow", text);
|
|
258
|
+
var dim = (text) => c("dim", text);
|
|
259
|
+
var cmd = (text) => c("cyan", text);
|
|
260
|
+
var bold = (text) => c("bold", text);
|
|
261
|
+
function printHints(lines, log) {
|
|
262
|
+
for (const line of lines) {
|
|
263
|
+
log(dim(line));
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
var BANNER = `
|
|
267
|
+
\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
|
|
268
|
+
\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D
|
|
269
|
+
\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557
|
|
270
|
+
\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D
|
|
271
|
+
\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557
|
|
272
|
+
\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D`;
|
|
273
|
+
var TAGLINE = " precision developer tools, built to last";
|
|
274
|
+
var CREDIT = "by Akal";
|
|
275
|
+
var BANNER_MIN_WIDTH = 80;
|
|
276
|
+
function printBanner(log) {
|
|
277
|
+
const cols = process.stdout.columns ?? BANNER_MIN_WIDTH;
|
|
278
|
+
if (cols >= BANNER_MIN_WIDTH) {
|
|
279
|
+
log(c("greenBright", BANNER));
|
|
280
|
+
} else {
|
|
281
|
+
log(c("greenBright", "\n \u2692 SupaForge"));
|
|
282
|
+
}
|
|
283
|
+
log(` ${dim(TAGLINE)} ${dim("\xB7")} ${dim(CREDIT)}
|
|
284
|
+
`);
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
export {
|
|
288
|
+
DEFAULT_IGNORE_SCHEMAS,
|
|
289
|
+
SUPABASE_PLATFORM_SCHEMAS,
|
|
290
|
+
schemaDiffIgnores,
|
|
291
|
+
INIT_HINTS,
|
|
292
|
+
RELATION_NOT_FOUND,
|
|
293
|
+
CLONE_SKIP_FLAGS,
|
|
294
|
+
expandEnvVars,
|
|
295
|
+
parseProjectRef,
|
|
296
|
+
loadConfig,
|
|
297
|
+
resolveConfig,
|
|
298
|
+
validateConfig,
|
|
299
|
+
validateSingleEnvConfig,
|
|
300
|
+
SUPAFORGE_DIR,
|
|
301
|
+
SNAPSHOTS_SUBDIR,
|
|
302
|
+
MIGRATIONS_SUBDIR,
|
|
303
|
+
BRANCHES_FILE,
|
|
304
|
+
SUPABASE_MGMT_API,
|
|
305
|
+
DBDIFF_EXEC_TIMEOUT_MS,
|
|
306
|
+
DB_CONNECT_TIMEOUT_MS,
|
|
307
|
+
DB_PROBE_TIMEOUT_MS,
|
|
308
|
+
DBDIFF_MAX_BUFFER,
|
|
309
|
+
PG_PIPELINE_TIMEOUT_MS,
|
|
310
|
+
CLONE_PROGRESS_INTERVAL_MS,
|
|
311
|
+
RUNTIME_DETECT_TIMEOUT_MS,
|
|
312
|
+
CONTAINER_RM_TIMEOUT_MS,
|
|
313
|
+
CONTAINER_START_TIMEOUT_MS,
|
|
314
|
+
SCORE_PENALTY_CRITICAL,
|
|
315
|
+
SCORE_PENALTY_WARNING,
|
|
316
|
+
SCORE_PENALTY_INFO,
|
|
317
|
+
SCORE_PENALTY_ERROR,
|
|
318
|
+
SCORE_MAX,
|
|
319
|
+
CHECK_LINE_PADDING,
|
|
320
|
+
CLONE_EXTRA_EXCLUDE_SCHEMAS,
|
|
321
|
+
MIGRATIONS_SCHEMA,
|
|
322
|
+
MIGRATIONS_TABLE,
|
|
323
|
+
STORAGE_LIST_LIMIT,
|
|
324
|
+
RUN_LOG_DIR,
|
|
325
|
+
RUN_LOG_FILE,
|
|
326
|
+
RUN_LOG_MAX_ENTRIES,
|
|
327
|
+
c,
|
|
328
|
+
ok,
|
|
329
|
+
warn,
|
|
330
|
+
dim,
|
|
331
|
+
cmd,
|
|
332
|
+
bold,
|
|
333
|
+
printHints,
|
|
334
|
+
printBanner
|
|
335
|
+
};
|
|
336
|
+
//# sourceMappingURL=chunk-6WAMNZLO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/defaults.ts","../src/config.ts","../src/env-loader.ts","../src/constants.ts","../src/ui.ts"],"sourcesContent":["/** Supabase internal schemas to ignore by default during drift scanning. */\nexport const DEFAULT_IGNORE_SCHEMAS = [\n 'auth',\n 'storage',\n 'realtime',\n // Supabase's own realtime internals live in _realtime (underscore), a\n // different schema from 'realtime'. Its tables are owned by supabase_admin,\n // so reporting \"RLS not enabled\" on them is a finding nobody can act on —\n // it dragged the posture score down with unfixable noise.\n '_realtime',\n 'vault',\n 'net',\n 'graphql_public',\n 'supabase_migrations',\n 'pgsodium',\n 'pgtle',\n 'supabase_functions',\n 'extensions',\n 'pg_catalog',\n 'information_schema',\n]\n\n/**\n * Every schema whose contents belong to Supabase rather than the project.\n *\n * DEFAULT_IGNORE_SCHEMAS plus the ones a scan never lists because nothing in\n * them is diffed, but which still hold objects and grants a project cannot\n * recreate: pg_cron's `cron`, the pooler's `pgbouncer`, and pg_graphql's\n * `graphql`. Grants in these differ between Supabase versions, not between\n * anybody's decisions, and a restore must never clear them.\n */\nexport const SUPABASE_PLATFORM_SCHEMAS = [\n ...DEFAULT_IGNORE_SCHEMAS,\n 'cron',\n 'pgbouncer',\n 'graphql',\n]\n\n/**\n * The schemas a schema diff leaves out: the project's `ignoreSchemas`, and\n * always the platform's own — those above, and the self-hosted stack's\n * `_realtime` and `_analytics`, and pgsodium's `pgsodium_masks`. Every other\n * schema is compared.\n */\nexport function schemaDiffIgnores(ignoreSchemas: readonly string[] = DEFAULT_IGNORE_SCHEMAS): string[] {\n return [...new Set([...ignoreSchemas, ...SUPABASE_PLATFORM_SCHEMAS.filter(s => !DEFAULT_IGNORE_SCHEMAS.includes(s)),\n '_realtime', '_analytics', 'pgsodium_masks'])]\n}\n\n/** Hint text shown during `supaforge init` to guide users through the Supabase UI. */\nexport const INIT_HINTS = {\n DB_URL: [\n ' In Supabase: click \"Connect\" (top bar) -> Direct -> Session pooler -> URI -> copy the Connection string.',\n ' Format: postgresql://postgres.[ref]:[password]@aws-0-[region].pooler.supabase.com:5432/postgres\\n',\n ],\n PROJECT_URL: [\n ' Dashboard overview \\u2192 click Copy \\u2192 Project URL, or Project Settings \\u2192 General \\u2192 Project ID.',\n ],\n ACCESS_TOKEN: [\n ' supabase.com/dashboard/account/tokens \\u2192 Generate new token.',\n ' This is a personal access token for the Supabase Management API (auth config, edge functions).\\n',\n ],\n DATA_TABLES: [\n ' Reference-data tables are rows that should be identical across environments',\n ' (e.g. countries, currencies, feature_flags, plans).\\n',\n ],\n} as const\n\n/** Error fragment for a relation that simply doesn't exist (expected for optional features). */\nexport const RELATION_NOT_FOUND = 'does not exist'\n\n/**\n * The checks a local clone can only report noise for.\n *\n * A clone is vanilla PostgreSQL restored from a pg_dump: the Supabase-managed\n * layers have no local equivalent, and Postgres Roles & Grants is the same\n * story — Supabase's service roles do not exist on a plain server, so every\n * one of them reads as drift. On the diff that prompted issue #47 that was 227\n * findings, all of them clone artefacts, confirmed by a remote-to-remote diff\n * reporting zero.\n *\n * One list because the same advice was written out by hand in three places and\n * had already drifted into three different answers. Roles was in none of them:\n * it arrived as Layer 14, after the clone advice was written for a 13-layer set.\n */\nexport const CLONE_NOISE_CHECKS = [\n 'storage',\n 'auth',\n 'edge-functions',\n 'vault',\n 'realtime',\n // different schema from 'realtime'. Its tables are owned by supabase_admin,\n // so reporting \"RLS not enabled\" on them is a finding nobody can act on —\n // it dragged the posture score down with unfixable noise.\n 'roles',\n] as const\n\n/** The `--skip=` flags that suppress clone-only noise, as one command fragment. */\nexport const CLONE_SKIP_FLAGS = CLONE_NOISE_CHECKS.map(c => `--skip=${c}`).join(' ')\n","import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport type { SupaForgeConfig, EnvironmentConfig } from './types/config'\nimport { DEFAULT_IGNORE_SCHEMAS } from './defaults'\nimport { loadEnvFiles } from './env-loader'\n\nconst CONFIG_FILENAME = 'supaforge.config.json'\n\n/** Match $VAR or ${VAR} references. */\nconst ENV_VAR_RE = /\\$\\{([^}]+)\\}|\\$([A-Z_][A-Z0-9_]*)/gi\n\n/**\n * Expand $VAR and ${VAR} references in a string using process.env.\n * Returns the original token unchanged if the env var is not set.\n */\nexport function expandEnvVars(value: string): string {\n return value.replace(ENV_VAR_RE, (match, braced, bare) => {\n const name = braced ?? bare\n return process.env[name] ?? match\n })\n}\n\n/**\n * Extract the project ref from a Supabase Project URL or return the value as-is\n * if it's already a bare ref.\n *\n * Accepted formats:\n * - https://abcdef123456.supabase.co\n * - https://abcdef123456.supabase.co/\n * - abcdef123456 (bare ref, returned unchanged)\n */\nexport function parseProjectRef(value: string): string {\n const trimmed = value.trim()\n try {\n const url = new URL(trimmed)\n const match = url.hostname.match(/^([^.]+)\\.supabase\\.co$/)\n if (match) return match[1]\n } catch {\n // Not a URL — treat as bare ref\n }\n return trimmed\n}\n\n/**\n * Expand env var references in all sensitive environment fields (dbUrl, accessToken).\n * Also normalises projectRef from full URL to bare ref.\n */\nfunction expandEnvironments(\n environments: Record<string, EnvironmentConfig>,\n): Record<string, EnvironmentConfig> {\n const result: Record<string, EnvironmentConfig> = {}\n for (const [name, env] of Object.entries(environments)) {\n result[name] = {\n ...env,\n dbUrl: expandEnvVars(env.dbUrl),\n ...(env.accessToken ? { accessToken: expandEnvVars(env.accessToken) } : {}),\n ...(env.projectRef ? { projectRef: parseProjectRef(env.projectRef) } : {}),\n }\n }\n return result\n}\n\nexport async function loadConfig(cwd = process.cwd()): Promise<SupaForgeConfig> {\n await loadEnvFiles(cwd)\n const configPath = resolve(cwd, CONFIG_FILENAME)\n const raw = await readFile(configPath, 'utf-8')\n const config = JSON.parse(raw) as SupaForgeConfig\n return resolveConfig(config)\n}\n\nexport function resolveConfig(config: SupaForgeConfig): SupaForgeConfig {\n return {\n ...config,\n environments: expandEnvironments(config.environments),\n ignoreSchemas: config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS,\n }\n}\n\nexport function validateConfig(config: SupaForgeConfig): string[] {\n const errors: string[] = []\n\n if (!config.environments || typeof config.environments !== 'object') {\n errors.push('environments is required and must be an object')\n return errors\n }\n\n if (Object.keys(config.environments).length < 2) {\n errors.push('At least two environments are required')\n }\n\n if (!config.source) errors.push('\"source\" environment name is required')\n if (!config.target) errors.push('\"target\" environment name is required')\n\n if (config.source && !config.environments[config.source]) {\n errors.push(`Source environment \"${config.source}\" not found in environments`)\n }\n if (config.target && !config.environments[config.target]) {\n errors.push(`Target environment \"${config.target}\" not found in environments`)\n }\n\n if (config.source && config.target && config.source === config.target) {\n errors.push('Source and target must be different environments')\n }\n\n for (const [name, env] of Object.entries(config.environments)) {\n if (!env.dbUrl) errors.push(`Environment \"${name}\" is missing dbUrl`)\n }\n\n return errors\n}\n\n/**\n * Validate config for single-environment operations (snapshot, clone, backup, restore).\n * Only requires that the specified environment exists and has a dbUrl.\n */\nexport function validateSingleEnvConfig(config: SupaForgeConfig, envName: string): string[] {\n const errors: string[] = []\n\n if (!config.environments || typeof config.environments !== 'object') {\n errors.push('environments is required and must be an object')\n return errors\n }\n\n if (!config.environments[envName]) {\n errors.push(`Environment \"${envName}\" not found in environments`)\n return errors\n }\n\n if (!config.environments[envName].dbUrl) {\n errors.push(`Environment \"${envName}\" is missing dbUrl`)\n }\n\n return errors\n}\n","import { readFile } from 'node:fs/promises'\nimport { resolve } from 'node:path'\nimport { existsSync } from 'node:fs'\n\n/**\n * Environment file candidates in descending priority order.\n * Follows the Next.js / Vite / CRA convention:\n * .env.{NODE_ENV}.local → .env.local → .env.{NODE_ENV} → .env\n *\n * All matching files are loaded (earlier entries win for duplicate keys).\n * Files that don't exist are silently skipped.\n */\nexport const ENV_FILE_PRIORITY = [\n '.env.local',\n '.env',\n] as const\n\n/**\n * Build the prioritised .env file list, inserting NODE_ENV-specific\n * variants when NODE_ENV is set (e.g. production, staging, development).\n *\n * Returns paths in descending priority — first file wins per key.\n */\nexport function buildEnvFilePriority(nodeEnv?: string): readonly string[] {\n if (!nodeEnv) return ENV_FILE_PRIORITY\n\n // .env.{NODE_ENV}.local → .env.local → .env.{NODE_ENV} → .env\n return [\n `.env.${nodeEnv}.local`,\n '.env.local',\n `.env.${nodeEnv}`,\n '.env',\n ]\n}\n\n/**\n * Parse a single .env file into a key-value map.\n * Handles KEY=value, KEY=\"value\", KEY='value', empty lines, and # comments.\n * Multi-line values are not supported.\n */\nexport function parseEnvContent(content: string): Map<string, string> {\n const result = new Map<string, string>()\n\n for (const line of content.split('\\n')) {\n const trimmed = line.trim()\n if (!trimmed || trimmed.startsWith('#')) continue\n\n const eqIndex = trimmed.indexOf('=')\n if (eqIndex < 1) continue\n\n const key = trimmed.slice(0, eqIndex).trim()\n let value = trimmed.slice(eqIndex + 1).trim()\n\n // Strip matching quotes\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1)\n }\n\n result.set(key, value)\n }\n\n return result\n}\n\nexport interface EnvLoadResult {\n /** Files that were found and loaded, in priority order. */\n loaded: string[]\n /** Total number of env vars injected into process.env. */\n injected: number\n}\n\n/**\n * Auto-detect and load .env files into process.env.\n *\n * Standard priority (industry convention matching Next.js / Vite / CRA):\n * .env.{NODE_ENV}.local → .env.local → .env.{NODE_ENV} → .env\n *\n * Never overwrites existing process.env values — system env always wins.\n * Returns metadata about which files were loaded.\n */\nexport async function loadEnvFiles(cwd = process.cwd()): Promise<EnvLoadResult> {\n const nodeEnv = process.env.NODE_ENV\n const candidates = buildEnvFilePriority(nodeEnv)\n const loaded: string[] = []\n let injected = 0\n\n // Track keys we've already set from higher-priority files\n const seen = new Set<string>()\n\n for (const candidate of candidates) {\n const fullPath = resolve(cwd, candidate)\n if (!existsSync(fullPath)) continue\n\n let content: string\n try {\n content = await readFile(fullPath, 'utf-8')\n } catch {\n continue\n }\n\n loaded.push(candidate)\n const entries = parseEnvContent(content)\n\n for (const [key, value] of entries) {\n // System env always wins, then higher-priority files\n if (key in process.env || seen.has(key)) continue\n process.env[key] = value\n seen.add(key)\n injected++\n }\n }\n\n return { loaded, injected }\n}\n","// ─── Directory & File Paths ──────────────────────────────────────────────────\n\n/** Root directory for all SupaForge local state. */\nexport const SUPAFORGE_DIR = '.supaforge'\n\n/** Subdirectory under SUPAFORGE_DIR for snapshot storage. */\nexport const SNAPSHOTS_SUBDIR = 'snapshots'\n\n/** Subdirectory under SUPAFORGE_DIR for migration files. */\nexport const MIGRATIONS_SUBDIR = 'migrations'\n\n/** Filename for snapshot manifests. */\nexport const SNAPSHOT_MANIFEST_FILE = 'manifest.json'\n\n/** File path (relative to cwd) for branch tracking. */\nexport const BRANCHES_FILE = `${SUPAFORGE_DIR}/branches.json`\n\n// ─── Supabase Management API ────────────────────────────────────────────────\n\n/** Supabase Management API base URL for project-level endpoints. */\nexport const SUPABASE_MGMT_API = 'https://api.supabase.com/v1/projects'\n\n// ─── Timeouts ────────────────────────────────────────────────────────────────\n\n/**\n * Default timeout for @dbdiff/cli execution (5 minutes).\n *\n * Large Supabase schemas can take several minutes to diff. The previous\n * 2-minute limit silently killed the process mid-run, surfacing dbdiff's\n * last progress log line as a bogus \"error\". Override at runtime with the\n * SUPAFORGE_DBDIFF_TIMEOUT environment variable (value in seconds), or per\n * environment via checks.schema.timeout in supaforge.config.json.\n *\n * Raised from 300s: the schema pre-scan made the common case much faster, so\n * the runs still approaching the ceiling are precisely the ones that need\n * headroom, and a timeout costs the whole layer rather than degrading it.\n */\nexport const DBDIFF_EXEC_TIMEOUT_MS = 600_000\n\n/**\n * Default bound on establishing a PostgreSQL connection (15 seconds).\n *\n * `pg` defaults connectionTimeoutMillis to 0 — wait forever. That is invisible\n * for the common failures, because the socket layer errors out on its own: a\n * refused connection fails immediately, an unroutable host after the OS TCP\n * timeout. But a host that *accepts* the connection and then never completes\n * the startup handshake — a paused container, a dropped VPN tunnel, an\n * overloaded server — leaves nothing to time it out, and the command blocks\n * indefinitely with no output (issue #44).\n *\n * 15s is long enough for a slow link and short enough to fail usefully.\n * Override with SUPAFORGE_CONNECT_TIMEOUT (in seconds).\n */\nexport const DB_CONNECT_TIMEOUT_MS = 15_000\n\n/**\n * Bound on the preflight version probe (15 seconds).\n *\n * The handshake can complete on a server that then stalls before answering,\n * so bounding the connect alone still leaves a way to hang. Applied only to\n * the probe — a scan or migration query is legitimately long-running and must\n * not inherit this.\n */\nexport const DB_PROBE_TIMEOUT_MS = 15_000\n\n/** Max stdout/stderr buffer for @dbdiff/cli (10 MB). */\nexport const DBDIFF_MAX_BUFFER = 10 * 1024 * 1024\n\n/** Timeout for pg_dump | pg_restore pipeline (30 minutes). */\nexport const PG_PIPELINE_TIMEOUT_MS = 1_800_000\n\n/** Interval between progress reports during clone (1 second). */\nexport const CLONE_PROGRESS_INTERVAL_MS = 1_000\n\n/** Timeout for container runtime detection commands (5 seconds). */\nexport const RUNTIME_DETECT_TIMEOUT_MS = 5_000\n\n/** Timeout for removing stopped containers (10 seconds). */\nexport const CONTAINER_RM_TIMEOUT_MS = 10_000\n\n/** Timeout for starting a new container (60 seconds). */\nexport const CONTAINER_START_TIMEOUT_MS = 60_000\n\n// ─── Scoring Weights ─────────────────────────────────────────────────────────\n\n/** Score penalty per critical drift issue. */\nexport const SCORE_PENALTY_CRITICAL = 15\n\n/** Score penalty per warning drift issue. */\nexport const SCORE_PENALTY_WARNING = 5\n\n/** Score penalty per info drift issue. */\nexport const SCORE_PENALTY_INFO = 1\n\n/** Score penalty per errored check (cannot confirm clean). */\nexport const SCORE_PENALTY_ERROR = 3\n\n/** Maximum (perfect) drift score. */\nexport const SCORE_MAX = 100\n\n// ─── Render / Formatting ─────────────────────────────────────────────────────\n\n/** Padding width for check status lines in terminal output. */\nexport const CHECK_LINE_PADDING = 40\n\n// ─── Clone-specific Schemas ──────────────────────────────────────────────────\n\n/**\n * Additional Supabase-internal schemas to exclude from pg_dump when cloning.\n * These reference extensions (pg_graphql, pgsodium, supautils, etc.)\n * unavailable in vanilla PostgreSQL.\n *\n * Combined with DEFAULT_IGNORE_SCHEMAS from defaults.ts to form the\n * full exclusion list for `supaforge clone`.\n */\nexport const CLONE_EXTRA_EXCLUDE_SCHEMAS = [\n 'graphql',\n '_realtime',\n '_analytics',\n 'pgsodium_masks',\n]\n\n// ─── Migration Tracking ──────────────────────────────────────────────────────\n\n/** Schema name for Supabase migration tracking. */\nexport const MIGRATIONS_SCHEMA = 'supabase_migrations'\n\n/** Unqualified table name for migration records. */\nexport const MIGRATIONS_TABLE_NAME = 'schema_migrations'\n\n/** Fully qualified migration tracking table name. */\nexport const MIGRATIONS_TABLE = `${MIGRATIONS_SCHEMA}.${MIGRATIONS_TABLE_NAME}`\n\n// ─── Storage ─────────────────────────────────────────────────────────────────\n\n/** Maximum number of objects to list per Supabase Storage API call. */\nexport const STORAGE_LIST_LIMIT = 1000\n\n// ─── Run Log ─────────────────────────────────────────────────────────────────\n\n/** Directory (relative to home) where the run log is stored. */\nexport const RUN_LOG_DIR = '.supaforge'\n\n/** Filename for the run log. */\nexport const RUN_LOG_FILE = 'run-log.jsonl'\n\n/** Maximum number of run log entries to keep. */\nexport const RUN_LOG_MAX_ENTRIES = 500\n","import { colorize } from '@oclif/core/ux'\n\ntype Style = Parameters<typeof colorize>[0]\n\n/** Apply an oclif color/style to text. */\nexport const c = (style: Style, text: string): string => colorize(style, text)\n\n/** Green text for success messages. */\nexport const ok = (text: string): string => c('green', text)\n\n/** Yellow text for warnings. */\nexport const warn = (text: string): string => c('yellow', text)\n\n/** Dim text for hints and secondary info. */\nexport const dim = (text: string): string => c('dim', text)\n\n/** Cyan text for commands and URIs. */\nexport const cmd = (text: string): string => c('cyan', text)\n\n/** Bold text for headings and emphasis. */\nexport const bold = (text: string): string => c('bold', text)\n\n/** Log an array of hint lines in dim. */\nexport function printHints(lines: readonly string[], log: (msg: string) => void): void {\n for (const line of lines) {\n log(dim(line))\n }\n}\n\nconst BANNER = `\n ███████╗██╗ ██╗██████╗ █████╗ ███████╗ ██████╗ ██████╗ ██████╗ ███████╗\n ██╔════╝██║ ██║██╔══██╗██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝ ██╔════╝\n ███████╗██║ ██║██████╔╝███████║█████╗ ██║ ██║██████╔╝██║ ███╗█████╗\n ╚════██║██║ ██║██╔═══╝ ██╔══██║██╔══╝ ██║ ██║██╔══██╗██║ ██║██╔══╝\n ███████║╚██████╔╝██║ ██║ ██║██║ ╚██████╔╝██║ ██║╚██████╔╝███████╗\n ╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝`\n\nconst TAGLINE = ' precision developer tools, built to last'\nconst CREDIT = 'by Akal'\n\n/** Minimum terminal width needed to render the full ASCII banner without wrapping. */\nconst BANNER_MIN_WIDTH = 80\n\n/** Print the SupaForge ASCII banner. Falls back to a compact header on narrow terminals. */\nexport function printBanner(log: (msg: string) => void): void {\n const cols = process.stdout.columns ?? BANNER_MIN_WIDTH\n if (cols >= BANNER_MIN_WIDTH) {\n log(c('greenBright', BANNER))\n } else {\n log(c('greenBright', '\\n ⚒ SupaForge'))\n }\n log(` ${dim(TAGLINE)} ${dim('·')} ${dim(CREDIT)}\\n`)\n}\n"],"mappings":";AACO,IAAM,yBAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAWO,IAAM,4BAA4B;AAAA,EACvC,GAAG;AAAA,EACH;AAAA,EACA;AAAA,EACA;AACF;AAQO,SAAS,kBAAkB,gBAAmC,wBAAkC;AACrG,SAAO,CAAC,GAAG,oBAAI,IAAI;AAAA,IAAC,GAAG;AAAA,IAAe,GAAG,0BAA0B,OAAO,OAAK,CAAC,uBAAuB,SAAS,CAAC,CAAC;AAAA,IAChH;AAAA,IAAa;AAAA,IAAc;AAAA,EAAgB,CAAC,CAAC;AACjD;AAGO,IAAM,aAAa;AAAA,EACxB,QAAQ;AAAA,IACN;AAAA,IACA;AAAA,EACF;AAAA,EACA,aAAa;AAAA,IACX;AAAA,EACF;AAAA,EACA,cAAc;AAAA,IACZ;AAAA,IACA;AAAA,EACF;AAAA,EACA,aAAa;AAAA,IACX;AAAA,IACA;AAAA,EACF;AACF;AAGO,IAAM,qBAAqB;AAgB3B,IAAM,qB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SAAS,gBAAgB;AAKlB,IAAM,IAAI,CAAC,OAAc,SAAyB,SAAS,OAAO,IAAI;AAGtE,IAAM,KAAK,CAAC,SAAyB,EAAE,SAAS,IAAI;AAGpD,IAAM,OAAO,CAAC,SAAyB,EAAE,UAAU,IAAI;AAGvD,IAAM,MAAM,CAAC,SAAyB,EAAE,OAAO,IAAI;AAGnD,IAAM,MAAM,CAAC,SAAyB,EAAE,QAAQ,IAAI;AAGpD,IAAM,OAAO,CAAC,SAAyB,EAAE,QAAQ,IAAI;AAGrD,SAAS,WAAW,OAA0B,KAAkC;AACrF,aAAW,QAAQ,OAAO;AACxB,QAAI,IAAI,IAAI,CAAC;AAAA,EACf;AACF;AAEA,IAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQf,IAAM,UAAU;AAChB,IAAM,SAAS;AAGf,IAAM,mBAAmB;AAGlB,SAAS,YAAY,KAAkC;AAC5D,QAAM,OAAO,QAAQ,OAAO,WAAW;AACvC,MAAI,QAAQ,kBAAkB;AAC5B,QAAI,EAAE,eAAe,MAAM,CAAC;AAAA,EAC9B,OAAO;AACL,QAAI,EAAE,eAAe,uBAAkB,CAAC;AAAA,EAC1C;AACA,MAAI,KAAK,IAAI,OAAO,CAAC,KAAK,IAAI,MAAG,CAAC,KAAK,IAAI,MAAM,CAAC;AAAA,CAAI;AACxD;","names":["c","readFile","resolve","resolve","readFile"]}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ensureMigrationsTable,
|
|
3
|
+
getAppliedVersions,
|
|
4
|
+
getPendingMigrations,
|
|
5
|
+
runMigration
|
|
6
|
+
} from "./chunk-VMTBLHN2.js";
|
|
7
|
+
import {
|
|
8
|
+
isDestructiveSql
|
|
9
|
+
} from "./chunk-VOXZWQ3N.js";
|
|
10
|
+
import {
|
|
11
|
+
splitSqlStatements
|
|
12
|
+
} from "./chunk-G2DIPIYU.js";
|
|
13
|
+
import {
|
|
14
|
+
BaseCommand
|
|
15
|
+
} from "./chunk-SF3YA42C.js";
|
|
16
|
+
import {
|
|
17
|
+
errMsg
|
|
18
|
+
} from "./chunk-X6V2GGDZ.js";
|
|
19
|
+
import {
|
|
20
|
+
bold,
|
|
21
|
+
dim,
|
|
22
|
+
ok,
|
|
23
|
+
warn
|
|
24
|
+
} from "./chunk-6WAMNZLO.js";
|
|
25
|
+
|
|
26
|
+
// src/commands/migrate/run.ts
|
|
27
|
+
import { Flags } from "@oclif/core";
|
|
28
|
+
import { readFile } from "fs/promises";
|
|
29
|
+
var MigrateRun = class _MigrateRun extends BaseCommand {
|
|
30
|
+
static description = "Execute pending migrations against a Supabase environment";
|
|
31
|
+
static examples = [
|
|
32
|
+
"<%= config.bin %> migrate run --env=prod",
|
|
33
|
+
"<%= config.bin %> migrate run --env=prod --apply",
|
|
34
|
+
"<%= config.bin %> migrate run --env=prod --up-to=003 --apply"
|
|
35
|
+
];
|
|
36
|
+
static flags = {
|
|
37
|
+
env: Flags.string({
|
|
38
|
+
char: "e",
|
|
39
|
+
description: "Target environment to run migrations against"
|
|
40
|
+
}),
|
|
41
|
+
apply: Flags.boolean({
|
|
42
|
+
description: "Execute the pending migrations (previews without it)",
|
|
43
|
+
default: false,
|
|
44
|
+
exclusive: ["dry-run"]
|
|
45
|
+
}),
|
|
46
|
+
"dry-run": Flags.boolean({
|
|
47
|
+
description: "Preview which migrations would run (the default; kept for existing scripts)",
|
|
48
|
+
default: false
|
|
49
|
+
}),
|
|
50
|
+
"up-to": Flags.string({
|
|
51
|
+
description: "Stop after applying this migration version (inclusive)"
|
|
52
|
+
}),
|
|
53
|
+
"allow-destructive": Flags.boolean({
|
|
54
|
+
description: "Permit migrations that drop tables or columns, delete rows, or drop policies",
|
|
55
|
+
default: false
|
|
56
|
+
})
|
|
57
|
+
};
|
|
58
|
+
async run() {
|
|
59
|
+
const { flags } = await this.parse(_MigrateRun);
|
|
60
|
+
const config = await this.loadConfigOrFail();
|
|
61
|
+
const { envName, env } = this.resolveEnv(config, flags.env);
|
|
62
|
+
const dir = this.resolveMigrationsDir(config);
|
|
63
|
+
const pre = this.createPreflight("Migrate run preflight checks").addDatabase("Target", envName, env.dbUrl);
|
|
64
|
+
await this.runPreflight(pre, "Migrate run");
|
|
65
|
+
this.log(`${bold("migrate run")} \u2192 ${dim(envName)} (${dim(this.redactUrl(env.dbUrl))})
|
|
66
|
+
`);
|
|
67
|
+
if (flags.apply) await ensureMigrationsTable(env.dbUrl);
|
|
68
|
+
const applied = await getAppliedVersions(env.dbUrl);
|
|
69
|
+
let pending = await getPendingMigrations(dir, applied);
|
|
70
|
+
if (pending.length === 0) {
|
|
71
|
+
this.log(`${ok("All migrations are up to date.")} \u2713`);
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (flags["up-to"]) {
|
|
75
|
+
const cutoff = flags["up-to"];
|
|
76
|
+
const idx = pending.findIndex((m) => m.version === cutoff);
|
|
77
|
+
if (idx === -1) {
|
|
78
|
+
if (applied.has(cutoff)) {
|
|
79
|
+
this.log(`${ok(`Version "${cutoff}" is already applied.`)} \u2713`);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
this.error(`Version "${cutoff}" not found in pending migrations. Available: ${pending.map((m) => m.version).join(", ")}`);
|
|
83
|
+
}
|
|
84
|
+
pending = pending.slice(0, idx + 1);
|
|
85
|
+
}
|
|
86
|
+
this.log(`Found ${bold(String(pending.length))} pending migration(s):
|
|
87
|
+
`);
|
|
88
|
+
for (const m of pending) {
|
|
89
|
+
this.log(` ${dim("\u25CB")} ${m.filename}`);
|
|
90
|
+
}
|
|
91
|
+
const destructive = flags["allow-destructive"] ? [] : await findDestructiveStatements(pending);
|
|
92
|
+
if (destructive.length > 0) {
|
|
93
|
+
this.log("");
|
|
94
|
+
this.log(warn(`${destructive.length} destructive statement(s) in the pending migrations:`));
|
|
95
|
+
for (const { filename, sql } of destructive) {
|
|
96
|
+
this.log(` ${warn("\u2717")} ${filename}`);
|
|
97
|
+
this.log(` ${dim(truncateSql(sql))}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (!flags.apply) {
|
|
101
|
+
this.log(`
|
|
102
|
+
${dim("Preview only \u2014 nothing was applied.")} Re-run with ${bold("--apply")} to execute` + (destructive.length > 0 ? `, and ${bold("--allow-destructive")} for the statements above.` : "."));
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (destructive.length > 0) {
|
|
106
|
+
this.log(`
|
|
107
|
+
${warn("Nothing was applied.")} Re-run with ${bold("--allow-destructive")} to proceed.`);
|
|
108
|
+
this.exit(1);
|
|
109
|
+
}
|
|
110
|
+
this.log("");
|
|
111
|
+
let applied_count = 0;
|
|
112
|
+
for (const migration of pending) {
|
|
113
|
+
try {
|
|
114
|
+
const result = await runMigration(env.dbUrl, migration);
|
|
115
|
+
applied_count++;
|
|
116
|
+
this.log(` ${ok("\u2713")} ${result.filename} ${dim(`(${result.durationMs}ms)`)}`);
|
|
117
|
+
} catch (err) {
|
|
118
|
+
this.log(` ${warn("\u2717")} ${migration.filename}: ${err instanceof Error ? err.message : String(err)}`);
|
|
119
|
+
this.log(`
|
|
120
|
+
${warn(`Stopped after ${applied_count} migration(s) due to error.`)}`);
|
|
121
|
+
this.exit(1);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
this.log(`
|
|
125
|
+
${ok(`Applied ${applied_count} migration(s) successfully.`)} \u2713`);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
async function findDestructiveStatements(migrations, readFileFn = (path) => readFile(path, "utf-8")) {
|
|
129
|
+
const found = [];
|
|
130
|
+
for (const migration of migrations) {
|
|
131
|
+
let sql;
|
|
132
|
+
try {
|
|
133
|
+
sql = await readFileFn(migration.path);
|
|
134
|
+
} catch (err) {
|
|
135
|
+
found.push({ filename: migration.filename, sql: `<unreadable: ${errMsg(err)}>` });
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
for (const statement of splitSqlStatements(sql)) {
|
|
139
|
+
if (isDestructiveSql(statement)) {
|
|
140
|
+
found.push({ filename: migration.filename, sql: statement });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return found;
|
|
145
|
+
}
|
|
146
|
+
function truncateSql(sql) {
|
|
147
|
+
const oneLine = sql.split("\n").filter((l) => !/^\s*--/.test(l)).join(" ").replace(/\s+/g, " ").trim();
|
|
148
|
+
return oneLine.length > 100 ? `${oneLine.slice(0, 97)}...` : oneLine;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export {
|
|
152
|
+
MigrateRun,
|
|
153
|
+
findDestructiveStatements,
|
|
154
|
+
truncateSql
|
|
155
|
+
};
|
|
156
|
+
//# sourceMappingURL=chunk-BHYLBKYD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/migrate/run.ts"],"sourcesContent":["import { Flags } from '@oclif/core'\nimport { BaseCommand } from '../../base-command.js'\nimport {\n ensureMigrationsTable,\n getAppliedVersions,\n getPendingMigrations,\n runMigration,\n} from '../../migrate.js'\nimport { ok, warn, dim, bold } from '../../ui.js'\nimport { isDestructiveSql } from '../../dbdiff.js'\nimport { splitSqlStatements } from '../../utils/sql-split.js'\nimport { readFile } from 'node:fs/promises'\nimport { errMsg } from '../../utils/error.js'\n\n/**\n * Execute pending migrations against a Supabase environment.\n *\n * Reads local migration files, executes unapplied ones in order,\n * and records each in supabase_migrations.schema_migrations.\n *\n * Previews unless given `--apply`, like every other command that writes. It\n * used to be the one exception, executing unless given `--dry-run`, so the\n * habit every other command teaches — run it bare to see what it would do —\n * ran migrations against whichever environment was named. `--dry-run` is\n * still accepted, and still previews.\n *\n * Replaces `supabase db push` for self-hosted Supabase instances.\n */\nexport default class MigrateRun extends BaseCommand {\n static override description = 'Execute pending migrations against a Supabase environment'\n\n static override examples = [\n '<%= config.bin %> migrate run --env=prod',\n '<%= config.bin %> migrate run --env=prod --apply',\n '<%= config.bin %> migrate run --env=prod --up-to=003 --apply',\n ]\n\n static override flags = {\n env: Flags.string({\n char: 'e',\n description: 'Target environment to run migrations against',\n }),\n apply: Flags.boolean({\n description: 'Execute the pending migrations (previews without it)',\n default: false,\n exclusive: ['dry-run'],\n }),\n 'dry-run': Flags.boolean({\n description: 'Preview which migrations would run (the default; kept for existing scripts)',\n default: false,\n }),\n 'up-to': Flags.string({\n description: 'Stop after applying this migration version (inclusive)',\n }),\n 'allow-destructive': Flags.boolean({\n description: 'Permit migrations that drop tables or columns, delete rows, or drop policies',\n default: false,\n }),\n }\n\n async run(): Promise<void> {\n const { flags } = await this.parse(MigrateRun)\n\n const config = await this.loadConfigOrFail()\n const { envName, env } = this.resolveEnv(config, flags.env)\n const dir = this.resolveMigrationsDir(config)\n\n // Preflight: verify database is reachable\n const pre = this.createPreflight('Migrate run preflight checks')\n .addDatabase('Target', envName, env.dbUrl)\n await this.runPreflight(pre, 'Migrate run')\n\n this.log(`${bold('migrate run')} → ${dim(envName)} (${dim(this.redactUrl(env.dbUrl))})\\n`)\n\n // The history is created only when migrations are applied: a preview\n // writes nothing, not even the table that records what ran.\n if (flags.apply) await ensureMigrationsTable(env.dbUrl)\n const applied = await getAppliedVersions(env.dbUrl)\n let pending = await getPendingMigrations(dir, applied)\n\n if (pending.length === 0) {\n this.log(`${ok('All migrations are up to date.')} ✓`)\n return\n }\n\n // Apply --up-to filter\n if (flags['up-to']) {\n const cutoff = flags['up-to']\n const idx = pending.findIndex(m => m.version === cutoff)\n if (idx === -1) {\n if (applied.has(cutoff)) {\n this.log(`${ok(`Version \"${cutoff}\" is already applied.`)} ✓`)\n return\n }\n this.error(`Version \"${cutoff}\" not found in pending migrations. Available: ${pending.map(m => m.version).join(', ')}`)\n }\n pending = pending.slice(0, idx + 1)\n }\n\n this.log(`Found ${bold(String(pending.length))} pending migration(s):\\n`)\n for (const m of pending) {\n this.log(` ${dim('○')} ${m.filename}`)\n }\n\n // A DROP TABLE in a migration file used to run with no opt-in at all,\n // while `diff --apply` held the same statement back (issue #88). The gate\n // is the same one, and the same flag opens it. Listed in the preview too,\n // so it is not first heard of when the apply refuses.\n const destructive = flags['allow-destructive'] ? [] : await findDestructiveStatements(pending)\n if (destructive.length > 0) {\n this.log('')\n this.log(warn(`${destructive.length} destructive statement(s) in the pending migrations:`))\n for (const { filename, sql } of destructive) {\n this.log(` ${warn('✗')} ${filename}`)\n this.log(` ${dim(truncateSql(sql))}`)\n }\n }\n\n if (!flags.apply) {\n this.log(`\\n${dim('Preview only — nothing was applied.')} Re-run with ${bold('--apply')} to execute`\n + (destructive.length > 0 ? `, and ${bold('--allow-destructive')} for the statements above.` : '.'))\n return\n }\n\n if (destructive.length > 0) {\n this.log(`\\n${warn('Nothing was applied.')} Re-run with ${bold('--allow-destructive')} to proceed.`)\n this.exit(1)\n }\n\n this.log('')\n\n // Execute migrations in order\n let applied_count = 0\n for (const migration of pending) {\n try {\n const result = await runMigration(env.dbUrl, migration)\n applied_count++\n this.log(` ${ok('✓')} ${result.filename} ${dim(`(${result.durationMs}ms)`)}`)\n } catch (err) {\n this.log(` ${warn('✗')} ${migration.filename}: ${err instanceof Error ? err.message : String(err)}`)\n this.log(`\\n${warn(`Stopped after ${applied_count} migration(s) due to error.`)}`)\n this.exit(1)\n }\n }\n\n this.log(`\\n${ok(`Applied ${applied_count} migration(s) successfully.`)} ✓`)\n }\n}\n\n/**\n * Destructive statements across a set of pending migration files.\n *\n * The SQL lives in the files rather than on the objects — `runMigration` reads\n * each one as it goes — so this reads them too. `readFileFn` is injectable for\n * the same reason `runMigration`'s is: so this can be tested without a\n * filesystem.\n *\n * Flat rather than grouped by file: the caller prints one line per statement,\n * and a migration with several destructive statements is worth seeing in full.\n * A file that cannot be read is not silently treated as safe — it is reported,\n * and `runMigration` will fail on it in a moment anyway.\n */\nexport async function findDestructiveStatements(\n migrations: Array<{ filename: string; path: string }>,\n readFileFn: (path: string) => Promise<string> = (path) => readFile(path, 'utf-8'),\n): Promise<Array<{ filename: string; sql: string }>> {\n const found: Array<{ filename: string; sql: string }> = []\n\n for (const migration of migrations) {\n let sql: string\n try {\n sql = await readFileFn(migration.path)\n } catch (err) {\n found.push({ filename: migration.filename, sql: `<unreadable: ${errMsg(err)}>` })\n continue\n }\n\n for (const statement of splitSqlStatements(sql)) {\n if (isDestructiveSql(statement)) {\n found.push({ filename: migration.filename, sql: statement })\n }\n }\n }\n\n return found\n}\n\n/**\n * One line of SQL for a listing, whatever the statement's shape.\n *\n * Comment lines are dropped first: the first statement of a file carries the\n * file's header, and a generated one its unit marker, which otherwise filled\n * the line before the statement began.\n */\nexport function truncateSql(sql: string): string {\n const oneLine = sql.split('\\n').filter(l => !/^\\s*--/.test(l)).join(' ').replace(/\\s+/g, ' ').trim()\n return oneLine.length > 100 ? `${oneLine.slice(0, 97)}...` : oneLine\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AAWtB,SAAS,gBAAgB;AAiBzB,IAAqB,aAArB,MAAqB,oBAAmB,YAAY;AAAA,EAClD,OAAgB,cAAc;AAAA,EAE9B,OAAgB,WAAW;AAAA,IACzB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EAEA,OAAgB,QAAQ;AAAA,IACtB,KAAK,MAAM,OAAO;AAAA,MAChB,MAAM;AAAA,MACN,aAAa;AAAA,IACf,CAAC;AAAA,IACD,OAAO,MAAM,QAAQ;AAAA,MACnB,aAAa;AAAA,MACb,SAAS;AAAA,MACT,WAAW,CAAC,SAAS;AAAA,IACvB,CAAC;AAAA,IACD,WAAW,MAAM,QAAQ;AAAA,MACvB,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,IACD,SAAS,MAAM,OAAO;AAAA,MACpB,aAAa;AAAA,IACf,CAAC;AAAA,IACD,qBAAqB,MAAM,QAAQ;AAAA,MACjC,aAAa;AAAA,MACb,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MAAqB;AACzB,UAAM,EAAE,MAAM,IAAI,MAAM,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