@rebasepro/server 0.25.1 → 0.26.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/{GCSStorageController-CRd9bFrc.js → GCSStorageController-40FyFeSx.js} +6 -2
- package/dist/GCSStorageController-40FyFeSx.js.map +1 -0
- package/dist/{S3StorageController-D00EFa5P.js → S3StorageController-Bl5shp94.js} +6 -2
- package/dist/S3StorageController-Bl5shp94.js.map +1 -0
- package/dist/access-BFAUvsSs.js +1897 -0
- package/dist/access-BFAUvsSs.js.map +1 -0
- package/dist/api/branch-routes.d.ts +25 -0
- package/dist/api/live-schema-routes.d.ts +10 -0
- package/dist/api/rest/api-generator.d.ts +9 -1
- package/dist/api/rest/idempotency.d.ts +15 -1
- package/dist/api/root-error-handler.d.ts +6 -5
- package/dist/api/types.d.ts +12 -0
- package/dist/{ast-schema-editor-mCeSC03x.js → ast-schema-editor-madTa9Hh.js} +2 -2
- package/dist/{ast-schema-editor-mCeSC03x.js.map → ast-schema-editor-madTa9Hh.js.map} +1 -1
- package/dist/auth/access.d.ts +10 -0
- package/dist/auth/adapter-middleware.d.ts +2 -1
- package/dist/auth/adapter-service-key.d.ts +24 -0
- package/dist/auth/api-keys/api-key-middleware.d.ts +21 -1
- package/dist/auth/api-keys/api-key-store.d.ts +8 -1
- package/dist/auth/api-keys/key-grant.d.ts +18 -1
- package/dist/auth/expired-token-sweep.d.ts +5 -0
- package/dist/auth/impersonation.d.ts +3 -1
- package/dist/auth/jwt.d.ts +8 -2
- package/dist/auth/oauth-signin-policy.d.ts +21 -35
- package/dist/auth/rls-scope.d.ts +17 -7
- package/dist/auth/rls-simulator-routes.d.ts +51 -0
- package/dist/auth/simulation-read-only.d.ts +28 -0
- package/dist/auth/simulation.d.ts +141 -0
- package/dist/auth/sql-rate-limit-store.d.ts +15 -1
- package/dist/{auth-Dkvo2tTJ.js → auth-izI7AEzC.js} +370 -1880
- package/dist/auth-izI7AEzC.js.map +1 -0
- package/dist/auth_adapter-B7RUMk6e.js +89 -0
- package/dist/auth_adapter-B7RUMk6e.js.map +1 -0
- package/dist/backend/create-backend.d.ts +6 -0
- package/dist/backend/options.d.ts +9 -4
- package/dist/{backend-DTAOsLQc.js → backend-CaG_Jyso.js} +9 -2
- package/dist/backend-CaG_Jyso.js.map +1 -0
- package/dist/{backup-B9m3cb3X.js → backup-BVbHoKo8.js} +6 -6
- package/dist/{backup-B9m3cb3X.js.map → backup-BVbHoKo8.js.map} +1 -1
- package/dist/boot/boot.d.ts +2 -15
- package/dist/boot/ddl-bootstrap.d.ts +34 -0
- package/dist/boot/env.d.ts +6 -0
- package/dist/boot/fetch-bundle.d.ts +5 -1
- package/dist/boot/provision-only.d.ts +23 -0
- package/dist/boot/provision.d.ts +53 -2
- package/dist/boot/role.d.ts +2 -0
- package/dist/boot/schema-change-recorder.d.ts +45 -0
- package/dist/boot/security-headers.d.ts +22 -0
- package/dist/branch-routes-B2vvEx53.js +84 -0
- package/dist/branch-routes-B2vvEx53.js.map +1 -0
- package/dist/{contract-routes-CsFXW7j4.js → contract-routes-CU2A3JnF.js} +2 -2
- package/dist/{contract-routes-CsFXW7j4.js.map → contract-routes-CU2A3JnF.js.map} +1 -1
- package/dist/cron/cron-store.d.ts +8 -1
- package/dist/{cron-loader-Dj6lA4HQ.js → cron-loader-mMhqbVsl.js} +2 -2
- package/dist/{cron-loader-Dj6lA4HQ.js.map → cron-loader-mMhqbVsl.js.map} +1 -1
- package/dist/{cron-routes-CwbLZguO.js → cron-routes-Cs33j_Kr.js} +3 -3
- package/dist/{cron-routes-CwbLZguO.js.map → cron-routes-Cs33j_Kr.js.map} +1 -1
- package/dist/{cron-scheduler-B04ACoUE.js → cron-scheduler-Be7CNghL.js} +2 -2
- package/dist/{cron-scheduler-B04ACoUE.js.map → cron-scheduler-Be7CNghL.js.map} +1 -1
- package/dist/{cron-store-DkyfuLOH.js → cron-store-DLn11M8H.js} +10 -9
- package/dist/cron-store-DLn11M8H.js.map +1 -0
- package/dist/{strings.es-BeZWAodn.js → data_driver-D0mg1Y_x.js} +2 -90
- package/dist/data_driver-D0mg1Y_x.js.map +1 -0
- package/dist/{ddl-bootstrap-Ck20GSIX.js → ddl-bootstrap-CjRrn12l.js} +91 -2
- package/dist/ddl-bootstrap-CjRrn12l.js.map +1 -0
- package/dist/deploy/pod-contract.d.ts +1 -1
- package/dist/email/dev-sink.d.ts +6 -0
- package/dist/email/index.d.ts +1 -1
- package/dist/{soft-delete-params-BmlVwecC.js → field-access-DYsvjI_P.js} +27 -57
- package/dist/field-access-DYsvjI_P.js.map +1 -0
- package/dist/{filter-dialect-O1HK6Nvr.js → filter-dialect-TrKFWLqT.js} +3 -3
- package/dist/{filter-dialect-O1HK6Nvr.js.map → filter-dialect-TrKFWLqT.js.map} +1 -1
- package/dist/{function-loader-KKDqTcIr.js → function-loader-B8YzXEsQ.js} +21 -14
- package/dist/function-loader-B8YzXEsQ.js.map +1 -0
- package/dist/functions/hono-like.d.ts +12 -0
- package/dist/functions/index.js +19 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/request-timeout.d.ts +3 -3
- package/dist/history/history-routes.d.ts +6 -0
- package/dist/history/retention-sweep.d.ts +5 -0
- package/dist/{history-recorder-B2rkuhuy.js → history-recorder-Bsau7h4X.js} +6 -6
- package/dist/history-recorder-Bsau7h4X.js.map +1 -0
- package/dist/{history-store-DPofGVDp.js → history-store-BQz5YCkW.js} +26 -2
- package/dist/history-store-BQz5YCkW.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.es.js +2449 -543
- package/dist/index.es.js.map +1 -1
- package/dist/init/process-safety.d.ts +4 -3
- package/dist/init/shutdown.d.ts +8 -0
- package/dist/init.d.ts +6 -1
- package/dist/jobs/job-store.d.ts +8 -1
- package/dist/{jobs-h1WRq3cp.js → jobs-Co6Ni5HP.js} +6 -6
- package/dist/jobs-Co6Ni5HP.js.map +1 -0
- package/dist/{jwt-D3oFauZI.js → jwt-rDS0884_.js} +4 -3
- package/dist/{jwt-D3oFauZI.js.map → jwt-rDS0884_.js.map} +1 -1
- package/dist/{keys-COzQ2aE8.js → keys-BXcdRNhJ.js} +2 -2
- package/dist/{keys-COzQ2aE8.js.map → keys-BXcdRNhJ.js.map} +1 -1
- package/dist/mcp/consent-page.d.ts +38 -1
- package/dist/mcp/mcp-routes.d.ts +9 -0
- package/dist/mcp/mcp-tools.d.ts +7 -1
- package/dist/mcp/oauth-store.d.ts +12 -5
- package/dist/metrics/history-recorder.d.ts +4 -1
- package/dist/metrics/history-store.d.ts +8 -0
- package/dist/{offline-BrqCRgih-BtDB1ecy.js → offline-AvuEcg7u-DFHL98OT.js} +127 -40
- package/dist/offline-AvuEcg7u-DFHL98OT.js.map +1 -0
- package/dist/{offline-store-BhYXViha-BW5j1We_.js → offline-store-BhYXViha-YTmjBpo2.js} +5 -5
- package/dist/{offline-store-BhYXViha-BW5j1We_.js.map → offline-store-BhYXViha-YTmjBpo2.js.map} +1 -1
- package/dist/{openapi-generator-BjHr6upl.js → openapi-generator-CyxEtYEX.js} +61 -22
- package/dist/openapi-generator-CyxEtYEX.js.map +1 -0
- package/dist/{proxy-CH8Jsovg.js → proxy-BYir8tWK.js} +4 -6
- package/dist/proxy-BYir8tWK.js.map +1 -0
- package/dist/{query-parser-otFZqJsC.js → query-parser-CDXWf2hH.js} +6 -5
- package/dist/{query-parser-otFZqJsC.js.map → query-parser-CDXWf2hH.js.map} +1 -1
- package/dist/{request-timeout-59crS-9u.js → request-timeout-DVjo-c_8.js} +4 -4
- package/dist/request-timeout-DVjo-c_8.js.map +1 -0
- package/dist/rls-simulator-routes-bEY7-5-u.js +190 -0
- package/dist/rls-simulator-routes-bEY7-5-u.js.map +1 -0
- package/dist/schema-edit/deployed-schema-guard.d.ts +47 -0
- package/dist/{schema-editor-routes-Bsut0bCC.js → schema-editor-routes-Dc3DU_jm.js} +3 -3
- package/dist/{schema-editor-routes-Bsut0bCC.js.map → schema-editor-routes-Dc3DU_jm.js.map} +1 -1
- package/dist/soft-delete-params-BRONCOA2.js +59 -0
- package/dist/soft-delete-params-BRONCOA2.js.map +1 -0
- package/dist/{sql-export-routes-DmB_uZ4l.js → sql-export-routes-QycX8W8S.js} +38 -4
- package/dist/sql-export-routes-QycX8W8S.js.map +1 -0
- package/dist/{src-D5Y3N-S4.js → src-Bh9LRPb9.js} +21 -2
- package/dist/{src-D5Y3N-S4.js.map → src-Bh9LRPb9.js.map} +1 -1
- package/dist/storage/GCSStorageController.d.ts +2 -0
- package/dist/storage/LocalStorageController.d.ts +8 -3
- package/dist/storage/S3StorageController.d.ts +2 -0
- package/dist/storage/maintenance-keys.d.ts +17 -0
- package/dist/storage/maintenance-routes.d.ts +28 -5
- package/dist/storage/maintenance.d.ts +136 -4
- package/dist/storage/orphan-scans.d.ts +120 -0
- package/dist/storage/types.d.ts +11 -0
- package/dist/strings.es-B7QLnHh2.js +96 -0
- package/dist/strings.es-B7QLnHh2.js.map +1 -0
- package/dist/upload-validation-Bgo626uY.js.map +1 -1
- package/package.json +5 -5
- package/dist/GCSStorageController-CRd9bFrc.js.map +0 -1
- package/dist/S3StorageController-D00EFa5P.js.map +0 -1
- package/dist/auth-Dkvo2tTJ.js.map +0 -1
- package/dist/auth_adapter-CIItCTc8.js +0 -21
- package/dist/auth_adapter-CIItCTc8.js.map +0 -1
- package/dist/backend-DTAOsLQc.js.map +0 -1
- package/dist/cron-store-DkyfuLOH.js.map +0 -1
- package/dist/ddl-bootstrap-Ck20GSIX.js.map +0 -1
- package/dist/function-loader-KKDqTcIr.js.map +0 -1
- package/dist/history-recorder-B2rkuhuy.js.map +0 -1
- package/dist/history-store-DPofGVDp.js.map +0 -1
- package/dist/jobs-h1WRq3cp.js.map +0 -1
- package/dist/offline-BrqCRgih-BtDB1ecy.js.map +0 -1
- package/dist/openapi-generator-BjHr6upl.js.map +0 -1
- package/dist/proxy-CH8Jsovg.js.map +0 -1
- package/dist/request-timeout-59crS-9u.js.map +0 -1
- package/dist/soft-delete-params-BmlVwecC.js.map +0 -1
- package/dist/sql-export-routes-DmB_uZ4l.js.map +0 -1
- package/dist/strings.es-BeZWAodn.js.map +0 -1
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createRequire as __rebaseCreateRequire } from "module";
|
|
2
|
+
import __rebaseProcess from "process";
|
|
3
|
+
globalThis.process ??= __rebaseProcess;
|
|
4
|
+
__rebaseCreateRequire(import.meta.url);
|
|
5
|
+
//#region ../types/src/types/auth_adapter.ts
|
|
6
|
+
/**
|
|
7
|
+
* The request header that asks for a data-plane request to run as another
|
|
8
|
+
* user, named by uid.
|
|
9
|
+
*
|
|
10
|
+
* The server honours it only on a signed-in administrator's own session —
|
|
11
|
+
* never on an API key or the service key — and only through an adapter that
|
|
12
|
+
* implements {@link AuthAdapter.resolveUser}. Everywhere else a request that
|
|
13
|
+
* carries it is refused, never run as its caller.
|
|
14
|
+
*
|
|
15
|
+
* @group Auth
|
|
16
|
+
*/
|
|
17
|
+
var IMPERSONATE_HEADER = "x-rebase-impersonate";
|
|
18
|
+
/**
|
|
19
|
+
* The request header that asks for a data-plane request to run as a role —
|
|
20
|
+
* the RLS simulator's "view as". Alone it runs as a signed-in holder of that
|
|
21
|
+
* role who owns no rows; with {@link SIMULATE_USER_ID_HEADER} it runs as that
|
|
22
|
+
* uid holding that role, whether or not such an account exists.
|
|
23
|
+
*
|
|
24
|
+
* `anon` (or `anonymous`) runs as a caller with no session at all.
|
|
25
|
+
*
|
|
26
|
+
* Like {@link IMPERSONATE_HEADER}, only a signed-in administrator's own session
|
|
27
|
+
* may send it; anyone else is refused with 403, never answered as themselves.
|
|
28
|
+
*
|
|
29
|
+
* @group Auth
|
|
30
|
+
*/
|
|
31
|
+
var SIMULATE_ROLE_HEADER = "x-rebase-simulate-role";
|
|
32
|
+
/**
|
|
33
|
+
* The uid a simulated request runs as. With {@link SIMULATE_ROLE_HEADER} it is
|
|
34
|
+
* a hypothetical — "u_1 holding customer" — and need not name an account;
|
|
35
|
+
* without it, the uid must be an active user and runs with their roles now.
|
|
36
|
+
*
|
|
37
|
+
* @group Auth
|
|
38
|
+
*/
|
|
39
|
+
var SIMULATE_USER_ID_HEADER = "x-rebase-simulate-user-id";
|
|
40
|
+
/**
|
|
41
|
+
* The id of a service API key a simulated request runs as: the key's identity,
|
|
42
|
+
* its RLS roles and its scopes, exactly as a request presenting the key would.
|
|
43
|
+
* Excludes the other two simulation headers.
|
|
44
|
+
*
|
|
45
|
+
* @group Auth
|
|
46
|
+
*/
|
|
47
|
+
var SIMULATE_API_KEY_ID_HEADER = "x-rebase-simulate-api-key-id";
|
|
48
|
+
/**
|
|
49
|
+
* The response header naming what a simulated request ran as:
|
|
50
|
+
* `role=<role>;sub=<uid>;masked_columns=<a,b>`, plus `api_key=<id>` and
|
|
51
|
+
* `collection=<slug>` when they apply. Every value is URI-encoded. Read it
|
|
52
|
+
* with {@link parseSimulatedContext}.
|
|
53
|
+
*
|
|
54
|
+
* @group Auth
|
|
55
|
+
*/
|
|
56
|
+
var SIMULATED_CONTEXT_HEADER = "x-rebase-simulated-context";
|
|
57
|
+
/**
|
|
58
|
+
* The request headers for an {@link AccessSimulation}. Empty when it asks for
|
|
59
|
+
* nothing, so spreading it into a header set is always safe.
|
|
60
|
+
*
|
|
61
|
+
* @group Auth
|
|
62
|
+
*/
|
|
63
|
+
function simulationHeaders(simulation) {
|
|
64
|
+
if (!simulation) return {};
|
|
65
|
+
const headers = {};
|
|
66
|
+
if (simulation.role) headers[SIMULATE_ROLE_HEADER] = simulation.role;
|
|
67
|
+
if (simulation.userId) headers[SIMULATE_USER_ID_HEADER] = simulation.userId;
|
|
68
|
+
if (simulation.apiKeyId) headers[SIMULATE_API_KEY_ID_HEADER] = simulation.apiKeyId;
|
|
69
|
+
return headers;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Write a {@link SimulatedContext} as the header value.
|
|
73
|
+
*
|
|
74
|
+
* @group Auth
|
|
75
|
+
*/
|
|
76
|
+
function formatSimulatedContext(context) {
|
|
77
|
+
const parts = [
|
|
78
|
+
`role=${encodeURIComponent(context.role)}`,
|
|
79
|
+
`sub=${encodeURIComponent(context.sub)}`,
|
|
80
|
+
`masked_columns=${context.maskedColumns.map(encodeURIComponent).join(",")}`
|
|
81
|
+
];
|
|
82
|
+
if (context.apiKeyId) parts.push(`api_key=${encodeURIComponent(context.apiKeyId)}`);
|
|
83
|
+
if (context.collection) parts.push(`collection=${encodeURIComponent(context.collection)}`);
|
|
84
|
+
return parts.join(";");
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
export { SIMULATE_USER_ID_HEADER as a, SIMULATE_ROLE_HEADER as i, SIMULATED_CONTEXT_HEADER as n, formatSimulatedContext as o, SIMULATE_API_KEY_ID_HEADER as r, simulationHeaders as s, IMPERSONATE_HEADER as t };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=auth_adapter-B7RUMk6e.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth_adapter-B7RUMk6e.js","names":[],"sources":["../../types/src/types/auth_adapter.ts"],"sourcesContent":["/**\n * @module AuthAdapter\n *\n * Pluggable authentication abstraction for Rebase.\n *\n * An `AuthAdapter` decouples authentication from the database layer,\n * allowing users to bring their own auth system (Clerk, Auth0, or other\n * external providers) while keeping the Rebase admin frontend fully functional.\n *\n * @example Built-in auth (default — zero config change)\n * ```ts\n * initializeRebaseBackend({\n * auth: { jwtSecret: \"...\", google: { clientId: \"...\" } },\n * database: createPostgresAdapter({ ... }),\n * });\n * ```\n *\n * @example Custom auth\n * ```ts\n * import { createCustomAuthAdapter } from \"@rebasepro/server\";\n *\n * initializeRebaseBackend({\n * auth: createCustomAuthAdapter({\n * verifyRequest: async (req) => { ... },\n * }),\n * database: createPostgresAdapter({ ... }),\n * });\n * ```\n *\n * @group Auth\n */\n\n/**\n * A sub-app an adapter hands back for the framework to mount.\n *\n * Structural on purpose. This was `Hono<any, any, any>`, and that one\n * `import type { Hono } from \"hono\"` was the whole reason `@rebasepro/types`\n * peer-depended on hono — which npm and pnpm auto-install, so **every browser\n * app that installed `@rebasepro/client` got a 2.8 MB server framework in its\n * lockfile and its security scanners**, for a type used by two optional methods\n * that a browser app can never call.\n *\n * The shape is the same duck-type the function loader already validates at\n * runtime (`isHonoLike`: a `fetch` method and a `routes` array), and a real\n * `Hono` satisfies it — asserted in `auth_adapter.test.ts`, which does import\n * hono, because a structural type is only worth having if something proves the\n * real thing still fits.\n *\n * @group Auth\n */\nexport interface MountableRouter {\n /** Handle a request. Hono, Elysia and a hand-rolled router all have this. */\n fetch: (request: Request) => Response | Promise<Response>;\n /** The routes the sub-app declares. Only its presence is contractual. */\n routes: readonly unknown[];\n}\n\n// ─── Impersonation ───────────────────────────────────────────────────────────\n\n/**\n * The request header that asks for a data-plane request to run as another\n * user, named by uid.\n *\n * The server honours it only on a signed-in administrator's own session —\n * never on an API key or the service key — and only through an adapter that\n * implements {@link AuthAdapter.resolveUser}. Everywhere else a request that\n * carries it is refused, never run as its caller.\n *\n * @group Auth\n */\nexport const IMPERSONATE_HEADER = \"x-rebase-impersonate\";\n\n// ─── Access simulation ───────────────────────────────────────────────────────\n\n/**\n * The request header that asks for a data-plane request to run as a role —\n * the RLS simulator's \"view as\". Alone it runs as a signed-in holder of that\n * role who owns no rows; with {@link SIMULATE_USER_ID_HEADER} it runs as that\n * uid holding that role, whether or not such an account exists.\n *\n * `anon` (or `anonymous`) runs as a caller with no session at all.\n *\n * Like {@link IMPERSONATE_HEADER}, only a signed-in administrator's own session\n * may send it; anyone else is refused with 403, never answered as themselves.\n *\n * @group Auth\n */\nexport const SIMULATE_ROLE_HEADER = \"x-rebase-simulate-role\";\n\n/**\n * The uid a simulated request runs as. With {@link SIMULATE_ROLE_HEADER} it is\n * a hypothetical — \"u_1 holding customer\" — and need not name an account;\n * without it, the uid must be an active user and runs with their roles now.\n *\n * @group Auth\n */\nexport const SIMULATE_USER_ID_HEADER = \"x-rebase-simulate-user-id\";\n\n/**\n * The id of a service API key a simulated request runs as: the key's identity,\n * its RLS roles and its scopes, exactly as a request presenting the key would.\n * Excludes the other two simulation headers.\n *\n * @group Auth\n */\nexport const SIMULATE_API_KEY_ID_HEADER = \"x-rebase-simulate-api-key-id\";\n\n/**\n * The response header naming what a simulated request ran as:\n * `role=<role>;sub=<uid>;masked_columns=<a,b>`, plus `api_key=<id>` and\n * `collection=<slug>` when they apply. Every value is URI-encoded. Read it\n * with {@link parseSimulatedContext}.\n *\n * @group Auth\n */\nexport const SIMULATED_CONTEXT_HEADER = \"x-rebase-simulated-context\";\n\n/**\n * What an administrator asks a request to run as. Exactly one of these\n * shapes is honoured: a role (optionally with a uid), a uid alone (an existing\n * user, with their roles), or an API key id alone.\n *\n * @group Auth\n */\nexport interface AccessSimulation {\n role?: string;\n userId?: string;\n apiKeyId?: string;\n}\n\n/**\n * The request headers for an {@link AccessSimulation}. Empty when it asks for\n * nothing, so spreading it into a header set is always safe.\n *\n * @group Auth\n */\nexport function simulationHeaders(simulation: AccessSimulation | null | undefined): Record<string, string> {\n if (!simulation) return {};\n const headers: Record<string, string> = {};\n if (simulation.role) headers[SIMULATE_ROLE_HEADER] = simulation.role;\n if (simulation.userId) headers[SIMULATE_USER_ID_HEADER] = simulation.userId;\n if (simulation.apiKeyId) headers[SIMULATE_API_KEY_ID_HEADER] = simulation.apiKeyId;\n return headers;\n}\n\n/**\n * What {@link SIMULATED_CONTEXT_HEADER} says a request ran as.\n *\n * @group Auth\n */\nexport interface SimulatedContext {\n role: string;\n sub: string;\n maskedColumns: string[];\n apiKeyId?: string;\n collection?: string;\n}\n\n/**\n * Write a {@link SimulatedContext} as the header value.\n *\n * @group Auth\n */\nexport function formatSimulatedContext(context: SimulatedContext): string {\n const parts = [\n `role=${encodeURIComponent(context.role)}`,\n `sub=${encodeURIComponent(context.sub)}`,\n `masked_columns=${context.maskedColumns.map(encodeURIComponent).join(\",\")}`\n ];\n if (context.apiKeyId) parts.push(`api_key=${encodeURIComponent(context.apiKeyId)}`);\n if (context.collection) parts.push(`collection=${encodeURIComponent(context.collection)}`);\n return parts.join(\";\");\n}\n\n/**\n * Read {@link SIMULATED_CONTEXT_HEADER}. `undefined` for an absent header or one\n * missing `role` or `sub`.\n *\n * @group Auth\n */\nexport function parseSimulatedContext(value: string | null | undefined): SimulatedContext | undefined {\n if (!value) return undefined;\n const fields = new Map<string, string>();\n for (const part of value.split(\";\")) {\n const at = part.indexOf(\"=\");\n if (at > 0) fields.set(part.slice(0, at).trim(), part.slice(at + 1).trim());\n }\n const role = fields.get(\"role\");\n const sub = fields.get(\"sub\");\n if (role === undefined || sub === undefined) return undefined;\n const decode = (raw: string) => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n };\n const masked = fields.get(\"masked_columns\") ?? \"\";\n const apiKeyId = fields.get(\"api_key\");\n const collection = fields.get(\"collection\");\n return {\n role: decode(role),\n sub: decode(sub),\n maskedColumns: masked === \"\" ? [] : masked.split(\",\").map(decode),\n ...(apiKeyId ? { apiKeyId: decode(apiKeyId) } : {}),\n ...(collection ? { collection: decode(collection) } : {})\n };\n}\n\n// ─── Authenticated User ──────────────────────────────────────────────────────\n\n/**\n * The normalized user object returned by `AuthAdapter.verifyRequest()`.\n *\n * Regardless of the auth provider, every request is resolved to this shape\n * so that downstream middleware (RLS scoping, route guards) can work uniformly.\n *\n * @group Auth\n */\nexport interface AuthenticatedUser {\n /** Unique user identifier (provider-specific). */\n uid: string;\n /** Primary email address. */\n email: string;\n /** Human-readable display name. */\n displayName?: string | null;\n /** Avatar URL. */\n photoUrl?: string | null;\n /** Role identifiers the user holds. */\n roles: string[];\n /**\n * Whether `roles` includes `admin`. Informational — every authorization\n * decision reads `roles` and the scopes they hold, so an adapter that\n * wants a user treated as an administrator gives them the `admin` role.\n */\n isAdmin: boolean;\n /**\n * Whether this session is a GUEST — anonymous sign-in rather than an\n * account.\n *\n * Optional, and absent means \"not a guest\", so an external adapter that\n * has no such concept keeps behaving exactly as it did. When present it\n * reaches the database as `rebase.is_anonymous()`, which is what lets a\n * policy say \"a signed-in person, not somebody who pressed Continue as\n * guest\" — two things that were the same principal inside every rule,\n * because anonymous sign-in mints a real user row with a real uid.\n */\n isAnonymous?: boolean;\n /** Raw bearer token from the request (for forwarding). */\n rawToken?: string;\n /** Extra claims/metadata from the auth provider. */\n claims?: Record<string, unknown>;\n /**\n * What this credential may do, when it is narrower than its person — set\n * for an API key. Absent means everything the user's roles hold\n * (`scopesForRoles`).\n */\n scopes?: string[];\n}\n\n// ─── Capabilities ────────────────────────────────────────────────────────────\n\n/**\n * Feature flags advertised by an auth adapter.\n *\n * The frontend reads these from `GET /api/auth/config` to dynamically\n * show/hide UI elements (login form, registration, password reset, etc.).\n *\n * @group Auth\n */\nexport interface AuthAdapterCapabilities {\n /**\n * Whether this adapter mounts its own `/auth/*` routes.\n *\n * - `true` for the built-in Rebase auth (login, register, refresh, etc.)\n * - `false` for external providers like Clerk or Auth0 that handle\n * auth flows outside of the Rebase backend.\n */\n hasBuiltInAuthRoutes: boolean;\n\n /** Supports email/password login. */\n emailPasswordLogin: boolean;\n /**\n * Whether self-registration is open **right now**.\n *\n * A runtime answer, not a static feature list: the built-in adapter also\n * reports `true` during the first-user bootstrap window (an empty user\n * table) and `false` the moment `disableSelfRegistration` is set. Whatever\n * this says, `POST /auth/register` does — both read the same predicate, so\n * the UI can never be sent to a form that can only 403.\n */\n registrationEnabled: boolean;\n /**\n * Supports the end-user password reset flow (emailing a reset link).\n *\n * This is about *self-service* reset, so it is typically tied to whether an\n * email service is configured. It says nothing about whether an admin can\n * reset someone else's password — see `adminPasswordReset`.\n */\n passwordReset: boolean;\n /**\n * Whether the adapter exposes `POST /admin/users/:uid/reset-password`,\n * letting an admin reset another user's password.\n *\n * Independent of `passwordReset`: the built-in adapter supports this even\n * with no email service configured (it returns a one-time temporary\n * password instead of sending a link). Adapters that mount their own admin\n * routes must set this to `true` only once that route actually exists —\n * the admin UI hides the \"Reset Password\" action when it is `false`.\n */\n adminPasswordReset: boolean;\n /** Supports session listing/revocation. */\n sessionManagement: boolean;\n /** Supports profile updates (display name, photo). */\n profileUpdate: boolean;\n /** Supports email verification. */\n emailVerification: boolean;\n /** Supports passwordless magic link login. */\n magicLink: boolean;\n /**\n * Supports passwordless sign-in with a six-digit code sent by email.\n *\n * Optional so that an external adapter written before this existed still\n * satisfies the interface; absent reads as \"no\", which is what an adapter\n * that has never heard of the flow means.\n */\n emailOtp?: boolean;\n /** Whether `POST /auth/anonymous` will mint a credential-less session. */\n anonymousLogin: boolean;\n /** List of enabled OAuth provider IDs (e.g. `[\"google\", \"github\"]`). */\n enabledProviders: string[];\n\n /**\n * For external auth (Clerk, Auth0, etc.): the URL where the user should\n * be redirected for login. The Rebase frontend will navigate here instead\n * of showing its own login form.\n */\n externalLoginUrl?: string;\n\n /**\n * True when no users exist yet — first-user bootstrap mode.\n * Only applicable for built-in auth.\n */\n needsSetup?: boolean;\n}\n\n/**\n * What `GET /api/auth/config` answers: the auth adapter's capabilities, plus\n * the optional features of the backend around it.\n *\n * The admin panel reads this document before anything else, so it is where\n * the panel learns that a feature is off, without first asking for that\n * feature and getting a refusal.\n *\n * @group Auth\n */\nexport interface AuthConfigDocument extends AuthAdapterCapabilities {\n /**\n * Whether this backend serves file storage. When it is `false`, no storage\n * backend is configured: `GET /storage/sources` lists nothing and every\n * other `/storage` route answers 501 `STORAGE_NOT_CONFIGURED`. Absent from\n * a backend that predates the field, so a client must ask\n * `GET /storage/sources` there.\n */\n storage?: boolean;\n}\n\n// ─── User Management ────────────────────────────────────────────────────────\n\n/**\n * Options for paginated user listing.\n * @group Auth\n */\nexport interface AuthUserListOptions {\n limit?: number;\n offset?: number;\n search?: string;\n orderBy?: string;\n orderDir?: \"asc\" | \"desc\";\n roleId?: string;\n}\n\n/**\n * Paginated user listing result.\n * @group Auth\n */\nexport interface AuthUserListResult {\n users: AuthUserData[];\n total: number;\n limit: number;\n offset: number;\n}\n\n/**\n * User data exposed by the auth adapter.\n * @group Auth\n */\nexport interface AuthUserData {\n id: string;\n email: string;\n displayName?: string | null;\n photoUrl?: string | null;\n emailVerified?: boolean;\n metadata?: Record<string, unknown>;\n createdAt?: Date;\n updatedAt?: Date;\n}\n\n/**\n * Data for creating a user.\n * @group Auth\n */\nexport interface AuthCreateUserData {\n email: string;\n password?: string;\n displayName?: string;\n photoUrl?: string;\n metadata?: Record<string, unknown>;\n /**\n * Store the address as verified: whoever creates the account named it\n * (an operator, an administrator), so nobody needs to prove it.\n */\n emailVerified?: boolean;\n}\n\n/**\n * User management operations for the admin panel.\n *\n * Optional — if not provided by the adapter, the user management UI is hidden.\n *\n * @group Auth\n */\nexport interface UserManagementAdapter {\n listUsers(options?: AuthUserListOptions): Promise<AuthUserListResult>;\n getUserById(id: string): Promise<AuthUserData | null>;\n createUser(data: AuthCreateUserData): Promise<AuthUserData>;\n updateUser(id: string, data: Partial<AuthCreateUserData>): Promise<AuthUserData | null>;\n deleteUser(id: string): Promise<void>;\n getUserRoles(uid: string): Promise<string[]>;\n setUserRoles(uid: string, roleIds: string[]): Promise<void>;\n}\n\n// ─── User Creation Lifecycle ─────────────────────────────────────────────────\n\n/**\n * Result of `AuthAdapter.prepareUserCreation()`.\n *\n * Contains the processed values ready for persistence and metadata\n * needed by the finalization step.\n *\n * @group Auth\n */\nexport interface UserCreationPrepareResult {\n /** Processed values to persist (passwordHash instead of raw password, etc.). */\n values: Record<string, unknown>;\n /** Cleartext password for post-save processing (email or admin display). */\n clearPassword?: string;\n /**\n * Whether the hook already handled the invitation (email, etc.). When\n * `true`, `finalizeUserCreation` is skipped and `clearPassword` is returned\n * to the admin as the temporary password.\n */\n hookHandledEmail: boolean;\n /** Whether an invitation was sent (only relevant when hookHandledEmail is true). */\n invitationSent: boolean;\n}\n\n/**\n * What the door creating a user knows about its caller, for\n * `AuthAdapter.prepareUserCreation()`.\n *\n * @group Auth\n */\nexport interface UserCreationOptions {\n /**\n * Whether the caller may waive the password policy with\n * `skipPasswordPolicy: true` in the body. The doors set it for an\n * administrator (the service key signs in as one) and for nobody else, so\n * an adapter that reads the flag is taking an administrator at their word —\n * an import of accounts whose passwords were set under another system's\n * rules. Absent, the flag waives nothing.\n */\n mayWaivePasswordPolicy?: boolean;\n}\n\n/**\n * What a create body for an auth collection may name beyond the collection's\n * own declared fields — see `AuthAdapter.describeUserCreationContract()`.\n *\n * @group Auth\n */\nexport interface UserCreationWriteContract {\n /**\n * Whether to check the body for fields neither the collection nor\n * {@link extraFields} declares. `false` skips the check entirely.\n */\n validate: boolean;\n /**\n * Credential and provider keys the adapter consumes itself, which the\n * collection therefore does not declare as columns. `password` is the\n * canonical one: `prepareUserCreation` hashes it into `passwordHash` and\n * deletes it before the row is ever built.\n */\n extraFields: string[];\n /**\n * Each body's `prepareUserCreation` touches nothing but its own result —\n * no hook, no email, no write — so a bulk create may prepare several at\n * once. The built-in adapter's path with no `onCreateUser`, no\n * `onAdminCreateUser` and the default `hashPassword` is: it hashes a\n * password and normalizes an email, and a 1,000-row bulk spent half a\n * minute hashing one password at a time. Leave it unset when a hook runs:\n * preparations then run one at a time, in the order the rows were given.\n */\n independent?: boolean;\n}\n\n/**\n * Result of `AuthAdapter.finalizeUserCreation()`.\n *\n * Returned to the REST API for inclusion in the response.\n *\n * @group Auth\n */\nexport interface UserCreationFinalizeResult {\n /** If set, returned to the admin in the API response. */\n temporaryPassword?: string;\n /** Whether an invitation email was sent. */\n invitationSent: boolean;\n /**\n * Whether an email service was configured but delivery failed, causing the\n * fallback to `temporaryPassword`. Absent when no email service is configured.\n */\n emailDeliveryFailed?: boolean;\n}\n\n// ─── Auth Response Transform ─────────────────────────────────────────────────\n\n/**\n * The auth response payload shape that flows through `transformAuthResponse`.\n *\n * For login, register, OAuth, anonymous, and magic-link flows the payload\n * contains both `user` and `tokens`. For refresh and MFA flows the payload\n * contains only `tokens` (no `user`).\n *\n * @group Auth\n */\nexport interface AuthResponsePayload {\n user?: {\n uid: string;\n email: string;\n displayName: string | null;\n photoURL: string | null;\n providerId?: string;\n isAnonymous?: boolean;\n emailVerified?: boolean;\n roles: string[];\n metadata: Record<string, unknown>;\n };\n tokens: {\n accessToken: string;\n refreshToken: string;\n accessTokenExpiresAt: number;\n /** Additional tokens injected by `transformAuthResponse`. */\n [key: string]: unknown;\n };\n}\n\n/**\n * Context passed to the `transformAuthResponse` hook.\n *\n * @group Auth\n */\nexport interface TransformAuthResponseContext {\n /** The authenticated user's ID. */\n uid: string;\n /** The auth method that triggered this response. */\n method: \"login\" | \"register\" | \"oauth\" | \"refresh\" | \"anonymous\" | \"magic-link\" | \"otp\" | \"mfa\";\n /** The raw HTTP request (for reading headers, IP, etc.). */\n request: Request;\n}\n\n// ─── Auth Adapter ────────────────────────────────────────────────────────────\n\n/**\n * Pluggable authentication adapter for Rebase.\n *\n * This is the **key interface** that decouples authentication from the\n * database layer. Each auth adapter knows how to:\n *\n * 1. Verify incoming HTTP requests (`verifyRequest`)\n * 2. Optionally manage users (for the admin panel)\n * 3. Optionally mount auth-specific routes (login, register, etc.)\n * 4. Advertise its capabilities so the frontend can adapt\n *\n * The built-in Rebase auth implements this interface internally.\n * External providers (Clerk, Auth0, or others) provide their own adapters.\n * Users with custom auth can use `createCustomAuthAdapter()` for a minimal setup.\n *\n * @group Auth\n */\nexport interface AuthAdapter {\n /**\n * Unique identifier for this auth adapter.\n *\n * @example \"rebase-builtin\", \"clerk\", \"auth0\", \"external-provider\", \"custom\"\n */\n readonly id: string;\n\n // ── Request Authentication ──────────────────────────────────────────\n\n /**\n * Verify an incoming request and extract the authenticated user.\n *\n * This replaces the hardcoded JWT verification in server's middleware.\n * Each adapter implements its own token verification strategy:\n * - Built-in: verify Rebase JWT\n * - Clerk: call Clerk's `verifyToken()`\n * - Auth0: validate Auth0 JWT with JWKS\n * - Custom: whatever logic the user provides\n *\n * @param request - The raw `Request` object (portable across Hono, Express, Fastify)\n * @returns The authenticated user, or `null` for unauthenticated requests.\n * Throw an error to reject the request with 401.\n */\n verifyRequest(request: Request): Promise<AuthenticatedUser | null>;\n\n /**\n * Verify a raw bearer token and extract the authenticated user.\n *\n * Used for **WebSocket authentication**, where there is no HTTP `Request`\n * object — only a token string sent over the socket.\n *\n * If not implemented, the default behavior synthesizes a minimal `Request`\n * with an `Authorization: Bearer <token>` header and delegates to\n * `verifyRequest()`. Adapters should override this if their token\n * verification logic doesn't depend on request headers/cookies.\n *\n * @param token - The raw bearer token string.\n * @returns The authenticated user, or `null` if the token is invalid.\n */\n verifyToken?(token: string): Promise<AuthenticatedUser | null>;\n\n /**\n * The identity a verified request from this account would carry right\n * now, with no credential involved: its uid, its roles as they are now,\n * its guest flag, and the custom claims a token minted for it now would\n * hold. `null` when no active account has this uid — none at all, or one\n * that is disabled.\n *\n * This is what lets an administrator run a request as another user (the\n * {@link IMPERSONATE_HEADER} header). The server calls it only after it\n * has decided the caller may do that, and it calls it for the caller too,\n * so the decision rests on the caller's roles as they are now rather than\n * on the ones their token claims.\n *\n * Optional. An adapter without it cannot be impersonated through, and a\n * request carrying the header is refused rather than run as its caller.\n */\n resolveUser?(uid: string): Promise<AuthenticatedUser | null>;\n\n // ── User Management (for admin panel) ────────────────────────────\n\n /**\n * User CRUD for the admin panel's user management UI.\n * Optional — if not provided, user management UI is hidden.\n */\n userManagement?: UserManagementAdapter;\n\n // ── Auth Routes ─────────────────────────────────────────────────────\n\n /**\n * Mount adapter-specific auth routes (login, register, refresh, etc.).\n *\n * - Built-in adapter: mounts `/auth/login`, `/auth/register`, etc.\n * - External adapter: typically returns `undefined` (auth is handled externally).\n * - Custom adapter: user mounts their own routes.\n *\n * The return type is the structural {@link MountableRouter} rather than\n * `Hono`, so this package needs no hono dependency. A real `Hono<HonoEnv>`\n * satisfies it, and implementations are free to use their own env.\n *\n * @returns A Hono sub-app with auth routes, or `undefined` to skip route mounting.\n */\n createAuthRoutes?(): MountableRouter | undefined;\n\n /**\n * Mount admin routes (e.g. password reset for users).\n *\n * @returns A Hono sub-app with admin routes, or `undefined` to skip.\n */\n createAdminRoutes?(): MountableRouter | undefined;\n\n // ── Feature Detection ───────────────────────────────────────────────\n\n /**\n * Advertise what this auth adapter supports.\n *\n * The frontend reads this from `GET /api/auth/config` to dynamically\n * show/hide UI elements. This is the bridge between backend capabilities\n * and the frontend's `AuthCapabilities` type.\n */\n getCapabilities(): AuthAdapterCapabilities | Promise<AuthAdapterCapabilities>;\n\n // ── Lifecycle ───────────────────────────────────────────────────────\n\n /**\n * Called during backend initialization.\n * Use for running migrations, creating tables, seeding initial data, etc.\n */\n initialize?(): Promise<void>;\n\n /**\n * Called during graceful shutdown.\n * Use for closing connections, flushing caches, etc.\n */\n destroy?(): Promise<void>;\n\n // ── Collection User Creation (for auth collections) ───────────────\n\n /**\n * Prepare values for creating a user via the auth collection's REST API.\n *\n * Called on POST to a collection with `auth: true`. Handles password\n * hashing, email normalization, and any collection/backend-level hooks.\n *\n * If not implemented, the collection saves values as-is (no password hashing).\n *\n * A chosen `password` is held to the password policy unless the body says\n * `skipPasswordPolicy: true` and `options.mayWaivePasswordPolicy` is set.\n *\n * @param values - Raw request body from the client.\n * @param collectionAuth - The parsed `AuthCollectionConfig` from the collection (if `auth` is an object).\n * @param options - What the door knows about its caller.\n * @returns Processed values ready for `driver.save()`, plus metadata for the post-save step.\n */\n prepareUserCreation?(\n values: Record<string, unknown>,\n collectionAuth?: unknown,\n options?: UserCreationOptions\n ): Promise<UserCreationPrepareResult>;\n\n /**\n * Describe what a create body for this auth collection is allowed to name,\n * so unknown-field validation can run on it.\n *\n * A signup body is not the collection's shape: it carries credential fields\n * like `password` that the users table never declares as columns, and\n * `prepareUserCreation` maps them onto real ones. Validating the raw body\n * against the collection alone would reject every legitimate signup — which\n * is why the check used to be skipped outright for auth collections. That\n * skip was total, so an undeclared field was silently dropped and the write\n * still returned 201, while the same typo on a normal collection was a 400.\n *\n * This narrows the exemption to the fields the adapter actually consumes.\n *\n * `validate: false` disables the check for this collection, and is the right\n * answer when a custom `onCreateUser` hook is configured: the body is then\n * the hook's contract, not the collection's, and this layer cannot know what\n * the hook accepts.\n *\n * If not implemented, validation is skipped — the pre-existing behaviour.\n *\n * @param collectionAuth - The parsed `AuthCollectionConfig` from the collection (if `auth` is an object).\n */\n describeUserCreationContract?(\n collectionAuth?: unknown\n ): UserCreationWriteContract;\n\n /**\n * Finalize a user creation after the entity has been persisted.\n *\n * Handles post-save work: sending invitation emails, generating\n * password-reset tokens, or falling back to returning a temporary password.\n *\n * Not called when `prepareUserCreation` reported `hookHandledEmail`. A\n * create hook then owns delivery, and the response carries the\n * `invitationSent` and `clearPassword` the prepare step returned. This\n * holds for both ways of creating a user: a `POST` to the auth collection\n * and `POST /admin/users`.\n *\n * @param entity - The persisted entity (id + values).\n * @param clearPassword - The cleartext password from the prepare step (if any).\n * @returns Metadata for the API response (temporary password, invitation status).\n */\n finalizeUserCreation?(\n entity: { id: string; values: Record<string, unknown> },\n clearPassword?: string\n ): Promise<UserCreationFinalizeResult>;\n\n // ── User Administration Through the Auth Collection ─────────────────\n\n /**\n * Check, and put in stored form, updates to rows of the auth collection\n * that arrive through the data API — `PATCH /<users>/:id`, `PATCH /bulk`,\n * `_batch`, the realtime socket.\n *\n * Those rows are the users, so an update to one is user administration,\n * and has to hold to what the admin user routes hold to: no update that\n * leaves the project without an administrator, and an email stored the\n * way sign-in looks it up. Throws to refuse; the updates are judged\n * together, so a bulk demotion of every admin is refused even though each\n * row alone would pass.\n *\n * If not implemented, the values are written as they arrived.\n *\n * @returns Each update's values, as they should be written, in order.\n */\n prepareUserUpdates?(\n updates: ReadonlyArray<{ uid: string; values: Record<string, unknown> }>\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * Check a deletion of these users through the data API before any row goes,\n * and run the hooks that may veto it (`beforeUserDelete`). Throws to\n * refuse — for one that would leave the project without an administrator,\n * among others.\n *\n * If not implemented, the rows are deleted as any other.\n */\n prepareUserDeletions?(uids: readonly string[]): Promise<void>;\n\n /**\n * After those users' rows are deleted through the data API: end their\n * sessions and run the after-delete hooks (`afterUserDelete`).\n */\n finalizeUserDeletions?(uids: readonly string[]): Promise<void>;\n\n // ── Service Key (optional) ──────────────────────────────────────────\n\n /**\n * A static secret key for server-to-server / script authentication.\n *\n * When set, requests with `Authorization: Bearer <serviceKey>` bypass\n * normal token verification and are granted admin-level access.\n */\n serviceKey?: string;\n\n // ── Response Transform ───────────────────────────────────────────────\n\n /**\n * Transform the auth response before sending it to the client.\n *\n * Called after successful login, register, refresh, OAuth, anonymous,\n * magic-link, and MFA flows. The hook receives the fully-formed\n * response and returns a (potentially enriched) response.\n *\n * Use cases:\n * - Inject tokens from external auth systems (custom provider tokens, etc.)\n * - Add project-specific metadata to the response\n * - Enrich the user object with data from external sources\n *\n * The hook runs in the request path — keep it fast.\n * Heavy work should be offloaded to `onAuthenticated` (fire-and-forget).\n */\n transformAuthResponse?(\n response: AuthResponsePayload,\n context: TransformAuthResponseContext\n ): Promise<AuthResponsePayload>;\n}\n\n// ─── Custom Auth Adapter Options ─────────────────────────────────────────────\n\n/**\n * Options for creating a minimal custom auth adapter via `createCustomAuthAdapter()`.\n *\n * This is the simplest way to plug an existing auth system into Rebase.\n * Only `verifyRequest` is required — everything else is optional.\n *\n * @group Auth\n */\nexport interface CustomAuthAdapterOptions {\n /**\n * Verify an incoming request and return the authenticated user.\n * This is the only required method.\n */\n verifyRequest: (request: Request) => Promise<AuthenticatedUser | null>;\n\n /**\n * Verify a raw bearer token for WebSocket authentication.\n * Optional — if omitted, a synthetic `Request` is constructed and passed\n * to `verifyRequest`.\n */\n verifyToken?: (token: string) => Promise<AuthenticatedUser | null>;\n\n /** Optional user management for the admin panel. */\n userManagement?: UserManagementAdapter;\n\n /** Static service key for server-to-server auth. */\n serviceKey?: string;\n\n /** Override default capabilities. */\n capabilities?: Partial<AuthAdapterCapabilities>;\n\n /**\n * Transform the auth response before sending it to the client.\n * Same semantics as `AuthAdapter.transformAuthResponse`.\n */\n transformAuthResponse?: (\n response: AuthResponsePayload,\n context: TransformAuthResponseContext\n ) => Promise<AuthResponsePayload>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsEA,IAAa,qBAAqB;;;;;;;;;;;;;;AAiBlC,IAAa,uBAAuB;;;;;;;;AASpC,IAAa,0BAA0B;;;;;;;;AASvC,IAAa,6BAA6B;;;;;;;;;AAU1C,IAAa,2BAA2B;;;;;;;AAqBxC,SAAgB,kBAAkB,YAAyE;CACvG,IAAI,CAAC,YAAY,OAAO,CAAC;CACzB,MAAM,UAAkC,CAAC;CACzC,IAAI,WAAW,MAAM,QAAQ,wBAAwB,WAAW;CAChE,IAAI,WAAW,QAAQ,QAAQ,2BAA2B,WAAW;CACrE,IAAI,WAAW,UAAU,QAAQ,8BAA8B,WAAW;CAC1E,OAAO;AACX;;;;;;AAoBA,SAAgB,uBAAuB,SAAmC;CACtE,MAAM,QAAQ;EACV,QAAQ,mBAAmB,QAAQ,IAAI;EACvC,OAAO,mBAAmB,QAAQ,GAAG;EACrC,kBAAkB,QAAQ,cAAc,IAAI,kBAAkB,CAAC,CAAC,KAAK,GAAG;CAC5E;CACA,IAAI,QAAQ,UAAU,MAAM,KAAK,WAAW,mBAAmB,QAAQ,QAAQ,GAAG;CAClF,IAAI,QAAQ,YAAY,MAAM,KAAK,cAAc,mBAAmB,QAAQ,UAAU,GAAG;CACzF,OAAO,MAAM,KAAK,GAAG;AACzB"}
|
|
@@ -273,6 +273,12 @@ export declare function wrapDatabaseAdapter(dbAdapter: DatabaseAdapter): Backend
|
|
|
273
273
|
* its backend. The one process-wide setting it touches is the log level, and
|
|
274
274
|
* only when `logging.level` is given: the logger is the process's.
|
|
275
275
|
*
|
|
276
|
+
* What it reads process-wide is the resource graph: the `database()`,
|
|
277
|
+
* `bucket()`, `topic()` and `queue()` declarations are module-level values,
|
|
278
|
+
* and every backend in the process sees all of them. So a process holds one
|
|
279
|
+
* project's resources — several backends of that project are fine, two
|
|
280
|
+
* projects declaring different resources are not.
|
|
281
|
+
*
|
|
276
282
|
* What the build logs at info is written when the backend first serves — see
|
|
277
283
|
* `boot-announcements.ts` — so a script that builds one and never mounts it
|
|
278
284
|
* prints nothing of the boot's on its stdout.
|
|
@@ -419,10 +419,15 @@ export interface RebaseBackendOptions {
|
|
|
419
419
|
* and their RLS policies, change capture for realtime, the database
|
|
420
420
|
* role requests run as, and the framework's own tables (API keys, cron
|
|
421
421
|
* runs, jobs, metrics). What a single-process deployment wants.
|
|
422
|
-
* - `false` — nothing
|
|
423
|
-
*
|
|
424
|
-
*
|
|
425
|
-
*
|
|
422
|
+
* - `false` — nothing, at boot or later: not even the tables other
|
|
423
|
+
* backends make on first use (idempotency keys, cron claims). The schema
|
|
424
|
+
* must already be there: applied by a migration, or by another process
|
|
425
|
+
* created with `provision: true`. What a script, a REPL, a test reading
|
|
426
|
+
* rows, a second process of a split deployment, or a database only a
|
|
427
|
+
* change process may change wants. Missing auth tables refuse at boot;
|
|
428
|
+
* a missing optional table turns its feature off and is named in the log.
|
|
429
|
+
* `initializeRebaseBackend` and the runtime image pass it for
|
|
430
|
+
* `REBASE_PROVISION=false`.
|
|
426
431
|
* - `{ collections: false, realtime: false }` — the framework's tables and
|
|
427
432
|
* the role, but not the collection schema or change capture: a process
|
|
428
433
|
* that is not the schema's owner in a split deployment.
|
|
@@ -24,7 +24,14 @@ function isSchemaEditingAdmin(admin) {
|
|
|
24
24
|
function isSQLAdmin(admin) {
|
|
25
25
|
return !!admin && typeof admin.executeSql === "function";
|
|
26
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* Type guard: does this admin support database branching?
|
|
29
|
+
* @group Admin
|
|
30
|
+
*/
|
|
31
|
+
function isBranchAdmin(admin) {
|
|
32
|
+
return !!admin && typeof admin.createBranch === "function";
|
|
33
|
+
}
|
|
27
34
|
//#endregion
|
|
28
|
-
export {
|
|
35
|
+
export { isSQLAdmin as n, isSchemaEditingAdmin as r, isBranchAdmin as t };
|
|
29
36
|
|
|
30
|
-
//# sourceMappingURL=backend-
|
|
37
|
+
//# sourceMappingURL=backend-CaG_Jyso.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"backend-CaG_Jyso.js","names":[],"sources":["../../types/src/types/backend.ts"],"sourcesContent":["import type { CollectionConfig, FilterValues, WhereFilterOp } from \"./collections\";\nimport type { CollectionCallbacks } from \"./entity_callbacks\";\nimport type { OrderByTuple } from \"./filter-operators\";\nimport type { LogicalCondition } from \"../controllers/data\";\nimport type { AuthAdapter } from \"./auth_adapter\";\nimport type { HistoryConfig } from \"../controllers/client\";\nimport type { ChannelBusSetting } from \"./channel_bus\";\nimport type { SchemaEditingAdmin } from \"./schema_editing\";\nimport type { AccessModel } from \"./scopes\";\nimport type { ApiKeyKind } from \"./api_keys\";\n\n// =============================================================================\n// DATABASE CONNECTION INTERFACES\n// =============================================================================\n\n/**\n * Abstract database connection interface.\n * Represents a connection to any database system.\n */\nexport interface DatabaseConnection {\n /**\n * Type identifier for this database (e.g., 'postgres', 'mongodb', 'mysql')\n */\n readonly type: string;\n\n /**\n * Whether the connection is currently active\n */\n readonly isConnected?: boolean;\n\n /**\n * Close the database connection and release resources.\n */\n close?(): Promise<void>;\n}\n\n// =============================================================================\n// QUERY BUILDING INTERFACES\n// =============================================================================\n\n/**\n * A single filter condition for database queries\n */\nexport interface QueryFilter {\n field: string;\n operator: WhereFilterOp;\n value: unknown;\n}\n\n/**\n * Options for fetching a collection of entities\n */\nexport interface FetchCollectionOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n /** See `FetchCollectionProps.orderBy`: a field name plus `order`, or a list of tuples. */\n orderBy?: string | OrderByTuple[];\n order?: \"desc\" | \"asc\";\n limit?: number;\n offset?: number;\n startAfter?: unknown;\n searchString?: string;\n databaseId?: string;\n collection?: CollectionConfig;\n}\n\n/**\n * Options for searching entities\n */\nexport interface SearchOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n /** See `FetchCollectionProps.orderBy`: a field name plus `order`, or a list of tuples. */\n orderBy?: string | OrderByTuple[];\n order?: \"desc\" | \"asc\";\n limit?: number;\n databaseId?: string;\n collection?: CollectionConfig;\n}\n\n/**\n * Options for counting entities\n */\nexport interface CountOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n filter?: FilterValues<Extract<keyof M, string>>;\n /**\n * An `or(...)`/`and(...)` group, alongside `filter`.\n *\n * Counted as well as fetched, or `total` describes a different set of rows\n * from the one that was served — the same reason `filter` is here.\n */\n logical?: LogicalCondition;\n searchString?: string;\n databaseId?: string;\n}\n\n/**\n * Abstract condition builder interface.\n * Implementations translate Rebase filter conditions to database-specific queries.\n *\n * Note: This interface can be implemented as instance methods or as a class with static methods.\n * For static implementations (like DrizzleConditionBuilder), use the ConditionBuilderStatic type.\n *\n * @template T The type of condition returned by the builder (e.g., SQL for PostgreSQL, Filter<Document> for MongoDB)\n */\nexport interface ConditionBuilder<T = unknown> {\n /**\n * Build filter conditions from Rebase FilterValues\n */\n buildFilterConditions<M extends Record<string, unknown>>(\n filter: FilterValues<Extract<keyof M, string>>,\n collectionPath: string,\n ...args: unknown[]\n ): T[];\n\n /**\n * Build search conditions for text search.\n *\n * At most one condition comes back, already complete: callers OR what they\n * get, and OR is right across the searchable *fields* but wrong across the\n * *terms* of the search string — a person typing two words means both, and\n * the two halves of a name are two different fields. The empty array still\n * means \"nothing here can be searched\", which every caller reads as \"no\n * rows\".\n */\n buildSearchConditions(\n searchString: string,\n properties: Record<string, unknown>,\n ...args: unknown[]\n ): T[];\n\n /**\n * Combine multiple conditions with AND operator\n */\n combineConditionsWithAnd(conditions: T[]): T | undefined;\n\n /**\n * Combine multiple conditions with OR operator\n */\n combineConditionsWithOr(conditions: T[]): T | undefined;\n}\n\n/**\n * Static condition builder type for implementations using static methods.\n * Use this type when the class provides static methods rather than instance methods.\n *\n * @example\n * // DrizzleConditionBuilder satisfies this type\n * const builder: ConditionBuilderStatic<SQL> = DrizzleConditionBuilder;\n */\nexport type ConditionBuilderStatic<T = unknown> = {\n buildFilterConditions<M extends Record<string, unknown>>(\n filter: FilterValues<Extract<keyof M, string>>,\n ...args: unknown[]\n ): T[];\n buildSearchConditions(\n searchString: string,\n properties: Record<string, unknown>,\n ...args: unknown[]\n ): T[];\n combineConditionsWithAnd(conditions: T[]): T | undefined;\n combineConditionsWithOr(conditions: T[]): T | undefined;\n};\n\n// =============================================================================\n// ENTITY REPOSITORY INTERFACES\n// =============================================================================\n\n/**\n * Abstract entity repository interface.\n * Handles all CRUD operations for entities in the database.\n *\n * Implementations should handle:\n * - Entity serialization/deserialization\n * - Relation resolution\n * - ID generation and conversion\n */\nexport interface DataRepository {\n /**\n * Fetch a single entity by ID\n */\n fetchOne<M extends Record<string, unknown>>(\n collectionPath: string,\n id: string | number,\n databaseId?: string\n ): Promise<Record<string, unknown> | undefined>;\n\n /**\n * Fetch a collection of entities with optional filtering, ordering, and pagination\n */\n fetchCollection<M extends Record<string, unknown>>(\n collectionPath: string,\n options?: FetchCollectionOptions<M>\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * Search entities by text\n */\n searchRows<M extends Record<string, unknown>>(\n collectionPath: string,\n searchString: string,\n options?: SearchOptions<M>\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * Count entities in a collection\n */\n count<M extends Record<string, unknown>>(\n collectionPath: string,\n options?: CountOptions<M>\n ): Promise<number>;\n\n /**\n * Save a entity (create or update)\n */\n save<M extends Record<string, unknown>>(\n collectionPath: string,\n values: Partial<M>,\n id?: string | number,\n databaseId?: string\n ): Promise<Record<string, unknown>>;\n\n /**\n * Delete a entity by ID\n */\n delete(\n collectionPath: string,\n id: string | number,\n databaseId?: string\n ): Promise<void>;\n\n /**\n * Check if a field value is unique in a collection\n */\n checkUniqueField(\n collectionPath: string,\n fieldName: string,\n value: unknown,\n excludeEntityId?: string,\n databaseId?: string\n ): Promise<boolean>;\n\n}\n\n// =============================================================================\n// REALTIME INTERFACES\n// =============================================================================\n\n/**\n * Configuration for subscribing to a collection\n */\nexport interface CollectionSubscriptionConfig {\n clientId: string;\n path: string;\n filter?: unknown;\n /**\n * An `or(...)`/`and(...)` group, applied alongside `filter`.\n *\n * Declared here because a subscription is a query, and every field a query\n * has this one needs too. It was missing, so the type-checked boundary\n * dropped it: the client sent the group, nothing rejected it, and the\n * subscription re-fetched with the group gone — pushing every row the\n * caller's policies allowed rather than the ones they asked for. The same\n * defect `FetchCollectionProps.logical` documents, one layer up.\n */\n logical?: LogicalCondition;\n /**\n * Where the subscription's page starts. Missing for the same reason, with\n * a quieter symptom: a subscriber watching page two was pushed page one,\n * and a `collection_update` frame carries no window for it to notice with.\n */\n offset?: number;\n /** See `FetchCollectionProps.orderBy`: a field name plus `order`, or a list of tuples. */\n orderBy?: string | OrderByTuple[];\n order?: \"desc\" | \"asc\";\n limit?: number;\n startAfter?: unknown;\n databaseId?: string;\n searchString?: string;\n /** Ask each row which declared search field matched. */\n searchExplain?: boolean;\n}\n\n/**\n * Configuration for subscribing to a single entity\n */\nexport interface SingleSubscriptionConfig {\n clientId: string;\n path: string;\n id: string | number;\n}\n\n/**\n * Opt-in retention for one set of broadcast channels.\n *\n * Retention is configured on the server and nowhere else. A channel is created\n * by whoever names it, so letting a client ask for its own history depth would\n * let any visitor commit the backend to unbounded storage; and presence-only or\n * notification-only channels — the overwhelming majority — must not pay for a\n * feature they never use. With no rules configured nothing is written, no table\n * is created, and broadcast behaves exactly as it did before history existed.\n */\nexport interface ChannelRetentionRule {\n /**\n * Channel name to match. Either exact (`\"doc:42\"`) or a trailing-`*` prefix\n * (`\"doc:*\"`). Deliberately not a full glob or RegExp: this decides what\n * gets written to disk, and a rule whose blast radius is not obvious at a\n * glance is the wrong shape for that.\n */\n match: string;\n /** Keep at most this many of the most recent messages per channel. */\n limit?: number;\n /**\n * Keep messages for at most this long. Accepts a millisecond count or a\n * short duration string (`\"30s\"`, `\"15m\"`, `\"24h\"`, `\"7d\"`).\n */\n ttl?: number | string;\n}\n\n/**\n * Server-side realtime options.\n *\n * The channel bus contract and its config live in `./channel_bus` so that a\n * transport shipped as its own package depends on the contract alone.\n */\nexport interface RealtimeChannelsConfig {\n /**\n * Retention rules, most specific first — the first match wins. Omitted or\n * empty means no channel retains anything.\n */\n channels?: ChannelRetentionRule[];\n /**\n * How channel broadcast and presence reach other backend instances.\n * Defaults to `{ type: \"memory\" }` — i.e. they don't.\n */\n bus?: ChannelBusSetting;\n /**\n * How many subscriptions one socket may hold; the next is refused with\n * `TOO_MANY_SUBSCRIPTIONS`. A positive whole number, checked at boot.\n * Defaults to 1000. `REALTIME_MAX_SUBSCRIPTIONS_PER_SOCKET` wins over it.\n */\n maxSubscriptionsPerSocket?: number;\n /**\n * How many sockets one user (one identity: a signed-in user, an API key's\n * user, an impersonated user) may hold open on one server instance. The\n * next one's `AUTHENTICATE` is refused with `TOO_MANY_SOCKETS` and the\n * socket closed with 4002; the SDK keeps retrying with backoff, so it gets\n * in once another closes. A positive whole number, checked at boot.\n * Unset (the default) is no ceiling. `REALTIME_MAX_SOCKETS_PER_USER` wins\n * over it.\n */\n maxSocketsPerUser?: number;\n /**\n * The longest a change waits for the refetch that delivers it, in ms. A\n * refetch waits for 300 ms without a change, and at most this long under a\n * steady stream of writes. Defaults to 1000. A positive whole number,\n * checked at boot. `REALTIME_REFETCH_MAX_WAIT_MS` wins over it.\n */\n refetchMaxWaitMs?: number;\n /**\n * How long a big list subscription's total may be reused before it is\n * counted again, in ms. Unset (the default), every frame counts. Frames\n * that reuse it carry `meta.totalAsOf`. `REALTIME_RECOUNT_INTERVAL_MS`\n * wins over it.\n */\n recountIntervalMs?: number;\n /**\n * The smallest last total at which {@link recountIntervalMs} applies;\n * smaller lists are counted on every frame. Defaults to 100 000.\n * `REALTIME_RECOUNT_MIN_ROWS` wins over it.\n */\n recountMinRows?: number;\n /**\n * How changes are captured for realtime. `auto` (the default) installs\n * database-level capture where the connection can and falls back to\n * announcing the API's own writes where it cannot; `trigger` asks for\n * capture and warns when it is refused; `wal` is `trigger` until WAL\n * streaming ships; `off` announces the API's own writes only.\n * `REALTIME_CDC` wins over it.\n */\n cdc?: \"auto\" | \"wal\" | \"trigger\" | \"off\";\n /**\n * The URL path the realtime socket accepts upgrades on. Defaults to the\n * one the server derives from where it is mounted — `/` for a server at\n * `/api`, which is where the SDK dials. Set it when clients dial elsewhere\n * (a `websocketUrl` with a path). See {@link RealtimeSocketOptions.path}.\n */\n path?: string;\n}\n\n/**\n * Abstract realtime provider interface.\n * Handles real-time subscriptions and notifications for entity changes.\n */\nexport interface RealtimeProvider {\n /**\n * Subscribe to collection changes.\n *\n * `onError` is called when a fetch behind the subscription fails, a\n * refetch after a change included, with the error as it was thrown. It is\n * not called for a fetch that newer rows have already overtaken, or after\n * the subscription is gone. Without it, a subscriber whose fetch failed\n * was told nothing and kept waiting for rows.\n */\n subscribeToCollection(\n subscriptionId: string,\n config: CollectionSubscriptionConfig,\n callback?: (rows: Record<string, unknown>[]) => void,\n onError?: (error: unknown) => void\n ): void;\n\n /**\n * Subscribe to single entity changes. `onError` as for\n * {@link RealtimeProvider.subscribeToCollection}.\n */\n subscribeToOne(\n subscriptionId: string,\n config: SingleSubscriptionConfig,\n callback?: (row: Record<string, unknown> | null) => void,\n onError?: (error: unknown) => void\n ): void;\n\n /**\n * Unsubscribe from a subscription\n */\n unsubscribe(subscriptionId: string): void;\n\n /**\n * Notify all relevant subscribers of a entity update\n */\n notifyUpdate(\n path: string,\n id: string,\n row: Record<string, unknown> | null,\n databaseId?: string\n ): Promise<void>;\n\n /**\n * Called when the HTTP server is ready and listening.\n * Useful for providers that need the server address for callbacks.\n */\n onServerReady?(serverInfo: { port: number; hostname?: string }): void;\n\n /**\n * Gracefully shut down the realtime provider.\n * Called during server shutdown to clean up resources.\n */\n destroy?(): Promise<void>;\n\n /**\n * Stop the internal LISTEN client (e.g., PostgreSQL LISTEN/NOTIFY).\n * Called during graceful shutdown before closing database connections.\n */\n stopListening?(): Promise<void>;\n\n /**\n * The long-lived connections realtime depends on, for `/health`. A change\n * feed that has gone quiet — a half-open LISTEN connection — loses every\n * external and cross-instance change while writes through this instance\n * still look live, so it is reported rather than inferred.\n */\n health?(): RealtimeListenerHealth[];\n\n /**\n * Run the provider's own background reads — the refetches a change\n * schedules, whatever announced it (a write here, change capture, another\n * instance) — through `run`. The server passes one that enters the backend\n * owning this provider, so a hook such a read reaches sees that backend as\n * `rebase`. Without it they run in the context of whatever scheduled them.\n */\n setScopeRunner?(run: <T>(fn: () => T) => T): void;\n}\n\n/**\n * One long-lived realtime connection, as `/health` reports it.\n * @group Backend\n */\nexport interface RealtimeListenerHealth {\n /** What it carries — `\"cdc\"`, `\"cross-instance\"`, `\"channel-bus\"`. */\n name: string;\n /** Listening on a connection that answered its last heartbeat. */\n connected: boolean;\n /** When (epoch ms) it went down, while it is down. */\n downSince?: number;\n}\n\n// =============================================================================\n// COLLECTION REGISTRY INTERFACES\n// =============================================================================\n\n/**\n * Abstract collection registry interface.\n * Manages registration and lookup of entity collections.\n */\nexport interface CollectionRegistryInterface {\n /**\n * Register a collection\n */\n register(collection: CollectionConfig): void;\n\n /**\n * Get a collection by its path\n */\n getCollectionByPath(path: string): CollectionConfig | undefined;\n\n /**\n * Get all registered collections\n */\n getCollections(): CollectionConfig[];\n\n /**\n * Get the currently registered global callbacks, if any.\n */\n getGlobalCallbacks(): any | undefined;\n\n /**\n * Take the global callbacks declared on `initializeRebaseBackend({ callbacks })`.\n *\n * A driver resolves callbacks from the registry it builds for itself, so\n * this is how the backend's global ones reach it: the coordinator hands\n * them over after `initializeDriver` returns. Optional so a registry for a\n * driver that runs no callbacks still type-checks, but a project that\n * declares global callbacks over a registry without it is refused at boot\n * — hooks that never run look exactly like hooks that passed.\n */\n setGlobalCallbacks?(callbacks: CollectionCallbacks): void;\n}\n\n// =============================================================================\n// DATA TRANSFORMER INTERFACES\n// =============================================================================\n\n/**\n * Abstract data transformer interface.\n * Handles serialization/deserialization between frontend and database formats.\n */\nexport interface DataTransformer {\n /**\n * Transform entity data for storage in the database\n */\n serializeToDatabase<M extends Record<string, unknown>>(\n entity: M,\n collection: CollectionConfig\n ): Record<string, unknown>;\n\n /**\n * Transform database data back to entity format\n */\n deserializeFromDatabase<M extends Record<string, unknown>>(\n data: Record<string, unknown>,\n collection: CollectionConfig\n ): Promise<M>;\n}\n\n// =============================================================================\n// DATABASE ADMIN — CAPABILITY-SPECIFIC INTERFACES (1.3)\n// =============================================================================\n\n/**\n * The table column a value of a {@link SqlScriptResult} was read from, as the\n * database itself reported it — not as the query's text suggests.\n *\n * @group Admin\n */\nexport interface SqlScriptColumnSource {\n schema: string;\n table: string;\n column: string;\n}\n\n/**\n * One column of a {@link SqlScriptResult}, in result order.\n *\n * @group Admin\n */\nexport interface SqlScriptColumn {\n /** The name the result gives it. Two columns of one result may share it. */\n name: string;\n /** Its type, as the database names it: `integer`, `text[]`, `timestamp with time zone`. */\n type?: string;\n /**\n * Where the database says the value came from: a plain reference to a\n * column of a table or view, through any number of subqueries.\n *\n * Absent for everything no stored row holds — an expression, a cast that\n * changes the type, a literal, an aggregate, a function's output, a\n * `UNION`.\n */\n source?: SqlScriptColumnSource;\n}\n\n/**\n * A table or view some column of a {@link SqlScriptResult} came from.\n *\n * @group Admin\n */\nexport interface SqlScriptTable {\n schema: string;\n table: string;\n /** What the relation is. Only a `table` or a `partitioned table` holds rows that can be updated by key. */\n kind: \"table\" | \"partitioned table\" | \"view\" | \"materialized view\" | \"foreign table\" | \"other\";\n /** Its primary key columns, in key order. Empty when it has none. */\n primaryKey: string[];\n /**\n * Other tables inherit this one (by `INHERITS`, not as partitions). A row\n * read from it may live in one of them, and a primary key is not unique\n * across them.\n */\n hasInheritors: boolean;\n}\n\n/**\n * Something the database said while a script ran: `there is no transaction in\n * progress` for a ROLLBACK with nothing to end, a `RAISE NOTICE`.\n *\n * @group Admin\n */\nexport interface SqlScriptNotice {\n severity: string;\n message: string;\n}\n\n/**\n * What a SQL script a person wrote returned. See {@link SQLAdmin.runSqlScript}.\n *\n * @group Admin\n */\nexport interface SqlScriptResult {\n /**\n * The last statement's rows, every value as the text the database wrote\n * for it and `null` for SQL NULL — so a value written back is the value\n * that was read, whatever its type. Keyed by column name: of two columns\n * that share a name, the row holds the last.\n */\n rows: Record<string, string | null>[];\n /** The last statement's columns, in order. */\n columns: SqlScriptColumn[];\n /** The tables and views {@link SqlScriptColumn.source} names. */\n tables: SqlScriptTable[];\n /** The last statement's command: `SELECT`, `UPDATE`, `CREATE TABLE` … */\n command?: string;\n /**\n * How many rows the last statement returned or changed, when its command\n * reports a count — or, for a {@link truncated} result, how many it\n * returned, of which {@link rows} holds the first.\n */\n rowCount?: number;\n /**\n * The last statement returned more than a run keeps, and {@link rows}\n * holds only its first rows. The Studio console's door keeps at most\n * 10,000 rows, or 32 Mi characters of values, of one result: a run that\n * held every row of a million-row table took the server down with it.\n */\n truncated?: boolean;\n /** What the database said while the script ran, in order. */\n notices: SqlScriptNotice[];\n /**\n * The database role the script ran as, when it asked for one — said by\n * the transport that ran it. The role asked for, unless the server has\n * role switching turned off (`DISABLE_DB_ROLE_SWITCHING`) and runs every\n * statement as the connection owner, who is named here instead.\n */\n effectiveRole?: string;\n}\n\n/**\n * A query's result being read a batch at a time — see `SQLAdmin.openSqlCursor`.\n *\n * @group Admin\n */\nexport interface SqlCursor {\n /** The result's column names, in order. */\n readonly columns: string[];\n /**\n * The next rows, each value the text the database wrote for it and `null`\n * for NULL — `null` once there are none left.\n */\n read(): Promise<(string | null)[][] | null>;\n /** End the read and give the session back. Safe to call more than once. */\n close(): Promise<void>;\n}\n\n/**\n * Administrative operations for SQL-based databases (PostgreSQL, MySQL, etc.).\n * Used by the SQL Editor, RLS Editor, and schema browser.\n *\n * @group Admin\n */\nexport interface SQLAdmin {\n /**\n * Execute raw SQL against the database.\n *\n * `isolateSession` runs it on a connection of its own and resets that\n * connection's session state — role, session authorization, settings —\n * before it is reused. For SQL a person wrote (the Studio editor), which\n * may `SET ROLE` and must not leave that on a pooled connection the\n * server's own queries use next.\n *\n * `maxResultBytes` refuses a result whose rows take more than that many\n * bytes, with an error whose `code` is `RESULT_TOO_LARGE`, rather than\n * return it — never a part of it. On a session of its own the read stops\n * there; elsewhere the rows are measured once read. The WebSocket\n * `EXECUTE_SQL` door sets it for every caller.\n */\n executeSql(sql: string, options?: { database?: string; role?: string; params?: unknown[]; isolateSession?: boolean; maxResultBytes?: number }): Promise<Record<string, unknown>[]>;\n\n /**\n * Run a script a person wrote — the Studio SQL console — and describe what\n * it returned.\n *\n * On a session of its own, reset afterwards, as `role` for every statement\n * of it. Values come back as the database's text, and each column says\n * which table column it was read from, when the database says so: what\n * the console needs to write a cell back to the row it came from and to\n * no other. A script that leaves a transaction open is refused, and the\n * transaction rolled back: nothing outlives the run to be committed or\n * rolled back by a later one.\n *\n * Aborting `signal` cancels the run: the statement in progress is stopped\n * (`pg_cancel_backend` on a Postgres server; the in-process development\n * database cannot be interrupted, and the run ends on its own), and the\n * promise rejects.\n */\n runSqlScript?(sql: string, options?: { database?: string; role?: string; signal?: AbortSignal }): Promise<SqlScriptResult>;\n\n /**\n * Read the whole result of ONE query a person wrote, a batch at a time —\n * the Studio SQL console's \"Download full result as CSV\", which the\n * console's 10,000-row cap would otherwise leave no way to get.\n *\n * Through a server-side cursor, in a read-only transaction, on a session\n * of its own, as `role`: a write is refused by the database, and a second\n * statement by the protocol. Each batch is read when the previous one has\n * been consumed, so memory holds one batch whatever the result's size;\n * every read runs under the session's `statement_timeout`. The session is\n * reset and returned when the cursor is closed — which the caller must do,\n * on success, failure or a reader that went away.\n */\n openSqlCursor?(sql: string, options?: { database?: string; role?: string; batchSize?: number }): Promise<SqlCursor>;\n\n /**\n * Fetch the available databases on the server.\n */\n fetchAvailableDatabases?(): Promise<string[]>;\n\n /**\n * Fetch the available *native PostgreSQL* database roles (from `pg_roles`).\n *\n * These are connection-level roles — what the SQL editor can `SET ROLE` to,\n * and what `SecurityRule.pgRoles` targets. They are NOT application roles;\n * for those use {@link fetchApplicationRoles}.\n */\n fetchAvailableRoles?(): Promise<string[]>;\n\n /**\n * Fetch the *application-level* roles in use in this project.\n *\n * These are the strings stored on the users table's `roles` column and\n * exposed to policies as `rebase.roles()` — what `SecurityRule.roles`\n * matches against. Distinct from {@link fetchAvailableRoles}; the two are\n * not interchangeable.\n */\n fetchApplicationRoles?(): Promise<string[]>;\n\n /**\n * Fetch the current database name.\n */\n fetchCurrentDatabase?(): Promise<string | undefined>;\n\n /**\n * Hold a `LISTEN` on `channel`, on a connection of its own that stays open\n * and comes back after a drop, and call `onNotify` with each payload — what\n * wakes the job worker when another process enqueues, instead of a poll\n * every two seconds.\n *\n * Resolves once listening, with the stop. Rejects when no such connection\n * can be had — an in-process database, a first connect that fails — so the\n * caller can fall back to polling. `onReconnect` is called each time a\n * dropped connection is listening again: whatever was sent meanwhile is\n * lost. `channel` must be a plain identifier.\n */\n listen?(\n channel: string,\n onNotify: (payload: string) => void,\n options?: { onReconnect?: () => void }\n ): Promise<() => Promise<void>>;\n}\n\n/**\n * Administrative operations for document-based databases (MongoDB, Firestore, etc.).\n * Used by future document administration tools.\n *\n * @group Admin\n */\nexport interface DocumentAdmin {\n /**\n * Execute an aggregation pipeline or equivalent query.\n */\n executeAggregate?(pipeline: Record<string, unknown>[]): Promise<Record<string, unknown>[]>;\n\n /**\n * Fetch statistics for a collection (document count, size, etc.).\n */\n fetchCollectionStats?(collectionName: string): Promise<{ count: number; sizeBytes?: number }>;\n}\n\n/**\n * Administrative operations for schema management.\n * Shared across SQL and document databases.\n *\n * @group Admin\n */\nexport interface SchemaAdmin {\n /**\n * Fetch database tables/collections not yet mapped to a Rebase collection.\n */\n fetchUnmappedTables?(mappedPaths?: string[]): Promise<string[]>;\n\n /**\n * Fetch column/field metadata for a single table/collection.\n * The return type is generic — SQL backends return TableMetadata,\n * document backends may return a different shape.\n */\n fetchTableMetadata?(tableName: string): Promise<unknown>;\n}\n\n/**\n * Metadata for a database branch.\n * @group Admin\n */\nexport interface BranchInfo {\n /** Branch name (without prefix). */\n name: string;\n /**\n * The PostgreSQL database the branch is — what to connect to, and what to\n * name as the source when copying it. As the branch's record says, never\n * derived from `name` again.\n */\n database: string;\n /** The database this branch was created from. */\n parentDatabase: string;\n /** When the branch was created. */\n createdAt: Date;\n /** Size in bytes, if available from the server. */\n sizeBytes?: number;\n /**\n * The transaction that created the branch database, recorded when it was\n * made: the fork point a branch diff tells the two sides' writes apart by.\n * Absent for a branch made before it was recorded, or by a server that\n * does not record it.\n */\n forkXid?: string;\n}\n\n/**\n * Administrative operations for database branching.\n * Allows creating isolated database copies for development/preview workflows.\n *\n * @group Admin\n */\nexport interface BranchAdmin {\n /** Create a new branch (database copy) from the current or specified source database. */\n createBranch(name: string, options?: { source?: string }): Promise<BranchInfo>;\n\n /** Delete a branch database. Cannot delete the main/default database. */\n deleteBranch(name: string): Promise<void>;\n\n /** List all branches (databases that were created via branching). */\n listBranches(): Promise<BranchInfo[]>;\n\n /** Get info about a specific branch. */\n getBranchInfo(name: string): Promise<BranchInfo | undefined>;\n\n /**\n * What the branch changed, against the database it was made from: its\n * tables, columns, constraints, indexes, triggers, row-level-security\n * policies, enum types, views and functions, and per table the rows it\n * inserted, updated and deleted. Reads only.\n */\n diffBranch?(name: string, options?: BranchDiffOptions): Promise<BranchDiff>;\n\n /**\n * Apply the rows the branch changed to the database it was made from. See\n * {@link BranchMergeOptions} for what wins, and when nothing is written.\n */\n mergeBranch?(name: string, options: BranchMergeOptions): Promise<BranchMergeResult>;\n}\n\n/**\n * What {@link BranchAdmin.diffBranch} compares.\n * @group Admin\n */\nexport interface BranchDiffOptions {\n /** Rows shown per table, across every kind of change. Default 100, at most 1,000. */\n sampleLimit?: number;\n /** Schemas to compare. Default: every schema but the system's, without Rebase's own tables. */\n schemas?: string[];\n /**\n * Rows a table may hold, on either side, for its rows to be matched one by\n * one. A larger table that differs is reported with its row counts only,\n * and cannot be merged. Default 100,000.\n */\n maxRowsPerTable?: number;\n}\n\n/**\n * One change to the schema: a table, a column, a policy, a table's row-level\n * security, a constraint (unique, foreign key, check, exclusion), an index, a\n * trigger — or, outside any table, an enum type, a view or a function.\n * @group Admin\n */\nexport interface BranchSchemaChange {\n object: \"table\" | \"column\" | \"policy\" | \"rls\" | \"constraint\" | \"index\" | \"trigger\" | \"enum\" | \"view\" | \"function\";\n change: \"added\" | \"dropped\" | \"altered\";\n schema: string;\n /**\n * The table the change is on — or, for an enum, a view or a function, the\n * object's own name (a function's with its argument types).\n */\n table: string;\n /** The column's, policy's, constraint's, index's or trigger's name. */\n name?: string;\n /** The definition on the target, as SQL. Absent for an addition. */\n before?: string;\n /** The definition on the branch, as SQL. Absent for a drop. */\n after?: string;\n}\n\n/**\n * Why the changed rows of a table cannot be merged.\n * @group Admin\n */\nexport interface BranchMergeBlock {\n /**\n * `TABLE_REWRITTEN`: one side wrote every row anew since the branch was\n * made (a column type change, a volatile default, `VACUUM FULL`), so which\n * side changed which row can no longer be told.\n */\n code: \"TABLE_ADDED\" | \"TABLE_DROPPED\" | \"COLUMNS_DIFFER\" | \"PRIMARY_KEY_DIFFERS\" | \"NO_PRIMARY_KEY\" | \"TOO_LARGE\" | \"TABLE_REWRITTEN\";\n message: string;\n}\n\n/**\n * One row the branch changed, or one both sides changed.\n *\n * Values are the text the database writes for them, `null` for SQL NULL, so a\n * `bigint` or a `numeric` reads exactly as it is stored — except a column named\n * like a credential (`password_hash`, `*_token`, `*secret*`, `*_hash`), whose\n * value reads `\"[redacted]\"`. It is still listed in {@link changedColumns}.\n *\n * A `\"conflict\"` with no {@link after} is a row the branch deleted that rows\n * the target wrote since the branch was made still reference — see\n * {@link BranchTableDataDiff.referencedBy}.\n * @group Admin\n */\nexport interface BranchRowChange {\n change: \"inserted\" | \"updated\" | \"deleted\" | \"conflict\";\n /** The primary key, as a JSON array of its columns' values. */\n key: string;\n /** The row on the target. Absent for an insert. */\n before?: Record<string, string | null>;\n /** The row on the branch. Absent for a delete. */\n after?: Record<string, string | null>;\n /** The columns whose values differ, for an update or a conflict. */\n changedColumns?: string[];\n}\n\n/**\n * The rows of one table that differ between the branch and its target.\n * @group Admin\n */\nexport interface BranchTableDataDiff {\n schema: string;\n table: string;\n /** The collection whose table this is, when the server knows one. */\n collection?: string;\n primaryKey: string[];\n /** Rows the branch inserted. */\n inserted: number;\n /** Rows the branch updated. */\n updated: number;\n /** Rows the branch deleted. */\n deleted: number;\n /**\n * Rows both sides changed since the branch was made, differently — and\n * rows the branch deleted that rows the target wrote since still\n * reference through a foreign key ({@link referencedBy}). Deleting one of\n * those on the target would cascade into, or rewrite, the target's own\n * rows, so it is a conflict {@link BranchMergeOptions.onConflict} decides.\n */\n conflicts: number;\n /**\n * Rows the target changed since the branch was made, and the branch did\n * not. A merge leaves them as they are.\n */\n targetChanges: number;\n /** Up to {@link BranchDiffOptions.sampleLimit} of the rows counted above, but not of {@link targetChanges}. */\n samples: BranchRowChange[];\n /** Present when this table's rows cannot be merged. A merge refuses it unless told to skip it. */\n blocked?: BranchMergeBlock;\n /**\n * Rows on each side, for a table whose rows were not matched one by one.\n * Its inserted, updated, deleted and conflict counts are then 0 because\n * they are unknown, not because nothing changed.\n */\n rowCounts?: { target: number; branch: number };\n /**\n * The foreign keys through which rows the target wrote since the branch\n * was made reference rows of this table the branch deleted. Each such\n * delete is counted in {@link conflicts}.\n */\n referencedBy?: BranchReferencingRows[];\n}\n\n/**\n * Rows of one table, written on the target since the branch was made, that\n * reference rows the branch deleted.\n * @group Admin\n */\nexport interface BranchReferencingRows {\n schema: string;\n table: string;\n /** The foreign key's name. */\n constraint: string;\n /** What deleting the referenced row does to them on the target. */\n onDelete: \"cascade\" | \"set null\" | \"set default\" | \"restrict\" | \"no action\";\n /** How many of them there are. */\n rows: number;\n}\n\n/**\n * What {@link BranchAdmin.diffBranch} returns.\n * @group Admin\n */\nexport interface BranchDiff {\n branch: string;\n /** The branch's database. */\n branchDatabase: string;\n /** The database the branch was made from, which a merge writes to. */\n targetDatabase: string;\n /** The schemas compared. */\n schemas: string[];\n /**\n * Whether rows could be told apart by which side changed them since the\n * branch was made. When `false`, every row that differs is counted as the\n * branch's change, and a merge would undo what the target changed.\n */\n forkPointKnown: boolean;\n /** Pass to {@link BranchAdmin.mergeBranch}: what this diff saw, on both sides. */\n fingerprint: string;\n schema: BranchSchemaChange[];\n /** Only the tables with rows that differ. */\n data: BranchTableDataDiff[];\n sampleLimit: number;\n computedAt: string;\n}\n\n/**\n * How {@link BranchAdmin.mergeBranch} applies a branch.\n *\n * A merge writes the rows the branch inserted, updated and deleted to the\n * target, in one statement: all of them, or none. Rows the target changed\n * since the branch was made are kept. Schema and policy changes are never\n * merged — they belong to the collections and their migrations.\n *\n * Nothing is written when either side changed since the diff that produced\n * {@link expectedFingerprint}, when a table with changed rows cannot be merged\n * (unless {@link skipBlocked}), or when a row was changed on both sides and\n * {@link onConflict} is `\"abort\"`.\n * @group Admin\n */\nexport interface BranchMergeOptions {\n /** {@link BranchDiff.fingerprint} of the diff that was reviewed. */\n expectedFingerprint: string;\n /**\n * A row both sides changed: `\"abort\"` (the default) writes nothing,\n * `\"branch\"` writes the branch's row over the target's, `\"target\"` keeps\n * the target's.\n *\n * A row the branch deleted that the target's newer rows reference\n * ({@link BranchTableDataDiff.referencedBy}) is a conflict too: `\"target\"`\n * keeps it, and with it the rows that reference it; `\"branch\"` deletes it,\n * and the foreign key's `ON DELETE` reaches those rows — the result's\n * `warnings` say which.\n */\n onConflict?: \"abort\" | \"branch\" | \"target\";\n /** Merge the other tables when some cannot be merged, instead of writing nothing. */\n skipBlocked?: boolean;\n /** The schemas the reviewed diff compared, when it was not the default. */\n schemas?: string[];\n /** The row limit the reviewed diff used, when it was not the default. */\n maxRowsPerTable?: number;\n}\n\n/**\n * What {@link BranchAdmin.mergeBranch} wrote.\n * @group Admin\n */\nexport interface BranchMergeResult {\n branch: string;\n targetDatabase: string;\n tables: { schema: string; table: string; inserted: number; updated: number; deleted: number }[];\n /** Tables left unmerged because they could not be, with `skipBlocked`. */\n skipped: { schema: string; table: string; reason: BranchMergeBlock }[];\n /** Rows both sides changed that kept the target's version, with `onConflict: \"target\"`. */\n conflictsKept: number;\n /** Schema and policy changes on the branch, none of which a merge applies. */\n schemaChangesNotMerged: number;\n /**\n * What the merge did beyond the rows it counts, or what went wrong after\n * they were written: a delete whose foreign keys reached the target's own\n * rows (with `onConflict: \"branch\"`), a sequence left behind them.\n */\n warnings: string[];\n}\n\n/**\n * Union type for all admin capabilities.\n * A backend may implement any combination of these interfaces.\n *\n * Use type guards (`isSQLAdmin`, `isDocumentAdmin`, `isSchemaAdmin`, `isBranchAdmin`)\n * to safely narrow the type before calling methods.\n *\n * @group Admin\n */\nexport type DatabaseAdmin = Partial<SQLAdmin> & Partial<DocumentAdmin> & Partial<SchemaAdmin>\n & Partial<BranchAdmin> & Partial<SchemaEditingAdmin>;\n\n/**\n * Type guard: can this admin plan a live schema change?\n *\n * Planning is engine-specific — it renders DDL, a Drizzle schema and the\n * declarative SQL artifacts — so the implementation lives in the driver\n * package. The server detects the capability structurally, exactly as it does\n * for SQL, rather than importing an engine it is supposed to know nothing\n * about.\n *\n * @group Admin\n */\nexport function isSchemaEditingAdmin(admin: DatabaseAdmin | undefined): admin is SchemaEditingAdmin {\n return !!admin && typeof (admin as SchemaEditingAdmin).planSchemaChange === \"function\";\n}\n\n/**\n * Type guard: does this admin support SQL operations?\n * @group Admin\n */\nexport function isSQLAdmin(admin: DatabaseAdmin | undefined): admin is SQLAdmin {\n return !!admin && typeof (admin as SQLAdmin).executeSql === \"function\";\n}\n\n/**\n * Type guard: does this admin support document operations?\n * @group Admin\n */\nexport function isDocumentAdmin(admin: DatabaseAdmin | undefined): admin is DocumentAdmin {\n return !!admin && (\n typeof (admin as DocumentAdmin).executeAggregate === \"function\" ||\n typeof (admin as DocumentAdmin).fetchCollectionStats === \"function\"\n );\n}\n\n/**\n * Type guard: does this admin support schema management?\n * @group Admin\n */\nexport function isSchemaAdmin(admin: DatabaseAdmin | undefined): admin is SchemaAdmin {\n return !!admin && (\n typeof (admin as SchemaAdmin).fetchUnmappedTables === \"function\" ||\n typeof (admin as SchemaAdmin).fetchTableMetadata === \"function\"\n );\n}\n\n/**\n * Type guard: does this admin support database branching?\n * @group Admin\n */\nexport function isBranchAdmin(admin: DatabaseAdmin | undefined): admin is BranchAdmin {\n return !!admin && typeof (admin as BranchAdmin).createBranch === \"function\";\n}\n\n// =============================================================================\n// LIFECYCLE INTERFACES (1.4)\n// =============================================================================\n\n/**\n * Health check result returned by `healthCheck()`.\n * @group Lifecycle\n */\nexport interface HealthCheckResult {\n /** Whether the backend is healthy and able to serve requests. */\n healthy: boolean;\n /** Round-trip latency to the database in milliseconds. */\n latencyMs: number;\n /** Optional details (e.g., pool stats, replication lag). */\n details?: Record<string, unknown>;\n}\n\n/**\n * Lifecycle contract for backend components that hold resources\n * (database connections, WebSocket pools, timers, etc.).\n *\n * All methods are optional — simple backends (e.g., in-memory) can skip them.\n * @group Lifecycle\n */\nexport interface BackendLifecycle {\n /**\n * Initialize the backend: open connections, run migrations, seed data.\n * Called once during startup. Idempotent.\n */\n initialize?(): Promise<void>;\n\n /**\n * Check whether the backend is healthy and reachable.\n * Should be fast (< 1 s) and safe to call frequently.\n */\n healthCheck?(): Promise<HealthCheckResult>;\n\n /**\n * Gracefully shut down: close connections, flush buffers, cancel timers.\n * After calling `destroy()`, no other methods should be called.\n */\n destroy?(): Promise<void>;\n}\n\n// =============================================================================\n// BACKEND FACTORY INTERFACES\n// =============================================================================\n\n/**\n * Configuration for creating a database backend\n */\nexport interface BackendConfig {\n /**\n * Type of database backend\n */\n type: string;\n\n /**\n * Database connection (implementation-specific)\n */\n connection: unknown;\n\n /**\n * Schema definition (implementation-specific, e.g., Drizzle schema for PostgreSQL)\n */\n schema?: unknown;\n}\n\n/**\n * A complete backend instance with all required services.\n *\n * Now includes optional lifecycle management and admin capabilities.\n */\nexport interface BackendInstance extends BackendLifecycle {\n /**\n * Entity repository for CRUD operations\n */\n entityRepository: DataRepository;\n\n /**\n * Realtime provider for subscriptions\n */\n realtimeProvider: RealtimeProvider;\n\n /**\n * Collection registry\n */\n collectionRegistry: CollectionRegistryInterface;\n\n /**\n * The underlying database connection\n */\n connection: DatabaseConnection;\n\n /**\n * Administrative operations (SQL, schema, documents).\n * What's available depends on the backend type — use type guards\n * (`isSQLAdmin`, `isSchemaAdmin`, etc.) to narrow.\n */\n admin?: DatabaseAdmin;\n}\n\n/**\n * Factory function type for creating backend instances\n */\nexport type BackendFactory<TConfig extends BackendConfig = BackendConfig> =\n (config: TConfig) => BackendInstance;\n\n// =============================================================================\n// BACKEND BOOTSTRAPPER (1.2)\n// =============================================================================\n\n/**\n * A caller of the data API as its rate limiter buckets one outside an HTTP\n * request: a realtime socket's frame, counted in the same bucket the same\n * person's HTTP requests are.\n * @group Backend\n */\nexport interface DataRateLimitCaller {\n /**\n * The signed-in user's uid. Absent, or the anonymous principal, buckets\n * the caller by address at the anonymous allowance.\n */\n uid?: string;\n /**\n * The API key the connection authenticated with. Its frames count in the\n * key's own bucket at the key's own `rate_limit`, the bucket its HTTP\n * requests count in, rather than as `uid`.\n */\n apiKey?: { id: string; rate_limit: number | null };\n /**\n * A header of the request that opened the connection, by lower-case name:\n * the proxy headers an address is read from when proxies are declared.\n */\n header(name: string): string | undefined;\n /** The address the connection comes from. */\n socketAddress?: string;\n}\n\n/**\n * What the realtime socket shares with the HTTP data API: its request limits,\n * so a frame carries the ones an HTTP request to the same rows does, and its\n * API-key verification, so a key means the same thing on both.\n * @group Backend\n */\nexport interface RealtimeSocketOptions {\n /**\n * Verify an `rk_` API key presented to `AUTHENTICATE`: the identity it acts\n * as and the scopes it holds, or why it does not authenticate. Absent when\n * the deployment has no API-key store, and then keys cannot authenticate\n * the socket.\n */\n resolveApiKey?: (token: string) => Promise<{\n uid: string;\n roles: string[];\n scopes: string[];\n /**\n * The key itself: its id and `rate_limit` decide which rate-limit\n * bucket its frames count in. With `name` and `kind`, collection\n * callbacks on its write frames read it as `context.credential`.\n */\n apiKey?: { id: string; rate_limit: number | null; name?: string; kind?: ApiKeyKind };\n } | { message: string }>;\n /**\n * Verify a session token presented to `AUTHENTICATE` with the backend's own\n * keys, when the socket has no auth adapter to ask: who it names, or null\n * when it does not verify. The server passes its backend's; absent, the\n * driver falls back to the process default.\n */\n verifyAccessToken?: (token: string) => Promise<{\n uid: string;\n roles?: string[];\n isAnonymous?: boolean;\n claims?: Record<string, unknown>;\n } | null>;\n /**\n * The backend's access model — what a session's roles hold on the socket's\n * admin frames. The server passes its backend's; absent, the driver falls\n * back to the process default.\n */\n accessModel?: AccessModel;\n /**\n * The largest frame accepted, in bytes — the data API's body limit. `0` or\n * less for none. Defaults to the server's default body limit.\n */\n maxPayload?: number;\n /**\n * Count one data request from `caller` in the data API's per-caller\n * buckets and say whether it is allowed; `null` for a caller who is not\n * limited. Absent when the deployment has rate limiting off.\n */\n dataRateLimit?: (caller: DataRateLimitCaller) => Promise<{ allowed: boolean; retryAfterMs: number } | null>;\n /**\n * How often a socket that only listens has its identity re-read, in ms\n * (default 30 000). A socket that sends frames is re-checked before each\n * one; this bounds how long a subscription keeps receiving rows as an\n * identity that has since signed out, been revoked, demoted or deleted.\n */\n identityRecheckIntervalMs?: number;\n /**\n * How often a socket that asked for heartbeats (`?rebase_caps=heartbeat`)\n * is sent one, in ms (default 30 000). The SDK redials after two missed.\n */\n heartbeatIntervalMs?: number;\n /**\n * How many sockets one identity may hold open on this server; the next\n * one's `AUTHENTICATE` is refused with `TOO_MANY_SOCKETS` and the socket\n * closed (4002). Unset for no ceiling. See `realtime.maxSocketsPerUser`.\n */\n maxSocketsPerUser?: number;\n /**\n * The URL path the socket accepts upgrades on (default `/`). The SDK dials\n * its `baseUrl` with no extra segment, so for a server mounted at `/api`\n * this is `/`, and for one at `/app/api` it is `/app`. A trailing `/` is\n * ignored, and so is the query string.\n *\n * An upgrade to any other path is not this socket's: it is left untouched\n * for another `upgrade` listener on the same `http.Server` — a host app's\n * own WebSocket server — or, when the socket's listener is the only one,\n * answered `404` and closed, so the client is not left hanging.\n */\n path?: string;\n /**\n * Run `fn` on behalf of the backend that owns this socket: each connection\n * and each frame is handled inside it, so a hook a frame reaches sees that\n * backend as `rebase`, as it does over REST. The server passes its own.\n * Absent, frames run in the context the HTTP connection was accepted in —\n * the process default's.\n */\n runInScope?: <T>(fn: () => T) => T;\n}\n\n/**\n * A `BackendBootstrapper` encapsulates all driver-specific initialization logic.\n *\n * Instead of hard-coding Postgres setup into `initializeRebaseBackend()`,\n * each database backend provides its own bootstrapper that knows how to:\n * - Create the DataDriver from a config object\n * - Optionally initialize auth tables\n * - Optionally create a realtime service\n * - Mount driver-specific API routes\n *\n * The main `initializeRebaseBackend()` becomes a **coordinator** that iterates\n * registered bootstrappers, calls their hooks, and wires the results together.\n *\n * @group Backend\n *\n * @example\n * ```typescript\n * // Third-party MySQL bootstrapper\n * const mysqlBootstrapper: BackendBootstrapper = {\n * type: \"mysql\",\n * initializeDriver: async (config) => new MySQLDataDriver(config.connection),\n * initializeRealtime: async (config) => new MySQLChangeStreamRealtime(config.connection),\n * };\n *\n * initializeRebaseBackend({\n * ...config,\n * bootstrappers: [postgresBootstrapper, mysqlBootstrapper]\n * });\n * ```\n */\nexport interface BackendBootstrapper {\n /**\n * Which driver type this bootstrapper handles.\n * Must match the `type` field on the driver config object\n * (e.g., `\"postgres\"`, `\"mongodb\"`, `\"mysql\"`).\n */\n type: string;\n\n /**\n * Unique identifier for this bootstrapper instance.\n * Used to register the driver in the driver registry.\n * Defaults to `type` if not set.\n */\n id?: string;\n\n /**\n * Whether this bootstrapper provides the default driver.\n * When true, the coordinator uses this driver as the primary one.\n */\n isDefault?: boolean;\n\n /**\n * Run database migrations for this driver.\n * Called by the coordinator after all drivers are initialized.\n */\n runMigrations?(config: unknown, driverResult: InitializedDriver): Promise<void>;\n\n /**\n * Create a DataDriver from the given config.\n * This is the only **required** method.\n */\n initializeDriver(config: unknown): Promise<InitializedDriver>;\n\n /**\n * Initialize auth tables / services if this driver supports them.\n * Return undefined if auth is not supported by this backend.\n */\n initializeAuth?(config: unknown, driverResult: InitializedDriver): Promise<BootstrappedAuth | undefined>;\n\n /**\n * Initialize history tables / services if this driver supports them.\n * Return undefined if history is not supported by this backend.\n */\n initializeHistory?(config: HistoryConfig, driverResult: InitializedDriver): Promise<{ historyService: unknown } | undefined>;\n\n /**\n * Create a realtime provider for this driver.\n * Return undefined if the driver does not support realtime.\n */\n initializeRealtime?(config: unknown, driverResult: InitializedDriver): Promise<RealtimeProvider | undefined>;\n\n /**\n * Never called: the server mounts no route on a bootstrapper's behalf. A\n * driver that needs HTTP routes exports a route factory, and the app\n * mounts it where it chooses.\n *\n * @deprecated Never called. Will be removed in a future release.\n */\n mountRoutes?(app: unknown, basePath: string, driverResult: InitializedDriver): void;\n\n /**\n * Return admin capabilities for this driver.\n */\n getAdmin?(driverResult: InitializedDriver): DatabaseAdmin | undefined;\n\n /**\n * Ask the database whether it is there, before anything else touches it.\n *\n * Boot's first database call is not `initializeDriver` — it is the schema\n * provisioning that runs ahead of it, and a driver's connection diagnosis\n * therefore never got the chance to run. A stopped database produced\n * `Failed query: [redacted]` and a stack through drizzle internals: no host,\n * no port, no `ECONNREFUSED`, and no hint about starting the thing.\n *\n * Implementations MUST issue the cheapest round trip they have (`SELECT 1`),\n * MUST throw an error whose message names the host, the port and the\n * driver's own reason, and MAY log a fuller diagnosis first. They MUST NOT\n * throw for a reachable database that merely answered something unexpected —\n * the caller treats a throw as fatal.\n *\n * `driverResult` is optional for the same reason as\n * {@link ensureCollectionSchema}: this runs before `initializeDriver`, so an\n * adapter that was constructed with its own connection has to fall back to\n * it.\n */\n verifyConnection?(driverResult?: InitializedDriver): Promise<void>;\n\n /**\n * Bring the database's collection tables up to date, additively.\n *\n * Optional because it is only meaningful for schema-ful drivers. A managed\n * runtime boots a compiled project against a database it has never seen; auth\n * tables are ensured on boot but collection tables were created by nothing,\n * so every data request answered 500 on a missing relation. The CLI's `db\n * push` cannot fill the gap — it needs Atlas, and the runtime image ships no\n * CLI.\n *\n * Implementations MUST be additive-only: create missing tables, columns and\n * enum types, and never drop, narrow or rewrite anything. This runs\n * unattended against live customer data with nobody reading a diff, so the\n * destructive half stays a deliberate migration.\n *\n * `driverResult` is optional: this runs before `initializeDriver`, and only\n * the bundle path has a pre-init stand-in to pass. An adapter built by an\n * application already holds its own connection and MUST use it when this is\n * `undefined` — dereferencing it unconditionally works for managed tenants\n * and breaks every app that builds its own adapter.\n */\n ensureCollectionSchema?(\n collections: unknown[],\n driverResult?: InitializedDriver,\n log?: (message: string) => void\n ): Promise<{ applied: number }>;\n\n /**\n * Apply the collections' row-level-security policies, additively and\n * idempotently — the companion to {@link ensureCollectionSchema}.\n *\n * That method creates the tables; a table with RLS disabled and no policies\n * is not servable, because authenticated requests run as a restricted role:\n * a read with no `SELECT` policy returns nothing (a public collection\n * answers 401) and a write with no `INSERT`/`UPDATE` policy is denied. The\n * `db push` CLI applies these from the same collections, but it cannot reach\n * a managed tenant's in-cluster database — the runtime, already connected,\n * is the only thing that can.\n *\n * MUST be idempotent (re-run on every boot) and MUST NOT be destructive.\n * Runs after auth initialization, because the generated policies call the\n * `auth.*` helper functions and `CREATE POLICY` validates they exist.\n */\n ensureCollectionPolicies?(\n collections: unknown[],\n driverResult?: InitializedDriver,\n log?: (message: string) => void\n ): Promise<{ applied: number }>;\n\n /**\n * Create the RLS helper functions on this source's database. See\n * `DatabaseAdapter.ensureRlsRuntime`; needed on every source that is not\n * the default, whose helpers arrive with the auth tables.\n */\n ensureRlsRuntime?(driverResult?: InitializedDriver): Promise<void>;\n\n /**\n * Re-check, after the schema exists, that requests will actually be\n * constrained by the database's own authorization.\n *\n * A driver that isolates user requests by switching to a restricted role has\n * to decide at connect time whether the switch is needed — and on a fresh\n * database that question is asked before there is anything to answer with.\n * The process then creates the schema, becomes its owner, and an owner is\n * exempt from the policies on what it owns. So the answer that was true when\n * the driver initialized can be false by the time it serves a request.\n *\n * This is where a driver asks again. It runs once, after collection tables,\n * auth tables and policies are all in place, and it MUST fail rather than\n * serve when the answer changed and cannot be acted on: booting anyway\n * produces exactly the unenforced server this exists to prevent.\n *\n * Optional, because it is only meaningful for drivers whose isolation\n * depends on state the schema affects. A driver with nothing to re-check\n * omits it.\n */\n finalizeSecurityPosture?(driverResult: InitializedDriver): Promise<void>;\n\n /**\n * Read the collections schema version this database was last provisioned\n * from, or `null` when nothing has ever stamped it.\n *\n * The companion to {@link stampCollectionsSchemaVersion}: one process writes\n * what it applied, every other process compares itself to it. This is what\n * lets a split deployment — several processes over one database, only one of\n * which provisions — notice that a unit is serving against a schema it was\n * not built for. That failure is otherwise silent in both directions: a\n * column that does not exist is a SQL error on one route, and a policy that\n * was never applied is a 200 with no rows.\n *\n * `null` is not an error and MUST NOT be treated as one — every database\n * provisioned before the stamp existed reads this way, and so does every\n * fresh one until its first provisioning boot finishes.\n */\n readCollectionsSchemaVersion?(\n driverResult?: InitializedDriver\n ): Promise<string | null>;\n\n /**\n * Record the collections schema version this process just applied.\n *\n * Called only by the process that provisions, and only after both\n * {@link ensureCollectionSchema} and {@link ensureCollectionPolicies} have\n * run — a stamp written before the policies would claim a schema that is\n * only half in place, and the half that is missing is the one that fails\n * without an error.\n */\n stampCollectionsSchemaVersion?(\n version: string,\n driverResult?: InitializedDriver\n ): Promise<void>;\n\n /**\n * Initialize WebSocket server for realtime operations.\n */\n initializeWebsockets?(server: unknown, realtimeService: RealtimeProvider, driver: import(\"../controllers/data_driver\").DataDriver, config?: unknown, authAdapter?: AuthAdapter, limits?: RealtimeSocketOptions): Promise<void> | void;\n}\n\n/**\n * Result of `BackendBootstrapper.initializeDriver()`.\n * @group Backend\n */\nexport interface InitializedDriver {\n /** The DataDriver instance, ready for use. */\n driver: import(\"../controllers/data_driver\").DataDriver;\n\n /** The realtime service, if the driver created one during init. */\n realtimeProvider?: RealtimeProvider;\n\n /** A collection registry to register schema / tables into. */\n collectionRegistry?: CollectionRegistryInterface;\n\n /**\n * Collections the driver derived from the live database schema.\n *\n * Set by drivers that introspect in `baas` mode; the server serves these\n * instead of collections loaded from config files.\n */\n collections?: import(\"./collections\").CollectionConfig[];\n\n /**\n * Tables the driver found while deriving {@link collections} and did not\n * serve, because row-level security is disabled on them and so they have\n * no authorization model (`baas.unprotectedTables` left at `\"exclude\"`).\n *\n * The server names them when it has nothing to serve: \"the database has\n * no tables\" is untrue of a database whose tables were all skipped.\n */\n unprotectedTables?: { schema: string; table: string }[];\n\n /** The underlying database connection (for lifecycle management). */\n connection?: DatabaseConnection;\n\n /**\n * Opaque handle that the bootstrapper can use in subsequent hooks\n * (e.g., `initializeAuth`, `getAdmin`) to access driver internals.\n * Not used by the coordinator.\n */\n internals?: unknown;\n}\n\n/**\n * Result of `BackendBootstrapper.initializeAuth()`.\n * @group Backend\n */\nexport interface BootstrappedAuth {\n /** User management service. */\n userService: unknown;\n /** Email service (optional). */\n emailService?: unknown;\n /** Combined Auth Repository for unified token and user management. */\n authRepository?: unknown;\n /**\n * Whether the auth schema in the database is one this runtime can serve.\n *\n * Folded into `healthCheck()` so a schema mismatch shows up as a degraded\n * health response. Without it, a server whose auth is entirely broken still\n * reports healthy — the database connection it probes is fine, and the\n * mismatch is only discovered one failed login at a time.\n */\n schemaHealthCheck?(): Promise<AuthSchemaHealth>;\n}\n\n/**\n * Result of {@link BootstrappedAuth.schemaHealthCheck}.\n * @group Lifecycle\n */\nexport interface AuthSchemaHealth {\n /** False when this runtime cannot be trusted to serve auth against this database. */\n healthy: boolean;\n /** Human-readable descriptions of each mismatch found. Empty when healthy. */\n problems: string[];\n /** Auth schema version recorded in the database, when it records one. */\n databaseVersion?: number | null;\n /** Auth schema version this runtime expects. */\n runtimeVersion?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAinCA,SAAgB,qBAAqB,OAA+D;CAChG,OAAO,CAAC,CAAC,SAAS,OAAQ,MAA6B,qBAAqB;AAChF;;;;;AAMA,SAAgB,WAAW,OAAqD;CAC5E,OAAO,CAAC,CAAC,SAAS,OAAQ,MAAmB,eAAe;AAChE;;;;;AA4BA,SAAgB,cAAc,OAAwD;CAClF,OAAO,CAAC,CAAC,SAAS,OAAQ,MAAsB,iBAAiB;AACrE"}
|
|
@@ -3,13 +3,13 @@ import __rebaseProcess from "process";
|
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
5
|
import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
|
|
6
|
-
import "./src-
|
|
7
|
-
import { a as parseEnvBoolean, r as isAlreadyExecutingSkip } from "./cron-scheduler-
|
|
6
|
+
import "./src-Bh9LRPb9.js";
|
|
7
|
+
import { a as parseEnvBoolean, r as isAlreadyExecutingSkip } from "./cron-scheduler-Be7CNghL.js";
|
|
8
8
|
import { a as logger } from "./logger-CW8pmTS6.js";
|
|
9
|
+
import { m as jwtOf } from "./jwt-rDS0884_.js";
|
|
9
10
|
import { i as errorHandler, t as ApiError } from "./errors-OMWkKSH-.js";
|
|
10
|
-
import {
|
|
11
|
-
import { t as
|
|
12
|
-
import { t as GCSStorageController } from "./GCSStorageController-CRd9bFrc.js";
|
|
11
|
+
import { t as S3StorageController } from "./S3StorageController-Bl5shp94.js";
|
|
12
|
+
import { t as GCSStorageController } from "./GCSStorageController-40FyFeSx.js";
|
|
13
13
|
import { Hono } from "hono";
|
|
14
14
|
import fs from "fs";
|
|
15
15
|
import path from "path";
|
|
@@ -582,4 +582,4 @@ var backup_exports = /* @__PURE__ */ __exportAll({
|
|
|
582
582
|
//#endregion
|
|
583
583
|
export { listBackupObjects as a, readBackupBytes as c, backupStorageFromEnv as i, createBackupLinkRoutes as n, parseBackupDestination as o, createBackupRoutes as r, parseBackupTimestamp as s, backup_exports as t };
|
|
584
584
|
|
|
585
|
-
//# sourceMappingURL=backup-
|
|
585
|
+
//# sourceMappingURL=backup-BVbHoKo8.js.map
|