@protobase/cli 0.31.0 → 0.31.1

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.
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.31.0";
2
+ var version = "0.31.1";
3
3
  //#endregion
4
4
  export { version };
package/dist/dev/entry.js CHANGED
@@ -3,7 +3,8 @@ import { devJobs } from "./dev-jobs.js";
3
3
  import { projectErrorReporter } from "../project/error-reporter.js";
4
4
  import { projectAdmin } from "../project/project-admin.js";
5
5
  import { loadProject, projectDb } from "./project.js";
6
- import { checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
6
+ import { setMissing, supabaseEnv } from "./supabase-env.js";
7
+ import { apiKeySettings, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
7
8
  import { upgradeWebSocket } from "@hono/node-server";
8
9
  import { Hono } from "hono";
9
10
  //#region src/dev/entry.ts
@@ -27,6 +28,12 @@ checkAi({
27
28
  env: process.env
28
29
  });
29
30
  if (project.webhooks) await checkWebhooksSchema(db, project.webhooks);
31
+ setMissing(process.env, supabaseEnv({
32
+ url: process.env.PROTOBASE_DEV_URL,
33
+ databaseUrl: process.env.PROTOBASE_DATABASE_URL,
34
+ keys: apiKeySettings(project.options?.apiKeys, process.env),
35
+ withAuth: Boolean(project.auth)
36
+ }));
30
37
  const reporter = await projectErrorReporter(project, process.env);
31
38
  const ui = {
32
39
  plugins: [],
package/dist/dev/run.js CHANGED
@@ -102,12 +102,13 @@ const runDev = async (options, out) => {
102
102
  ]
103
103
  });
104
104
  await server.listen();
105
+ const address = server.httpServer?.address();
106
+ const port = typeof address === "object" && address ? address.port : options.port;
107
+ process.env.PROTOBASE_DEV_URL = `http://localhost:${port}`;
105
108
  await server.ssrLoadModule(entry).catch(async (error) => {
106
109
  await server.close();
107
110
  throw error;
108
111
  });
109
- const address = server.httpServer?.address();
110
- const port = typeof address === "object" && address ? address.port : options.port;
111
112
  out(`protobase dev ready at http://localhost:${port}\n`);
112
113
  out(` project ${options.projectDir}\n api http://localhost:${port}/api/v1 (docs at /api/docs)\n`);
113
114
  out(" login sign in with a user created by `protobase users create`\n");
@@ -0,0 +1,27 @@
1
+ import { goTruePath, supabasePath } from "@protobase/server";
2
+ //#region src/dev/supabase-env.ts
3
+ /**
4
+ * The variables Supabase gives its Edge Functions, from the app's own URL, database and keys, so `@supabase/server`
5
+ * and supabase-js inside a function call this app. A key the app lacks leaves its variables out.
6
+ */
7
+ const supabaseEnv = ({ url, databaseUrl, keys, withAuth }) => ({
8
+ SUPABASE_URL: `${url}${supabasePath}`,
9
+ SUPABASE_DB_URL: databaseUrl,
10
+ ...withAuth && { SUPABASE_JWKS_URL: `${url}${goTruePath}/.well-known/jwks.json` },
11
+ ...keys.publishable && {
12
+ SUPABASE_ANON_KEY: keys.publishable,
13
+ SUPABASE_PUBLISHABLE_KEY: keys.publishable,
14
+ SUPABASE_PUBLISHABLE_KEYS: JSON.stringify({ default: keys.publishable })
15
+ },
16
+ ...keys.secret && {
17
+ SUPABASE_SERVICE_ROLE_KEY: keys.secret,
18
+ SUPABASE_SECRET_KEY: keys.secret,
19
+ SUPABASE_SECRET_KEYS: JSON.stringify({ default: keys.secret })
20
+ }
21
+ });
22
+ /** Sets each of `values` that `env` lacks: a variable the developer set, such as in .env, wins. */
23
+ const setMissing = (env, values) => {
24
+ for (const [name, value] of Object.entries(values)) env[name] ??= value;
25
+ };
26
+ //#endregion
27
+ export { setMissing, supabaseEnv };
@@ -3,7 +3,7 @@ import { projectAdmin } from "../project/project-admin.js";
3
3
  import { createPgDb } from "../project/pg-db.js";
4
4
  import { createServeApp } from "./app.js";
5
5
  import { startCleanupTimer } from "./cleanup-timer.js";
6
- import { checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
6
+ import { backgroundSettled, checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
7
7
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
8
8
  import { WebSocketServer } from "ws";
9
9
  import pg from "pg";
@@ -74,6 +74,7 @@ const startServe = async ({ project, env, createDb = (url) => createPgDb(pg, url
74
74
  const timer = cleanup && env.filesCleanupMinutes > 0 ? startCleanupTimer(cleanup.run, env.filesCleanupMinutes, (error) => console.error(error)) : void 0;
75
75
  const close = async () => {
76
76
  await closeServer(server);
77
+ await backgroundSettled();
77
78
  await timer?.stop();
78
79
  await jobs?.stop();
79
80
  await ownDb?.destroy();
@@ -1,6 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import path from "node:path";
3
- import { readdir } from "node:fs/promises";
4
3
  //#region src/supabase/checkout.ts
5
4
  /** The Supabase CLI's files in a checkout: `supabase/config.toml`, `supabase/migrations/`, `supabase/functions/`. */
6
5
  const checkoutMarkers = (projectDir) => [
@@ -8,11 +7,5 @@ const checkoutMarkers = (projectDir) => [
8
7
  "supabase/migrations",
9
8
  "supabase/functions"
10
9
  ].filter((marker) => existsSync(path.join(projectDir, marker)));
11
- /** The Edge Functions in `supabase/functions/`: its folders, except `_shared` and the like. */
12
- const edgeFunctions = async (projectDir) => {
13
- const dir = path.join(projectDir, "supabase", "functions");
14
- if (!existsSync(dir)) return [];
15
- return (await readdir(dir, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith("_") && !entry.name.startsWith(".")).map((entry) => entry.name).sort();
16
- };
17
10
  //#endregion
18
- export { checkoutMarkers, edgeFunctions };
11
+ export { checkoutMarkers };
@@ -1,7 +1,9 @@
1
1
  import { nextMigrationName } from "../auth/migration-file.js";
2
2
  import { connect } from "../db/connect.js";
3
- import { checkoutMarkers, edgeFunctions } from "./checkout.js";
3
+ import { checkoutMarkers } from "./checkout.js";
4
4
  import { cronPlan } from "./cron-plan.js";
5
+ import { planFunctions } from "./functions/plan-functions.js";
6
+ import { writeFunctions } from "./functions/write-functions.js";
5
7
  import { importPlan, probedExtensions } from "./import-plan.js";
6
8
  import { importState } from "./import-state.js";
7
9
  import { runPgTool } from "./pg-tools.js";
@@ -114,6 +116,7 @@ const pattern = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
114
116
  const runDumpPhase = async (options, out) => {
115
117
  const checkout = checkoutMarkers(options.projectDir);
116
118
  if (checkout.length > 0) out(`found the Supabase project's ${checkout.join(", ")}\n`);
119
+ const functions = await planFunctions(options.projectDir);
117
120
  const state = importState(options.projectDir);
118
121
  const sql = connect(options.sourceUrl);
119
122
  const reserved = await sql.reserve();
@@ -153,14 +156,20 @@ const runDumpPhase = async (options, out) => {
153
156
  await mkdir(options.migrationsDir, { recursive: true });
154
157
  const file = nextMigrationName(await readdir(options.migrationsDir), "supabase_schema");
155
158
  await writeFile(path.join(options.migrationsDir, file), migration.text, { flag: "wx" });
159
+ const packages = await writeFunctions(options.projectDir, functions);
156
160
  await state.writeManifest({
157
161
  migration: file,
158
162
  leftOut: migration.leftOut,
159
163
  checkout,
160
- functions: await edgeFunctions(options.projectDir),
164
+ functions: {
165
+ converted: functions.functions,
166
+ packages,
167
+ left: functions.left
168
+ },
161
169
  ...source
162
170
  });
163
171
  out(`wrote ${path.relative(options.projectDir, path.join(options.migrationsDir, file))}, the schemas ${source.schemas.join(", ")}\n`);
172
+ if (functions.functions.length > 0) out(`converted ${functions.functions.length} Edge Functions into functions/${packages.length > 0 ? `, adding ${packages.length} packages to package.json: install them` : ""}\n`);
164
173
  out(`dumped ${source.tables.length} tables' data into ${path.relative(options.projectDir, state.data)}, which git ignores\n`);
165
174
  if (replay) out(`kept Vault's secrets, pgmq's queues and pg_cron's jobs to make again in ${path.relative(options.projectDir, state.replay)}, which git ignores\n`);
166
175
  out("next: apply the migration with the project's migrations, then run `protobase import supabase` again to load the data\n");
@@ -0,0 +1,167 @@
1
+ import { resolveImport } from "./import-map.js";
2
+ import { bareImport } from "./specifier.js";
3
+ import { ts } from "ts-morph";
4
+ //#region src/supabase/functions/convert-source.ts
5
+ const stdServer = /^https:\/\/deno\.land\/std(@[^/]+)?\/http\/server\.ts$/;
6
+ const isEdgeRuntimeTypes = (specifier) => specifier.endsWith("/edge-runtime.d.ts");
7
+ const runtimeGlobals = /* @__PURE__ */ new Set([
8
+ "Deno",
9
+ "EdgeRuntime",
10
+ "Supabase"
11
+ ]);
12
+ const isAccess = (node, object, ...names) => {
13
+ if (!ts.isPropertyAccessExpression(node) || node.name.text !== names.at(-1)) return false;
14
+ if (names.length === 1) return ts.isIdentifier(node.expression) && node.expression.text === object;
15
+ return isAccess(node.expression, object, ...names.slice(0, -1));
16
+ };
17
+ const serveHandler = (call) => {
18
+ const [first, second] = call.arguments;
19
+ if (call.arguments.length === 1 && !ts.isObjectLiteralExpression(first)) return first;
20
+ if (call.arguments.length === 2) return second;
21
+ };
22
+ const applyEdits = (code, edits) => {
23
+ const sorted = [...edits].sort((a, b) => a.start - b.start || a.end - b.end);
24
+ let out = "";
25
+ let at = 0;
26
+ for (const edit of sorted) {
27
+ out += code.slice(at, edit.start) + edit.text;
28
+ at = Math.max(at, edit.end);
29
+ }
30
+ return out + code.slice(at);
31
+ };
32
+ /**
33
+ * Converts one file of a Supabase Edge Function for Protobase, by its syntax tree: `npm:`, `jsr:` and esm.sh imports
34
+ * become bare imports of the packages it reports, `Deno.env.get(x)` becomes `process.env[x]`, and
35
+ * `EdgeRuntime.waitUntil` Protobase's `waitUntil`. In a function's entry, `Deno.serve(handler)` or std's
36
+ * `serve(handler)` becomes `export default { fetch: handler }`. Anything else of Deno's or Supabase's runtime, and
37
+ * imports of no npm package, stay as they are and are listed in `left`.
38
+ */
39
+ const convertSource = (code, options) => {
40
+ const source = ts.createSourceFile(options.file, code, ts.ScriptTarget.Latest, true);
41
+ const edits = [];
42
+ const packages = [];
43
+ const left = [];
44
+ const handled = /* @__PURE__ */ new Set();
45
+ const serveNames = /* @__PURE__ */ new Set();
46
+ const imports = /* @__PURE__ */ new Set();
47
+ const note = (node, what) => left.push(`${options.file}:${source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1}: ${what}`);
48
+ const remove = (statement) => {
49
+ const end = code[statement.end] === "\n" ? statement.end + 1 : statement.end;
50
+ edits.push({
51
+ start: statement.getStart(source),
52
+ end,
53
+ text: ""
54
+ });
55
+ };
56
+ const defaultExport = source.statements.find((statement) => ts.isExportAssignment(statement) && !statement.isExportEquals);
57
+ let served = false;
58
+ const rewriteSpecifier = (literal, statement) => {
59
+ const specifier = resolveImport(literal.text, options.importMap);
60
+ if (statement && !statement.importClause && isEdgeRuntimeTypes(specifier)) return remove(statement);
61
+ const named = statement?.importClause?.namedBindings;
62
+ if (options.entry && stdServer.test(specifier) && named && ts.isNamedImports(named) && named.elements.every((element) => (element.propertyName ?? element.name).text === "serve")) {
63
+ named.elements.forEach((element) => serveNames.add(element.name.text));
64
+ return remove(statement);
65
+ }
66
+ const bare = bareImport(specifier);
67
+ if (bare) {
68
+ packages.push(bare.package);
69
+ if (bare.specifier !== literal.text) edits.push({
70
+ start: literal.getStart(source) + 1,
71
+ end: literal.end - 1,
72
+ text: bare.specifier
73
+ });
74
+ return;
75
+ }
76
+ if (specifier !== literal.text && !/^(https?:|jsr:|npm:)/.test(specifier)) {
77
+ edits.push({
78
+ start: literal.getStart(source) + 1,
79
+ end: literal.end - 1,
80
+ text: specifier
81
+ });
82
+ return;
83
+ }
84
+ if (/^(https?:|jsr:|npm:)/.test(specifier)) note(literal, `import of ${specifier}, which is no npm package: import one that does the same`);
85
+ };
86
+ const convertServe = (call) => {
87
+ handled.add(call.expression);
88
+ const statement = call.parent;
89
+ const handler = serveHandler(call);
90
+ if (!options.entry || !ts.isExpressionStatement(statement) || statement.parent !== source || !handler || defaultExport || served) return note(call, `${call.expression.getText(source)}(...), which Protobase does not run: default-export { fetch: handler }`);
91
+ served = true;
92
+ const open = options.public ? "defineFunction({ public: true }, { fetch: " : "{ fetch: ";
93
+ if (options.public) imports.add("defineFunction");
94
+ edits.push({
95
+ start: statement.getStart(source),
96
+ end: handler.getStart(source),
97
+ text: `export default ${open}`
98
+ });
99
+ edits.push({
100
+ start: handler.end,
101
+ end: statement.end,
102
+ text: options.public ? " })" : " }"
103
+ });
104
+ };
105
+ const visit = (node) => {
106
+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) rewriteSpecifier(node.moduleSpecifier, ts.isImportDeclaration(node) ? node : void 0);
107
+ else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) rewriteSpecifier(node.arguments[0]);
108
+ else if (ts.isCallExpression(node) && (isAccess(node.expression, "Deno", "serve") || ts.isIdentifier(node.expression) && serveNames.has(node.expression.text))) convertServe(node);
109
+ else if (ts.isCallExpression(node) && isAccess(node.expression, "Deno", "env", "get") && node.arguments.length === 1) {
110
+ handled.add(node.expression);
111
+ edits.push({
112
+ start: node.getStart(source),
113
+ end: node.arguments[0].getStart(source),
114
+ text: "process.env["
115
+ });
116
+ edits.push({
117
+ start: node.arguments[0].end,
118
+ end: node.end,
119
+ text: "]"
120
+ });
121
+ } else if (ts.isCallExpression(node) && isAccess(node.expression, "EdgeRuntime", "waitUntil")) {
122
+ handled.add(node.expression);
123
+ imports.add("waitUntil");
124
+ edits.push({
125
+ start: node.expression.getStart(source),
126
+ end: node.expression.end,
127
+ text: "waitUntil"
128
+ });
129
+ } else if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression) && runtimeGlobals.has(node.expression.text)) {
130
+ let top = node;
131
+ while (ts.isPropertyAccessExpression(top.parent) && top.parent.expression === top) top = top.parent;
132
+ if (!handled.has(top)) note(node, `${top.getText(source)}, of ${node.expression.text === "Deno" ? "Deno" : "Supabase's runtime"}: rewrite it for Node or Bun`);
133
+ }
134
+ ts.forEachChild(node, visit);
135
+ };
136
+ visit(source);
137
+ if (options.entry && !served && !defaultExport) note(source.statements[0] ?? source, "no Deno.serve or default export to serve");
138
+ if (options.entry && options.public && defaultExport) {
139
+ imports.add("defineFunction");
140
+ edits.push({
141
+ start: defaultExport.expression.getStart(source),
142
+ end: defaultExport.expression.getStart(source),
143
+ text: "defineFunction({ public: true }, "
144
+ });
145
+ edits.push({
146
+ start: defaultExport.expression.end,
147
+ end: defaultExport.expression.end,
148
+ text: ")"
149
+ });
150
+ }
151
+ if (imports.size > 0) {
152
+ const first = source.statements[0];
153
+ const at = first ? first.getStart(source) : 0;
154
+ edits.push({
155
+ start: at,
156
+ end: at,
157
+ text: `import { ${[...imports].sort().join(", ")} } from '@protobase/server'\n`
158
+ });
159
+ }
160
+ return {
161
+ code: applyEdits(code, edits),
162
+ packages,
163
+ left
164
+ };
165
+ };
166
+ //#endregion
167
+ export { convertSource };
@@ -0,0 +1,19 @@
1
+ import { ts } from "ts-morph";
2
+ //#region src/supabase/functions/import-map.ts
3
+ /** The `imports` of a `deno.json`, `deno.jsonc` or `import_map.json`, comments allowed; a file that does not parse is an error naming it. */
4
+ const readImportMap = (file, text) => {
5
+ const { config, error } = ts.parseConfigFileTextToJson(file, text);
6
+ if (error) throw new Error(`${file} is not JSON: ${ts.flattenDiagnosticMessageText(error.messageText, "\n")}`);
7
+ const imports = config?.imports;
8
+ if (imports === void 0) return {};
9
+ if (typeof imports !== "object" || imports === null) throw new Error(`${file}: "imports" is not an object`);
10
+ return Object.fromEntries(Object.entries(imports).filter((entry) => typeof entry[1] === "string"));
11
+ };
12
+ /** What `specifier` stands for under `map`: its exact entry, or the longest prefix entry, as Deno resolves it. */
13
+ const resolveImport = (specifier, map) => {
14
+ if (map[specifier] !== void 0) return map[specifier];
15
+ const prefix = Object.keys(map).filter((key) => key.endsWith("/") && specifier.startsWith(key)).sort((a, b) => b.length - a.length)[0];
16
+ return prefix === void 0 ? specifier : map[prefix] + specifier.slice(prefix.length);
17
+ };
18
+ //#endregion
19
+ export { readImportMap, resolveImport };
@@ -0,0 +1,99 @@
1
+ import { readImportMap } from "./import-map.js";
2
+ import { convertSource } from "./convert-source.js";
3
+ import { publicFunctions } from "./public-functions.js";
4
+ import { existsSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { readFile, readdir } from "node:fs/promises";
7
+ //#region src/supabase/functions/plan-functions.ts
8
+ const code = /\.(ts|tsx|mts|js|jsx|mjs)$/;
9
+ const denoFiles = /* @__PURE__ */ new Set([
10
+ "deno.json",
11
+ "deno.jsonc",
12
+ "deno.lock",
13
+ "import_map.json"
14
+ ]);
15
+ const importMapOf = async (dir) => {
16
+ const maps = await Promise.all([
17
+ "import_map.json",
18
+ "deno.json",
19
+ "deno.jsonc"
20
+ ].map(async (name) => {
21
+ const file = path.join(dir, name);
22
+ return existsSync(file) ? readImportMap(file, await readFile(file, "utf8")) : {};
23
+ }));
24
+ return Object.assign({}, ...maps);
25
+ };
26
+ const filesBelow = async (dir) => {
27
+ return (await readdir(dir, {
28
+ withFileTypes: true,
29
+ recursive: true
30
+ })).filter((entry) => entry.isFile()).map((entry) => path.join(entry.parentPath, entry.name)).sort();
31
+ };
32
+ /**
33
+ * How `supabase/functions` becomes the project's `functions/`, without writing anything: every function folder, and
34
+ * the shared ones such as `_shared`, with its code converted (`convertSource`) and its other files as they are.
35
+ * `verify_jwt = false` in `supabase/config.toml` makes a function public. A folder without an `index.ts` is left out
36
+ * and reported. Fails when the project's `functions/` has a function or folder of a name it would write.
37
+ */
38
+ const planFunctions = async (projectDir) => {
39
+ const from = path.join(projectDir, "supabase", "functions");
40
+ const plan = {
41
+ files: [],
42
+ functions: [],
43
+ packages: [],
44
+ left: []
45
+ };
46
+ if (!existsSync(from)) return plan;
47
+ const config = path.join(projectDir, "supabase", "config.toml");
48
+ const open = existsSync(config) ? publicFunctions(await readFile(config, "utf8")) : /* @__PURE__ */ new Set();
49
+ const sharedMap = await importMapOf(from);
50
+ const folders = (await readdir(from, { withFileTypes: true })).filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")).map((entry) => entry.name).sort();
51
+ const taken = folders.filter((name) => existsSync(path.join(projectDir, "functions", name)) || existsSync(path.join(projectDir, "functions", `${name}.ts`)));
52
+ if (taken.length > 0) throw new Error(`The project's functions/ already has ${taken.join(", ")}; move them aside to import supabase/functions`);
53
+ for (const name of folders) {
54
+ const dir = path.join(from, name);
55
+ const shared = name.startsWith("_");
56
+ if (!shared && !existsSync(path.join(dir, "index.ts"))) {
57
+ plan.left.push(`supabase/functions/${name} has no index.ts, so it was not imported: move its entry point there`);
58
+ continue;
59
+ }
60
+ const importMap = {
61
+ ...sharedMap,
62
+ ...await importMapOf(dir)
63
+ };
64
+ for (const file of await filesBelow(dir)) {
65
+ const relative = path.relative(projectDir, file).replace(/^supabase[/\\]/, "");
66
+ if (denoFiles.has(path.basename(file))) continue;
67
+ if (!code.test(file)) {
68
+ plan.files.push({
69
+ path: relative,
70
+ content: await readFile(file)
71
+ });
72
+ continue;
73
+ }
74
+ const converted = convertSource(await readFile(file, "utf8"), {
75
+ file: relative,
76
+ entry: !shared && file === path.join(dir, "index.ts"),
77
+ public: open.has(name),
78
+ importMap
79
+ });
80
+ plan.files.push({
81
+ path: relative,
82
+ content: converted.code
83
+ });
84
+ plan.left.push(...converted.left);
85
+ for (const pkg of converted.packages) {
86
+ const known = plan.packages.find((other) => other.name === pkg.name);
87
+ if (!known) plan.packages.push(pkg);
88
+ else if (known.range !== pkg.range) plan.left.push(`${relative} asks for ${pkg.name} ${pkg.range}, another file for ${known.range}; package.json has ${known.range}`);
89
+ }
90
+ }
91
+ if (!shared) plan.functions.push({
92
+ name,
93
+ public: open.has(name)
94
+ });
95
+ }
96
+ return plan;
97
+ };
98
+ //#endregion
99
+ export { planFunctions };
@@ -0,0 +1,22 @@
1
+ //#region src/supabase/functions/public-functions.ts
2
+ const functionTable = /^\[functions\.(?:"([^"]+)"|([A-Za-z0-9_-]+))\]$/;
3
+ /**
4
+ * The functions `supabase/config.toml` opens to anyone with `verify_jwt = false`; Supabase checks a token for the
5
+ * others. Only the lines of `[functions.<name>]` tables are read.
6
+ */
7
+ const publicFunctions = (toml) => {
8
+ const names = /* @__PURE__ */ new Set();
9
+ let current;
10
+ for (const raw of toml.split("\n")) {
11
+ const line = raw.replace(/\s+#.*$/, "").trim();
12
+ if (line.startsWith("[")) {
13
+ const table = functionTable.exec(line);
14
+ current = table ? table[1] ?? table[2] : void 0;
15
+ continue;
16
+ }
17
+ if (current !== void 0 && /^verify_jwt\s*=\s*false$/.test(line)) names.add(current);
18
+ }
19
+ return names;
20
+ };
21
+ //#endregion
22
+ export { publicFunctions };
@@ -0,0 +1,56 @@
1
+ //#region src/supabase/functions/specifier.ts
2
+ const packageSpec = /^((?:@[^/@]+\/)?[^/@?]+)(?:@([^/?]+))?(\/[^?]*)?(?:\?.*)?$/;
3
+ const esmShPrefix = /^(?:v\d+\/|stable\/)?\*?/;
4
+ const parse = (spec) => {
5
+ const match = packageSpec.exec(spec);
6
+ if (!match) return void 0;
7
+ const [, name, range, path] = match;
8
+ return {
9
+ name,
10
+ range: range ?? "*",
11
+ path: path ?? ""
12
+ };
13
+ };
14
+ const jsrAlias = (name, range) => `npm:@jsr/${name.slice(1).replace("/", "__")}@${range}`;
15
+ /**
16
+ * The bare import of an `npm:`, `jsr:` or `https://esm.sh/` specifier, and the package it needs; `undefined` for any
17
+ * other specifier. An import without a version takes any version.
18
+ */
19
+ const bareImport = (specifier) => {
20
+ if (specifier.startsWith("npm:")) {
21
+ const spec = parse(specifier.slice(4));
22
+ return spec && {
23
+ specifier: spec.name + spec.path,
24
+ package: {
25
+ name: spec.name,
26
+ range: spec.range
27
+ }
28
+ };
29
+ }
30
+ if (specifier.startsWith("jsr:")) {
31
+ const spec = parse(specifier.slice(4).replace(/^\//, ""));
32
+ if (!spec?.name.startsWith("@")) return void 0;
33
+ return {
34
+ specifier: spec.name + spec.path,
35
+ package: {
36
+ name: spec.name,
37
+ range: jsrAlias(spec.name, spec.range)
38
+ }
39
+ };
40
+ }
41
+ if (specifier.startsWith("https://esm.sh/")) {
42
+ const spec = parse(specifier.slice(15).replace(esmShPrefix, ""));
43
+ if (!spec || spec.name === "gh" || spec.name === "pr") return void 0;
44
+ return {
45
+ specifier: spec.name + spec.path,
46
+ package: {
47
+ name: spec.name,
48
+ range: spec.range
49
+ }
50
+ };
51
+ }
52
+ };
53
+ /** Whether a package installs from jsr's npm registry, which .npmrc must name. */
54
+ const isJsrPackage = (pkg) => pkg.range.startsWith("npm:@jsr/");
55
+ //#endregion
56
+ export { bareImport, isJsrPackage };
@@ -0,0 +1,43 @@
1
+ import { isJsrPackage } from "./specifier.js";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
5
+ //#region src/supabase/functions/write-functions.ts
6
+ const jsrRegistry = "@jsr:registry=https://npm.jsr.io";
7
+ /** Adds to package.json's dependencies each package it lacks, making the file when there is none; returns those added. */
8
+ const addDependencies = async (projectDir, packages) => {
9
+ const file = path.join(projectDir, "package.json");
10
+ const manifest = existsSync(file) ? JSON.parse(await readFile(file, "utf8")) : { private: true };
11
+ const listed = {
12
+ ...manifest.dependencies,
13
+ ...manifest.devDependencies
14
+ };
15
+ const added = packages.filter((pkg) => listed[pkg.name] === void 0);
16
+ if (added.length === 0) return added;
17
+ manifest.dependencies = {
18
+ ...manifest.dependencies,
19
+ ...Object.fromEntries(added.map((pkg) => [pkg.name, pkg.range]))
20
+ };
21
+ await writeFile(file, `${JSON.stringify(manifest, null, 2)}\n`);
22
+ return added;
23
+ };
24
+ /** Names jsr's npm registry in .npmrc, as `npx jsr add` does, unless a line says it already. */
25
+ const addJsrRegistry = async (projectDir) => {
26
+ const file = path.join(projectDir, ".npmrc");
27
+ const text = existsSync(file) ? await readFile(file, "utf8") : "";
28
+ if (text.split("\n").some((line) => line.trim() === jsrRegistry)) return;
29
+ await appendFile(file, `${text === "" || text.endsWith("\n") ? "" : "\n"}${jsrRegistry}\n`);
30
+ };
31
+ /** Writes the converted functions into the project and their packages into package.json; returns the packages added. */
32
+ const writeFunctions = async (projectDir, plan) => {
33
+ for (const file of plan.files) {
34
+ const target = path.join(projectDir, file.path);
35
+ await mkdir(path.dirname(target), { recursive: true });
36
+ await writeFile(target, file.content, { flag: "wx" });
37
+ }
38
+ const added = await addDependencies(projectDir, plan.packages);
39
+ if (added.some(isJsrPackage)) await addJsrRegistry(projectDir);
40
+ return added;
41
+ };
42
+ //#endregion
43
+ export { writeFunctions };
@@ -67,7 +67,9 @@ const importReport = (manifest, doctor, jobsWired, live) => [
67
67
  section("To convert", "Supabase dropped timescaledb, plv8, plls and plcoffee after Postgres 15. The migration restores a hypertable as a plain table without its rows, and leaves out a function in a language the project's database does not have, as comments; convert each.", conversions(manifest)),
68
68
  section("HTTP triggers", "These triggers call out over HTTP with pg_net or a database webhook, and the project's database has no pg_net. The migration keeps a trigger calling the app's own function, but nothing sends; it leaves out a webhook's. Move each call to a Protobase event subscription or job.", manifest.httpSent ? [] : manifest.httpTriggers.map(trigger)),
69
69
  "## Storage files\n\nThe load restored Storage's buckets and objects with their policies, but a dump holds no file bytes. Run `protobase import supabase --storage-url https://<ref>.supabase.co` with the project's secret key in `SUPABASE_SERVICE_ROLE_KEY` to copy them into the app's Storage file provider; it writes what it copied to `supabase-import/storage.md`, and a rerun copies what is left.\n",
70
- section("Edge Functions", "`supabase/functions` holds these, which the import does not convert.", manifest.functions),
70
+ section("Edge Functions", "The import converted `supabase/functions` into `functions/`. Each function answers at `/api/functions/<name>`, and at `/api/sb/functions/v1/<name>` for `supabase.functions.invoke`.", manifest.functions.converted.map((fn) => fn.public ? `${fn.name}, public: \`verify_jwt = false\`` : fn.name)),
71
+ section("Packages added", "The functions import these, which the import added to package.json's dependencies. Install them.", manifest.functions.packages.map((pkg) => `${pkg.name} ${code(pkg.range)}`)),
72
+ section("Edge Function code to rewrite", "Node and Bun lack these, or no npm package has them. Rewrite each, by hand or with an AI assistant.", manifest.functions.left),
71
73
  `## Indexes the scan guard needs\n\n${doctor === void 0 ? "No resources were scaffolded, so `protobase doctor` had nothing to check." : `\`protobase doctor\` on the scaffolded config. The API refuses a read that no index serves; add each index it names in a migration of its own.\n\n\`\`\`\n${doctor.trimEnd()}\n\`\`\``}\n`
72
74
  ].join("\n");
73
75
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.31.0",
3
+ "version": "0.31.1",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -36,11 +36,11 @@
36
36
  "@better-auth/core": "^1.7.7",
37
37
  "@hono/node-server": "^2.1.3",
38
38
  "@hono/vite-dev-server": "^0.26.1",
39
- "@protobase/layout": "0.31.0",
40
- "@protobase/query": "0.31.0",
41
- "@protobase/schema": "0.31.0",
42
- "@protobase/server": "0.31.0",
43
- "@protobase/ui": "0.31.0",
39
+ "@protobase/layout": "0.31.1",
40
+ "@protobase/query": "0.31.1",
41
+ "@protobase/schema": "0.31.1",
42
+ "@protobase/server": "0.31.1",
43
+ "@protobase/ui": "0.31.1",
44
44
  "@react-email/render": "^2.1.0",
45
45
  "@scalar/hono-api-reference": "^0.12.10",
46
46
  "@tailwindcss/vite": "^4.3.3",
@@ -63,7 +63,10 @@
63
63
  "zod": "^4.6.5"
64
64
  },
65
65
  "devDependencies": {
66
+ "@supabase/server": "^1.9.2",
67
+ "@supabase/supabase-js": "^2.118.0",
66
68
  "@types/ws": "^8.18.2",
69
+ "stripe": "^22.6.2",
67
70
  "tsx": "^4.23.15"
68
71
  }
69
72
  }
@@ -235,6 +235,15 @@ Preflight requests are answered before authentication, because a browser sends t
235
235
  - **Problems:** throw an `HttpProblem` (or `badRequest`, `unauthorized`, `forbidden`, `notFound` from `@protobase/server`) to answer with an [RFC 9457 problem](../reference/api.md#errors)). Hono's `HTTPException` works too.
236
236
  - **Everything else:** any other error, or a handler that returns something other than a `Response`, becomes a `500 internal-error` problem without its message. The error goes to `options.onUnhandledError`, which `protobase dev` and `serve` print.
237
237
 
238
+ ## Functions moved from Supabase
239
+
240
+ [`protobase import supabase`](../reference/cli.md#import-supabase)) converts `supabase/functions` into `functions/`. A converted function keeps Supabase's shape, a default export with a `fetch` method, and keeps working with `@supabase/server` and supabase-js:
241
+
242
+ - **At `/api/sb/functions/v1/<name>` too,** so `supabase.functions.invoke` callers do not change. There a protected function lets in a request with the app's publishable or secret key in the `apikey` header, and a user token of [`/api/sb/auth/v1`](../reference/auth.md#supabase-js-and-supabasessr)) as the bearer, if any, as Supabase's `verify_jwt` does. A public function lets in anyone. The keys are those of [supabase-js's Realtime](../reference/supabase-realtime.md)): without them, only public functions answer there. As on Supabase, the request's path starts at the function's name (`/<name>/more/parts`), and a CORS preflight reaches the function, which answers it.
243
+ - **Its context there** is `{ name, db, caller() }`, where `caller()` resolves to who the key and token make the request: `{ role: 'anon' }` for the publishable key alone, `{ role: 'app' }` for the secret key, or `{ role: 'authenticated', claims }`. There is no `session` and no `records`. A function with `roles` answers at `/api/functions/<name>` only, and so should one that reads `session`.
244
+ - **Supabase's variables:** `protobase dev` sets `SUPABASE_URL` to the app's address with `/api/sb`, where supabase-js finds it, `SUPABASE_ANON_KEY`, `SUPABASE_PUBLISHABLE_KEY` and `SUPABASE_PUBLISHABLE_KEYS` to the publishable key, `SUPABASE_SERVICE_ROLE_KEY`, `SUPABASE_SECRET_KEY` and `SUPABASE_SECRET_KEYS` to the secret key, `SUPABASE_JWKS_URL` to the key set of `/api/sb/auth/v1`, and `SUPABASE_DB_URL` to the database. A variable set in `.env` wins. Under `protobase serve`, set them where the host keeps its settings.
245
+ - **`waitUntil(promise)`** from `@protobase/server` takes the place of `EdgeRuntime.waitUntil`. The response goes out at once, and the process waits for the work when it shuts down gracefully. Work still running when the host kills the process is lost. On Protobase Cloud's Starter plan an app stops 30 seconds after its last request, with 10 seconds to finish, so move longer work into a [job](../reference/jobs.md)).
246
+
238
247
  ## What functions are not
239
248
 
240
249
  - **Not under `/api/v1`,** which stays resources only. Functions live beside the system endpoints, like `/api/meta`.
@@ -472,9 +472,9 @@ protobase import supabase [<connection> | --source-env <variable>] [--env DATABA
472
472
 
473
473
  Turns a Supabase project's database into the project in the current directory, in two runs with the project's migrations between them. It needs PostgreSQL's `pg_dump` and `psql` on `PATH`, of the Supabase database's major version or newer, and reads the `.env` nearest the current directory for the project's database (`--env`).
474
474
 
475
- 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
475
+ 1. **The first run** takes the Supabase database's connection string, for its `postgres` role (the session pooler's or the direct one; the transaction pooler cannot hold the snapshot the dumps share). It fails unless the database has Supabase's `auth` and `storage` schemas and its `supabase_admin` role, and notes the Supabase CLI's `supabase/config.toml`, `supabase/migrations/` and `supabase/functions/` when the checkout has them. It converts `supabase/functions` into the project's `functions/` (see [functions moved from Supabase](../guides/api-functions.md#functions-moved-from-supabase))): `Deno.serve(handler)` and std's `serve(handler)` become `export default { fetch: handler }`, `npm:`, `jsr:` and esm.sh imports become bare imports of packages it adds to `package.json`, `Deno.env.get(name)` becomes `process.env[name]`, `EdgeRuntime.waitUntil` becomes `waitUntil` of `@protobase/server`, a function with `verify_jwt = false` in `config.toml` becomes public, and `_shared` and the like are converted beside them. It stops before anything else when `functions/` already has one of their names. It dumps `auth`, `storage` and every schema the app made, schema and data apart, as of one snapshot, leaving out the platform's own migration tables, and writes the schemas as the project's next migration, `NNN_supabase_schema.sql`. It asks the project's database which of the app's extensions its role may create, by trying each in a transaction it rolls back: Postgres alone allows the trusted ones, Supabase's Postgres image all it allowlists, such as pg_net, pgmq and Vault. The migration creates those first, then, where pg_net is among them and the app has Database Webhooks, the `supabase_functions.http_request` function their triggers call, over pg_net; then the dump without what fails there, as comments: grants and default privileges for `dashboard_user`, `supabase_*`, `authenticator` and `postgres`, statements about the `public` schema, Realtime's publication, database webhooks without pg_net, functions in plv8, plls or plcoffee where the database has no such language, and a timescaledb hypertable's insert-blocking trigger. The project's database needs the roles `anon`, `authenticated` and `service_role` that the dump's grants and policies name; the command makes them when its role may, and otherwise stops, naming them. The data dump goes to `supabase-import/`, which it adds to `.gitignore`, since it holds every row and the users' password hashes. Where the project's database can create Vault, pgmq and pg_cron, `supabase-import/replay.sql` holds what a dump cannot carry: Vault's secrets with their values, read decrypted since only Supabase's key opens their ciphertext, pgmq's queues with their messages, since pgmq owns their tables, and pg_cron's jobs, which live in its own schema.
476
476
  2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
477
- 3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/api/sb/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, Edge Functions, and the indexes [`doctor`](#doctor) finds missing.
477
+ 3. **The second run**, without a connection string, loads the data in one transaction, with the app's triggers off so a sign-up trigger on `auth.users` does not run again for users who already have their rows, and fails the transaction unless every table holds the source's number of rows. In the same transaction it makes Vault's secrets and pgmq's queues again through `vault.create_secret`, `pgmq.create` and `pgmq.send`, each message with its headers and the time it becomes visible. Where the project's database has pg_cron, as Supabase's Postgres image does when it serves that database, it schedules pg_cron's jobs again there with `cron.schedule`, run by the importing role, an inactive one inactive. Elsewhere it writes each job of plain SQL as a [recurring job](jobs.md#recurring-jobs)) of its own in `jobs/`, of the same name, schedule and `cron.timezone`, that runs its SQL as the app's database role, tried once each time as pg_cron did, exports it from `jobs/index.ts` and adds `jobs` to `protobase.config.ts` (or writes one); they run once [`migration`](#migration) has added the jobs schema. Recurring jobs wake an app that sleeps, so they run where a host stops an idle app too. A job that calls what the database lacks, such as pg_net's `net.http_*`, `cron` or Vault, an inactive one and a schedule recurring jobs do not take, such as `30 seconds` or `$`, stay in the report, as does a job of another database. It loads only into empty tables, deletes the data dump and the replay, runs [`scaffold`](#scaffold) on the imported tables of the app's schemas (not `auth` or `storage`), giving the tables of the `supabase_realtime` publication [`.live()`](live.md)) so [`/api/sb/realtime/v1`](supabase-realtime.md)) keeps sending their `postgres_changes` once [`migration`](#migration) has written their capture triggers, and writes `supabase-import/report.md`: the rows loaded, the imported tables' size against the Starter plan's 500 MB, what it made again, the tables it made live, and what needs a person: the pg_cron jobs it could not carry over, each with why, Realtime tables it made no resource of, Vault secrets by name and pgmq queues where the database has no such extension (and partitioned queues), the extensions it cannot create, hypertables and plv8, plls or plcoffee functions to convert, triggers that call out over HTTP without pg_net, the converted Edge Functions with the packages to install and the code the conversion left (`deno.land/x` imports, Deno's file, KV and WebSocket APIs, `Supabase.ai`), and the indexes [`doctor`](#doctor) finds missing.
478
478
 
479
479
  4. **Storage's files**: with `--storage-url https://<ref>.supabase.co` and the project's secret key in the variable `--storage-key-env` names, `SUPABASE_SERVICE_ROLE_KEY` by default, the second run, or any run after it, copies the bytes of every object in `storage.objects` from the Supabase project's Storage API into the app's [Storage file provider](supabase-storage.md#where-things-are-kept)), where [`/api/sb/storage/v1`](supabase-storage.md)) serves them, with the type and cache control the rows recorded. It streams each object, checks its byte count against the size Supabase recorded and its MD5 against the ETag where that is one, and deletes a copy that does not match. It first prints each bucket's size and stops when what is left to copy and what the provider holds exceed the provider's `max_bytes`, unless `--yes`. An object that fails does not stop the rest; the run then fails, listing them in `supabase-import/storage.md`, and a rerun copies only what the provider does not hold yet. The key goes only in the requests' headers, never in a file.
480
480