@protobase/cli 0.30.1 → 0.31.0
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/api-websockets.js +1 -1
- package/dist/dev/run.js +1 -1
- package/dist/project/project-admin.js +1 -1
- package/dist/supabase/import-state.js +4 -2
- package/dist/supabase/in-parallel.js +16 -0
- package/dist/supabase/project-files.js +12 -0
- package/dist/supabase/register.js +13 -2
- package/dist/supabase/report.js +3 -2
- package/dist/supabase/run.js +17 -3
- package/dist/supabase/storage-copy.js +48 -0
- package/dist/supabase/storage-download.js +10 -0
- package/dist/supabase/storage-objects.js +16 -0
- package/dist/supabase/storage-phase.js +42 -0
- package/dist/supabase/storage-report.js +18 -0
- package/dist/supabase/storage-sizes.js +22 -0
- package/dist/supabase/storage-verify.js +16 -0
- package/package.json +6 -6
- package/skills/protobase/references/reference/access.md +1 -1
- package/skills/protobase/references/reference/api.md +1 -1
- package/skills/protobase/references/reference/auth.md +3 -3
- package/skills/protobase/references/reference/cli.md +5 -2
- package/skills/protobase/references/reference/supabase-realtime.md +4 -4
- package/skills/protobase/references/reference/supabase-rest.md +6 -6
- package/skills/protobase/references/reference/supabase-storage.md +7 -7
package/dist/cli/package.js
CHANGED
|
@@ -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/run.js
CHANGED
|
@@ -96,7 +96,7 @@ const runDev = async (options, out) => {
|
|
|
96
96
|
tailwindcss(),
|
|
97
97
|
devServer({
|
|
98
98
|
entry,
|
|
99
|
-
exclude: [/^(?!\/
|
|
99
|
+
exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)).*/],
|
|
100
100
|
injectClientScript: false
|
|
101
101
|
})
|
|
102
102
|
]
|
|
@@ -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);
|
|
@@ -5,7 +5,8 @@ import { appendFile, mkdir, readFile, writeFile } from "node:fs/promises";
|
|
|
5
5
|
/**
|
|
6
6
|
* The project's folder for an import in progress, kept out of git: the data dump, which holds the users' password
|
|
7
7
|
* hashes and every row, and the replay of Vault's secrets, pgmq's queues and pg_cron's jobs, which holds the secrets'
|
|
8
|
-
* values, each readable by its owner only until the load deletes it; the manifest; and the report
|
|
8
|
+
* values, each readable by its owner only until the load deletes it; the manifest; the report; and the report of the
|
|
9
|
+
* copy of Storage's bytes.
|
|
9
10
|
*/
|
|
10
11
|
const importState = (projectDir) => {
|
|
11
12
|
const dir = path.join(projectDir, "supabase-import");
|
|
@@ -14,7 +15,8 @@ const importState = (projectDir) => {
|
|
|
14
15
|
replay: path.join(dir, "replay.sql"),
|
|
15
16
|
load: path.join(dir, "load.sql"),
|
|
16
17
|
manifest: path.join(dir, "import.json"),
|
|
17
|
-
report: path.join(dir, "report.md")
|
|
18
|
+
report: path.join(dir, "report.md"),
|
|
19
|
+
storage: path.join(dir, "storage.md")
|
|
18
20
|
};
|
|
19
21
|
return {
|
|
20
22
|
dir,
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/supabase/in-parallel.ts
|
|
2
|
+
/** `run` over `items`, at most `limit` at a time, giving the results in the items' order. */
|
|
3
|
+
const inParallel = async (items, limit, run) => {
|
|
4
|
+
const results = new Array(items.length);
|
|
5
|
+
let next = 0;
|
|
6
|
+
const worker = async () => {
|
|
7
|
+
while (next < items.length) {
|
|
8
|
+
const index = next++;
|
|
9
|
+
results[index] = await run(items[index]);
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
13
|
+
return results;
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { inParallel };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { importProjectFile } from "../project/import-project-file.js";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
//#region src/supabase/project-files.ts
|
|
5
|
+
/** `files` of the project's protobase.config.ts, or none when it has no such file or no `files`. */
|
|
6
|
+
const projectFilesOptions = async (projectDir) => {
|
|
7
|
+
const file = path.join(projectDir, "protobase.config.ts");
|
|
8
|
+
if (!existsSync(file)) return {};
|
|
9
|
+
return (await importProjectFile(file)).default?.files ?? {};
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { projectFilesOptions };
|
|
@@ -8,8 +8,14 @@ const variable = (name) => {
|
|
|
8
8
|
if (!value) throw new Error(`Environment variable ${name} is not set`);
|
|
9
9
|
return value;
|
|
10
10
|
};
|
|
11
|
+
const projectUrl = (text) => {
|
|
12
|
+
const url = URL.canParse(text) ? new URL(text) : void 0;
|
|
13
|
+
if (!url || url.protocol !== "https:" && url.protocol !== "http:") throw new Error("--storage-url is not a URL; write it like https://<ref>.supabase.co");
|
|
14
|
+
if (url.username || url.password) throw new Error("--storage-url must not hold credentials; put the secret key in the variable --storage-key-env names");
|
|
15
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
16
|
+
};
|
|
11
17
|
const registerImport = (program) => {
|
|
12
|
-
program.command("import").description("Turn another platform's project into this Protobase project").command("supabase").description("Import a Supabase database into the project in the current directory. The first run dumps it and writes its schemas as the project's next migration; once the project's migrations are applied, the second run loads the data, scaffolds the config and writes supabase-import/report.md").argument("[source]", "the Supabase database's connection string, for the first run").option("--source-env <variable>", "read the Supabase connection string from this environment variable").option("--env <variable>", "environment variable holding the project's database URL", "DATABASE_URL").option("--dir <dir>", "migrations folder", "db/migrations").option("--config <dir>", "config folder", "config").action(async (source, opts) => {
|
|
18
|
+
program.command("import").description("Turn another platform's project into this Protobase project").command("supabase").description("Import a Supabase database into the project in the current directory. The first run dumps it and writes its schemas as the project's next migration; once the project's migrations are applied, the second run loads the data, scaffolds the config and writes supabase-import/report.md. With --storage-url, the second run, or any later one, copies Storage's files into the app's file provider").argument("[source]", "the Supabase database's connection string, for the first run").option("--source-env <variable>", "read the Supabase connection string from this environment variable").option("--env <variable>", "environment variable holding the project's database URL", "DATABASE_URL").option("--dir <dir>", "migrations folder", "db/migrations").option("--config <dir>", "config folder", "config").option("--storage-url <url>", "the Supabase project's URL, such as https://<ref>.supabase.co, to copy Storage's files from").option("--storage-key-env <variable>", "environment variable holding the Supabase project's secret key, for --storage-url", "SUPABASE_SERVICE_ROLE_KEY").option("--yes", "copy Storage's files even when they exceed the file provider's max_bytes", false).action(async (source, opts) => {
|
|
13
19
|
if (source && opts.sourceEnv) throw new Error("Pass either a connection string or --source-env, not both");
|
|
14
20
|
const projectDir = process.cwd();
|
|
15
21
|
loadNearestEnvFile(projectDir);
|
|
@@ -18,7 +24,12 @@ const registerImport = (program) => {
|
|
|
18
24
|
targetUrl: variable(opts.env),
|
|
19
25
|
projectDir,
|
|
20
26
|
migrationsDir: path.resolve(opts.dir),
|
|
21
|
-
configDir: path.resolve(opts.config)
|
|
27
|
+
configDir: path.resolve(opts.config),
|
|
28
|
+
storage: opts.storageUrl ? {
|
|
29
|
+
url: projectUrl(opts.storageUrl),
|
|
30
|
+
key: variable(opts.storageKeyEnv)
|
|
31
|
+
} : void 0,
|
|
32
|
+
yes: opts.yes
|
|
22
33
|
}, out);
|
|
23
34
|
});
|
|
24
35
|
};
|
package/dist/supabase/report.js
CHANGED
|
@@ -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,12 +60,13 @@ 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
|
+
"## 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",
|
|
69
70
|
section("Edge Functions", "`supabase/functions` holds these, which the import does not convert.", manifest.functions),
|
|
70
71
|
`## 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`
|
|
71
72
|
].join("\n");
|
package/dist/supabase/run.js
CHANGED
|
@@ -1,18 +1,32 @@
|
|
|
1
1
|
import { importState } from "./import-state.js";
|
|
2
2
|
import { runDumpPhase } from "./dump-phase.js";
|
|
3
3
|
import { runLoadPhase } from "./load-phase.js";
|
|
4
|
+
import { runStorageCopy } from "./storage-phase.js";
|
|
4
5
|
//#region src/supabase/run.ts
|
|
5
6
|
/**
|
|
6
7
|
* `protobase import supabase`, in two runs with the project's migrations between them: the first dumps the source
|
|
7
8
|
* and writes the schema migration, the second loads the data into the migrated database. Which run this is follows
|
|
8
|
-
* from `supabase-import/`: a manifest with its data dump is an import waiting for its load.
|
|
9
|
+
* from `supabase-import/`: a manifest with its data dump is an import waiting for its load. Given a Supabase project
|
|
10
|
+
* to copy Storage's bytes from, the second run copies them after the load, and a later run copies what is left.
|
|
9
11
|
*/
|
|
10
12
|
const runSupabaseImport = async (options, out) => {
|
|
11
13
|
const state = importState(options.projectDir);
|
|
12
14
|
const pending = state.hasManifest() && state.hasData();
|
|
15
|
+
const copyStorage = (source) => runStorageCopy({
|
|
16
|
+
targetUrl: options.targetUrl,
|
|
17
|
+
projectDir: options.projectDir,
|
|
18
|
+
source,
|
|
19
|
+
yes: options.yes
|
|
20
|
+
}, out);
|
|
13
21
|
if (pending && options.sourceUrl) throw new Error("An import is waiting in supabase-import/: apply its migration and run `protobase import supabase` without a source to load it, or remove supabase-import/ to start over");
|
|
14
|
-
if (pending)
|
|
15
|
-
|
|
22
|
+
if (pending) {
|
|
23
|
+
await runLoadPhase(options, out);
|
|
24
|
+
if (options.storage) await copyStorage(options.storage);
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (state.hasManifest() && options.storage && !options.sourceUrl) return copyStorage(options.storage);
|
|
28
|
+
if (state.hasManifest()) throw new Error(`This project imported a Supabase database already (see ${state.report}); pass --storage-url to copy Storage's files, or remove supabase-import/ to import again`);
|
|
29
|
+
if (options.storage) throw new Error("--storage-url copies Storage's files once the data is loaded; dump the database first");
|
|
16
30
|
if (!options.sourceUrl) throw new Error("Pass the Supabase database's connection string, or --source-env <VARIABLE>: the session pooler's or the direct one, for the postgres role");
|
|
17
31
|
return runDumpPhase({
|
|
18
32
|
...options,
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { copyFault } from "./storage-verify.js";
|
|
2
|
+
import { HttpProblem, objectKey } from "@protobase/server";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
//#region src/supabase/storage-copy.ts
|
|
5
|
+
const measured = () => {
|
|
6
|
+
const hash = createHash("md5");
|
|
7
|
+
let size = 0;
|
|
8
|
+
return {
|
|
9
|
+
stream: new TransformStream({ transform: (chunk, controller) => {
|
|
10
|
+
size += chunk.length;
|
|
11
|
+
hash.update(chunk);
|
|
12
|
+
controller.enqueue(chunk);
|
|
13
|
+
} }),
|
|
14
|
+
result: () => ({
|
|
15
|
+
size,
|
|
16
|
+
md5: hash.digest("hex")
|
|
17
|
+
})
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
const copyBytes = async (download, store, object, key) => {
|
|
21
|
+
const response = await download(object.bucket, object.name);
|
|
22
|
+
if (!response.ok || !response.body) {
|
|
23
|
+
await response.body?.cancel();
|
|
24
|
+
return `Supabase answered ${response.status}`;
|
|
25
|
+
}
|
|
26
|
+
const measure = measured();
|
|
27
|
+
await store.put(key, response.body.pipeThrough(measure.stream));
|
|
28
|
+
const fault = copyFault(object, measure.result(), (await store.head(key))?.size);
|
|
29
|
+
if (fault) await store.delete(key);
|
|
30
|
+
return fault;
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
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
|
+
* refuses, a copy that does not match, or a store that is full fails this object only; anything else, such as the
|
|
35
|
+
* connection failing, stops the copy, which a rerun resumes.
|
|
36
|
+
*/
|
|
37
|
+
const copyObject = async (download, store, object) => {
|
|
38
|
+
const key = await objectKey(object.bucket, object.name, object.version);
|
|
39
|
+
return {
|
|
40
|
+
object,
|
|
41
|
+
fault: await copyBytes(download, store, object, key).catch((error) => {
|
|
42
|
+
if (error instanceof HttpProblem && error.status === 507) return "the file provider is full";
|
|
43
|
+
throw error;
|
|
44
|
+
})
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
//#endregion
|
|
48
|
+
export { copyObject };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
//#region src/supabase/storage-download.ts
|
|
2
|
+
/** Where Supabase's Storage API serves an object's bytes to the secret key: each segment of the name encoded. */
|
|
3
|
+
const objectUrl = (projectUrl, bucket, name) => `${projectUrl.replace(/\/+$/, "")}/storage/v1/object/authenticated/${encodeURIComponent(bucket)}/${name.split("/").map(encodeURIComponent).join("/")}`;
|
|
4
|
+
/** Downloads from the Supabase project `source` with its secret key, which goes in the request's headers only. */
|
|
5
|
+
const supabaseDownload = (source) => (bucket, name) => fetch(objectUrl(source.url, bucket, name), { headers: {
|
|
6
|
+
apikey: source.key,
|
|
7
|
+
authorization: `Bearer ${source.key}`
|
|
8
|
+
} });
|
|
9
|
+
//#endregion
|
|
10
|
+
export { objectUrl, supabaseDownload };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/supabase/storage-objects.ts
|
|
2
|
+
/** Every object the load restored to `storage.objects`, by bucket and name. */
|
|
3
|
+
const storageObjects = async (sql) => {
|
|
4
|
+
return (await sql`
|
|
5
|
+
select bucket_id as bucket, name, version, metadata->>'size' as size, metadata->>'eTag' as etag
|
|
6
|
+
from storage.objects where name is not null order by bucket_id, name
|
|
7
|
+
`).map((row) => ({
|
|
8
|
+
bucket: row.bucket,
|
|
9
|
+
name: row.name,
|
|
10
|
+
version: row.version,
|
|
11
|
+
size: row.size === null ? void 0 : Number(row.size),
|
|
12
|
+
eTag: row.etag ?? void 0
|
|
13
|
+
}));
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { storageObjects };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { connect } from "../db/connect.js";
|
|
2
|
+
import { importState } from "./import-state.js";
|
|
3
|
+
import { inParallel } from "./in-parallel.js";
|
|
4
|
+
import { projectFilesOptions } from "./project-files.js";
|
|
5
|
+
import { alreadyCopied } from "./storage-verify.js";
|
|
6
|
+
import { copyObject } from "./storage-copy.js";
|
|
7
|
+
import { supabaseDownload } from "./storage-download.js";
|
|
8
|
+
import { storageObjects } from "./storage-objects.js";
|
|
9
|
+
import { bucketLines, megabytes, objectCount, overQuota, totalBytes } from "./storage-sizes.js";
|
|
10
|
+
import { storageReport } from "./storage-report.js";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { writeFile } from "node:fs/promises";
|
|
13
|
+
import { objectKey, storageProvider, storeUsage } from "@protobase/server";
|
|
14
|
+
//#region src/supabase/storage-phase.ts
|
|
15
|
+
/** Objects copied at once: enough to keep a connection busy, few enough for any host. */
|
|
16
|
+
const parallel = 4;
|
|
17
|
+
/**
|
|
18
|
+
* Copies the bytes of every object the load restored to `storage.objects` from the Supabase project into the app's
|
|
19
|
+
* Storage file provider, streaming each, and checks each copy. Objects already in the provider are skipped, so a rerun
|
|
20
|
+
* resumes; a failed object does not stop the rest, and the run fails at the end, listing them in the storage report.
|
|
21
|
+
* It stops first when the bytes to copy exceed the provider's quota, unless `yes`.
|
|
22
|
+
*/
|
|
23
|
+
const runStorageCopy = async (options, out, download = supabaseDownload(options.source)) => {
|
|
24
|
+
const state = importState(options.projectDir);
|
|
25
|
+
const { name, provider } = storageProvider(await projectFilesOptions(options.projectDir), process.env);
|
|
26
|
+
const sql = connect(options.targetUrl);
|
|
27
|
+
const objects = await storageObjects(sql).finally(() => sql.end());
|
|
28
|
+
out(`Supabase Storage holds ${objectCount(objects.length)}, ${megabytes(totalBytes(objects))}:\n${bucketLines(objects).join("")}`);
|
|
29
|
+
const stored = await inParallel(objects, parallel, async (object) => (await provider.store.head(await objectKey(object.bucket, object.name, object.version)))?.size);
|
|
30
|
+
const todo = objects.filter((object, index) => !alreadyCopied(object, stored[index]));
|
|
31
|
+
const over = provider.maxBytes === void 0 ? void 0 : overQuota(totalBytes(todo), (await storeUsage(provider.store)).bytes, provider.maxBytes);
|
|
32
|
+
if (over && !options.yes) throw new Error(over);
|
|
33
|
+
out(`copying ${objectCount(todo.length)}, ${megabytes(totalBytes(todo))}, into the file provider ${name}; ${objects.length - todo.length} are there already\n`);
|
|
34
|
+
const outcomes = await inParallel(todo, parallel, (object) => copyObject(download, provider.store, object));
|
|
35
|
+
const failed = outcomes.filter((outcome) => outcome.fault);
|
|
36
|
+
await writeFile(state.storage, storageReport(options.source.url, name, objects, outcomes), { mode: 384 });
|
|
37
|
+
const report = path.relative(options.projectDir, state.storage);
|
|
38
|
+
if (failed.length > 0) throw new Error(`${failed.length} of ${objectCount(todo.length)} did not copy, listed in ${report}; run the command again to retry them`);
|
|
39
|
+
out(`copied ${objectCount(todo.length)}; each byte count matches the source. Wrote ${report}\n`);
|
|
40
|
+
};
|
|
41
|
+
//#endregion
|
|
42
|
+
export { runStorageCopy };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { megabytes, objectCount, totalBytes } from "./storage-sizes.js";
|
|
2
|
+
//#region src/supabase/storage-report.ts
|
|
3
|
+
const cell = (text) => text.replaceAll("|", "\\|").replaceAll("\n", " ");
|
|
4
|
+
/**
|
|
5
|
+
* `supabase-import/storage.md`: what the last copy of Storage's bytes did, from the Supabase project at `url`, into the
|
|
6
|
+
* file provider `provider`, and each object that failed, which the next run tries again.
|
|
7
|
+
*/
|
|
8
|
+
const storageReport = (url, provider, objects, outcomes) => {
|
|
9
|
+
const failed = outcomes.filter((outcome) => outcome.fault);
|
|
10
|
+
const copied = outcomes.length - failed.length;
|
|
11
|
+
return [
|
|
12
|
+
"# Supabase Storage copy\n",
|
|
13
|
+
`From ${url} into the file provider \`${provider}\`: ${objectCount(objects.length)}, ${megabytes(totalBytes(objects))}. This run copied ${copied}, found ${objects.length - outcomes.length} copied already and failed ${failed.length}. Each copy's byte count matched the size Supabase recorded, and its MD5 the object's ETag where that is one.\n`,
|
|
14
|
+
failed.length === 0 ? "## Failed\n\nNone.\n" : `## Failed\n\nRun \`protobase import supabase --storage-url ${url}\` again to retry these.\n\n| Bucket | Object | Why |\n| --- | --- | --- |\n${failed.map(({ object, fault }) => `| ${cell(object.bucket)} | ${cell(object.name)} | ${cell(fault)} |`).join("\n")}\n`
|
|
15
|
+
].join("\n");
|
|
16
|
+
};
|
|
17
|
+
//#endregion
|
|
18
|
+
export { storageReport };
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//#region src/supabase/storage-sizes.ts
|
|
2
|
+
/** Bytes in decimal megabytes, as `max_bytes=500MB` counts them. */
|
|
3
|
+
const megabytes = (bytes) => `${(bytes / 1e6).toFixed(1)} MB`;
|
|
4
|
+
const objectCount = (count) => `${count} object${count === 1 ? "" : "s"}`;
|
|
5
|
+
/** The bytes Supabase recorded for `objects`; an object without a recorded size counts as empty. */
|
|
6
|
+
const totalBytes = (objects) => objects.reduce((sum, object) => sum + (object.size ?? 0), 0);
|
|
7
|
+
/** Each bucket's objects and bytes, as lines to print before the copy. */
|
|
8
|
+
const bucketLines = (objects) => {
|
|
9
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
10
|
+
for (const object of objects) buckets.set(object.bucket, [...buckets.get(object.bucket) ?? [], object]);
|
|
11
|
+
return [...buckets].map(([bucket, inBucket]) => ` ${bucket}: ${objectCount(inBucket.length)}, ${megabytes(totalBytes(inBucket))}\n`);
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Why the copy stops before it starts, or `undefined` when it fits: the bytes still to copy (`todo`) and those the
|
|
15
|
+
* store holds already (`used`) together exceed the provider's `maxBytes`.
|
|
16
|
+
*/
|
|
17
|
+
const overQuota = (todo, used, maxBytes) => {
|
|
18
|
+
if (maxBytes === void 0 || todo + used <= maxBytes) return void 0;
|
|
19
|
+
return `The objects still to copy take ${megabytes(todo)} and the file provider holds ${megabytes(used)} already, more than its ${megabytes(maxBytes)}: pick a larger plan or raise its max_bytes, or pass --yes to copy until it is full`;
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
export { bucketLines, megabytes, objectCount, overQuota, totalBytes };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/supabase/storage-verify.ts
|
|
2
|
+
const md5ETag = /^"?([0-9a-f]{32})"?$/i;
|
|
3
|
+
/** Whether a copy already in the store, of `storedSize` bytes, is the object's, so a rerun skips it. */
|
|
4
|
+
const alreadyCopied = (object, storedSize) => storedSize !== void 0 && (object.size === void 0 || storedSize === object.size);
|
|
5
|
+
/**
|
|
6
|
+
* What is wrong with a copy, or `undefined` when it is the object's: the bytes read (`read`, with their MD5) and those
|
|
7
|
+
* the store holds after the write (`stored`) must be the size Supabase recorded, and the MD5 its ETag where that is one.
|
|
8
|
+
*/
|
|
9
|
+
const copyFault = (object, read, stored) => {
|
|
10
|
+
if (object.size !== void 0 && read.size !== object.size) return `read ${read.size} bytes, Supabase recorded ${object.size}`;
|
|
11
|
+
if (stored !== read.size) return `the file provider holds ${stored ?? "no"} bytes of the ${read.size} written`;
|
|
12
|
+
const etag = object.eTag?.match(md5ETag)?.[1]?.toLowerCase();
|
|
13
|
+
if (etag && etag !== read.md5) return `MD5 ${read.md5} differs from the ETag ${etag}`;
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { alreadyCopied, copyFault };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.31.0",
|
|
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.
|
|
40
|
-
"@protobase/query": "0.
|
|
41
|
-
"@protobase/schema": "0.
|
|
42
|
-
"@protobase/server": "0.
|
|
43
|
-
"@protobase/ui": "0.
|
|
39
|
+
"@protobase/layout": "0.31.0",
|
|
40
|
+
"@protobase/query": "0.31.0",
|
|
41
|
+
"@protobase/schema": "0.31.0",
|
|
42
|
+
"@protobase/server": "0.31.0",
|
|
43
|
+
"@protobase/ui": "0.31.0",
|
|
44
44
|
"@react-email/render": "^2.1.0",
|
|
45
45
|
"@scalar/hono-api-reference": "^0.12.10",
|
|
46
46
|
"@tailwindcss/vite": "^4.3.3",
|
|
@@ -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
|
|
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
|
|
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`,
|
|
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).
|
|
@@ -467,13 +467,16 @@ Run inside a project whose `protobase.config.ts` exports `auth`, against its dat
|
|
|
467
467
|
|
|
468
468
|
```sh
|
|
469
469
|
protobase import supabase [<connection> | --source-env <variable>] [--env DATABASE_URL] [--dir db/migrations] [--config config]
|
|
470
|
+
[--storage-url <url>] [--storage-key-env SUPABASE_SERVICE_ROLE_KEY] [--yes]
|
|
470
471
|
```
|
|
471
472
|
|
|
472
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`).
|
|
473
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
476
|
2. **Apply the migration** with the project's other migrations, such as `bun run db:migrate`.
|
|
476
|
-
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, Edge Functions, and the indexes [`doctor`](#doctor) finds missing.
|
|
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 [`/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.
|
|
477
480
|
|
|
478
481
|
Remove `supabase-import/` to import again. Signing in Supabase's users with Protobase's auth is not part of this command yet.
|
|
479
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. `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
|
|
|
@@ -47,7 +47,7 @@ Public buckets are served at `/storage/v1/object/public/<bucket>/<name>` without
|
|
|
47
47
|
|
|
48
48
|
A download is sent with the type it was uploaded with, `nosniff` and a sandboxing Content-Security-Policy, so an uploaded page cannot run on the app's origin, and `?download` makes it an attachment.
|
|
49
49
|
|
|
50
|
-
Not yet: image transforms, resumable (TUS) uploads, the S3 protocol, object versioning
|
|
50
|
+
Not yet: image transforms, resumable (TUS) uploads, the S3 protocol, and object versioning.
|
|
51
51
|
|
|
52
52
|
## Errors
|
|
53
53
|
|