@protobase/cli 0.26.5 → 0.26.7

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.
@@ -0,0 +1,28 @@
1
+ import { isProjectFile } from "./project-files.js";
2
+ import { createAdaptorServer } from "@hono/node-server";
3
+ import { WebSocketServer } from "ws";
4
+ //#region src/dev/api-websockets.ts
5
+ const isApiWebSocket = (url) => /^\/realtime\/v1\/websocket(\?|$)/.test(url);
6
+ const restartCode = 1012;
7
+ const apiWebSockets = (entry, dirs) => {
8
+ const wss = new WebSocketServer({ noServer: true });
9
+ return {
10
+ name: "protobase-api-websockets",
11
+ configureServer: (server) => {
12
+ const upgrades = createAdaptorServer({
13
+ fetch: async (request, env) => (await server.ssrLoadModule(entry)).default.fetch(request, env),
14
+ overrideGlobalObjects: false,
15
+ websocket: { server: wss }
16
+ });
17
+ server.httpServer?.on("upgrade", (request, socket, head) => {
18
+ if (isApiWebSocket(request.url ?? "")) upgrades.emit("upgrade", request, socket, head);
19
+ });
20
+ server.httpServer?.on("close", () => upgrades.emit("close"));
21
+ },
22
+ handleHotUpdate: ({ file }) => {
23
+ if (isProjectFile(dirs, file)) wss.clients.forEach((client) => client.close(restartCode));
24
+ }
25
+ };
26
+ };
27
+ //#endregion
28
+ export { apiWebSockets, isApiWebSocket };
package/dist/dev/entry.js CHANGED
@@ -3,6 +3,7 @@ import { projectErrorReporter } from "../project/error-reporter.js";
3
3
  import { projectAdmin } from "../project/project-admin.js";
4
4
  import { loadProject, projectDb } from "./project.js";
5
5
  import { checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkWebhooksSchema, configExports, hasUsers } from "@protobase/server";
6
+ import { upgradeWebSocket } from "@hono/node-server";
6
7
  import { Hono } from "hono";
7
8
  //#region src/dev/entry.ts
8
9
  const projectDir = process.env.PROTOBASE_PROJECT;
@@ -29,7 +30,7 @@ const reporter = await projectErrorReporter(project, process.env);
29
30
  const { admin, jobs } = projectAdmin({
30
31
  ...project,
31
32
  authenticate: project.authenticate
32
- }, project.exports, db, void 0, reporter);
33
+ }, project.exports, db, void 0, reporter, upgradeWebSocket);
33
34
  await devJobs(db, jobs);
34
35
  var entry_default = new Hono().route("/", admin);
