@protobase/cli 0.30.2 → 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.30.2";
2
+ var version = "0.31.1";
3
3
  //#endregion
4
4
  export { version };
@@ -2,7 +2,7 @@ import { isProjectFile } from "./project-files.js";
2
2
  import { createAdaptorServer } from "@hono/node-server";
3
3
  import { WebSocketServer } from "ws";
4
4
  //#region src/dev/api-websockets.ts
5
- const isApiWebSocket = (url) => /^\/realtime\/v1\/websocket(\?|$)/.test(url);
5
+ const isApiWebSocket = (url) => /^\/api\/sb\/realtime\/v1\/websocket(\?|$)/.test(url);
6
6
  const restartCode = 1012;
7
7
  const apiWebSockets = (entry, dirs) => {
8
8
  const wss = new WebSocketServer({ noServer: true });
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
@@ -96,18 +96,19 @@ const runDev = async (options, out) => {
96
96
  tailwindcss(),
97
97
  devServer({
98
98
  entry,
99
- exclude: [/^(?!\/(api|auth\/v1|realtime\/v1)(\/|\?|$)|\/\.well-known\/webauthn(\?|$)).*/],
99
+ exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)).*/],
100
100
  injectClientScript: false
101
101
  })
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 };
@@ -5,7 +5,7 @@ import { configExports, createAdmin, jobDefinitions } from "@protobase/server";
5
5
  * pages and subscriptions, and the rest of its config; served from a bundle, the plugins it carries, their field
6
6
  * types and which icons are the project's own (`protobase dev` passes the project's icons alone). `jobs` are the project's own and the delivery of its events and history. With a `reporter`, every error the API turns
7
7
  * into a 500 goes to the error tracker too, besides the project's `onUnhandledError` or the console. With the host's
8
- * `upgradeWebSocket`, it serves `/realtime/v1` too.
8
+ * `upgradeWebSocket`, it serves `/api/sb/realtime/v1` too.
9
9
  */
