@protobase/cli 0.31.0 → 0.31.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/package.js +1 -1
- package/dist/dev/entry.js +8 -1
- package/dist/dev/run.js +3 -2
- package/dist/dev/supabase-env.js +27 -0
- package/dist/serve/lifecycle.js +2 -1
- package/dist/supabase/checkout.js +1 -8
- package/dist/supabase/dump-phase.js +11 -2
- package/dist/supabase/functions/convert-source.js +167 -0
- package/dist/supabase/functions/import-map.js +19 -0
- package/dist/supabase/functions/plan-functions.js +99 -0
- package/dist/supabase/functions/public-functions.js +22 -0
- package/dist/supabase/functions/specifier.js +56 -0
- package/dist/supabase/functions/write-functions.js +43 -0
- package/dist/supabase/report.js +3 -1
- package/package.json +9 -6
- package/skills/protobase/SKILL.md +2 -0
- package/skills/protobase/references/guides/api-functions.md +9 -0
- package/skills/protobase/references/reference/cli.md +5 -3
- package/skills/supabase-move/SKILL.md +113 -0
- package/skills/supabase-move/references/deno.md +33 -0
package/dist/cli/package.js
CHANGED
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 {
|
|
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 };
|
package/dist/serve/lifecycle.js
CHANGED
|
@@ -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
|
|
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
|
|
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:
|
|
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 };
|
package/dist/supabase/report.js
CHANGED
|
@@ -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`
|
|
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.
|
|
3
|
+
"version": "0.31.2",
|
|
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.
|
|
40
|
-
"@protobase/query": "0.31.
|
|
41
|
-
"@protobase/schema": "0.31.
|
|
42
|
-
"@protobase/server": "0.31.
|
|
43
|
-
"@protobase/ui": "0.31.
|
|
39
|
+
"@protobase/layout": "0.31.2",
|
|
40
|
+
"@protobase/query": "0.31.2",
|
|
41
|
+
"@protobase/schema": "0.31.2",
|
|
42
|
+
"@protobase/server": "0.31.2",
|
|
43
|
+
"@protobase/ui": "0.31.2",
|
|
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
|
}
|
|
@@ -27,6 +27,8 @@ Run the CLI as the project does: `npx protobase <command>`, or `bun run protobas
|
|
|
27
27
|
|
|
28
28
|
An app hosted on protobase-cloud deploys from a push to its GitHub branch instead: the `protobase-cloud` skill, which `protobase skill install` writes next to this one, covers it.
|
|
29
29
|
|
|
30
|
+
A project moved from Supabase with `protobase import supabase` has what the import could not convert in `supabase-import/report.md`: the `supabase-move` skill, written next to this one too, finishes it.
|
|
31
|
+
|
|
30
32
|
## Rules of thumb
|
|
31
33
|
|
|
32
34
|
- Records live at the framework's standard addresses and API; give a resource another look through its views, layouts or a plugin, not a page with routes of its own.
|
|
@@ -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,12 +472,14 @@ 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
|
|
|
481
|
+
An agent with the `supabase-move` skill of [`skill install`](#skill) finishes what the report leaves: it rewrites each item, checking the project's database for the extensions an item needs, and runs `doctor` and the typecheck until both pass, leaving the values of Vault's secrets for you to enter.
|
|
482
|
+
|
|
481
483
|
Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
|
|
482
484
|
|
|
483
485
|
## `mobile`
|
|
@@ -513,7 +515,7 @@ curl -H "Authorization: Bearer $(protobase token me@x)" http://localhost:5173/ap
|
|
|
513
515
|
protobase skill install [name]
|
|
514
516
|
```
|
|
515
517
|
|
|
516
|
-
Copies the agent skills of this CLI's version into the current project, or only the one `name` names. `protobase`, the protobase agent skill, goes to `.agents/skills/protobase/` (read by Codex, Cursor, OpenCode and Amp) and `.claude/skills/protobase/` (read by Claude Code): a short `SKILL.md` with the everyday workflow and the checks before calling a change done, and the guides and reference of this version as files it points to. `protobase-cloud` goes to `.agents/skills/protobase-cloud/` and `.claude/skills/protobase-cloud/`: how an app hosted on protobase-cloud deploys from GitHub, how to check that a change went live, and why a deploy failed. Each replaces an earlier copy, and refuses to touch a folder of its name that holds another skill. Commit the folders, and run the command again after upgrading the `@protobase` packages. The skills also ship in `node_modules/@protobase/cli/skills`, where the `skills` CLI's `experimental_sync` finds it.
|
|
518
|
+
Copies the agent skills of this CLI's version into the current project, or only the one `name` names. `protobase`, the protobase agent skill, goes to `.agents/skills/protobase/` (read by Codex, Cursor, OpenCode and Amp) and `.claude/skills/protobase/` (read by Claude Code): a short `SKILL.md` with the everyday workflow and the checks before calling a change done, and the guides and reference of this version as files it points to. `protobase-cloud` goes to `.agents/skills/protobase-cloud/` and `.claude/skills/protobase-cloud/`: how an app hosted on protobase-cloud deploys from GitHub, how to check that a change went live, and why a deploy failed. `supabase-move` goes beside them: it has an agent work through `supabase-import/report.md` after [`import supabase`](#import-supabase), item by item, until `doctor` and the app's typecheck pass. Each replaces an earlier copy, and refuses to touch a folder of its name that holds another skill. Commit the folders, and run the command again after upgrading the `@protobase` packages. The skills also ship in `node_modules/@protobase/cli/skills`, where the `skills` CLI's `experimental_sync` finds it.
|
|
517
519
|
|
|
518
520
|
## ERP example
|
|
519
521
|
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: supabase-move
|
|
3
|
+
description: Finish a move from Supabase to Protobase after `protobase import supabase`, item by item from its report (supabase-import/report.md), until `protobase doctor` and the app's typecheck pass. Use it when a project has supabase-import/report.md, or when asked to finish or complete a Supabase import.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Finishing a move from Supabase
|
|
7
|
+
|
|
8
|
+
`protobase import supabase` converts what it can and writes `supabase-import/report.md` with the rest. This skill works through that report, one `## ` section at a time, in the report's order. The `protobase` skill beside this one has the guides and reference it links to.
|
|
9
|
+
|
|
10
|
+
## Rules
|
|
11
|
+
|
|
12
|
+
- **Never invent data.** Copy only what the Supabase project states: a URL, a header, a schedule, a column's value. A secret's value is never in the report or the code: leave it for the user to enter. A column with nothing to go on stays NULL; add no `DEFAULT` that stands in for "unknown".
|
|
13
|
+
- **Rewrite only what the project's database lacks.** Before rewriting the use of an extension, check that database, not the report alone: a Pro or Business app's own Postgres runs every extension it had on Supabase, and there pg_net, pg_cron, pgmq and Vault stay as they are.
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
psql "$DATABASE_URL" -Atc "select name, installed_version is not null from pg_available_extensions where name in ('pg_net', 'pg_cron', 'pgmq', 'supabase_vault') order by 1"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
An extension that is listed but not installed is created by a migration (`create extension if not exists <name>;`), not rewritten.
|
|
20
|
+
- **Database changes are new migrations** in the project's migrations folder, numbered after the last one, applied with the project's own migrate script (`db:migrate`). Never edit the import's `NNN_supabase_schema.sql` once it is applied, and never change the database by hand.
|
|
21
|
+
- **Never loosen a check** to make it pass: not the scan guard, not `strict`, not a `// @ts-ignore`.
|
|
22
|
+
- When a conversion needs a decision only the user can make, such as a paid service to replace one Supabase ran, stop on that item, say what it needs, and go on with the others.
|
|
23
|
+
|
|
24
|
+
## The loop
|
|
25
|
+
|
|
26
|
+
1. Read `supabase-import/report.md` and work through its sections below.
|
|
27
|
+
2. `protobase migration`, then the project's migrate script: it writes the jobs schema, the events' capture and the rest of what the config now enables.
|
|
28
|
+
3. The app's typecheck (`tsc --noEmit`, or its `typecheck` script).
|
|
29
|
+
4. `protobase doctor --env DATABASE_URL`.
|
|
30
|
+
5. Fix what 3 and 4 report and go back to 2, until both pass.
|
|
31
|
+
6. Tell the user what is theirs to do: the variables to fill in, items you stopped on, and `--storage-url` if the files are not copied yet.
|
|
32
|
+
|
|
33
|
+
## The report, section by section
|
|
34
|
+
|
|
35
|
+
### Rows loaded
|
|
36
|
+
|
|
37
|
+
Nothing to do: each table's count matched the source before the load committed.
|
|
38
|
+
|
|
39
|
+
### Made again
|
|
40
|
+
|
|
41
|
+
Nothing to do: the project's database has these extensions and the load made each item again there.
|
|
42
|
+
|
|
43
|
+
### Recurring jobs
|
|
44
|
+
|
|
45
|
+
The import wrote these in `jobs/`. Wire `jobs/index.ts` into `protobase.config.ts`'s `jobs` if the report says it is not, then run step 2 of the loop. See [Jobs](../protobase/references/reference/jobs.md#recurring-jobs).
|
|
46
|
+
|
|
47
|
+
### Cron jobs
|
|
48
|
+
|
|
49
|
+
Each line is a pg_cron job, its schedule, its command and why it did not come over.
|
|
50
|
+
|
|
51
|
+
- Calls `net.http_get` or `net.http_post`, and the database has pg_net: schedule it again with `cron.schedule` in a migration, as it was, when the database has pg_cron, or keep its SQL as a recurring job when it does not.
|
|
52
|
+
- Calls pg_net, and the database has none: a recurring job in `jobs/<name>.ts` with `defineJob({ name, schedule, timezone, run })`, of the same name and schedule, whose `run` makes the same request with `fetch`: the same method, URL, headers and body. A header or URL that read a Vault secret reads `requireEnv('<NAME>')` instead (see Vault secrets). Throw when the response is not `ok`, so the failure shows. Export it from `jobs/index.ts`.
|
|
53
|
+
- A schedule recurring jobs do not take, such as `30 seconds`: the closest cron expression only if the user agrees; otherwise leave it and say so.
|
|
54
|
+
- Inactive: ask the user whether it should run before making it a job.
|
|
55
|
+
|
|
56
|
+
### Live tables
|
|
57
|
+
|
|
58
|
+
Nothing to do but step 2 of the loop, which writes their capture triggers.
|
|
59
|
+
|
|
60
|
+
### Realtime tables
|
|
61
|
+
|
|
62
|
+
Give each table a resource with `.live()` in `config/` where the app listens to its changes (look for `postgres_changes` with this table in the app's client code). A table without a primary key needs one first, as a migration, only when the user agrees. See [Supabase Realtime](../protobase/references/reference/supabase-realtime.md).
|
|
63
|
+
|
|
64
|
+
### Vault secrets
|
|
65
|
+
|
|
66
|
+
Each secret moves to an environment variable the user enters again. Name it after the secret, upper case (`stripe_key` → `STRIPE_KEY`), and:
|
|
67
|
+
|
|
68
|
+
- add it to `.env.example` (create it if missing) with an empty value and the secret's description as a comment;
|
|
69
|
+
- where code read it (`vault.decrypted_secrets` in SQL, a function or a cron job), read `requireEnv('<NAME>')` in TypeScript instead. SQL that needs the secret moves into a job or function that does;
|
|
70
|
+
- never write the value anywhere, and never put one in `.env.example`.
|
|
71
|
+
|
|
72
|
+
### pgmq queues
|
|
73
|
+
|
|
74
|
+
With pgmq in the database, make each queue again in a migration (`select pgmq.create('<name>')`, or `pgmq.create_partitioned`); the user sends the messages again, since the report gives only their count. Without pgmq, move the queue's producers and consumers to a Protobase job: `defineJob` with the consumer's work as `run`, and `jobs.enqueue('<name>', payload)` where SQL called `pgmq.send`. See [Jobs](../protobase/references/reference/jobs.md#from-sql).
|
|
75
|
+
|
|
76
|
+
### Extensions left out
|
|
77
|
+
|
|
78
|
+
For each, find what uses it: `grep -n '<extension>\|<schema>\.' db/migrations/*supabase_schema.sql` and the app's code. A use the app's code can take over (`pgjwt` → `jose` in a function, `http` → `fetch` in a job, `pg_hashids` → an npm package) moves there. A use that needs the extension itself, such as PostGIS columns, needs a database that has it: stop on it and tell the user.
|
|
79
|
+
|
|
80
|
+
### To convert
|
|
81
|
+
|
|
82
|
+
- A hypertable: a plain table, or one partitioned by time with a migration; its rows came over empty, so the user copies them from Supabase with `INSERT … SELECT`. Do not make them up.
|
|
83
|
+
- A function in plv8, plls or plcoffee: rewrite it in plpgsql in a migration, keeping its name, arguments and result; or as a Protobase API function when nothing in SQL calls it.
|
|
84
|
+
|
|
85
|
+
### HTTP triggers
|
|
86
|
+
|
|
87
|
+
Each line is a trigger, its table, and the function it calls (`supabase_functions.http_request` for a Database Webhook). The report lists them only when the database lacked pg_net; check again, as above.
|
|
88
|
+
|
|
89
|
+
Without pg_net, replace each with an event and a subscription:
|
|
90
|
+
|
|
91
|
+
1. On the table's resource, declare the event the trigger fired on: `e.created()`, `e.updated()`, `e.deleted()` or `e.crud()`, with a `when` for its `WHEN` clause. See [Events](../protobase/references/reference/events.md).
|
|
92
|
+
2. Export a `subscription(...)` from the config module with that event, and as target: `function: '<name>'` when the URL was one of the app's own Edge Functions (`.../functions/v1/<name>`), otherwise `url` with the URL the trigger named. Copy its headers into `headers`, a secret one from the environment. A receiver that reads Supabase's payload (`type`, `table`, `schema`, `record`, `old_record`) gets it through `body`. See [Webhooks](../protobase/references/reference/webhooks.md).
|
|
93
|
+
3. Drop the trigger, and a trigger function only it used, in a migration.
|
|
94
|
+
|
|
95
|
+
### Storage files
|
|
96
|
+
|
|
97
|
+
Ask the user to run `protobase import supabase --storage-url https://<ref>.supabase.co` with their project's secret key in `SUPABASE_SERVICE_ROLE_KEY`, unless `supabase-import/storage.md` says the files are copied. Never ask for the key in the conversation.
|
|
98
|
+
|
|
99
|
+
### Edge Functions
|
|
100
|
+
|
|
101
|
+
`supabase/functions` keeps the Deno originals, which the app no longer runs: add `supabase` to the `exclude` of `tsconfig.json` so the typecheck leaves them out, and remove the folder only when the user says so. Look in each for `waitUntil(`: work in it that can outlast about 10 seconds after the response, such as sending mail, calling a slow API or a loop over many records, moves into a job enqueued instead (`await job.enqueue(db, payload)`), since a host stops an idle app and loses work still running. See [Functions moved from Supabase](../protobase/references/guides/api-functions.md#functions-moved-from-supabase).
|
|
102
|
+
|
|
103
|
+
### Packages added
|
|
104
|
+
|
|
105
|
+
Run the project's install (`npm install`, `bun install`, ...). A `npm:@jsr/...` range needs `@jsr:registry=https://npm.jsr.io` in `.npmrc`.
|
|
106
|
+
|
|
107
|
+
### Edge Function code to rewrite
|
|
108
|
+
|
|
109
|
+
Each line is `<file>:<line>: <what>`. Rewrite each for Node and Bun as [Deno and Supabase's runtime](references/deno.md) says, keeping what the code does.
|
|
110
|
+
|
|
111
|
+
### Indexes the scan guard needs
|
|
112
|
+
|
|
113
|
+
Each `error` doctor printed ends in `fix: create index ...`. Add each index in a migration of its own, apply it, and run doctor again.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Deno and Supabase's runtime, for Node and Bun
|
|
2
|
+
|
|
3
|
+
What the conversion leaves in `functions/`, by the note the report gives, and what replaces it. A function runs under Node and Bun with Web APIs (`fetch`, `Request`, `Response`, `crypto.subtle`, `URL`) and Node's built-in modules.
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
| Note | Rewrite |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| `import of https://deno.land/std@.../<module>/...` | The same module from JSR, `@std/<module>`, in `package.json` as `"@std/<module>": "npm:@jsr/std__<module>@^1"` with `@jsr:registry=https://npm.jsr.io` in `.npmrc`; or Node's own, where it has one (`std/path` → `node:path`, `std/encoding/base64` → `Buffer.from(x).toString('base64')`, `std/crypto` → `crypto.subtle`). |
|
|
10
|
+
| `import of https://deno.land/x/<module>...` | The npm package of the same library, when its README names one; otherwise a maintained npm package that does the same, which the user agrees to. Take its version from `npm view <package> version`, never from memory. A database client (`deno.land/x/postgres`) becomes the function's `db` (Kysely on the app's database). |
|
|
11
|
+
| `import of https://<other host>/...` | The npm package the URL serves, by the same rule. |
|
|
12
|
+
|
|
13
|
+
## Deno
|
|
14
|
+
|
|
15
|
+
| Note | Rewrite |
|
|
16
|
+
| --- | --- |
|
|
17
|
+
| `Deno.readTextFile`, `Deno.readFile`, `Deno.writeTextFile`, `Deno.writeFile` | `readFile`, `writeFile` of `node:fs/promises`. A file beside the function: `new URL('./<file>', import.meta.url)`. Bundled apps have no writable folder: data a function wrote to disk goes to a table or the app's Storage instead. |
|
|
18
|
+
| `Deno.env.toObject` | `process.env`. |
|
|
19
|
+
| `Deno.cwd`, `Deno.args`, `Deno.exit` | `process.cwd()`; no arguments; throw an error instead of exiting. |
|
|
20
|
+
| `Deno.openKv` | A table, in a migration, in a schema named for what it keeps (`create table <schema>.<name> (key text[] primary key, value jsonb not null, expires_at timestamptz)`), read and written with the function's `db`. `expireIn` becomes `expires_at`, and readers skip expired rows. Deno KV's data does not come over: start empty, unless the user exports it. |
|
|
21
|
+
| `Deno.upgradeWebSocket` | A function answers HTTP only. Move the messages to Realtime broadcast on a channel, which supabase-js reaches at `/api/sb/realtime/v1` (see [Supabase Realtime](../../protobase/references/reference/supabase-realtime.md)), and change the client to it; when that does not fit, stop on it and tell the user. |
|
|
22
|
+
| `Deno.serve(...)` or `serve(...)`, `which Protobase does not run` | Make the file's default export `{ fetch: handler }` itself, once per function, in its `index.ts`. |
|
|
23
|
+
| `no Deno.serve or default export to serve` | Find the handler and default-export `{ fetch: handler }`. |
|
|
24
|
+
| `<dir> has no index.ts, so it was not imported` | Move its entry point to `index.ts` in `supabase/functions/<name>`, and convert it as the import did: rerun it in a scratch checkout, or apply this table by hand. |
|
|
25
|
+
| `asks for <package> <range>, another file for <range>` | Make both files work with one version, the range `package.json` has. |
|
|
26
|
+
|
|
27
|
+
## Supabase's runtime
|
|
28
|
+
|
|
29
|
+
| Note | Rewrite |
|
|
30
|
+
| --- | --- |
|
|
31
|
+
| `Supabase.ai.Session('gte-small')` | The same model under Node with `@huggingface/transformers`: `const embed = await pipeline('feature-extraction', 'Supabase/gte-small')` once per process, then `Array.from((await embed(text, { pooling: 'mean', normalize: true })).data)` where the code called `session.run(text, { mean_pool: true, normalize: true })`. It gives the same 384 numbers, so stored embeddings keep matching. |
|
|
32
|
+
| `Supabase.ai.Session('<an LLM>')` | A call to an OpenAI-compatible chat completions endpoint with `fetch`, its URL, key and model from `requireEnv`; the user picks the provider and fills them in. |
|
|
33
|
+
| `EdgeRuntime.<anything but waitUntil>` | Drop it, or its Node equivalent (`process.version` for the version). |
|