35
36
  if (project.auth && !store.__protobaseNoUsersShown) {
@@ -0,0 +1,5 @@
1
+ import path from "node:path";
2
+ //#region src/dev/project-files.ts
3
+ const isProjectFile = (dirs, file) => dirs.some((dir) => file.startsWith(`${dir}${path.sep}`)) && !file.includes(`${path.sep}node_modules${path.sep}`);
4
+ //#endregion
5
+ export { isProjectFile };
package/dist/dev/run.js CHANGED
@@ -9,6 +9,8 @@ import { faviconLink } from "../project/favicon-link.js";
9
9
  import { themeLink } from "../project/theme-link.js";
10
10
  import { checkDatabase } from "./check-database.js";
11
11
  import { stopDevJobs } from "./dev-jobs.js";
12
+ import { isProjectFile } from "./project-files.js";
13
+ import { apiWebSockets } from "./api-websockets.js";
12
14
  import { existsSync } from "node:fs";
13
15
  import path from "node:path";
14
16
  import { createServer, searchForWorkspaceRoot } from "vite";
@@ -24,7 +26,7 @@ const requireAppFiles = (appDir) => {
24
26
  const reloadOnProjectChange = (dirs) => ({
25
27
  name: "protobase-project-reload",
26
28
  handleHotUpdate: ({ file, server }) => {
27
- if (dirs.some((dir) => file.startsWith(`${dir}${path.sep}`)) && !file.includes(`${path.sep}node_modules${path.sep}`)) server.environments.ssr.moduleGraph.invalidateAll();
29
+ if (isProjectFile(dirs, file)) server.environments.ssr.moduleGraph.invalidateAll();
28
30
  }
29
31
  });
30
32
  const stopJobsOnClose = {
@@ -56,6 +58,7 @@ const runDev = async (options, out) => {
56
58
  requireAppFiles(appDir);
57
59
  await checkDatabase(url, options.projectDir);
58
60
  const extensions = options.extensions ?? [];
61
+ const projectDirs = [options.projectDir, ...extensions.map((extension) => extension.dir)];
59
62
  process.env.PROTOBASE_PROJECT = options.projectDir;
60
63
  process.env.PROTOBASE_EXTENSIONS = JSON.stringify(extensions);
61
64
  process.env.PROTOBASE_DATABASE_URL = url;
@@ -79,7 +82,8 @@ const runDev = async (options, out) => {
79
82
  ] }
80
83
  },
81
84
  plugins: [
82
- reloadOnProjectChange([options.projectDir, ...extensions.map((extension) => extension.dir)]),
85
+ reloadOnProjectChange(projectDirs),
86
+ apiWebSockets(entry, projectDirs),
83
87
  stopJobsOnClose,
84
88
  sharedModulesPlugin(),
85
89
  themeLink(options.projectDir),
@@ -92,7 +96,7 @@ const runDev = async (options, out) => {
92
96
  tailwindcss(),
93
97
  devServer({
94
98
  entry,
95
- exclude: [/^(?!\/api(\/|\?|$)|\/\.well-known\/webauthn(\?|$)).*/],
99
+ exclude: [/^(?!\/(api|auth\/v1|realtime\/v1)(\/|\?|$)|\/\.well-known\/webauthn(\?|$)).*/],
96
100
  injectClientScript: false
97
101
  })
98
102
  ]
package/dist/package.js CHANGED
@@ -1,4 +1,4 @@
1
1
  //#region package.json
2
- var version = "0.26.5";
2
+ var version = "0.26.7";
3
3
  //#endregion
4
4
  export { version };
@@ -1,11 +1,11 @@
1
1
  import * as server from "@protobase/server";
2
2
  import * as postgres$1 from "postgres";
3
+ import * as nodeServer from "@hono/node-server";
3
4
  import * as query from "@protobase/query";
4
5
  import * as kysely from "kysely";
5
6
  import * as pg$1 from "pg";
6
7
  import * as schema from "@protobase/schema";
7
8
  import * as layout from "@protobase/layout";
8
- import * as nodeServer from "@hono/node-server";
9
9
  import * as hono from "hono";
10
10
  import * as reactEmailRender from "@react-email/render";
11
11
  import * as apiReference from "@scalar/hono-api-reference";
@@ -3,9 +3,9 @@ import { createPgDb } from "../project/pg-db.js";
3
3
  import { createServeApp } from "./app.js";
4
4
  import { startCleanupTimer } from "./cleanup-timer.js";
5
5
  import { checkAi, checkAuthSchema, checkChanges, checkComments, checkComputed, checkJobsSchema, checkWebhooksSchema, configExports, createFileCleanup, startJobs } from "@protobase/server";
6
- import pg from "pg";
7
6
  import { createAdaptorServer, upgradeWebSocket } from "@hono/node-server";
8
7
  import { WebSocketServer } from "ws";
8
+ import pg from "pg";
9
9
  //#region src/serve/lifecycle.ts
10
10
  const listen = (server, port) => new Promise((resolve, reject) => {
11
11
  server.once("error", reject);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/cli",
3
- "version": "0.26.5",
3
+ "version": "0.26.7",
4
4
  "description": "The protobase command: scaffold, doctor, dev, build and serve a Protobase project.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -35,11 +35,11 @@
35
35
  "dependencies": {
36
36
  "@hono/node-server": "^2.1.3",
37
37
  "@hono/vite-dev-server": "^0.26.1",
38
- "@protobase/layout": "0.26.5",
39
- "@protobase/query": "0.26.5",
40
- "@protobase/schema": "0.26.5",
41
- "@protobase/server": "0.26.5",
42
- "@protobase/ui": "0.26.5",
38
+ "@protobase/layout": "0.26.7",
39
+ "@protobase/query": "0.26.7",
40
+ "@protobase/schema": "0.26.7",
41
+ "@protobase/server": "0.26.7",
42
+ "@protobase/ui": "0.26.7",
43
43
  "@react-email/render": "^2.1.0",
44
44
  "@scalar/hono-api-reference": "^0.12.10",
45
45
  "@tailwindcss/vite": "^4.3.3",
@@ -60,6 +60,7 @@ Reference:
60
60
  - When defining views, columns, filters, charts, related records and actions → read [UI config](references/reference/ui-config.md)
61
61
  - When asking how the packages fit together → read [Architecture](references/reference/architecture.md)
62
62
  - When calling or changing the REST API, its filters, writes and errors → read [REST API](references/reference/api.md)
63
+ - When an app calls it with supabase-js, `from()` and `rpc()` under RLS → read [Supabase client API](references/reference/supabase-rest.md)
63
64
  - When working with file fields and uploads → read [Files](references/reference/files.md)
64
65
  - When reacting to changes of records → read [Events](references/reference/events.md)
65
66
  - When delivering events to URLs → read [Webhooks](references/reference/webhooks.md)
@@ -186,9 +186,9 @@ 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 origins), or other [origins of the app](auth.md#several-origins)), which are always allowed.
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, and supabase-js's sign-in at [`/auth/v1`](auth.md#supabase-js-and-supabasessr)).
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
- - Preflights are answered before authentication, for `authorization`, `content-type`, `if-match` and `if-none-match`, and kept for 10 minutes. `Location`, `ETag`, `X-Meta-Version` and `X-Protobase-Warning` are exposed.
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.
193
193
 
194
194
  ## Safety
@@ -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`. Open `http://localhost:<port>`; the API reference is at `/api/docs`.
104
+ One process, one port: Vite serves the admin app from `@protobase/ui`'s `src/app/` (`dist/app/` when installed; `index.html` and `main.tsx`, or `main.js`; the command fails with a clear message when they are missing) and `@hono/vite-dev-server` mounts the Hono app from `createAdmin` under `/api`, with supabase-js's `/auth/v1` and `/realtime/v1`. 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).
@@ -20,7 +20,7 @@ supabase
20
20
 
21
21
  The keys are `options.apiKeys` of `createAdmin`, `{ publishable_key, secret_key }`, or else `PROTOBASE_PUBLISHABLE_KEY` and `PROTOBASE_SECRET_KEY`. The socket sends the key in its URL and is refused with `401` without a key of the app. Each channel joins with the client's access token: a signed-in user's token makes it `authenticated` with the token's claims, the publishable key alone `anon`, the secret key alone the app's own role. A token the client refreshes on an open socket replaces the channel's; a channel whose token expires is closed with a `Token has expired` system message, as on Supabase.
22
22
 
23
- The server serves the socket when the host gives `createAdmin` its WebSocket upgrade: `protobase serve` does, on Bun and Node. `protobase dev` does not serve it yet.
23
+ The server serves the socket when the host gives `createAdmin` its WebSocket upgrade: `protobase serve` does, on Bun and Node, and so does `protobase dev`, beside Vite's hot reload socket. An edit to the project under `protobase dev` closes the open sockets with code `1012`, and supabase-js reconnects to the rebuilt API.
24
24
 
25
25
  ## Which tables
26
26
 
@@ -0,0 +1,48 @@
1
+ <!-- Generated by scripts/protobase-skill.ts from website/src/content/docs/reference/supabase-rest.md: run `bun run docs:skill`, do not edit. -->
2
+
3
+ # Supabase client API
4
+
5
+ The PostgREST-compatible /rest/v1 that supabase-js's from() and rpc() call, under the tables' RLS policies.
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.
8
+
9
+ ```ts
10
+ import { createClient } from '@supabase/supabase-js'
11
+
12
+ const supabase = createClient('https://my-app.example.com', 'sb_publishable_...')
13
+ const { data, error } = await supabase.from('todos').select('id, title').eq('done', false).order('id')
14
+ ```
15
+
16
+ ## Keys and roles
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:
19
+
20
+ | The request sends | It runs as |
21
+ | --- | --- |
22
+ | the publishable key | `anon` |
23
+ | either key and a signed-in user's token | `authenticated` |
24
+ | the secret key | the app's own role, which owns the tables |
25
+
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
+
28
+ `/rest/v1` serves the tables the app declares as resources, in the `public` schema, under their table names. Any other table is `404`.
29
+
30
+ ## What it understands
31
+
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
+ - `select` with columns, aliases (`key:id`), casts (`priority::text`) and JSON paths.
34
+ - `order`, `limit`, `offset` and the `Range` header. A read returns at most 1000 rows, Supabase's default.
35
+ - `Prefer: count=exact|planned|estimated`, with the count in `Content-Range` and `206` for part of the rows.
36
+ - `Prefer: return=minimal|representation`, `resolution=merge-duplicates|ignore-duplicates`, `missing=default`, and `on_conflict` and `columns`.
37
+ - `.single()` and `.maybeSingle()`, through `Accept: application/vnd.pgrst.object+json`.
38
+ - `rpc/<function>` by POST and by GET, which runs read-only. A function returning rows takes `select`, filters, `order`, a range and a count.
39
+
40
+ Not yet: embedding other tables through foreign keys, CSV, other schemas, aggregates and `tx=rollback`.
41
+
42
+ ## Scan guard
43
+
44
+ As on the [REST API](api.md#safety)), a filter or a sort reads only columns an index serves: a btree index for comparisons, `in`, `is` and sorts, a pg_trgm index for patterns and regular expressions, a GIN index for text search and `cs`, `cd` and `ov` (or GiST), and a GiST index for the range operators. A JSON path needs an index on that expression. Any other read is `400` with code `expensive-query` and the statement that adds the index as its `hint`. Functions are not judged.
45
+
46
+ ## Errors
47
+
48
+ Errors come back as PostgREST sends them, `{ code, details, hint, message }`. A database error keeps its Postgres code, message, detail and hint, with PostgREST's status: an RLS refusal (`42501`) is `401` for `anon` and `403` for others, a duplicate (`23505`) `409`, a function that writes called by GET (`25006`) `405`. `.single()` on no or several rows is `406` `PGRST116`, an unknown table `404` `PGRST205`, an unknown function `404` `PGRST202`, and a missing or wrong key or token `401` `PGRST301`.