10
10
  const projectAdmin = (project, config, db, ui, reporter, upgradeWebSocket) => {
11
11
  const { resources, views, pages, userMenu, bottomBars, subscriptions } = configExports(config);
@@ -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 };
@@ -28,7 +28,7 @@ const liveTables = (live) => {
28
28
  if (live.length === 0) return [];
29
29
  return [`## Live tables
30
30
 
31
- The \`supabase_realtime\` publication sent these tables' changes to Realtime clients, so the scaffold gave each resource \`.live()\`. \`/realtime/v1\` sends their \`postgres_changes\` once the database has the jobs schema, their capture triggers and the notices table: run \`protobase migration\` and apply it.
31
+ The \`supabase_realtime\` publication sent these tables' changes to Realtime clients, so the scaffold gave each resource \`.live()\`. \`/api/sb/realtime/v1\` sends their \`postgres_changes\` once the database has the jobs schema, their capture triggers and the notices table: run \`protobase migration\` and apply it.
32
32
 
33
33
  ${live.map((table) => `- ${table}`).join("\n")}
34
34
  `];
@@ -60,14 +60,16 @@ const importReport = (manifest, doctor, jobsWired, live) => [
60
60
  ...recurringJobs(manifest, jobsWired),
61
61
  section("Cron jobs", "These pg_cron jobs did not come over, each for the reason it gives. Make each a Protobase recurring job, or schedule it where the database has pg_cron.", cronLeft(manifest.cronJobs)),
62
62
  ...liveTables(live),
63
- section("Realtime tables", "The `supabase_realtime` publication sends these tables' changes to Realtime clients, but the scaffold made no resource of them, such as for a table without a primary key or one in auth or storage, so `/realtime/v1` refuses them. Give each a resource with `.live()` where the app listens to its changes.", manifest.realtimeTables.map(tableName).filter((table) => !live.includes(table))),
63
+ section("Realtime tables", "The `supabase_realtime` publication sends these tables' changes to Realtime clients, but the scaffold made no resource of them, such as for a table without a primary key or one in auth or storage, so `/api/sb/realtime/v1` refuses them. Give each a resource with `.live()` where the app listens to its changes.", manifest.realtimeTables.map(tableName).filter((table) => !live.includes(table))),
64
64
  section("Vault secrets", "The project's database has no Vault, or the importing role could not read the secrets' values, so they stay in Supabase. Enter each again where the app reads it, such as an environment variable.", manifest.vaultReplayed ? [] : manifest.vaultSecrets?.map(secretName)),
65
65
  section("pgmq queues", "pgmq owns its queues' tables, so the dump leaves them out. Make each again with pgmq where the project's database has it, partitioned ones with `pgmq.create_partitioned`, and send its messages again.", queuesLeft(manifest)),
66
66
  section("Extensions left out", "The project's database does not let the importing role create these, so the migration does not. Replace what the app uses them for, or have the database's administrator make them available.", manifest.extensionsLeftOut.map((extension) => `${extension.name} (schema ${extension.schema})`)),
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
@@ -30,7 +30,7 @@ const copyBytes = async (download, store, object, key) => {
30
30
  return fault;
31
31
  };
32
32
  /**
33
- * Copies one object's bytes into `store`, at the key `/storage/v1` serves the object's row from. A download Supabase
33
+ * Copies one object's bytes into `store`, at the key `/api/sb/storage/v1` serves the object's row from. A download Supabase
34
34
  * refuses, a copy that does not match, or a store that is full fails this object only; anything else, such as the
35
35
  * connection failing, stops the copy, which a rerun resumes.
36
36
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.30.2",
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.30.2",
40
- "@protobase/query": "0.30.2",
41
- "@protobase/schema": "0.30.2",
42
- "@protobase/server": "0.30.2",
43
- "@protobase/ui": "0.30.2",
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`.
@@ -159,7 +159,7 @@ export const operations = resource('operations')
159
159
  - **`update` follows the parent's own parents**, so with VMs under `.parent((r) => r.folder_id, 'update')` an operation needs update on the VM's folder too. A write that would put a record under itself, or under a cycle already in the data, is refused. A `read` parent is not followed further.
160
160
  - **Several parents** are each checked with their own access, also two of one resource, such as a transfer that reads its `source_vm_id` and updates its `target_vm_id`.
161
161
  - **The parent is locked until the write commits** (`FOR NO KEY UPDATE`), so a VM handed to someone else or deleted at the same moment is waited for and checked again. That is the cost: writes of records under one parent, and through an `update` parent under one ancestor, run one after another. The server's database role needs `UPDATE` on the parent's table to take the lock. Two writes that lock the same records in opposite orders, such as two batches writing under VM A then B and B then A, can deadlock: Postgres rolls one back, which answers `409` and writes nothing, and the client sends it again.
162
- - The record page and `/api/meta` count the check, so the admin app offers no Edit or Delete the server would refuse. `/rest/v1` does not use Protobase's access rules at all, so this check is not part of it.
162
+ - The record page and `/api/meta` count the check, so the admin app offers no Edit or Delete the server would refuse. `/api/sb/rest/v1` does not use Protobase's access rules at all, so this check is not part of it.
163
163
 
164
164
  ## Restricted model and row filters
165
165
 
@@ -186,7 +186,7 @@ Real login is [Better Auth](auth.md)). Lower level:
186
186
 
187
187
  The API sends no CORS headers until it has something to allow: other websites in `options.cors` (a list of origins, or `'*'` for any), which defaults to `PROTOBASE_CORS_ORIGINS` (`*` or comma separated http and https origins), other [origins of the app](auth.md#several-origins)), which are always allowed, or a [mobile section](../guides/mobile-app.md)), which allows the app's Capacitor origins, `capacitor://localhost` and `https://localhost`. `PROTOBASE_CORS_ORIGINS` refuses other schemes at startup.
188
188
 
189
- - It covers `/api/*` but Better Auth's `/api/auth/*`, which checks origins itself, and [API functions](../guides/api-functions.md)) with a `cors` of their own, and supabase-js's sign-in at [`/auth/v1`](auth.md#supabase-js-and-supabasessr)).
189
+ - It covers `/api/*` but Better Auth's `/api/auth/*`, which checks origins itself, and [API functions](../guides/api-functions.md)) with a `cors` of their own; supabase-js's [`/api/sb`](auth.md#supabase-js-and-supabasessr)) is under it too.
190
190
  - An allowed origin gets `Access-Control-Allow-Origin` with its name and `Vary: Origin`, or `*` with `'*'`. No credentials: browser code calls the API with a bearer token.
191
191
  - Preflights are answered before authentication, for `authorization`, `content-type`, `if-match`, `if-none-match` and supabase-js's `apikey`, `x-client-info` and `x-supabase-api-version`, and kept for 10 minutes. `Location`, `ETag`, `X-Meta-Version` and `X-Protobase-Warning` are exposed.
192
192
  - An API whose resources another app draws as [remote resources](remote-resources.md#cors)) lists that app's origin here.
@@ -482,15 +482,15 @@ Their tokens are verified against that app's keys at `<issuer>/api/auth/jwks`; a
482
482
 
483
483
  ## supabase-js and @supabase/ssr
484
484
 
485
- An app moving from Supabase keeps its `supabase.auth` calls and its `@supabase/ssr` session checks: the app serves GoTrue's endpoints at `/auth/v1`, over the same Better Auth sign-in, so `createClient(<the app's origin>, <publishable key>)` signs in, refreshes, reads the user and signs out as on Supabase.
485
+ An app moving from Supabase keeps its `supabase.auth` calls and its `@supabase/ssr` session checks: the app serves GoTrue's endpoints at `/api/sb/auth/v1`, over the same Better Auth sign-in, so `createClient(<the app's origin>/api/sb, <publishable key>)` signs in, refreshes, reads the user and signs out as on Supabase.
486
486
 
487
487
  - `signInWithPassword`, `signInWithOtp` then `verifyOtp({ email, token, type: 'email' })`, `signInWithOAuth` with one of the app's [sign-in providers](#sign-in-with-github) (PKCE, as `@supabase/ssr` uses, or the implicit flow), `refreshSession`, `getUser`, `getClaims`, `updateUser({ password, data })` and `signOut` work. Each goes through Better Auth's own endpoint, with its rate limits and the [sign-in policy](#sign-in-policy).
488
488
  - The implicit flow is for an https `redirect_to` only. For http, including localhost, and custom schemes, use PKCE: supabase-js `flowType: 'pkce'`; `@supabase/ssr` already uses it.
489
- - The sign-in must start at `/auth/v1/authorize` in the same browser: `/auth/v1/callback` hands a code or a session only at the end of a provider sign-in started there.
489
+ - The sign-in must start at `/api/sb/auth/v1/authorize` in the same browser: `/api/sb/auth/v1/callback` hands a code or a session only at the end of a provider sign-in started there.
490
490
  - The browser keeps no Protobase session afterwards: the app holds its own.
491
491
  - A wildcard pattern in `TRUSTED_ORIGINS` lets implicit-flow tokens go to any https host it matches.
492
492
  - Addresses are proved with the emailed 6-digit code, never a link. `signUp({ email, password, options: { data } })` needs [open sign-up](#open-sign-up) and mails a sign-up code; `verifyOtp({ email, token, type: 'signup' })` makes the account, with `data` in the [user metadata column](#an-existing-users-table), and signs in. Until then there is no account and `signUp` answers no user. `resetPasswordForEmail` mails a sign-in code; `verifyOtp` with `type: 'recovery'` signs in, and `updateUser({ password })` sets the new password.
493
- - The access token is ES256, valid for an hour, with Supabase's claims: `sub`, `role: authenticated`, `aud: authenticated`, `email`, `app_metadata`, `user_metadata`, `aal`, `session_id`, issued by `<baseURL>/auth/v1`. Its keys are at `/auth/v1/.well-known/jwks.json`. It is apart from the EdDSA token of [Tokens and roles](#tokens-and-roles): neither is accepted for the other.
493
+ - The access token is ES256, valid for an hour, with Supabase's claims: `sub`, `role: authenticated`, `aud: authenticated`, `email`, `app_metadata`, `user_metadata`, `aal`, `session_id`, issued by `<baseURL>/api/sb/auth/v1`. Its keys are at `/api/sb/auth/v1/.well-known/jwks.json`. It is apart from the EdDSA token of [Tokens and roles](#tokens-and-roles): neither is accepted for the other.
494
494
  - The refresh token is the Better Auth session's token. Each refresh gives the session a new one, so a refresh token works once, and signing out, a ban or a revoked session ends it.
495
495
  - `email_confirmed_at` is the time the address was confirmed, in the user table's `email_confirmed_at` column. An account verified before that column existed has none.
496
496
  - Not offered: MFA, passkeys, SSO, phone sign-in, anonymous sign-in, the admin API and changing the address.
@@ -101,7 +101,7 @@ Exit code is 1 when there are errors. Run it after the project's migrations and
101
101
  protobase dev [--port 5173] [--env DATABASE_URL] [--cache-dir <dir>] [--allowed-hosts <hosts>] [--extend <dir>] # run inside a project, e.g. bun run --cwd examples/erp dev
102
102
  ```
103
103
 
104
- One process, one port: Vite serves the admin app from `@protobase/ui`'s `src/app/` (`dist/app/` when installed; `index.html` and `main.tsx`, or `main.js`; the command fails with a clear message when they are missing) and `@hono/vite-dev-server` mounts the Hono app from `createAdmin` under `/api`, with supabase-js's `/auth/v1` and `/realtime/v1`. Open `http://localhost:<port>`; the API reference is at `/api/docs`.
104
+ One process, one port: Vite serves the admin app from `@protobase/ui`'s `src/app/` (`dist/app/` when installed; `index.html` and `main.tsx`, or `main.js`; the command fails with a clear message when they are missing) and `@hono/vite-dev-server` mounts the Hono app from `createAdmin` under `/api`, supabase-js's `/api/sb` included. Open `http://localhost:<port>`; the API reference is at `/api/docs`.
105
105
 
106
106
  - **Database:** the URL comes from the variable named by `--env`, read from the environment or the nearest `.env` at or above the project. The connection is checked before anything starts; if it fails, the command names host, port and reason (and points to its `db:up` script when it has one). The project needs `pg` installed, because the API connects with Kysely over the project's own `pg`.
107
107
  - **Cache:** Vite's dependency cache is `node_modules/.vite`; two dev servers sharing it can disturb each other's optimisation, so pass `--cache-dir` for a second one (the integration test does).
@@ -472,11 +472,11 @@ 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 [`/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
- 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 [`/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.
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
 
481
481
  Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
482
482
 
@@ -2,14 +2,14 @@
2
2
 
3
3
  # Supabase Realtime
4
4
 
5
- The Realtime-compatible /realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence.
5
+ The Realtime-compatible /api/sb/realtime/v1 that supabase-js's channel() joins, for postgres_changes checked under the subscriber's RLS policies, broadcasts and presence.
6
6
 
7
- An app with API keys also serves `/realtime/v1/websocket`, the socket that supabase-js's `channel()` joins. An app moved from Supabase keeps its `postgres_changes` listeners, broadcasts and presence: point the client at the app and give it the publishable key.
7
+ An app with API keys also serves `/api/sb/realtime/v1/websocket`, the socket that supabase-js's `channel()` joins. An app moved from Supabase keeps its `postgres_changes` listeners, broadcasts and presence: point the client at the app's `/api/sb` and give it the publishable key.
8
8
 
9
9
  ```ts
10
10
  import { createClient } from '@supabase/supabase-js'
11
11
 
12
- const supabase = createClient('https://my-app.example.com', 'sb_publishable_...')
12
+ const supabase = createClient('https://my-app.example.com/api/sb', 'sb_publishable_...')
13
13
  supabase
14
14
  .channel('my-todos')
15
15
  .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'todos', filter: 'done=eq.false' }, (payload) => console.log(payload.new))
@@ -44,7 +44,7 @@ room
44
44
 
45
45
  A broadcast reaches the topic's other channels, and the sender's own with `self`; with `ack`, `send` resolves once the server has it. Binary payloads go to clients on the default serializer (`vsn` 2.0.0) only. Presence follows Phoenix Presence: a channel tracks one presence under its `presence.key` (a random one when it names none), tracking again replaces it, and channels with presence enabled get the state when they join and each join and leave after, their own included. A channel that leaves, closes or whose token expires leaves the presence it tracked.
46
46
 
47
- Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; several processes behind one address do not reach each other's channels. Sending without a joined channel, which supabase-js does over `POST /realtime/v1/api/broadcast`, is not supported.
47
+ Broadcasts and presence go between the channels of one serving process, which is how a cloud app runs; several processes behind one address do not reach each other's channels. Sending without a joined channel, which supabase-js does over `POST /api/sb/realtime/v1/api/broadcast`, is not supported.
48
48
 
49
49
  ## What a subscriber receives
50
50
 
@@ -2,20 +2,20 @@
2
2
 
3
3
  # Supabase client API
4
4
 
5
- The PostgREST-compatible /rest/v1 that supabase-js's from() and rpc() call, under the tables' RLS policies.
5
+ The PostgREST-compatible /api/sb/rest/v1 that supabase-js's from() and rpc() call, under the tables' RLS policies.
6
6
 
7
- An app with API keys also serves `/rest/v1`, the API that supabase-js's `from()` and `rpc()` call. An app moved from Supabase keeps its data calls: point the client at the app and give it the publishable key.
7
+ An app with API keys also serves `/api/sb/rest/v1`, the API that supabase-js's `from()` and `rpc()` call. An app moved from Supabase keeps its data calls: point the client at the app's `/api/sb` and give it the publishable key.
8
8
 
9
9
  ```ts
10
10
  import { createClient } from '@supabase/supabase-js'
11
11
 
12
- const supabase = createClient('https://my-app.example.com', 'sb_publishable_...')
12
+ const supabase = createClient('https://my-app.example.com/api/sb', 'sb_publishable_...')
13
13
  const { data, error } = await supabase.from('todos').select('id, title').eq('done', false).order('id')
14
14
  ```
15
15
 
16
16
  ## Keys and roles
17
17
 
18
- The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. Without either, or with `apiKeys: false`, the app serves no `/rest/v1`. Each request sends a key in the `apikey` header, and runs in one transaction as:
18
+ The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. Without either, or with `apiKeys: false`, the app serves no `/api/sb/rest/v1`. Each request sends a key in the `apikey` header, and runs in one transaction as:
19
19
 
20
20
  | The request sends | It runs as |
21
21
  | --- | --- |
@@ -25,13 +25,13 @@ The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key
25
25
 
26
26
  The transaction sets the role with `SET LOCAL ROLE` and the token's claims in `request.jwt.claims` and `request.jwt.claim.sub`, so Supabase's `auth.uid()`, `auth.role()` and `auth.jwt()` work, and the tables' RLS policies decide what the request may read and write. The `role` claim is the database role, as on Supabase. The database needs the `anon` and `authenticated` roles, and the app's role must be allowed to `SET ROLE` to them.
27
27
 
28
- `/rest/v1` serves the tables the app declares as resources, in the `public` schema, under their table names. Any other table is `404`.
28
+ `/api/sb/rest/v1` serves the tables the app declares as resources, in the `public` schema, under their table names. Any other table is `404`.
29
29
 
30
30
  ## What it understands
31
31
 
32
32
  - Filters: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `like`, `ilike`, `match`, `imatch`, `in`, `is`, `isdistinct`, `fts`, `plfts`, `phfts`, `wfts` with a language, `cs`, `cd`, `ov`, `sl`, `sr`, `nxr`, `nxl`, `adj`, `any` and `all` modifiers, `not.`, and `or`, `and`, `not.or` and `not.and` trees, on columns and JSON paths (`meta->>kind`).
33
33
  - `select` with columns, aliases (`key:id`), casts (`priority::text`) and JSON paths.
34
- - Embedded rows of related tables, through their foreign keys: `select('*, author:profiles(name), comments(*)')`. A many-to-one or one-to-one embed is an object or `null`, a one-to-many one an array. A hint picks the foreign key when several relate the tables, by its name or column (`profiles!sender_id(name)`), and `!inner` keeps only the rows with a related row. Filters, `order`, `limit` and `offset` take the embed's name or alias as a prefix (`comments.likes=gte.2`, `comments.order=id.desc`), as supabase-js's `referencedTable` option sends them. The embedded tables' RLS policies apply too. Only tables `/rest/v1` serves are embedded.
34
+ - Embedded rows of related tables, through their foreign keys: `select('*, author:profiles(name), comments(*)')`. A many-to-one or one-to-one embed is an object or `null`, a one-to-many one an array. A hint picks the foreign key when several relate the tables, by its name or column (`profiles!sender_id(name)`), and `!inner` keeps only the rows with a related row. Filters, `order`, `limit` and `offset` take the embed's name or alias as a prefix (`comments.likes=gte.2`, `comments.order=id.desc`), as supabase-js's `referencedTable` option sends them. The embedded tables' RLS policies apply too. Only tables `/api/sb/rest/v1` serves are embedded.
35
35
  - `order`, `limit`, `offset` and the `Range` header. A read returns at most 1000 rows, Supabase's default.
36
36
  - `Prefer: count=exact|planned|estimated`, with the count in `Content-Range` and `206` for part of the rows.
37
37
  - `Prefer: return=minimal|representation`, `resolution=merge-duplicates|ignore-duplicates`, `missing=default`, and `on_conflict` and `columns`.
@@ -2,24 +2,24 @@
2
2
 
3
3
  # Supabase Storage API
4
4
 
5
- The Storage-compatible /storage/v1 that supabase-js's storage calls, over the app's file provider, under the restored storage policies.
5
+ The Storage-compatible /api/sb/storage/v1 that supabase-js's storage calls, over the app's file provider, under the restored storage policies.
6
6
 
7
- An app with API keys also serves `/storage/v1`, the API that supabase-js's `storage` calls. An app moved from Supabase keeps its uploads, downloads, public URLs and signed URLs: point the client at the app and give it the publishable key.
7
+ An app with API keys also serves `/api/sb/storage/v1`, the API that supabase-js's `storage` calls. An app moved from Supabase keeps its uploads, downloads, public URLs and signed URLs: point the client at the app's `/api/sb` and give it the publishable key.
8
8
 
9
9
  ```ts
10
10
  import { createClient } from '@supabase/supabase-js'
11
11
 
12
- const supabase = createClient('https://my-app.example.com', 'sb_publishable_...')
12
+ const supabase = createClient('https://my-app.example.com/api/sb', 'sb_publishable_...')
13
13
  const { data, error } = await supabase.storage.from('avatars').upload(`${userId}/avatar.png`, file)
14
14
  ```
15
15
 
16
16
  ## Where things are kept
17
17
 
18
- The buckets and objects are the rows of `storage.buckets` and `storage.objects`, the schema that `protobase import supabase` restores with its policies. The bytes go to one of the app's [file providers](files.md)): `files.storage.provider` in `protobase.config.ts`, `private` by default, so a local folder or an S3-compatible bucket, with that provider's `max_bytes` and `max_files` quota. An object's bytes are kept at `storage/<SHA-256 of bucket and name>/<version>` in the provider, where [`protobase import supabase --storage-url`](cli.md#import-supabase)) copies a Supabase project's. `files.storage.maxFileSize` caps every upload, `50 MB` by default, and a bucket's `file_size_limit` can only lower it. `files: { storage: false }` serves no `/storage/v1`.
18
+ The buckets and objects are the rows of `storage.buckets` and `storage.objects`, the schema that `protobase import supabase` restores with its policies. The bytes go to one of the app's [file providers](files.md)): `files.storage.provider` in `protobase.config.ts`, `private` by default, so a local folder or an S3-compatible bucket, with that provider's `max_bytes` and `max_files` quota. An object's bytes are kept at `storage/<SHA-256 of bucket and name>/<version>` in the provider, where [`protobase import supabase --storage-url`](cli.md#import-supabase)) copies a Supabase project's. `files.storage.maxFileSize` caps every upload, `50 MB` by default, and a bucket's `file_size_limit` can only lower it. `files: { storage: false }` serves no `/api/sb/storage/v1`.
19
19
 
20
20
  ## Keys and roles
21
21
 
22
- The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. Without either, or with `apiKeys: false`, the app serves no `/storage/v1`. A request sends a key in the `apikey` header and runs as:
22
+ The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. Without either, or with `apiKeys: false`, the app serves no `/api/sb/storage/v1`. A request sends a key in the `apikey` header and runs as:
23
23
 
24
24
  | The request sends | It runs as |
25
25
  | --- | --- |
@@ -36,7 +36,7 @@ The role is set with `SET LOCAL ROLE` and the token's claims in `request.jwt.cla
36
36
 
37
37
  An upload is checked against the policies before its bytes are stored, then its row is written as the caller in one transaction. A refused upload stores nothing, and the bytes of a write that fails are deleted.
38
38
 
39
- Public buckets are served at `/storage/v1/object/public/<bucket>/<name>` without a key. A signed URL serves one object to anyone until it expires; a signed upload URL takes one upload for two hours, written for the user who signed it.
39
+ Public buckets are served at `/api/sb/storage/v1/object/public/<bucket>/<name>` without a key. A signed URL serves one object to anyone until it expires; a signed upload URL takes one upload for two hours, written for the user who signed it.
40
40
 
41
41
  ## What it serves
42
42