sodabase 0.1.10 → 0.1.11
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 +9 -0
- package/dist/api/client.js +4 -0
- package/dist/cli.js +55 -3
- package/dist/config/tokenStore.js +4 -0
- package/dist/functionsLint.js +162 -0
- package/dist/installMcp.js +1 -1
- package/dist/rulesPull.js +181 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -38,12 +38,21 @@ install fails; a skill failure warns with a manual fallback.
|
|
|
38
38
|
|
|
39
39
|
Point at a local backend with `SODABASE_API_URL=http://localhost:8080`.
|
|
40
40
|
|
|
41
|
+
## Pipeline checks (Edge Functions)
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
npx sodabase rules pull --project <ref> # save supabase/functions/_shared/sodabase.rules.yml + its static_files entries (signed-in owner/admin)
|
|
45
|
+
npx sodabase functions lint # flag writes in supabase/functions/** without a check() line before them (offline; exits 1 if any)
|
|
46
|
+
```
|
|
47
|
+
|
|
41
48
|
## Layout
|
|
42
49
|
|
|
43
50
|
```
|
|
44
51
|
src/
|
|
45
52
|
cli.tsx entry — renders <App/> (or runs the install-mcp subcommand)
|
|
46
53
|
installMcp.ts `install-mcp`: arg parsing, agent detection, plain-output install
|
|
54
|
+
rulesPull.ts `rules pull`: the rules file + a line-based config.toml static_files edit
|
|
55
|
+
functionsLint.ts `functions lint`: unchecked-write heuristic over supabase/functions/**
|
|
47
56
|
agentPicker.tsx `install-mcp`'s inline agent checkbox list
|
|
48
57
|
app.tsx the Ink app (flow orchestrator + screens)
|
|
49
58
|
api/
|
package/dist/api/client.js
CHANGED
|
@@ -317,6 +317,10 @@ export class SodabaseClient {
|
|
|
317
317
|
});
|
|
318
318
|
return { command };
|
|
319
319
|
}
|
|
320
|
+
// ── `rules pull`: the project's pipeline rules file (writers only; GET /projects/{ref}/edge/rules-file) ──
|
|
321
|
+
async rulesFile(projectRef) {
|
|
322
|
+
return this.get(`/projects/${encodeURIComponent(projectRef)}/edge/rules-file`);
|
|
323
|
+
}
|
|
320
324
|
// ── low-level helpers ───────────────────────────────────────────────────────
|
|
321
325
|
authHeaders() {
|
|
322
326
|
return this.bearer ? { authorization: `Bearer ${this.bearer}` } : {};
|
package/dist/cli.js
CHANGED
|
@@ -9,8 +9,11 @@ import { SodabaseClient } from "./api/client.js";
|
|
|
9
9
|
import { FakeClient } from "./api/fakeClient.js";
|
|
10
10
|
import { pickAgents } from "./agentPicker.js";
|
|
11
11
|
import { App } from "./app.js";
|
|
12
|
-
import { clearCreds, loadCreds } from "./config/tokenStore.js";
|
|
12
|
+
import { clearCreds, isSignedIn, loadCreds } from "./config/tokenStore.js";
|
|
13
|
+
import { runLint } from "./functionsLint.js";
|
|
13
14
|
import { INSTALL_MCP_HELP, detectAgents, installedAgents, parseInstallMcpArgs, resolveAgents, runInstallMcp, } from "./installMcp.js";
|
|
15
|
+
import { RULES_PULL_HELP, parseRulesPullArgs, runRulesPull } from "./rulesPull.js";
|
|
16
|
+
import { ApiError } from "./api/types.js";
|
|
14
17
|
const argv = process.argv.slice(2);
|
|
15
18
|
const args = new Set(argv);
|
|
16
19
|
/** process.exit() drops output still queued on a pipe (async on macOS, e.g. `| tee log`): await this first. */
|
|
@@ -56,15 +59,64 @@ if (argv[0] === "install-mcp") {
|
|
|
56
59
|
await drained();
|
|
57
60
|
process.exit(code);
|
|
58
61
|
}
|
|
62
|
+
// `functions lint`: static and offline — flags writes in supabase/functions/** with no check() line before them.
|
|
63
|
+
if (argv[0] === "functions" && argv[1] === "lint") {
|
|
64
|
+
const code = runLint(process.cwd(), (line) => process.stdout.write(`${line}\n`));
|
|
65
|
+
await drained();
|
|
66
|
+
process.exit(code);
|
|
67
|
+
}
|
|
68
|
+
// `rules pull --project <ref>`: the project's pipeline rules file + its static_files entries (signed-in writer).
|
|
69
|
+
if (argv[0] === "rules" && argv[1] === "pull") {
|
|
70
|
+
const opts = parseRulesPullArgs(argv.slice(2));
|
|
71
|
+
const fail = async (msg, code = 1) => {
|
|
72
|
+
process.stderr.write(`sodabase rules pull: ${msg}\n${code === 2 ? `\n${RULES_PULL_HELP}` : ""}`);
|
|
73
|
+
await drained();
|
|
74
|
+
process.exit(code);
|
|
75
|
+
};
|
|
76
|
+
if ("error" in opts)
|
|
77
|
+
await fail(opts.error, 2);
|
|
78
|
+
const { project, help } = opts;
|
|
79
|
+
if (help) {
|
|
80
|
+
process.stdout.write(RULES_PULL_HELP);
|
|
81
|
+
await drained();
|
|
82
|
+
process.exit(0);
|
|
83
|
+
}
|
|
84
|
+
const creds = loadCreds();
|
|
85
|
+
const login = "not signed in (or the session expired) — run `npx sodabase --login` first";
|
|
86
|
+
if (!isSignedIn(creds))
|
|
87
|
+
await fail(login);
|
|
88
|
+
const client = new SodabaseClient();
|
|
89
|
+
client.setBearer(creds.accessToken);
|
|
90
|
+
try {
|
|
91
|
+
const code = await runRulesPull(project, (r) => client.rulesFile(r), process.cwd(), (line) => process.stdout.write(`${line}\n`));
|
|
92
|
+
await drained();
|
|
93
|
+
process.exit(code);
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
if (!(err instanceof ApiError))
|
|
97
|
+
throw err;
|
|
98
|
+
if (err.status === 401)
|
|
99
|
+
await fail(login);
|
|
100
|
+
if (err.status === 403)
|
|
101
|
+
await fail("only a workspace owner or admin can pull the rules file");
|
|
102
|
+
if (err.status === 404)
|
|
103
|
+
await fail("no such project in your workspace, or pipeline checks aren't on for it yet");
|
|
104
|
+
await fail(err.message);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
59
107
|
if (args.has("--help") || args.has("-h")) {
|
|
60
108
|
process.stdout.write([
|
|
61
109
|
"sodabase — data-quality onboarding wizard",
|
|
62
110
|
"",
|
|
63
111
|
"Usage: npx sodabase [options]",
|
|
64
112
|
" npx sodabase install-mcp [-a, --agent <id>] [--all] [--no-skill] [--no-input]",
|
|
113
|
+
" npx sodabase rules pull --project <ref>",
|
|
114
|
+
" npx sodabase functions lint",
|
|
65
115
|
"",
|
|
66
116
|
"Commands:",
|
|
67
|
-
" install-mcp
|
|
117
|
+
" install-mcp install the MCP + trust-advisor skill for your coding agent, then exit",
|
|
118
|
+
" rules pull save the project's pipeline rules file and list it in each function's static_files",
|
|
119
|
+
" functions lint flag writes in supabase/functions without a check() line before them",
|
|
68
120
|
"",
|
|
69
121
|
"Options:",
|
|
70
122
|
" --demo run the whole flow offline against a fake backend",
|
|
@@ -125,7 +177,7 @@ const services = demo
|
|
|
125
177
|
// (e.g. a leftover --demo session) skipping sign-in and then 401-ing on /api/v1.
|
|
126
178
|
if (creds?.accessToken && creds.accessToken.startsWith("eyJ")) {
|
|
127
179
|
c.setBearer(creds.accessToken);
|
|
128
|
-
signedIn =
|
|
180
|
+
signedIn = isSignedIn(creds);
|
|
129
181
|
}
|
|
130
182
|
return c;
|
|
131
183
|
})();
|
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
7
|
import { dirname, join } from "node:path";
|
|
8
|
+
/** A real GoTrue JWT (starts "eyJ"; a leftover --demo token doesn't) with over a minute left on it. */
|
|
9
|
+
export function isSignedIn(creds) {
|
|
10
|
+
return !!creds?.accessToken?.startsWith("eyJ") && (!creds.expiresAt || creds.expiresAt > Date.now() + 60_000);
|
|
11
|
+
}
|
|
8
12
|
function credsPath() {
|
|
9
13
|
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
10
14
|
return join(base, "sodabase", "credentials.json");
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
// `npx sodabase functions lint` — flags database writes in supabase/functions/** that no `check()` line from
|
|
2
|
+
// @sodabase/edge covers (planning repo edge-function-writes-mvp-spec §4.1, §11 P5). Static and offline: no sign-in.
|
|
3
|
+
//
|
|
4
|
+
// What counts as a write: supabase-js / Drizzle `.insert(` `.upsert(` `.update(`, and a postgres.js
|
|
5
|
+
// sql`insert …` / sql`update …` template. A write is covered when the file imports @sodabase/edge and a `check(`
|
|
6
|
+
// call comes earlier in the same block or an enclosing one (a check inside a sibling, already-closed block doesn't).
|
|
7
|
+
// shortcut: brace-depth heuristic, not an AST (typescript is dev-only); an outer function's earlier check() can mask a
|
|
8
|
+
// write, `${}` inside templates and regex literals aren't parsed — upgrade to the TS compiler API if it misleads.
|
|
9
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
|
|
10
|
+
import { join, relative } from "node:path";
|
|
11
|
+
const EDGE_IMPORT = /\bfrom\s*["'](?:jsr:|npm:)?@sodabase\/edge(?:@[^"']*)?(?:\/[^"']*)?["']/;
|
|
12
|
+
const CALL_WRITE = /\.(insert|upsert|update)\s*\(/g;
|
|
13
|
+
const SQL_TAG = /\bsql\s*$/;
|
|
14
|
+
const SQL_WRITE = /^\s*(insert|update)\b/i;
|
|
15
|
+
const CHECK = /\bcheck\s*\(/g;
|
|
16
|
+
// node:crypto's hash.update(data) is not a database write: neither the same-line chain nor a name bound to one
|
|
17
|
+
const HASH_CHAIN = /create(?:Hash|Hmac)\s*\(/;
|
|
18
|
+
const HASH_BINDING = /\b(?:const|let|var)\s+(\w+)\s*=\s*(?:[\w.]+\.)?create(?:Hash|Hmac)\s*\(/g;
|
|
19
|
+
/** Blank comments, strings and template bodies (keeping newlines and the quote characters), so braces and calls
|
|
20
|
+
* inside them don't count. Returns the blanked code and each template's start offset + raw body. */
|
|
21
|
+
function blank(src) {
|
|
22
|
+
const out = src.split("");
|
|
23
|
+
const templates = [];
|
|
24
|
+
const wipe = (from, to) => {
|
|
25
|
+
for (let k = from; k < to; k++)
|
|
26
|
+
if (out[k] !== "\n")
|
|
27
|
+
out[k] = " ";
|
|
28
|
+
};
|
|
29
|
+
let i = 0;
|
|
30
|
+
while (i < src.length) {
|
|
31
|
+
const c = src[i];
|
|
32
|
+
if (c === "/" && src[i + 1] === "/") {
|
|
33
|
+
const end = src.indexOf("\n", i);
|
|
34
|
+
const stop = end === -1 ? src.length : end;
|
|
35
|
+
wipe(i, stop);
|
|
36
|
+
i = stop;
|
|
37
|
+
}
|
|
38
|
+
else if (c === "/" && src[i + 1] === "*") {
|
|
39
|
+
const end = src.indexOf("*/", i + 2);
|
|
40
|
+
const stop = end === -1 ? src.length : end + 2;
|
|
41
|
+
wipe(i, stop);
|
|
42
|
+
i = stop;
|
|
43
|
+
}
|
|
44
|
+
else if (c === "'" || c === '"' || c === "`") {
|
|
45
|
+
let j = i + 1;
|
|
46
|
+
while (j < src.length && src[j] !== c && !(c !== "`" && src[j] === "\n"))
|
|
47
|
+
j += src[j] === "\\" ? 2 : 1;
|
|
48
|
+
if (c === "`")
|
|
49
|
+
templates.push({ at: i, body: src.slice(i + 1, j) });
|
|
50
|
+
wipe(i + 1, Math.min(j, src.length));
|
|
51
|
+
i = j + 1;
|
|
52
|
+
}
|
|
53
|
+
else
|
|
54
|
+
i++;
|
|
55
|
+
}
|
|
56
|
+
return { code: out.join(""), templates };
|
|
57
|
+
}
|
|
58
|
+
/** The unchecked writes in one source file. */
|
|
59
|
+
export function lintSource(src) {
|
|
60
|
+
const { code, templates } = blank(src);
|
|
61
|
+
const imported = EDGE_IMPORT.test(src);
|
|
62
|
+
const checks = new Set();
|
|
63
|
+
for (const m of code.matchAll(CHECK))
|
|
64
|
+
checks.add(m.index);
|
|
65
|
+
const hashes = new Set([...code.matchAll(HASH_BINDING)].map((m) => m[1]));
|
|
66
|
+
const writes = [];
|
|
67
|
+
for (const m of code.matchAll(CALL_WRITE)) {
|
|
68
|
+
// at most 256 chars back (a hostile long line stays linear); `\b` stops the name regex retrying inside a word
|
|
69
|
+
const before = code.slice(Math.max(code.lastIndexOf("\n", m.index) + 1, m.index - 256), m.index);
|
|
70
|
+
if (m[1] === "update" && (HASH_CHAIN.test(before) || hashes.has(/\b(\w+)\s*$/.exec(before)?.[1] ?? "")))
|
|
71
|
+
continue;
|
|
72
|
+
writes.push({ at: m.index, kind: m[1] });
|
|
73
|
+
}
|
|
74
|
+
for (const t of templates) {
|
|
75
|
+
const w = SQL_WRITE.exec(t.body);
|
|
76
|
+
if (w && SQL_TAG.test(code.slice(Math.max(0, t.at - 64), t.at)))
|
|
77
|
+
writes.push({ at: t.at, kind: `sql ${w[1].toLowerCase()}` });
|
|
78
|
+
}
|
|
79
|
+
// One forward pass: a stack of "a check() ran earlier in this block", one entry per open block (plus the file). A
|
|
80
|
+
// write is covered when its block or an enclosing one has one; a check inside a closed sibling block doesn't count.
|
|
81
|
+
const covered = new Set();
|
|
82
|
+
if (imported) {
|
|
83
|
+
const at = new Set(writes.map((w) => w.at));
|
|
84
|
+
const stack = [false];
|
|
85
|
+
for (let i = 0; i < code.length; i++) {
|
|
86
|
+
const c = code[i];
|
|
87
|
+
if (c === "{")
|
|
88
|
+
stack.push(false);
|
|
89
|
+
else if (c === "}") {
|
|
90
|
+
if (stack.length > 1)
|
|
91
|
+
stack.pop();
|
|
92
|
+
}
|
|
93
|
+
if (checks.has(i))
|
|
94
|
+
stack[stack.length - 1] = true;
|
|
95
|
+
if (at.has(i) && stack.includes(true))
|
|
96
|
+
covered.add(i);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const starts = [0];
|
|
100
|
+
for (let i = 0; i < src.length; i++)
|
|
101
|
+
if (src[i] === "\n")
|
|
102
|
+
starts.push(i + 1);
|
|
103
|
+
const lineOf = (pos) => {
|
|
104
|
+
let lo = 0;
|
|
105
|
+
let hi = starts.length - 1;
|
|
106
|
+
while (lo < hi) {
|
|
107
|
+
const mid = (lo + hi + 1) >> 1;
|
|
108
|
+
if (starts[mid] <= pos)
|
|
109
|
+
lo = mid;
|
|
110
|
+
else
|
|
111
|
+
hi = mid - 1;
|
|
112
|
+
}
|
|
113
|
+
return lo + 1;
|
|
114
|
+
};
|
|
115
|
+
return writes
|
|
116
|
+
.filter((w) => !covered.has(w.at))
|
|
117
|
+
.map((w) => ({ line: lineOf(w.at), kind: w.kind }))
|
|
118
|
+
.sort((a, b) => a.line - b.line);
|
|
119
|
+
}
|
|
120
|
+
const SOURCE = /\.(ts|tsx|js|mjs)$/;
|
|
121
|
+
const MAX_BYTES = 1_000_000; // a bigger "source" file is generated or hostile: skipped, and said so
|
|
122
|
+
/** The source files under `dir`, relative to it. Symlinks are never followed (a link out of the tree, or a loop). */
|
|
123
|
+
function sources(dir, rel = "") {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const d of readdirSync(join(dir, rel), { withFileTypes: true })) {
|
|
126
|
+
if (d.isSymbolicLink() || d.name === "node_modules")
|
|
127
|
+
continue;
|
|
128
|
+
const path = rel ? join(rel, d.name) : d.name;
|
|
129
|
+
if (d.isDirectory())
|
|
130
|
+
out.push(...sources(dir, path));
|
|
131
|
+
else if (d.isFile() && SOURCE.test(d.name))
|
|
132
|
+
out.push(path);
|
|
133
|
+
}
|
|
134
|
+
return out;
|
|
135
|
+
}
|
|
136
|
+
/** Lint supabase/functions/** under `cwd`; prints file:line per finding. 1 = findings, 2 = no functions folder. */
|
|
137
|
+
export function runLint(cwd, log) {
|
|
138
|
+
const root = join(cwd, "supabase", "functions");
|
|
139
|
+
if (!existsSync(root)) {
|
|
140
|
+
log("No supabase/functions folder here — run this from your Supabase project's root.");
|
|
141
|
+
return 2;
|
|
142
|
+
}
|
|
143
|
+
const files = sources(root).sort();
|
|
144
|
+
let found = 0;
|
|
145
|
+
for (const f of files) {
|
|
146
|
+
const full = join(root, f);
|
|
147
|
+
if (statSync(full).size > MAX_BYTES) {
|
|
148
|
+
log(`${relative(cwd, full)}: skipped (over 1 MB)`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
for (const x of lintSource(readFileSync(full, "utf8"))) {
|
|
152
|
+
found++;
|
|
153
|
+
log(`${relative(cwd, full)}:${x.line} ${x.kind} without a check() before it`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
if (found) {
|
|
157
|
+
log(`\n${found} write(s) without a check() line. Add sb.check("<schema>.<table>", rows) before each one.`);
|
|
158
|
+
return 1;
|
|
159
|
+
}
|
|
160
|
+
log(`No unchecked writes in ${files.length} file(s).`);
|
|
161
|
+
return 0;
|
|
162
|
+
}
|
package/dist/installMcp.js
CHANGED
|
@@ -30,7 +30,7 @@ const hasJsonEntry = (text) => text.includes(MCP_URL) &&
|
|
|
30
30
|
JSON.parse(text).mcpServers?.sodabase?.url === MCP_URL;
|
|
31
31
|
// Line by line, not one regex: our table's keys run from `[mcp_servers.sodabase]` to the next table header, a
|
|
32
32
|
// value may itself contain `[` (`args = ["x"]`), and a `url` under a subtable (`[mcp_servers.sodabase.env]`) isn't ours.
|
|
33
|
-
const TOML_HEADER = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/;
|
|
33
|
+
export const TOML_HEADER = /^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$/;
|
|
34
34
|
const TOML_URL = /^\s*url\s*=\s*(["'])(.*?)\1\s*(#.*)?$/;
|
|
35
35
|
function hasTomlEntry(text) {
|
|
36
36
|
let ours = false;
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// `npx sodabase rules pull --project <ref>` — fetch the project's pipeline rules file (the backend's generator, the
|
|
2
|
+
// same one the MCP `pipeline_rules` tool uses), save it as supabase/functions/_shared/sodabase.rules.yml, and make sure
|
|
3
|
+
// every function lists it in `static_files` in supabase/config.toml (planning repo edge-function-writes-mvp-spec §5.3).
|
|
4
|
+
// shortcut: line-based TOML edit, not a parser (no deps); upgrade if config.toml shapes defeat it.
|
|
5
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join, relative } from "node:path";
|
|
7
|
+
import { TOML_HEADER } from "./installMcp.js";
|
|
8
|
+
export const RULES_FILE = join("supabase", "functions", "_shared", "sodabase.rules.yml");
|
|
9
|
+
export const STATIC_PATH = "./functions/_shared/sodabase.rules.yml"; // relative to supabase/, as config.toml has it
|
|
10
|
+
export const RULES_PULL_HELP = [
|
|
11
|
+
"sodabase rules pull — save the project's pipeline rules file and list it in each function's static_files",
|
|
12
|
+
"",
|
|
13
|
+
"Usage: npx sodabase rules pull --project <ref>",
|
|
14
|
+
"",
|
|
15
|
+
"Options:",
|
|
16
|
+
" --project <ref> your 20-character Supabase project ref",
|
|
17
|
+
" --help, -h show this help",
|
|
18
|
+
"",
|
|
19
|
+
"Run it from your Supabase project's root, signed in (`npx sodabase --login`) as a workspace owner or admin.",
|
|
20
|
+
"",
|
|
21
|
+
].join("\n");
|
|
22
|
+
/** Parse the args AFTER `rules pull`. Returns the project ref (or help), or an error message for bad input. */
|
|
23
|
+
export function parseRulesPullArgs(argv) {
|
|
24
|
+
if (argv.some((a) => a === "--help" || a === "-h"))
|
|
25
|
+
return { project: "", help: true };
|
|
26
|
+
let project;
|
|
27
|
+
for (let i = 0; i < argv.length; i++) {
|
|
28
|
+
const arg = argv[i];
|
|
29
|
+
if (arg === "--project")
|
|
30
|
+
project = argv[++i];
|
|
31
|
+
else if (arg.startsWith("--project="))
|
|
32
|
+
project = arg.slice("--project=".length);
|
|
33
|
+
else
|
|
34
|
+
return { error: `unknown option: ${arg}` };
|
|
35
|
+
}
|
|
36
|
+
if (!project || !/^[a-z0-9]{20}$/.test(project))
|
|
37
|
+
return { error: "--project <ref> is required (your 20-character project ref)" };
|
|
38
|
+
return { project, help: false };
|
|
39
|
+
}
|
|
40
|
+
/** The index just past the `]` that closes the first `[` at or after `from` (quotes respected), or -1. */
|
|
41
|
+
function closeOf(line, from) {
|
|
42
|
+
let depth = 0;
|
|
43
|
+
let quote = "";
|
|
44
|
+
for (let i = from; i < line.length; i++) {
|
|
45
|
+
const c = line[i];
|
|
46
|
+
if (quote) {
|
|
47
|
+
if (c === "\\" && quote === '"')
|
|
48
|
+
i++;
|
|
49
|
+
else if (c === quote)
|
|
50
|
+
quote = "";
|
|
51
|
+
}
|
|
52
|
+
else if (c === '"' || c === "'")
|
|
53
|
+
quote = c;
|
|
54
|
+
else if (c === "#")
|
|
55
|
+
return -1;
|
|
56
|
+
else if (c === "[")
|
|
57
|
+
depth++;
|
|
58
|
+
else if (c === "]" && --depth === 0)
|
|
59
|
+
return i;
|
|
60
|
+
}
|
|
61
|
+
return -1;
|
|
62
|
+
}
|
|
63
|
+
function sectionOf(key, fn) {
|
|
64
|
+
return key === `functions.${fn}` || key === `functions."${fn}"` || key === `functions.'${fn}'`;
|
|
65
|
+
}
|
|
66
|
+
/** Add `path` to each function's `static_files` (adding the key or the `[functions.<fn>]` section when missing).
|
|
67
|
+
* Every other line is left byte-identical. `changed` names the functions whose config moved. */
|
|
68
|
+
export function ensureStaticFiles(toml, functions, path = STATIC_PATH) {
|
|
69
|
+
const eol = toml.includes("\r\n") ? "\r\n" : "\n";
|
|
70
|
+
const lines = toml.split(eol);
|
|
71
|
+
const entry = JSON.stringify(path);
|
|
72
|
+
const listed = (s) => s.includes(entry) || s.includes(`'${path}'`);
|
|
73
|
+
const changed = [];
|
|
74
|
+
for (const fn of functions) {
|
|
75
|
+
const start = lines.findIndex((l) => {
|
|
76
|
+
const h = TOML_HEADER.exec(l);
|
|
77
|
+
return !!h && !l.trim().startsWith("[[") && sectionOf(h[1], fn);
|
|
78
|
+
});
|
|
79
|
+
if (start === -1) {
|
|
80
|
+
const at = lines.length && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
|
|
81
|
+
const add = [`[functions.${fn}]`, `static_files = [${entry}]`];
|
|
82
|
+
if (at > 0 && lines[at - 1].trim() !== "")
|
|
83
|
+
add.unshift("");
|
|
84
|
+
lines.splice(at, 0, ...add);
|
|
85
|
+
changed.push(fn);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
let end = lines.findIndex((l, i) => i > start && TOML_HEADER.test(l));
|
|
89
|
+
if (end === -1)
|
|
90
|
+
end = lines.length;
|
|
91
|
+
const key = lines.findIndex((l, i) => i > start && i < end && /^\s*static_files\s*=/.test(l));
|
|
92
|
+
if (key === -1) {
|
|
93
|
+
lines.splice(start + 1, 0, `static_files = [${entry}]`);
|
|
94
|
+
changed.push(fn);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
// the array runs from `key` to the line holding its closing `]`
|
|
98
|
+
let close = key;
|
|
99
|
+
let at = closeOf(lines[key], lines[key].indexOf("="));
|
|
100
|
+
if (at === -1) {
|
|
101
|
+
close = lines.findIndex((l, i) => i > key && i < end && /^[^#]*\]/.test(l) && !/^\s*#/.test(l));
|
|
102
|
+
if (close === -1)
|
|
103
|
+
continue; // shapes we don't understand stay untouched
|
|
104
|
+
at = lines[close].indexOf("]");
|
|
105
|
+
}
|
|
106
|
+
if (listed(lines.slice(key, close + 1).join(eol)))
|
|
107
|
+
continue;
|
|
108
|
+
const line = lines[close];
|
|
109
|
+
const before = line.slice(0, at);
|
|
110
|
+
if (close === key || before.trim() !== "") {
|
|
111
|
+
// `static_files = ["a"]` / `= []` / ` "b" ]`: insert before the `]`
|
|
112
|
+
const head = before.replace(/\s*$/, "");
|
|
113
|
+
const sep = head.endsWith("[") ? "" : head.endsWith(",") ? " " : ", ";
|
|
114
|
+
lines[close] = `${head}${sep}${entry}${line.slice(at)}`;
|
|
115
|
+
}
|
|
116
|
+
else {
|
|
117
|
+
// multi-line with `]` on its own line: a new element line before it (and a comma after the previous one)
|
|
118
|
+
let prev = close - 1;
|
|
119
|
+
while (prev > key && (lines[prev].trim() === "" || lines[prev].trim().startsWith("#")))
|
|
120
|
+
prev--;
|
|
121
|
+
const indent = prev > key ? /^\s*/.exec(lines[prev])[0] : " ";
|
|
122
|
+
if (prev > key && !/,\s*(#.*)?$/.test(lines[prev]))
|
|
123
|
+
lines[prev] = lines[prev].replace(/\s*(#.*)?$/, (m) => `,${m}`);
|
|
124
|
+
lines.splice(close, 0, `${indent}${entry},`);
|
|
125
|
+
}
|
|
126
|
+
changed.push(fn);
|
|
127
|
+
}
|
|
128
|
+
return { text: lines.join(eol), changed };
|
|
129
|
+
}
|
|
130
|
+
/** True when `path` exists and is a symlink (a cloned repo can plant one to redirect our writes). */
|
|
131
|
+
function isLink(path) {
|
|
132
|
+
try {
|
|
133
|
+
return lstatSync(path).isSymbolicLink();
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** The deployable functions: the folders under supabase/functions not starting with `_` or `.`. */
|
|
140
|
+
export function functionDirs(cwd) {
|
|
141
|
+
const root = join(cwd, "supabase", "functions");
|
|
142
|
+
if (!existsSync(root))
|
|
143
|
+
return [];
|
|
144
|
+
return readdirSync(root, { withFileTypes: true })
|
|
145
|
+
// the backend's function-name rule: anything else (`a.b`, `x]`, a newline) would break or inject into config.toml
|
|
146
|
+
.filter((d) => d.isDirectory() && !/^[_.]/.test(d.name) && /^[A-Za-z0-9_-]{1,64}$/.test(d.name))
|
|
147
|
+
.map((d) => d.name)
|
|
148
|
+
.sort();
|
|
149
|
+
}
|
|
150
|
+
/** Write the rules file + the static_files entries; prints what changed. 0 ok, 1 no supabase/config.toml here. */
|
|
151
|
+
export async function runRulesPull(ref, fetchRules, cwd, log) {
|
|
152
|
+
const config = join(cwd, "supabase", "config.toml");
|
|
153
|
+
if (!existsSync(config)) {
|
|
154
|
+
log("No supabase/config.toml here — run this from your Supabase project's root.");
|
|
155
|
+
return 1;
|
|
156
|
+
}
|
|
157
|
+
const rules = join(cwd, RULES_FILE); // never a path from the server
|
|
158
|
+
const linked = [join(cwd, "supabase"), dirname(dirname(rules)), dirname(rules), rules, config].find(isLink);
|
|
159
|
+
if (linked) {
|
|
160
|
+
log(`${relative(cwd, linked) || linked} is a symlink — refusing to write through it. Replace it with a real file or folder.`);
|
|
161
|
+
return 1;
|
|
162
|
+
}
|
|
163
|
+
const { content } = await fetchRules(ref);
|
|
164
|
+
const old = existsSync(rules) ? readFileSync(rules, "utf8") : null;
|
|
165
|
+
mkdirSync(dirname(rules), { recursive: true });
|
|
166
|
+
writeFileSync(rules, content);
|
|
167
|
+
log(`${old === null ? "Created" : old === content ? "Unchanged" : "Updated"} ${RULES_FILE}`);
|
|
168
|
+
const fns = functionDirs(cwd);
|
|
169
|
+
const { text, changed } = ensureStaticFiles(readFileSync(config, "utf8"), fns);
|
|
170
|
+
if (changed.length) {
|
|
171
|
+
writeFileSync(config, text);
|
|
172
|
+
for (const fn of changed)
|
|
173
|
+
log(`Added ${STATIC_PATH} to static_files for [functions.${fn}] in supabase/config.toml`);
|
|
174
|
+
}
|
|
175
|
+
else if (fns.length)
|
|
176
|
+
log(`supabase/config.toml already ships it for ${fns.length} function(s).`);
|
|
177
|
+
else
|
|
178
|
+
log("No functions under supabase/functions yet — run this again once you add one.");
|
|
179
|
+
log("Review the diff and commit both files; deploy your functions to use the new rules.");
|
|
180
|
+
return 0;
|
|
181
|
+
}
|