@rebasepro/server 0.33.0 → 0.33.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-B3p3aUX-.js → GCSStorageController-kCv5MH2B.js} +3 -3
- package/dist/{GCSStorageController-B3p3aUX-.js.map → GCSStorageController-kCv5MH2B.js.map} +1 -1
- package/dist/{S3StorageController-C9LjuMhL.js → S3StorageController-DqK533Sl.js} +3 -3
- package/dist/{S3StorageController-C9LjuMhL.js.map → S3StorageController-DqK533Sl.js.map} +1 -1
- package/dist/{access-BxkEYQh1.js → access-CRQBlEZY.js} +4 -4
- package/dist/{access-BxkEYQh1.js.map → access-CRQBlEZY.js.map} +1 -1
- package/dist/auth/api-keys/api-key-routes.d.ts +10 -1
- package/dist/auth/scope-routes.d.ts +7 -0
- package/dist/{auth-Bfwjg4Bg.js → auth-BanB_pZj.js} +18 -16
- package/dist/{auth-Bfwjg4Bg.js.map → auth-BanB_pZj.js.map} +1 -1
- package/dist/{backup-g2ohsDe0.js → backup-CVNce2jz.js} +6 -6
- package/dist/{backup-g2ohsDe0.js.map → backup-CVNce2jz.js.map} +1 -1
- package/dist/{branch-routes-DtNtc0Vh.js → branch-routes-aLDaGOD1.js} +2 -2
- package/dist/{branch-routes-DtNtc0Vh.js.map → branch-routes-aLDaGOD1.js.map} +1 -1
- package/dist/{contract-routes-CZTlAP7p.js → contract-routes-a4ZbN1h3.js} +3 -3
- package/dist/{contract-routes-CZTlAP7p.js.map → contract-routes-a4ZbN1h3.js.map} +1 -1
- package/dist/{cron-loader-BBP0kBIl.js → cron-loader-CWhyA5eR.js} +2 -2
- package/dist/{cron-loader-BBP0kBIl.js.map → cron-loader-CWhyA5eR.js.map} +1 -1
- package/dist/{cron-routes-Du03uJ7K.js → cron-routes-CMGAz1my.js} +4 -4
- package/dist/{cron-routes-Du03uJ7K.js.map → cron-routes-CMGAz1my.js.map} +1 -1
- package/dist/{cron-scheduler-CopTWKYB.js → cron-scheduler-DQBdkkfb.js} +2 -2
- package/dist/{cron-scheduler-CopTWKYB.js.map → cron-scheduler-DQBdkkfb.js.map} +1 -1
- package/dist/{cron-store-FGaZOdMf.js → cron-store-CjUydRyp.js} +2 -2
- package/dist/{cron-store-FGaZOdMf.js.map → cron-store-CjUydRyp.js.map} +1 -1
- package/dist/{filter-dialect-XtPJOCbD.js → filter-dialect-nsQ2ozPY.js} +2 -2
- package/dist/{filter-dialect-XtPJOCbD.js.map → filter-dialect-nsQ2ozPY.js.map} +1 -1
- package/dist/{function-loader-D3YEHF6E.js → function-loader-Cihj_r86.js} +2 -2
- package/dist/{function-loader-D3YEHF6E.js.map → function-loader-Cihj_r86.js.map} +1 -1
- package/dist/{function-routes-DNDFIa7t.js → function-routes-CWaldgEj.js} +2 -2
- package/dist/{function-routes-DNDFIa7t.js.map → function-routes-CWaldgEj.js.map} +1 -1
- package/dist/{history-recorder-C5RkbKS2.js → history-recorder-B8TJMEfO.js} +2 -2
- package/dist/{history-recorder-C5RkbKS2.js.map → history-recorder-B8TJMEfO.js.map} +1 -1
- package/dist/index.es.js +63 -59
- package/dist/index.es.js.map +1 -1
- package/dist/{jobs-CFUwQTao.js → jobs-IJX3fE3X.js} +2 -2
- package/dist/{jobs-CFUwQTao.js.map → jobs-IJX3fE3X.js.map} +1 -1
- package/dist/{jwt-CqhXs8Iz.js → jwt-BuEprb39.js} +3 -3
- package/dist/{jwt-CqhXs8Iz.js.map → jwt-BuEprb39.js.map} +1 -1
- package/dist/{keys-Btt6ZNqF.js → keys-C8gpPIOG.js} +2 -2
- package/dist/{keys-Btt6ZNqF.js.map → keys-C8gpPIOG.js.map} +1 -1
- package/dist/{load-schema-CSEXeduP.js → load-schema-BvRxAuaD.js} +6 -3
- package/dist/{load-schema-CSEXeduP.js.map → load-schema-BvRxAuaD.js.map} +1 -1
- package/dist/{logs-routes-C3CLYP-n.js → logs-routes-BAq2ZxuY.js} +2 -2
- package/dist/{logs-routes-C3CLYP-n.js.map → logs-routes-BAq2ZxuY.js.map} +1 -1
- package/dist/{offline-ET6xI1ZO-BQpLQ7wh.js → offline-ET6xI1ZO-CIdB1ilf.js} +4 -4
- package/dist/{offline-ET6xI1ZO-BQpLQ7wh.js.map → offline-ET6xI1ZO-CIdB1ilf.js.map} +1 -1
- package/dist/{offline-store-DtmBwmKE-C9ba2NJv.js → offline-store-DtmBwmKE-CzyvC_Zj.js} +3 -3
- package/dist/{offline-store-DtmBwmKE-C9ba2NJv.js.map → offline-store-DtmBwmKE-CzyvC_Zj.js.map} +1 -1
- package/dist/{openapi-generator-CAhJiwBm.js → openapi-generator-CCLtAJ2s.js} +2 -2
- package/dist/{openapi-generator-CAhJiwBm.js.map → openapi-generator-CCLtAJ2s.js.map} +1 -1
- package/dist/{project-root-CIrVZi-r.js → project-root-CuCOXvbk.js} +2 -2
- package/dist/{project-root-CIrVZi-r.js.map → project-root-CuCOXvbk.js.map} +1 -1
- package/dist/{proxy-clweqa43.js → proxy-DUUXXoQo.js} +2 -2
- package/dist/{proxy-clweqa43.js.map → proxy-DUUXXoQo.js.map} +1 -1
- package/dist/{query-parser-Cd70kZO8.js → query-parser-C9l1eFov.js} +3 -3
- package/dist/{query-parser-Cd70kZO8.js.map → query-parser-C9l1eFov.js.map} +1 -1
- package/dist/{request-timeout-cC3HT1Pf.js → request-timeout-DOu8ItLQ.js} +2 -2
- package/dist/{request-timeout-cC3HT1Pf.js.map → request-timeout-DOu8ItLQ.js.map} +1 -1
- package/dist/{rls-simulator-routes-DI2sYaQt.js → rls-simulator-routes-DIAjffhq.js} +3 -3
- package/dist/{rls-simulator-routes-DI2sYaQt.js.map → rls-simulator-routes-DIAjffhq.js.map} +1 -1
- package/dist/schema/index.js.map +1 -1
- package/dist/{schema-editor-routes-BxN0Q85n.js → schema-editor-routes-qWGWBPi0.js} +4 -4
- package/dist/{schema-editor-routes-BxN0Q85n.js.map → schema-editor-routes-qWGWBPi0.js.map} +1 -1
- package/dist/{schema-tables-DKFg6vMV.js → schema-tables-BneB2KZ7.js} +3 -3
- package/dist/{schema-tables-DKFg6vMV.js.map → schema-tables-BneB2KZ7.js.map} +1 -1
- package/dist/{schema-tables-routes-BfsNG4c4.js → schema-tables-routes-BBZJK8_S.js} +4 -4
- package/dist/{schema-tables-routes-BfsNG4c4.js.map → schema-tables-routes-BBZJK8_S.js.map} +1 -1
- package/dist/{securityRuleToConditions-Bk5zRSoa.js → securityRuleToConditions-Cj5ZR7TS.js} +2 -2
- package/dist/{securityRuleToConditions-Bk5zRSoa.js.map → securityRuleToConditions-Cj5ZR7TS.js.map} +1 -1
- package/dist/{selection-BOnbJvXD.js → selection-BB8ejqa2.js} +2 -2
- package/dist/{selection-BOnbJvXD.js.map → selection-BB8ejqa2.js.map} +1 -1
- package/dist/{sql-export-routes-B3oqb1Jw.js → sql-export-routes-CPXI3qZ7.js} +2 -2
- package/dist/{sql-export-routes-B3oqb1Jw.js.map → sql-export-routes-CPXI3qZ7.js.map} +1 -1
- package/dist/{src-CNZB3fuE.js → src-BdPKCs9u.js} +4 -2
- package/dist/src-BdPKCs9u.js.map +1 -0
- package/dist/{table-source-editor-DCJgZEz9.js → table-source-editor-D3m_VMwN.js} +6 -3
- package/dist/table-source-editor-D3m_VMwN.js.map +1 -0
- package/package.json +5 -5
- package/dist/src-CNZB3fuE.js.map +0 -1
- package/dist/table-source-editor-DCJgZEz9.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-BdPKCs9u.js","names":[],"sources":["../../types/src/errors.ts","../../types/src/types/filter-operators.ts","../../types/src/types/search.ts","../../types/src/types/relations.ts","../../types/src/types/policy.ts","../../types/src/types/rls-functions.ts","../../types/src/types/security_rules.ts","../../types/src/types/tenancy.ts","../../types/src/types/backend.ts","../../types/src/types/schema_editing.ts","../../types/src/types/channel_bus.ts","../../types/src/types/data_source.ts","../../types/src/types/resources.ts","../../types/src/types/storage_source.ts","../../types/src/types/resource_kinds.ts","../../types/src/types/env_boolean.ts","../../types/src/types/auth_adapter.ts","../../types/src/types/scopes.ts","../../types/src/types/project_manifest.ts","../../types/src/types/content_hash.ts","../../types/src/types/schema_version.ts","../../types/src/types/mcp_app_modules.ts","../../types/src/types/ui_preferences.ts","../../types/src/controllers/data.ts","../../types/src/controllers/data_driver.ts","../../types/src/controllers/storage.ts","../../types/src/controllers/storage-references.ts","../../types/src/controllers/aggregates.ts","../../types/src/schema/column_type.ts","../../types/src/schema/column_options.ts","../../types/src/schema/json.ts","../../types/src/schema/columns.ts","../../types/src/schema/relations.ts","../../types/src/schema/table.ts","../../types/src/schema/table_patch.ts","../../types/src/index.ts"],"sourcesContent":["/**\n * The error codes every route can produce, as `RebaseApiError.code`.\n *\n * These are the defaults on `ApiError`'s static constructors server-side, so\n * any endpoint can answer with one. They are **not** the complete set: routes\n * pass their own more specific codes too (`EMAIL_EXISTS`, `TOKEN_EXPIRED`,\n * `INVALID_BULK_BODY`, …), and auth alone defines a couple of dozen.\n *\n * Hence the union is deliberately open rather than closed. It exists to give\n * autocomplete and to catch a typo in the common cases — `code` was a bare\n * `string`, so `e.code === \"NOT_FOUND\"` and `e.code === \"NOTFOUND\"` were\n * equally valid and only one of them worked. Closing it would be a lie that\n * broke the moment a route added a code.\n *\n * @example\n * if (e instanceof RebaseApiError) {\n * switch (e.code) {\n * case \"NOT_FOUND\": return null; // completed\n * case \"FORBIDDEN\": return redirect();\n * default: throw e; // routes' own codes land here\n * }\n * }\n *\n * @group Errors\n */\nexport type RebaseErrorCode =\n | \"BAD_REQUEST\"\n | \"UNAUTHORIZED\"\n | \"FORBIDDEN\"\n | \"NOT_FOUND\"\n | \"CONFLICT\"\n | \"INTERNAL_ERROR\"\n | \"SERVICE_UNAVAILABLE\"\n | \"NETWORK_ERROR\"\n | \"OFFLINE\"\n | \"DB_PERMISSION_DENIED\"\n | \"SCHEMA_DRIFT\"\n /**\n * Realtime: the socket closed after a request was written and before the\n * server answered — the request may or may not have run, and it is never\n * re-sent. On a live subscription's `onError`: the connection has been\n * down longer than a blip; the subscription is kept and resumes, with a\n * fresh `onUpdate`, when the socket is back.\n */\n | \"CONNECTION_LOST\"\n /**\n * Realtime: no answer within the request timeout of the call — either it\n * waited for a socket the whole time and was never sent, or it was written\n * and never answered.\n */\n | \"REQUEST_TIMEOUT\"\n // `string & {}` keeps the union open while preserving completion on the\n // literals above — a bare `| string` would collapse them and offer nothing.\n | (string & {});\n\n/**\n * Structured initializer for {@link RebaseApiError}.\n *\n * @group Errors\n */\nexport interface RebaseErrorInit {\n /**\n * HTTP status code, when the error originated from an HTTP response.\n *\n * Three states, and they mean different things:\n *\n * - a real status — the server answered, and this is what it said;\n * - **`0`** — the request never reached a server: DNS, a refused\n * connection, CORS, an abort. `XMLHttpRequest` has always spelled that\n * `0`, and a fabricated 5xx would be indistinguishable from one the\n * server actually sent. The original failure is on `cause`;\n * - `undefined` — nothing was sent at all: a realtime/WebSocket failure,\n * or a client-side logic error raised before any request.\n */\n status?: number;\n /** Stable, machine-readable error code. See {@link RebaseErrorCode}. */\n code?: RebaseErrorCode;\n /** Structured error payload returned by the server, when present. */\n details?: unknown;\n /**\n * The server's correlation id for the request that failed, when it sent\n * one — the `requestId` in the error envelope, which also comes back on the\n * `X-Request-ID` header.\n *\n * The envelope has carried it for a while; the client dropped it on the\n * floor, so a bug report from an app could never quote the one string that\n * finds the server-side line.\n */\n requestId?: string;\n /**\n * Seconds to wait before retrying, from the response's `Retry-After`\n * header. Present on a 429 and on some 503s.\n *\n * Also dropped. The offline queue's own backoff therefore ignored a server\n * that had said exactly how long to wait — the one number that turns a\n * retry storm into a queue that drains.\n */\n retryAfterSeconds?: number;\n /** The underlying error this one wraps, if any. */\n cause?: unknown;\n}\n\n/**\n * The single error type thrown across the entire Rebase client surface —\n * HTTP data/control-plane calls, realtime/WebSocket operations, and\n * client-side logic errors (e.g. an unknown collection accessor). A `catch`\n * block only ever needs to check for this one class:\n *\n * ```ts\n * import { RebaseApiError } from \"@rebasepro/client\"; // re-exported\n *\n * try {\n * await client.data.products.update(id, { price: 9 });\n * } catch (e) {\n * if (e instanceof RebaseApiError) {\n * if (e.status === 404) { ... } // HTTP failures carry a status\n * console.error(e.code, e.details);\n * }\n * }\n * ```\n *\n * `status` is present for HTTP failures and `undefined` otherwise, so its\n * presence distinguishes transport-level errors from realtime/logic errors.\n *\n * @group Errors\n */\nexport class RebaseApiError extends Error {\n /** HTTP status code, or `undefined` for non-HTTP errors. */\n readonly status?: number;\n /** Stable machine-readable error code, when the server supplied one. See {@link RebaseErrorCode}. */\n readonly code?: RebaseErrorCode;\n /** Structured error payload from the server, when present. */\n readonly details?: unknown;\n /** See {@link RebaseErrorInit.requestId}. Quote it in a bug report. */\n readonly requestId?: string;\n /** See {@link RebaseErrorInit.retryAfterSeconds}. */\n readonly retryAfterSeconds?: number;\n\n constructor(message: string, init: RebaseErrorInit = {}) {\n super(message);\n this.name = \"RebaseApiError\";\n this.status = init.status;\n this.code = init.code;\n this.details = init.details;\n this.requestId = init.requestId;\n this.retryAfterSeconds = init.retryAfterSeconds;\n if (init.cause !== undefined) {\n // `cause` is standard on Error but not always in the lib target's type.\n (this as { cause?: unknown }).cause = init.cause;\n }\n }\n}\n\n/**\n * Client-side logic error — raised before any request is made (e.g. accessing\n * an unknown collection accessor when a typed dictionary is configured).\n *\n * A subclass of {@link RebaseApiError} (with no `status`), so a single\n * `catch (e) { if (e instanceof RebaseApiError) ... }` handles it too.\n *\n * @group Errors\n */\nexport class RebaseClientError extends RebaseApiError {\n /**\n * `init` is the same one {@link RebaseApiError} takes, and it is what makes\n * `code` reachable at all.\n *\n * The constructor used to accept a message and nothing else, so every\n * client-side failure — an undefined filter value, an unknown accessor,\n * `listen()` on a client built with `realtime: false`, a function name with\n * a `/` in it, `refreshSession()` while signed out — arrived with `code ===\n * undefined`. The documented `switch (e.code)` in this file's own example\n * fell to `default: throw e` for all of them, and the only client-side error\n * that *did* carry a code was `OFFLINE`, because that one path minted a\n * `RebaseApiError` instead.\n */\n constructor(message: string, init: RebaseErrorInit = {}) {\n super(message, init);\n this.name = \"RebaseClientError\";\n }\n}\n\n/**\n * Brand for a contract method a particular client cannot serve.\n *\n * `Symbol.for` rather than a fresh symbol: two copies of `@rebasepro/types` in\n * one tree — which happens, see `docs/dependency-duplication-traps.md` — must\n * agree about it, and a module-local symbol would not.\n */\nconst UNSUPPORTED_METHOD = Symbol.for(\"rebase.unsupportedMethod\");\n\n/**\n * Build the stub a client installs for a contract method it cannot serve.\n *\n * `listen`, `listenById` and `count` are part of `SDKTableClient`, not\n * optional extras — a caller should be able to write\n * `client.data.posts.count()` without asking first, and a transport that cannot\n * serve it should answer with a sentence naming the configuration that would,\n * rather than with `undefined is not a function` at the call site. Where the\n * transport genuinely cannot (a client built with `realtime: false`, a driver\n * with no `listenCollection`), it installs one of these instead of omitting the\n * method.\n *\n * @param message What to tell the caller, naming the fix.\n * @group Errors\n */\n/**\n * The tag {@link unsupportedMethod} puts on the stub it returns.\n *\n * Written as an optional member on a callable, which is what a tagged stub\n * actually is — so both the write and the read below are single casts and tsc\n * checks the symbol and the value type on each. Reading it as\n * `Record<symbol, boolean>` made every symbol key on the object a `boolean`\n * (which is not true of a function, and is why that needed a double cast to\n * be written at all), and the write and the read were then free to disagree\n * about the tag.\n */\ntype UnsupportedTagged = ((...args: never[]) => unknown) & { [UNSUPPORTED_METHOD]?: boolean };\n\nexport function unsupportedMethod<F>(message: string): F {\n const stub = (): never => {\n // The two reasons a method is a stub — `realtime: false`, and a driver\n // with no `listenCollection` — are one thing to a caller: this client\n // cannot do realtime. One code covers both, and the message says which.\n throw new RebaseClientError(message, { code: \"REALTIME_DISABLED\" });\n };\n (stub as UnsupportedTagged)[UNSUPPORTED_METHOD] = true;\n return stub as F;\n}\n\n/**\n * Can this method actually do anything?\n *\n * `true` for a stub from {@link unsupportedMethod} **and** for a method that is\n * simply not there — a partial client, a hand-built test double, an\n * implementation written against an older shape of the interface. Both mean the\n * same thing to a caller, so both answer the same way, and an adapter that\n * checks this cannot be caught out by either.\n *\n * Ordinary code does not need it: calling the method and letting it throw is\n * the normal path. Adapters do — the admin panel chooses between subscribing\n * and a one-shot `find()` by asking whether the client can listen, and a UI\n * that subscribes into a throw is worse than one that polls. This is the\n * question `if (accessor.listen)` used to be asking, made explicit now that the\n * method is always there to call.\n *\n * @group Errors\n */\nexport function isUnsupported(method: unknown): boolean {\n if (typeof method !== \"function\") return true;\n return (method as UnsupportedTagged)[UNSUPPORTED_METHOD] === true;\n}\n","/**\n * Canonical filter operators and REST wire-format mappings.\n *\n * `WhereFilterOp` is THE operator type used at every layer — from React\n * components through the SDK, server, and down to the database driver.\n *\n * PostgREST short-codes (`eq`, `gt`, `cs`, …) exist **only** at the\n * HTTP wire boundary, handled by `serializeFilter` / `deserializeFilter`\n * in `@rebasepro/common`.\n *\n * ┌──────────────────────┬───────────────┬──────────────────────────────┐\n * │ Canonical │ REST short │ Meaning │\n * ├──────────────────────┼───────────────┼──────────────────────────────┤\n * │ \"==\" │ \"eq\" │ Equal │\n * │ \"!=\" │ \"neq\" │ Not equal │\n * │ \">\" │ \"gt\" │ Greater than │\n * │ \">=\" │ \"gte\" │ Greater than or equal │\n * │ \"<\" │ \"lt\" │ Less than │\n * │ \"<=\" │ \"lte\" │ Less than or equal │\n * │ \"in\" │ \"in\" │ Value in list │\n * │ \"not-in\" │ \"nin\" │ Value not in list │\n * │ \"array-contains\" │ \"cs\" │ Array contains element │\n * │ \"array-contains-any\" │ \"csa\" │ Array contains any of │\n * │ \"array-contains-all\" │ \"csall\" │ Array contains all of │\n * │ \"array-contained-by\" │ \"cd\" │ Array holds only elements of │\n * │ \"like\" │ \"like\" │ SQL LIKE (case-sensitive) │\n * │ \"ilike\" │ \"ilike\" │ SQL ILIKE (case-insensitive) │\n * │ \"not-like\" │ \"nlike\" │ NOT LIKE (case-sensitive) │\n * │ \"not-ilike\" │ \"nilike\" │ NOT ILIKE (case-insensitive) │\n * │ \"is-null\" │ \"isnull\" │ Field IS NULL │\n * │ \"is-not-null\" │ \"notnull\" │ Field IS NOT NULL │\n * └──────────────────────┴───────────────┴──────────────────────────────┘\n *\n * Pattern matching (`like`/`ilike`) uses SQL wildcard syntax: `%` matches any\n * sequence of characters, `_` matches a single character. Firestore has no\n * native pattern matching and rejects these operators (use `searchString` instead).\n *\n * @module\n */\n\n/**\n * Where NULLs sort relative to real values on one key.\n *\n * Absent means the convention Postgres itself applies and the driver writes\n * out: `NULLS LAST` ascending, `NULLS FIRST` descending. That convention was\n * hardcoded and unstateable — a \"newest first\" list put every row with no date\n * at the very top, and the only way out was to add a `is-not-null` filter and\n * lose those rows entirely.\n *\n * The keyset comparison honours whatever is chosen here, so a cursor over a\n * nullable key stays correct under either placement.\n *\n * @group Models\n */\nexport type NullsPlacement = \"first\" | \"last\";\n\n/**\n * Canonical sort representation: `[fieldName, direction]`, optionally with a\n * {@link NullsPlacement}.\n *\n * Used in `FindParams.orderBy`, `collection.sort`, and `FilterPreset.sort`.\n * The colon-string form (`\"field:direction\"`, or `\"field:direction:nulls\"`)\n * exists only at the HTTP wire boundary, handled by `serializeOrderBy` /\n * `deserializeOrderBy` in `@rebasepro/common`.\n *\n * The third slot is optional so every `[field, direction]` written before it\n * existed is still exactly this type, and every `const [field, direction] =`\n * destructure still reads what it always read.\n *\n * @group Models\n */\nexport type OrderByTuple<Key extends string = string> = [Key, \"asc\" | \"desc\", NullsPlacement?];\n\n/**\n * One sort key, or several applied in order of significance.\n *\n * ```ts\n * orderBy: [\"created_at\", \"desc\"] // one key\n * orderBy: [[\"roles\", \"asc\"], [\"created_at\", \"desc\"]] // roles, then newest first\n * ```\n *\n * The two forms are told apart by whether the first element is itself an\n * array, so a single tuple never needs wrapping and every existing caller\n * keeps working unchanged. `normalizeOrderBy` in `@rebasepro/common` collapses\n * both to the list form, which is what every layer below the call site speaks.\n *\n * Ties on the last key are broken by the row id, so a multi-key sort is a\n * total order and pages over it neither repeat nor skip rows.\n *\n * @group Models\n */\nexport type OrderBySpec<Key extends string = string> =\n | OrderBySortTuple<Key>\n | OrderBySortTuple<Key>[];\n\n/**\n * A sort key: a field name, or an aggregate over a to-many relation.\n *\n * @group Models\n */\nexport type SortKey<Key extends string = string> = Key | RelationAggregateSort;\n\n/**\n * `[sortKey, direction]` — the authoring form of {@link OrderByTuple}, which\n * additionally accepts a {@link RelationAggregateSort} object.\n *\n * The object never reaches a driver: `normalizeOrderBy` in `@rebasepro/common`\n * encodes it to its string spelling on the way down, and everything below that\n * point speaks plain `OrderByTuple`. See {@link RelationAggregateSort} for why\n * the wire form is a string.\n *\n * @group Models\n */\nexport type OrderBySortTuple<Key extends string = string> = [SortKey<Key>, \"asc\" | \"desc\", NullsPlacement?];\n\n/**\n * The aggregate functions a relation sort can apply.\n *\n * Five, and no `array_agg`/`string_agg`: an aggregate used as a sort key has to\n * produce something with an order, and these are the ones that do.\n *\n * @group Models\n */\nexport type RelationAggregateFn = \"min\" | \"max\" | \"count\" | \"sum\" | \"avg\";\n\n/**\n * Order rows by an aggregate over the rows a to-many relation reaches —\n * \"candidates, oldest waiting first\", \"clients, busiest first\".\n *\n * ```ts\n * // The date of each candidate's earliest open application.\n * orderBy: [[{ relation: \"applications\", field: \"created_at\", agg: \"min\" }, \"asc\"]]\n *\n * // How many applications each candidate has.\n * orderBy: [[{ relation: \"applications\", agg: \"count\" }, \"desc\"]]\n * ```\n *\n * This is the half of a queue that cannot be worked around client-side. A\n * *filter* over a relation can be approximated by denormalising a flag onto the\n * row; an *ordering* cannot be approximated at all once the result set is\n * paged, because the client only ever holds one page and the page was chosen by\n * the wrong order.\n *\n * Rows the relation reaches nothing from sort last ascending and first\n * descending — the placement Postgres gives a `NULL`, stated rather than\n * inherited, because the keyset comparison behind cursor paging has to agree\n * with it exactly. Ties are broken by the row id, so the order is total and\n * paging over it neither repeats nor skips.\n *\n * Compiled by the driver into a correlated subquery, so it is subject to the\n * reader's own row-level security on the target table: a related row the reader\n * cannot see does not contribute to the aggregate. Offered only where\n * {@link DataSourceCapabilities.relationAggregateSorts} says the driver can\n * compile it.\n *\n * @group Models\n */\nexport interface RelationAggregateSort {\n /** The to-many relation to aggregate over, by its name on this collection. */\n relation: string;\n\n /** The aggregate to apply. */\n agg: RelationAggregateFn;\n\n /**\n * The column of the *target* to aggregate. Required by every function\n * except `count`, which counts the related rows themselves when it is\n * omitted — and counts the rows whose column is non-null when it is not.\n */\n field?: string;\n}\n\n/** The wire spelling of a {@link RelationAggregateSort}: `min(applications.created_at)`. */\nconst RELATION_AGGREGATE_SORT_PATTERN = /^(min|max|count|sum|avg)\\(([^().]+)(?:\\.([^()]+))?\\)$/;\n\n/**\n * A {@link RelationAggregateSort} as a single string — `min(applications.created_at)`,\n * `count(applications)`.\n *\n * The wire form is a string because every layer below the call site already is\n * one: `OrderByTuple` is `[string, direction]`, the REST parameter is\n * `?orderBy=key:direction`, the driver contract takes `orderBy?: string |\n * OrderByTuple[]`, and a cursor names its keys by string. `_score` established\n * the same pattern — a sort key that is not a column, spelled as one — and this\n * reuses it rather than widening five signatures to carry an object that would\n * be flattened at the end anyway.\n *\n * SQL's own spelling, so the key reads as what it compiles to. Neither `:` nor\n * `,` appears in it, which is what keeps it safe in the colon-delimited wire\n * shorthand.\n *\n * @group Models\n */\nexport function encodeRelationAggregateSort(sort: RelationAggregateSort): string {\n return `${sort.agg}(${sort.relation}${sort.field ? `.${sort.field}` : \"\"})`;\n}\n\n/**\n * Read the string spelling back, or `undefined` if it is not one.\n *\n * `undefined` rather than a throw: this is asked of *every* sort key to find\n * out which kind it is, and an ordinary column name is not an error.\n *\n * @group Models\n */\nexport function parseRelationAggregateSort(key: string): RelationAggregateSort | undefined {\n const match = RELATION_AGGREGATE_SORT_PATTERN.exec(key);\n if (!match) return undefined;\n const [, agg, relation, field] = match;\n // `min()` and friends have nothing to aggregate without a column, and a\n // key that parses to a half-built sort would resolve to no expression and\n // be dropped — leaving the rows unsorted while the caller believes\n // otherwise. `count` is the one function that means something on its own.\n if (!field && agg !== \"count\") return undefined;\n return { agg: agg as RelationAggregateFn, relation, ...(field && { field }) };\n}\n\n/** Is this sort key the object form rather than a field name? */\nexport function isRelationAggregateSort(key: unknown): key is RelationAggregateSort {\n return typeof key === \"object\" && key !== null &&\n typeof (key as RelationAggregateSort).relation === \"string\" &&\n typeof (key as RelationAggregateSort).agg === \"string\";\n}\n\n/** A sort key in the single-string form every layer below the call site speaks. */\nexport function sortKeyToString(key: SortKey): string {\n return isRelationAggregateSort(key) ? encodeRelationAggregateSort(key) : key;\n}\n\n/**\n * Canonical filter operators supported across all database backends.\n * Each DB driver translates these to its native query format.\n *\n * @group Models\n */\nexport type WhereFilterOp =\n | \"<\"\n | \"<=\"\n | \"==\"\n | \"!=\"\n | \">=\"\n | \">\"\n | \"array-contains\"\n | \"in\"\n | \"not-in\"\n | \"array-contains-any\"\n | \"array-contains-all\"\n | \"array-contained-by\"\n | \"like\"\n | \"ilike\"\n | \"not-like\"\n | \"not-ilike\"\n | \"is-null\"\n | \"is-not-null\";\n\n/**\n * Used to define filters applied in collections.\n *\n * A single condition is a tuple `[operator, value]`.\n * Multiple conditions on the same field use an array of tuples.\n *\n * @example\n * // Single condition per field\n * { status: [\"==\", \"active\"], price: [\">=\", 9.99] }\n *\n * // Multiple conditions on one field\n * { age: [[\">=\", 18], [\"<\", 65]] }\n *\n * // Array operators\n * { role: [\"in\", [\"admin\", \"editor\"]] }\n * { tags: [\"array-contains\", \"featured\"] }\n *\n * // Pattern matching (SQL wildcards: % and _)\n * { name: [\"ilike\", \"%john%\"] }\n * { slug: [\"like\", \"post-%\"] }\n *\n * // Null checks (the value is ignored; `null` is conventional, and an\n * // untyped caller may leave it out: `[\"is-null\"]`)\n * { deleted_at: [\"is-null\", null] }\n * { published_at: [\"is-not-null\", null] }\n *\n * @group Models\n */\nexport type FilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][]>>;\n\n/**\n * The field names a query may address on a row type: every column, plus a\n * dotted path reaching inside one — or *through a relation* to a column of the\n * related row.\n *\n * A dotted path is not checked at all, in either direction. That is a\n * deliberate loosening, and it is worth being exact about what it costs. The\n * root used to be checked: `\"meta.tag\"` required a `meta` column. It cannot\n * stay checked, because the other thing a dotted path now means is\n * `\"applications.status\"` — and `applications` is a *relation*, which comes\n * from the collection's `relations` and is not a column of `M` at all. There is\n * nothing in a generated row type that could validate one. `FindParams.include`\n * is `string[]` for exactly this reason and says so.\n *\n * So the guarantee moves rather than disappears: an unresolvable path is a 400\n * from the driver, not a silently dropped condition. See\n * `UnknownFilterFieldsMode` in `@rebasepro/server-postgres` — dropping a filter\n * key *widens* the read to every row, which is why that resolution fails\n * closed. A typo'd relation path is refused at runtime with the target\n * collection's real column list in the message.\n *\n * A JSON path — `metadata->>tier` — is admitted on the same terms and for the\n * same reason. It addresses a key *inside* a `json`/`jsonb` column, so nothing\n * in a generated row type describes it either; the driver resolves it and\n * refuses what it cannot. It has no dot, so the dotted branch above never\n * covered it, and every documented `?metadata->>tier=eq.gold` filter was a\n * compile error on a typed client while working perfectly over HTTP.\n *\n * Undotted keys are unaffected and still checked against `keyof M`.\n *\n * When `M` is left at its default `Record<string, unknown>`, `keyof M` is\n * `string` and this collapses to `string`, so every query stays permissive.\n * That is what keeps an untyped `createRebaseClient()` behaving exactly as it\n * did before the row type was threaded through.\n *\n * @group Models\n */\nexport type FieldPath<M extends Record<string, unknown> = Record<string, unknown>> =\n | Extract<keyof M, string>\n | NonColumnFieldPath;\n\n/**\n * A field key that is not a column: a relation path (`author.name`) or a JSON\n * path (`metadata->>tier`).\n *\n * The fluent builder needs this on its own, where `FindParams` does not. Its\n * `where(column, operator, value)` types the value against `M[column]`, which\n * only means something for a real column — so paths take a second overload\n * whose value is `unknown`. Keying that overload on the *shape* of a path,\n * rather than on \"everything that is not a column\", is what keeps a real column\n * with a wrong value type from falling through to it and being accepted: a\n * mistyped column name has neither a dot nor a `->>`, so it matches neither\n * overload and is still refused.\n *\n * @group Models\n */\nexport type NonColumnFieldPath =\n | `${string}.${string}`\n | `${string}->>${string}`\n | CaseFoldedFieldPath;\n\n/**\n * A text column compared in one case: `lower(artist)` or `upper(code)`. Every\n * operator applies to the folded value, so the values written beside it are\n * written in that case — `{ \"lower(artist)\": [\"in\", [\"abba\", \"queen\"]] }`\n * matches \"ABBA\" and \"Queen\". Compiled to `lower(artist)`, which an index on\n * that expression serves. The same spelling an aggregate's `groupBy` uses.\n *\n * @group Models\n */\nexport type CaseFoldedFieldPath = `lower(${string})` | `upper(${string})`;\n\n/**\n * Read a {@link CaseFoldedFieldPath}: the function and the field it folds, or\n * `undefined` for any other key.\n *\n * @group Models\n */\nexport function parseCaseFoldedFieldPath(key: string): { fn: \"lower\" | \"upper\"; field: string } | undefined {\n const match = /^(lower|upper)\\(\\s*([^()\\s]+)\\s*\\)$/.exec(key);\n return match ? { fn: match[1] as \"lower\" | \"upper\", field: match[2] } : undefined;\n}\n\n/**\n * Relaxed filter type that also accepts pre-serialized PostgREST strings.\n * **Internal only** — used at the wire-format boundary\n * (`serializeFilter` / `deserializeFilter` in `@rebasepro/common`).\n *\n * Application code, UI components, and SDK consumers should use\n * {@link FilterValues} instead.\n *\n * @internal\n */\nexport type WireFilterValues<Key extends string> =\n Partial<Record<Key, [WhereFilterOp, unknown] | [WhereFilterOp, unknown][] | string>>;\n\n/**\n * PostgREST short-code operators. Wire format only — these never appear\n * in application code. Used by `serializeFilter`/`deserializeFilter`\n * in `@rebasepro/common`.\n */\nexport type RestFilterOp =\n | \"eq\" | \"neq\"\n | \"gt\" | \"gte\"\n | \"lt\" | \"lte\"\n | \"in\" | \"nin\"\n | \"cs\" | \"csa\" | \"csall\" | \"cd\"\n | \"like\" | \"ilike\"\n | \"nlike\" | \"nilike\"\n | \"isnull\" | \"notnull\";\n\n/** Maps canonical operators to their REST short-code equivalents. */\nexport const CANONICAL_TO_REST: Readonly<Record<WhereFilterOp, RestFilterOp>> = {\n \"==\": \"eq\",\n \"!=\": \"neq\",\n \">\": \"gt\",\n \">=\": \"gte\",\n \"<\": \"lt\",\n \"<=\": \"lte\",\n \"in\": \"in\",\n \"not-in\": \"nin\",\n \"array-contains\": \"cs\",\n \"array-contains-any\": \"csa\",\n \"array-contains-all\": \"csall\",\n \"array-contained-by\": \"cd\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"not-like\": \"nlike\",\n \"not-ilike\": \"nilike\",\n \"is-null\": \"isnull\",\n \"is-not-null\": \"notnull\"\n};\n\n/** Maps REST short-code operators to their canonical equivalents. */\nexport const REST_TO_CANONICAL: Readonly<Record<RestFilterOp, WhereFilterOp>> = {\n \"eq\": \"==\",\n \"neq\": \"!=\",\n \"gt\": \">\",\n \"gte\": \">=\",\n \"lt\": \"<\",\n \"lte\": \"<=\",\n \"in\": \"in\",\n \"nin\": \"not-in\",\n \"cs\": \"array-contains\",\n \"csa\": \"array-contains-any\",\n \"csall\": \"array-contains-all\",\n \"cd\": \"array-contained-by\",\n \"like\": \"like\",\n \"ilike\": \"ilike\",\n \"nlike\": \"not-like\",\n \"nilike\": \"not-ilike\",\n \"isnull\": \"is-null\",\n \"notnull\": \"is-not-null\"\n};\n\n/**\n * Operators that test for null/not-null and therefore ignore their value.\n * Codecs normalize the value of these conditions to `null`.\n */\nexport const NULL_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"is-null\", \"is-not-null\"\n]);\n\n/**\n * Operators whose operand is a **list** of values rather than one value.\n *\n * On the wire that list is always parenthesised — `in.(draft,review)` — which\n * is what lets the REST codec tell `?status=in.(a,b)` (the operator) from\n * `?status=in.progress` (a value that happens to start with an operator's\n * name). See `deserializeSingle` in `@rebasepro/common`.\n *\n * @group Models\n */\nexport const LIST_OPS: ReadonlySet<WhereFilterOp> = new Set<WhereFilterOp>([\n \"in\", \"not-in\", \"array-contains-any\", \"array-contains-all\", \"array-contained-by\"\n]);\n\n/**\n * Every canonical operator, in a stable order. Useful for engine capability\n * declarations ({@link DataSourceCapabilities.filterOperators}) and for\n * building operator subsets.\n * @group Models\n */\nexport const ALL_WHERE_FILTER_OPS: readonly WhereFilterOp[] = [\n \"<\", \"<=\", \"==\", \"!=\", \">=\", \">\",\n \"in\", \"not-in\",\n \"array-contains\", \"array-contains-any\", \"array-contains-all\", \"array-contained-by\",\n \"like\", \"ilike\", \"not-like\", \"not-ilike\",\n \"is-null\", \"is-not-null\"\n];\n\n/** All canonical operator strings for runtime validation. */\nconst CANONICAL_OPS: ReadonlySet<string> = new Set<WhereFilterOp>(ALL_WHERE_FILTER_OPS);\n\n/**\n * The REST table as a `Map`, because the key `toCanonicalOp` is handed comes\n * off the wire.\n *\n * Indexed as a plain object, every `Object.prototype` member answered:\n * `toCanonicalOp(\"valueOf\")` returned the inherited *function* as though it\n * were a `WhereFilterOp`, and every caller here treats a defined result as\n * \"known operator\". Same defect the REST codec's own lookup tables were\n * converted away from in `filter-dialect.ts`; this is the copy that survived\n * one package over, and it now sits under the operator validation the REST\n * parser does, which would otherwise have admitted `[\"constructor\", x]`.\n */\nconst REST_OP_LOOKUP: ReadonlyMap<string, WhereFilterOp> = new Map<string, WhereFilterOp>(\n Object.entries(REST_TO_CANONICAL) as [string, WhereFilterOp][]\n);\n\n/**\n * Resolve any operator string (canonical or REST short-code) to its\n * canonical `WhereFilterOp` form. Returns `undefined` for unknown operators.\n *\n * @example\n * toCanonicalOp(\"==\") // \"==\"\n * toCanonicalOp(\"eq\") // \"==\"\n * toCanonicalOp(\"cs\") // \"array-contains\"\n * toCanonicalOp(\"xyz\") // undefined\n */\nexport function toCanonicalOp(op: string): WhereFilterOp | undefined {\n if (CANONICAL_OPS.has(op)) return op as WhereFilterOp;\n return REST_OP_LOOKUP.get(op);\n}\n","/**\n * Opt-in full-text search configuration.\n *\n * ## Why this is opt-in\n *\n * Without a `search` block, `.search()` is `ILIKE '%term%'` per whitespace-\n * separated term, OR-ed across the collection's top-level, non-enum `string`\n * properties and AND-ed across the terms — so two typed words may be found in\n * two different columns, as they are here. Declaring this block is the only way\n * to get anything more than that.\n *\n * The default has three limits that no amount of tuning inside it can fix:\n * it cannot reach inside `map` (JSONB) or `array` properties, it has no notion\n * of relevance, and a leading `%` means it can never use an index. Collections\n * that outgrow those limits declare what they want searched; collections that\n * have not are left completely alone.\n *\n * ## What declaring it does\n *\n * One `tsvector` column, `GENERATED ALWAYS AS … STORED`, plus one GIN index on\n * it. Postgres recomputes the column on every write of a source field, so it\n * cannot drift from the row, and refuses any attempt to write it directly.\n * `.search()` then compiles to `@@ websearch_to_tsquery(…)` against that\n * column, which stems, drops stopwords, AND-es the terms, and ranks.\n *\n * These are stated consequences, not hidden ones: the column and the index\n * appear in generated DDL, in `schema.generated.ts`, and in `rebase db push`\n * output like any other declared object.\n *\n * @example\n * ```ts\n * const talents: PostgresCollectionConfig = {\n * slug: \"talents\",\n * table: \"talents\",\n * properties: { … },\n * search: {\n * language: \"spanish\",\n * unaccent: true,\n * fields: [\n * { path: \"full_name\", weight: \"A\" },\n * \"location\",\n * \"questionnaire.certifications\" // into the JSONB\n * ]\n * }\n * };\n * ```\n *\n * @group Search\n */\nexport interface SearchConfig {\n /**\n * The fields to index, in the author's own words. Nothing is inferred: a\n * field is searched if and only if it is named here.\n *\n * A bare string is shorthand for `{ path, weight: \"B\" }`.\n *\n * A path may address:\n * - a top-level `string` property — `\"full_name\"`\n * - a `string[]` property — `\"tags\"` (every element is indexed)\n * - a path into a `map` property — `\"questionnaire.certifications\"`,\n * which indexes every string found at or below that point, including\n * nested objects and arrays of strings. JSON *keys* are never indexed,\n * only values.\n *\n * A path that does not resolve to one of those is a boot-time error, not\n * a silent omission — a search field you believe is live and is not is the\n * failure this whole block exists to prevent.\n */\n fields: readonly (string | SearchField)[];\n\n /**\n * How a search string is matched against the indexed fields.\n *\n * - `\"fts\"` (default) — one `@@ websearch_to_tsquery` against the generated\n * `tsvector`. Stems, drops stopwords, reaches inside JSONB and arrays,\n * uses the GIN index, and ranks. It matches **whole lexemes**, so `seb`\n * does not find `sebastian` and `audit` does not find `Auditor`.\n * - `\"hybrid\"` — that predicate `OR` a substring match over the same\n * declared fields, with accents folded on both sides. So one collection\n * gets accent folding *and* substring/prefix matching, which is what a\n * search box is: measured on five rows in `search-mode-matrix.test.ts`,\n * `munoz` finds `Sebastian Munoz`, `seb` finds both Sebastians, `audit`\n * finds the `ISO 14001 Lead Auditor`, and `iso 14001` does **not** drag\n * in the `ISO 9001` row the way a loose `fuzzy` threshold does.\n *\n * ### Why this is a mode rather than the default\n *\n * The substring half cannot use the GIN index — a leading `%` never can —\n * so it is a scan over the declared fields' text, evaluated per row. The\n * `@@` half still runs first and still uses the index; what the mode costs\n * is the rows the index rejected, which the planner has to look at anyway\n * to apply the `OR`. On a large table that is the difference between an\n * index scan and a sequential one, and that is the author's call to make\n * rather than this default's.\n *\n * ### Changing this on a live collection\n *\n * Safe, and deliberately so. `mode` is **query-side only**: it changes no\n * generated column, no generation expression and no index, so it does not\n * trip the boot-time refusal a changed `search` block otherwise gets\n * (`searchDriftMessage` — rebuilding a STORED generated column rewrites the\n * table under an ACCESS EXCLUSIVE lock). Turning `\"hybrid\"` on for a\n * collection whose column already exists takes a deploy and nothing else.\n *\n * The accent folding on the substring half is likewise query-side and\n * unconditional under `\"hybrid\"` — it does **not** require\n * {@link SearchConfig.unaccent}, which is what makes the switch free. What\n * `unaccent` still buys is folding on the `@@` half, where the lexemes are\n * stored, and that one *is* a column rebuild.\n *\n * It does add the `unaccent` extension and one IMMUTABLE helper function to\n * the database if they are not there already. Both are `IF NOT EXISTS` /\n * `CREATE OR REPLACE`, so both are additive and idempotent.\n *\n * @default \"fts\"\n */\n mode?: SearchMode;\n\n /**\n * The Postgres text search configuration, which decides stemming and\n * stopwords. `\"spanish\"` stems `auditores` to `auditor` and drops `de`;\n * `\"simple\"` does neither.\n *\n * Defaults to `\"simple\"`, which is the only choice that is never wrong:\n * a stemmer applied to the wrong language silently mangles lexemes. Set it\n * to your content's language to get stemming.\n *\n * @default \"simple\"\n */\n language?: string;\n\n /**\n * Fold accents before indexing, so `auditoria` matches `auditoría`.\n *\n * This is not cosmetic in accented languages. Postgres stems the two\n * spellings to *different* lexemes — `to_tsvector('spanish', 'auditoría')`\n * yields `auditor` while `'auditoria'` yields `auditori` — so without this\n * a query typed without accents misses the rows that carry them, which is\n * most queries most users type.\n *\n * Requires the `unaccent` extension. Boot fails with an explicit message if\n * it is not installed and cannot be created, rather than quietly indexing\n * accented text as-is.\n *\n * @default false\n */\n unaccent?: boolean;\n\n /**\n * Name of the generated column holding the `tsvector`.\n *\n * Only change this if `search_vector` collides with a column you already\n * have. It is part of your schema once created: renaming it later is a\n * column drop and recreate, which rewrites the table.\n *\n * @default \"search_vector\"\n */\n column?: string;\n\n /**\n * Also match on trigram similarity, so near-misses and typos still rank —\n * `iso14000` reaching `ISO 14001`, which no amount of stemming will do\n * because they are simply different lexemes.\n *\n * Adds a second generated `text` column and a GIN trigram index alongside\n * the `tsvector`, and requires the `pg_trgm` extension. Costs write time\n * and disk; buys the single most common class of failed search.\n *\n * Also changes what `_score` means: the trigram similarity is added to\n * `ts_rank`. It has to be. A typo matches nothing on the exact path, so\n * every row this finds has a `ts_rank` of zero — ranking by that alone\n * would order the results arbitrarily, which is the failure `fuzzy` exists\n * to fix.\n *\n * @default false\n */\n fuzzy?: boolean;\n\n /**\n * Similarity floor for {@link SearchConfig.fuzzy}, between 0 and 1. A row\n * whose trigram similarity to the query falls below this never matches on\n * the fuzzy path (it can still match on the exact one).\n *\n * Lower admits more typos and more noise. Ignored unless `fuzzy` is set.\n *\n * @default 0.3\n */\n fuzzyThreshold?: number;\n}\n\n/**\n * One indexed field, with the weight it carries in the ranking.\n *\n * @group Search\n */\nexport interface SearchField {\n /**\n * Property name, or dotted path into a `map` property.\n * @see SearchConfig.fields\n */\n path: string;\n\n /**\n * Postgres weight class. `ts_rank` scores an `A` hit far above a `D` hit,\n * which is how a name outranks a passing mention in a long description.\n *\n * The four classes are Postgres's own and there are exactly four.\n *\n * @default \"B\"\n */\n weight?: SearchWeight;\n}\n\n/**\n * How {@link SearchConfig.mode} matches a search string.\n *\n * @group Search\n */\nexport type SearchMode = \"fts\" | \"hybrid\";\n\n/**\n * Postgres tsvector weight classes, strongest to weakest.\n *\n * @group Search\n */\nexport type SearchWeight = \"A\" | \"B\" | \"C\" | \"D\";\n\n/** The column name used when {@link SearchConfig.column} is not given. */\nexport const DEFAULT_SEARCH_COLUMN = \"search_vector\";\n\n/** The matching strategy used when {@link SearchConfig.mode} is not given. */\nexport const DEFAULT_SEARCH_MODE: SearchMode = \"fts\";\n\n/** The text search configuration used when {@link SearchConfig.language} is not given. */\nexport const DEFAULT_SEARCH_LANGUAGE = \"simple\";\n\n/** The weight a field carries when it does not name one. */\nexport const DEFAULT_SEARCH_WEIGHT: SearchWeight = \"B\";\n\n/** The similarity floor used when {@link SearchConfig.fuzzyThreshold} is not given. */\nexport const DEFAULT_FUZZY_THRESHOLD = 0.3;\n\n/**\n * Sort keys a query computes rather than reads from a column.\n *\n * `orderBy` is otherwise typed against the row — `keyof M` — which is exactly\n * right for a column and exactly wrong for relevance: `_score` is produced by\n * the query, so it appears in no generated row type and a project with a\n * generated SDK could not name it. The runtime accepted it, the docs told\n * people to use it, and the types rejected it.\n *\n * Kept as a named union rather than a loose `string` so the other half of the\n * guarantee survives: a typo'd column is still a compile error, and remains a\n * 400 at runtime rather than a silently unsorted list.\n *\n * `_distance` is deliberately not here. A vector search orders by distance on\n * its own and overrides `orderBy` outright, so naming it would imply a choice\n * the caller does not have.\n *\n * @group Search\n */\nexport type ComputedSortField = typeof RELEVANCE_SORT_FIELD;\n\n/**\n * The relevance sort key. Valid only on a collection that declares a\n * {@link SearchConfig} *and* on a query that carries a search string; anywhere\n * else it is an unknown field and the request is refused.\n */\nexport const RELEVANCE_SORT_FIELD = \"_score\";\n\n/**\n * One field that matched, and the text around the hit.\n *\n * Returned per row as `_matches` when a query asks for it — see the `explain`\n * option on `.search()`. Answers the question a ranked list otherwise leaves\n * open: *why is this row here?* A candidate surfacing for \"iso 14001\" because\n * of a certification is a different result from one surfacing because the\n * string appears in a paragraph about something else, and the score alone\n * cannot tell them apart.\n *\n * @group Search\n */\nexport interface SearchMatch {\n /**\n * The declared field path that matched, exactly as written in\n * {@link SearchConfig.fields} — e.g. `\"questionnaire.certifications\"`.\n * Map it to a label for display; the path is stable, a label is yours.\n */\n field: string;\n\n /**\n * The matching text, with each hit wrapped in `<mark>…</mark>`.\n *\n * Built by Postgres's `ts_headline` over the same normalized text that was\n * indexed. With {@link SearchConfig.unaccent} on that means the snippet\n * reads with accents folded — `Auditoria` rather than `Auditoría`. That is\n * deliberate: `ts_headline` over the *original* text cannot find a hit the\n * unaccented query produced, so it returns the text with nothing marked at\n * all. A readable snippet that highlights beats a prettier one that\n * silently does not.\n *\n * Contains markup by construction. Render it as HTML or strip the tags —\n * do not display it raw, and do not trust it as plain text.\n */\n snippet: string;\n}\n","\n/**\n * @group Models\n */\nexport type OnAction = \"cascade\" | \"restrict\" | \"no action\" | \"set null\" | \"set default\";\n\n/**\n * The key a junction row's own columns are carried under, in both directions.\n *\n * A read that includes a `manyToMany` relation serves each related row with its\n * link's columns nested here — `{ id: 5, name: \"ts\", _pivot: { role: \"owner\" } }`\n * — and a membership write may name the same key on an element to state what\n * the link should hold. One constant because the two have to be the same word:\n * a wire name that differs between the read and the write it round-trips\n * through is a shape no client can echo back.\n *\n * Leading underscore, like `_matches`: it reads as metadata about the row\n * rather than as one of its columns. A payload property may not be named\n * `_pivot` either — `checkJunctionPayload` refuses it — so the key means one\n * thing wherever it appears.\n *\n * @group Models\n */\nexport const JUNCTION_PIVOT_KEY = \"_pivot\";\n\n/**\n * The key a row carries the totals of its counted relations under.\n *\n * An include that asks for a count — `include: { tags: { limit: 4, count: true } }`\n * — serves, beside the (capped) `tags`, how many related rows there are in all:\n * `{ id: 1, tags: [ …4 rows ], _count: { tags: 37 } }`. One object per row,\n * keyed by relation name, so counting a second relation adds a key rather than\n * a second top-level name.\n *\n * Leading underscore, like {@link JUNCTION_PIVOT_KEY} and `_matches`: it\n * describes the read, not the record, and no column or form writes it. A\n * collection with a property of this name cannot ask for a count — the read\n * answers 400 rather than writing over the column.\n *\n * @group Models\n */\nexport const INCLUDE_COUNT_KEY = \"_count\";\n\n/**\n * What kind of link a relation is.\n *\n * The discriminant. Every other field a relation carries belongs to exactly one\n * of these, which is the point: a relation used to be a single open interface\n * where `cardinality`, `direction`, `localKey`, `foreignKeyOnTarget`, `through`\n * and `joinPath` were all optional and any combination typechecked. Which link\n * you meant then had to be *inferred* from which fields you happened to set,\n * and the inference was ~200 lines that guessed, fell back on naming\n * conventions, and swallowed its own failures.\n *\n * Most of that guessing produced bugs rather than convenience. A `many`\n * relation carrying a `localKey` — a combination the old type permitted — made\n * the write path stamp the parent's own foreign key onto the child row. Under\n * these kinds that state cannot be written down.\n *\n * @group Models\n */\nexport type RelationKind = \"belongsTo\" | \"hasOne\" | \"hasMany\" | \"manyToMany\" | \"via\";\n\n/**\n * Defines a single, explicit step in a multi-join path.\n *\n * Each step represents one JOIN operation in the sequence. The `from` columns\n * refer to the previous table in the chain (or the source table for the first step),\n * and the `to` columns refer to the current table being joined.\n *\n * @example Single column join:\n * ```typescript\n * {\n * table: \"authors\",\n * on: {\n * from: \"author_id\", // Column from previous table (e.g., posts.author_id)\n * to: \"id\" // Column from current table (authors.id)\n * }\n * }\n * ```\n *\n * @example Multi-column composite key join:\n * ```typescript\n * {\n * table: \"order_items\",\n * on: {\n * from: [\"order_id\", \"store_id\"], // Multiple columns from previous table\n * to: [\"order_id\", \"store_id\"] // Corresponding columns in current table\n * }\n * }\n * ```\n */\nexport interface JoinStep {\n /**\n * The database table name to join TO in this step.\n * This is the table you're joining into, not the table you're joining from.\n *\n * @example \"authors\", \"user_roles\", \"product_categories\"\n */\n table: string;\n\n /**\n * The join condition for this step. Defines how the previous table\n * connects to the current table.\n *\n * - `from`: Column name(s) on the PREVIOUS table in the join chain\n * - `to`: Column name(s) on the CURRENT table (specified in `table`)\n *\n * For the first step, `from` refers to the source collection's table.\n * For subsequent steps, `from` refers to the table from the previous step.\n *\n * Both `from` and `to` support:\n * - Single column: `\"user_id\"`\n * - Multiple columns: `[\"company_id\", \"region_id\"]` for composite keys\n *\n * When using arrays, both `from` and `to` must have the same length,\n * and columns are matched by position (index 0 with index 0, etc.).\n *\n * A list of conditions joins a row that meets **any one** of them. That is\n * how a link stored in either of two columns is read: a friendship kept as\n * one row with the smaller account first holds a person in `a` on some rows\n * and in `b` on others, and both are their friends.\n *\n * ```typescript\n * { table: \"friendships\", on: [{ from: \"id\", to: \"a\" }, { from: \"id\", to: \"b\" }] }\n * ```\n *\n * A step with two or more alternatives is read-only, whatever its\n * position in the chain: a new link could go in either column, and which\n * one is the application's rule, not something to guess. A list of one is\n * the bare condition, and is read and written the same.\n */\n on: JoinCondition | JoinCondition[];\n}\n\n/**\n * One way a {@link JoinStep} can match: every `from` column equal to its `to`\n * column.\n * @group Models\n */\nexport interface JoinCondition {\n from: string | string[];\n to: string | string[];\n}\n\n/**\n * The conditions of a join step, as a list: one entry for a plain step, one\n * per alternative for a step that joins on any of several.\n * @group Models\n */\nexport function joinConditions(step: Pick<JoinStep, \"on\">): JoinCondition[] {\n return Array.isArray(step.on) ? step.on : [step.on];\n}\n\n/**\n * The one condition of a step that has no alternatives — for the write paths,\n * which only run on a writable chain and a chain with alternatives never is.\n * Throws rather than pick one of several: writing a link into the wrong column\n * is the mistake read-only exists to prevent.\n * @group Models\n */\nexport function soleJoinCondition(step: Pick<JoinStep, \"on\" | \"table\">): JoinCondition {\n if (Array.isArray(step.on)) {\n if (step.on.length === 1) return step.on[0];\n if (step.on.length === 0) throw new Error(`The join into '${step.table}' lists no conditions, so it joins nothing.`);\n throw new Error(`The join into '${step.table}' matches any of ${step.on.length} conditions, so it is read-only: there is no one column to write a link into.`);\n }\n return step.on;\n}\n","/**\n * Structured, engine-agnostic policy expressions.\n *\n * A {@link PolicyExpression} is the single source of truth for a row-level\n * security condition. It is compiled to Postgres `USING`/`WITH CHECK` SQL\n * (authoritative enforcement) and independently evaluated in JavaScript (to\n * drive the admin UI). Because both the SQL and the JS decision derive from\n * the *same* expression, the UI matches database enforcement by construction —\n * no drift between two hand-written implementations.\n *\n * The only escape hatch that cannot be evaluated client-side is the\n * {@link RawPolicyExpression} node (`{ kind: \"raw\" }`): it preserves full\n * PostgreSQL power but, being arbitrary SQL, is treated as *unknown* by the\n * JavaScript evaluator (never silently allowed) and reflected exactly in the UI\n * via server-computed capability flags.\n *\n * @group Models\n */\nexport type PolicyExpression =\n | TruePolicyExpression\n | FalsePolicyExpression\n | AndPolicyExpression\n | OrPolicyExpression\n | NotPolicyExpression\n | ComparePolicyExpression\n | RolesOverlapPolicyExpression\n | RolesContainPolicyExpression\n | AuthenticatedPolicyExpression\n | RegisteredPolicyExpression\n | ServerContextPolicyExpression\n | ExistsInPolicyExpression\n | RawPolicyExpression;\n\n/**\n * The id a request without a logged-in user reports as `rebase.uid()`.\n *\n * A user-context request always sets `app.uid`: blank would read back as\n * `NULL`, and `NULL` is how the trusted server context is recognised, so an\n * anonymous visitor would be promoted to server privileges. The driver\n * therefore substitutes this sentinel at the single chokepoint where the GUC\n * is set.\n *\n * The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a\n * tautology on the user path** — it is true for anonymous visitors too. Use\n * {@link policy.authenticated} to mean \"signed in\", and\n * {@link policy.serverContext} to mean \"the trusted server context\". Do not\n * hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one\n * literal is not enough.\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_ID = \"anonymous\";\n\n/**\n * Every uid that has ever meant \"nobody is signed in\" — newest first.\n *\n * There are two because there were two. The types, the policy compiler, the\n * JavaScript evaluator and the linter were all built on\n * {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated\n * callers as `'anon'` — so `policy.authenticated()`, which compiled to\n * `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The\n * sanctioned way to write \"signed in\" granted to everyone, and the linter\n * flagged the spelling that actually worked as a foreign convention.\n *\n * The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here\n * because policies outlive the server that generated them: a database still\n * holding policies from before the fix, or a project whose server has not been\n * upgraded yet, must not become a grant in either direction. Compile against\n * this list, not against a single literal.\n *\n * No real user id is ever one of these, so a match is always \"not signed in\".\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_IDS: readonly string[] = [ANONYMOUS_USER_ID, \"anon\"];\n\n/**\n * Whether a uid stands for \"no one is signed in\", in any spelling rebase has\n * used. `null`/`undefined` is the trusted server context, not an anonymous\n * caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.\n *\n * @group Models\n */\nexport function isAnonymousUid(uid: string | null | undefined): boolean {\n return typeof uid === \"string\" && ANONYMOUS_USER_IDS.includes(uid);\n}\n\n/** Always allows. Compiles to `true`. @group Models */\nexport interface TruePolicyExpression {\n kind: \"true\";\n}\n\n/** Always denies. Compiles to `false`. @group Models */\nexport interface FalsePolicyExpression {\n kind: \"false\";\n}\n\n/** Logical AND — every operand must pass. @group Models */\nexport interface AndPolicyExpression {\n kind: \"and\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical OR — at least one operand must pass. @group Models */\nexport interface OrPolicyExpression {\n kind: \"or\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical negation. @group Models */\nexport interface NotPolicyExpression {\n kind: \"not\";\n operand: PolicyExpression;\n}\n\n/** Comparison operators available to {@link ComparePolicyExpression}. @group Models */\nexport type PolicyCompareOperator = \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\";\n\n/**\n * Compares two operands, e.g. `owner_id = rebase.uid()`.\n * @group Models\n */\nexport interface ComparePolicyExpression {\n kind: \"compare\";\n op: PolicyCompareOperator;\n left: PolicyOperand;\n right: PolicyOperand;\n}\n\n/**\n * True when the user holds *at least one* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') && ARRAY[...]`.\n * @group Models\n */\nexport interface RolesOverlapPolicyExpression {\n kind: \"rolesOverlap\";\n roles: readonly string[];\n}\n\n/**\n * True when the user holds *all* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') @> ARRAY[...]`.\n * @group Models\n */\nexport interface RolesContainPolicyExpression {\n kind: \"rolesContain\";\n roles: readonly string[];\n}\n\n/**\n * True when a signed-in user is making the request. Compiles to\n * `rebase.uid() IS NOT NULL AND rebase.uid() <> 'anonymous'`.\n *\n * Both halves are load-bearing. `IS NOT NULL` excludes the server context;\n * the {@link ANONYMOUS_USER_ID} comparison excludes anonymous visitors, who\n * *do* carry a non-null `rebase.uid()`. Checking only `IS NOT NULL` grants to\n * everyone — see {@link ANONYMOUS_USER_ID}.\n *\n * `policy.not(policy.authenticated())` therefore means \"anonymous visitor or\n * the server context\". To single out the server context, use\n * {@link ServerContextPolicyExpression}.\n * @group Models\n */\nexport interface AuthenticatedPolicyExpression {\n kind: \"authenticated\";\n}\n\n/**\n * True for a signed-in caller who has an ACCOUNT — not a guest.\n *\n * The distinction {@link AuthenticatedPolicyExpression} cannot make. Anonymous\n * SIGN-IN (`POST /auth/anonymous`) mints a real user row with a real uid and a\n * real session, so such a caller is \"authenticated\" by every test that looks at\n * `rebase.uid()`: same shape, same default role, indistinguishable inside a\n * policy. On a deployment with anonymous sign-in enabled, every rule meaning\n * \"a signed-in person\" therefore also meant \"anybody at all\", since pressing\n * Continue as guest needs no email, no password and no agreement to anything.\n *\n * Note the two senses of \"anonymous\", which is the reason this was easy to\n * miss. {@link ANONYMOUS_USER_ID} is the sentinel for a request carrying NO\n * session, and `authenticated()` already excludes it. A guest is the other\n * thing: a session with nobody behind it. This node excludes both.\n *\n * Compiles to `authenticated() AND NOT rebase.is_anonymous()`.\n *\n * Use it wherever a rule is about a person who could be held responsible for\n * something — writing a review, joining an organization, spending money. Use\n * `authenticated()` where a guest is genuinely welcome, which is what\n * anonymous sign-in is for: a cart before checkout, a draft before signup.\n * @group Models\n */\nexport interface RegisteredPolicyExpression {\n kind: \"registered\";\n}\n\n/**\n * True only in the trusted **server context** — the built-in flows that run\n * without a user (signup, migrations, `dataAsAdmin`) set no user GUC, so\n * `rebase.uid()` is `NULL` for them and only for them. Compiles to\n * `rebase.uid() IS NULL`.\n *\n * This is what lets the owner connection satisfy a policy even under FORCE RLS.\n * It is deliberately a primitive rather than `not(authenticated())`: the two\n * meant the same thing while `authenticated` ignored {@link ANONYMOUS_USER_ID},\n * and conflating them is what turns a server-only grant into an anonymous one.\n *\n * The JavaScript evaluator always returns `false` for this node — a client is\n * never the server context.\n * @group Models\n */\nexport interface ServerContextPolicyExpression {\n kind: \"serverContext\";\n}\n\n/**\n * Membership / relational access: true when at least one row exists in another\n * table (a join/membership table) matching `where`. This is what lets you\n * scope reads to \"rows whose team the caller belongs to\" without an N+1\n * per-row lookup — it compiles to a single correlated `EXISTS` subquery.\n *\n * Inside `where`, {@link FieldPolicyOperand} (`policy.field`) references a column\n * of the joined table, while {@link OuterFieldPolicyOperand}\n * (`policy.outerField`) references a column of the row being checked (the outer\n * table under RLS). Combine with {@link AuthUidPolicyOperand} to correlate to\n * the caller.\n *\n * @example\n * ```ts\n * // documents visible only to members of the document's team:\n * policy.existsIn({\n * table: \"team_members\",\n * where: policy.and(\n * policy.compare(policy.field(\"team_id\"), \"eq\", policy.outerField(\"team_id\")),\n * policy.compare(policy.field(\"user_id\"), \"eq\", policy.authUid()),\n * ),\n * })\n * // → EXISTS (SELECT 1 FROM team_members _ex0\n * // WHERE _ex0.team_id = documents.team_id AND _ex0.user_id = rebase.uid())\n * ```\n *\n * Postgres-authoritative: like {@link RawPolicyExpression}, the JavaScript\n * evaluator treats it as *unknown* (it cannot run a subquery client-side), so\n * enforcement is always the database's.\n * @group Models\n */\nexport interface ExistsInPolicyExpression {\n kind: \"existsIn\";\n /**\n * The table to search (the join / membership table), by its slug.\n *\n * Spelled `collection` before tables replaced collections in the backend\n * vocabulary. A policy's name hashes the rule as written, so the name\n * hash still reads this field as `collection` (see `getPolicyNameHash`).\n */\n table: string;\n /** Condition evaluated against the joined table's rows. */\n where: PolicyExpression;\n}\n\n/**\n * A raw PostgreSQL boolean expression — the full-power escape hatch.\n *\n * Columns can be referenced as `{column_name}`. This is Postgres-only and\n * **server-authoritative**: the JavaScript evaluator cannot evaluate arbitrary\n * SQL, so it treats this node as *unknown* rather than guessing.\n * @group Models\n */\nexport interface RawPolicyExpression {\n kind: \"raw\";\n sql: string;\n}\n\n/**\n * An operand referenced by a {@link ComparePolicyExpression}.\n * @group Models\n */\nexport type PolicyOperand =\n | FieldPolicyOperand\n | OuterFieldPolicyOperand\n | LiteralPolicyOperand\n | AuthUidPolicyOperand\n | AuthRolesPolicyOperand\n | AuthClaimPolicyOperand;\n\n/** A column value on the row being evaluated. @group Models */\nexport interface FieldPolicyOperand {\n kind: \"field\";\n /** The property/column name (resolved to its DB column when compiled). */\n name: string;\n}\n\n/**\n * A column value on the *outer* row when used inside {@link ExistsInPolicyExpression}\n * — i.e. the row the RLS policy is being evaluated for, referenced from within the\n * subquery. Outside an `existsIn` it is equivalent to {@link FieldPolicyOperand}.\n * @group Models\n */\nexport interface OuterFieldPolicyOperand {\n kind: \"outerField\";\n /** The property/column name on the outer table. */\n name: string;\n}\n\n/** A constant value. @group Models */\nexport interface LiteralPolicyOperand {\n kind: \"literal\";\n value: string | number | boolean | null;\n}\n\n/** The current user's id — compiles to `rebase.uid()`. @group Models */\nexport interface AuthUidPolicyOperand {\n kind: \"authUid\";\n}\n\n/**\n * The current user's roles as an array — compiles to\n * `string_to_array(rebase.roles(), ',')`.\n * @group Models\n */\nexport interface AuthRolesPolicyOperand {\n kind: \"authRoles\";\n}\n\n/**\n * A named claim on the caller's session token — compiles to\n * `NULLIF(rebase.jwt() ->> '<name>', '')`.\n *\n * The operand multi-tenancy is built on, and the reason it is an operand rather\n * than a {@link RawPolicyExpression}: a claim arrives as **text**, and the\n * column it is compared against usually is not. `org_id = rebase.jwt() ->>\n * 'org_id'` on a `uuid` column is not a policy that denies — it is\n * `CREATE POLICY` failing with \"operator does not exist: uuid = text\", and a\n * table left with RLS enabled and no policy denies every row. Casting the\n * *column* to text instead compiles, but takes the index off the one predicate\n * that is ANDed into every read of the table.\n *\n * As an operand the compiler can see both sides: it casts the claim to the\n * column's type, guarded so a malformed claim denies rather than raising\n * `invalid input syntax` on every query, and the column keeps its index.\n *\n * An absent claim, and a claim set to the empty string, are both NULL — and a\n * comparison against NULL is never true, so a caller carrying no claim sees no\n * rows rather than all of them.\n *\n * Only *custom* claims are reachable. `uid`, `roles`, `aal` and `isAnonymous`\n * are identity claims written after the custom ones when a token is minted,\n * precisely so a claims hook cannot assert them; they have their own operands\n * ({@link AuthUidPolicyOperand}, {@link AuthRolesPolicyOperand}) and naming one\n * here is refused.\n *\n * Postgres-authoritative: the JavaScript evaluator reports *unknown* rather\n * than reproducing Postgres's cast semantics (uuid case folding, numeric\n * widening) a second time and getting them subtly wrong.\n * @group Models\n */\nexport interface AuthClaimPolicyOperand {\n kind: \"authClaim\";\n /** The claim's name on the token, e.g. `\"org_id\"`. */\n name: string;\n}\n\n// ── Shorthand conditions ─────────────────────────────────────────────\n\n/**\n * A value a {@link PolicyShorthand} compares a column with.\n * @group Models\n */\nexport type PolicyShorthandValue = string | number | boolean | null;\n\n/**\n * The plain-object form of a row condition: `{ status: \"published\" }`.\n *\n * Every key is a column key of the table and every value a literal; the\n * condition holds when **each** column equals its value (an AND of\n * equalities), and a `null` value means the column `IS NULL`. It is what\n * `policy.and(policy.compare(policy.field(k), \"eq\", policy.literal(v)), …)`\n * spells longhand, and compiles to the same SQL — except `null`, which no\n * comparison can express (`x = NULL` is never true) and which therefore\n * compiles to `x IS NULL`.\n *\n * - **No key may be named `kind`.** `kind` is how a {@link PolicyExpression}\n * is recognised at runtime, so `{ kind: \"true\" }` would be read as the\n * expression that grants everything. The type refuses it and so does the\n * compiler; compare a column called `kind` with the longhand form.\n * - **At least one key.** `{}` would be an AND of nothing, which is `true`;\n * the compiler refuses it — write `policy.true()` if every row is meant.\n * - The keys are checked against the table when the rule is compiled: a key\n * that names no column is refused, with the table and the key in the error.\n *\n * Use {@link isPolicyShorthand} to tell it apart from a `PolicyExpression`.\n *\n * @example\n * { operation: \"select\", access: \"public\", condition: { status: \"published\" } }\n * { operation: \"select\", condition: { orgId: \"acme\", deletedAt: null } }\n *\n * @group Models\n */\nexport type PolicyShorthand = { readonly [column: string]: PolicyShorthandValue } & { readonly kind?: never };\n\n/**\n * What a rule's `condition` / `check` accepts: a structured\n * {@link PolicyExpression}, or the {@link PolicyShorthand} object form.\n * @group Models\n */\nexport type PolicyCondition = PolicyExpression | PolicyShorthand;\n\n/**\n * Every `kind` a {@link PolicyExpression} node can have — the discriminator\n * {@link isPolicyShorthand} and {@link isPolicyExpressionKind} read.\n * @group Models\n */\nexport const POLICY_EXPRESSION_KINDS: readonly PolicyExpression[\"kind\"][] = [\n \"true\", \"false\", \"and\", \"or\", \"not\", \"compare\", \"rolesOverlap\", \"rolesContain\",\n \"authenticated\", \"registered\", \"serverContext\", \"existsIn\", \"raw\"\n];\n\n/**\n * Whether `kind` names a {@link PolicyExpression} node.\n * @group Models\n */\nexport function isPolicyExpressionKind(kind: unknown): kind is PolicyExpression[\"kind\"] {\n return typeof kind === \"string\" && (POLICY_EXPRESSION_KINDS as readonly string[]).includes(kind);\n}\n\nconst isShorthandValue = (value: unknown): value is PolicyShorthandValue =>\n value === null || typeof value === \"string\" || typeof value === \"boolean\"\n || (typeof value === \"number\" && Number.isFinite(value));\n\n/**\n * Whether a rule's `condition` / `check` is a {@link PolicyShorthand} rather\n * than a {@link PolicyExpression}.\n *\n * True only for a plain object with at least one key, none of them `kind`,\n * whose every value is a string, a finite number, a boolean or `null`. Every\n * expression node carries `kind`, so no expression is ever taken for a\n * shorthand — and an object that has a `kind` key is never taken for a\n * shorthand either, whatever its value: such an object is ambiguous (a column\n * called `kind`, or a misspelt node) and the compiler refuses it rather than\n * guessing.\n *\n * @group Models\n */\nexport function isPolicyShorthand(value: unknown): value is PolicyShorthand {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const proto: unknown = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return false;\n if (Object.prototype.hasOwnProperty.call(value, \"kind\")) return false;\n const entries = Object.entries(value);\n return entries.length > 0 && entries.every(([, v]) => isShorthandValue(v));\n}\n\n// ── Constructor helpers ──────────────────────────────────────────────\n// Small, dependency-free builders so callers (and the desugaring in\n// `@rebasepro/common`) can assemble expressions without object-literal noise.\n\n/** @group Models */\nexport const policy = {\n true: (): TruePolicyExpression => ({ kind: \"true\" }),\n false: (): FalsePolicyExpression => ({ kind: \"false\" }),\n and: (...operands: readonly PolicyExpression[]): AndPolicyExpression => ({ kind: \"and\",\noperands: operands as PolicyExpression[] }),\n or: (...operands: readonly PolicyExpression[]): OrPolicyExpression => ({ kind: \"or\",\noperands: operands as PolicyExpression[] }),\n not: (operand: PolicyExpression): NotPolicyExpression => ({ kind: \"not\",\noperand }),\n compare: (left: PolicyOperand, op: PolicyCompareOperator, right: PolicyOperand): ComparePolicyExpression =>\n ({ kind: \"compare\",\nop,\nleft,\nright }),\n rolesOverlap: (roles: readonly string[]): RolesOverlapPolicyExpression => ({ kind: \"rolesOverlap\",\nroles: roles as string[] }),\n rolesContain: (roles: readonly string[]): RolesContainPolicyExpression => ({ kind: \"rolesContain\",\nroles: roles as string[] }),\n authenticated: (): AuthenticatedPolicyExpression => ({ kind: \"authenticated\" }),\n registered: (): RegisteredPolicyExpression => ({ kind: \"registered\" }),\n serverContext: (): ServerContextPolicyExpression => ({ kind: \"serverContext\" }),\n existsIn: (args: { table: string; where: PolicyExpression }): ExistsInPolicyExpression =>\n ({ kind: \"existsIn\",\ntable: args.table,\nwhere: args.where }),\n raw: (sql: string): RawPolicyExpression => ({ kind: \"raw\",\nsql }),\n field: (name: string): FieldPolicyOperand => ({ kind: \"field\",\nname }),\n outerField: (name: string): OuterFieldPolicyOperand => ({ kind: \"outerField\",\nname }),\n literal: (value: string | number | boolean | null): LiteralPolicyOperand => ({ kind: \"literal\",\nvalue }),\n authUid: (): AuthUidPolicyOperand => ({ kind: \"authUid\" }),\n authRoles: (): AuthRolesPolicyOperand => ({ kind: \"authRoles\" }),\n authClaim: (name: string): AuthClaimPolicyOperand => ({ kind: \"authClaim\",\nname })\n};\n","/**\n * The SQL helper functions RLS policies call, and the schema they live in.\n *\n * ## One schema, and it is ours\n *\n * Rebase creates exactly one schema in a project's database: `rebase`. These\n * three functions live in it alongside the framework's own tables, and that is\n * the whole contract — a reader can look at a database and know precisely which\n * namespace belongs to the framework and that nothing else was touched.\n *\n * It used to be two. `uid()`, `jwt()` and `roles()` sat in a schema called\n * `auth`, which is Supabase's name, chosen so that a developer who had written\n * Supabase RLS would recognise `auth.uid()`. The familiarity was real but the\n * name was not Rebase's to take, and taking it had a concrete cost: pointing\n * Rebase at a database that already had a Supabase `auth` schema meant\n * `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` against Supabase's\n * `RETURNS uuid`, which Postgres rejects outright —\n *\n * ERROR: cannot change return type of existing function\n * HINT: Use DROP FUNCTION auth.uid() first.\n *\n * — and the failure landed inside a catch-all that logged a warning and carried\n * on, leaving a database with auth tables, no helper functions, and policies\n * calling functions that did not exist. Under `rebase db migrate` the same\n * statements aborted the migration instead.\n *\n * `rebase.uid()` collides with nobody. A Supabase database keeps its `auth`\n * schema untouched and gains a `rebase` one, which is what a gradual migration\n * needs.\n *\n * ## Why functions at all, rather than inlining `current_setting`\n *\n * Because the indirection has already been spent once. `uid()` resolves\n * `app.uid` and falls back to the pre-rename `app.user_id`, so that during a\n * rolling deploy — old and new pods serving one database — both eras resolve\n * the principal. That was a single `CREATE OR REPLACE`. Inlined into policy\n * bodies it would have been a rewrite of every policy on every table.\n *\n * ## Why the name is not configurable\n *\n * A policy body is stored SQL: Postgres parses `USING (…)` once and keeps it, so\n * these strings are written into every policy in every database Rebase has\n * provisioned. Everything that reads policies back — the SQL-to-policy parser\n * behind the admin UI, the drift checker, `rls-check` — would have to know the\n * configured value to recognise its own output. One frozen name is the feature.\n */\n\n/** The schema Rebase owns. The only schema Rebase creates. */\nexport const REBASE_SCHEMA = \"rebase\";\n\n/**\n * The principal of the current request, as text, or NULL in the server context.\n *\n * Never NULL for a user request — an anonymous one carries\n * {@link ANONYMOUS_USER_ID} — which is what makes `IS NULL` a reliable test for\n * the trusted server plane and `IS NOT NULL` a tautology.\n */\nexport const RLS_UID_SQL = `${REBASE_SCHEMA}.uid()`;\n/**\n * Is the caller one of this database's request roles? What a permissive\n * policy is ANDed with under `rls.policyTarget: \"requestRole\"`, so another\n * application's role holding a grant on the table gets nothing from it.\n * `current_user` is passed in — inside the function, which reads the recorded\n * roles with its owner's rights, `current_user` would be the owner — and the\n * sub-select makes it one evaluation per statement, not one per row.\n */\nexport const RLS_IS_REQUEST_ROLE_SQL = `(SELECT ${REBASE_SCHEMA}.is_request_role(current_user::text))`;\n\n/** The request's roles as a comma-separated string, for `string_to_array`. */\nexport const RLS_ROLES_SQL = `${REBASE_SCHEMA}.roles()`;\n\n/**\n * The Postgres role that policies granting only the server context or admins\n * are written `TO`: the injected `<table>_default_admin_*` baseline, and any\n * permissive rule whose every clause requires one of the two (`roles: [\"admin\"]`).\n *\n * Postgres ORs the permissive policies that apply to the current role. Written\n * `TO public`, the baseline applied to every signed-in user too, as\n * `(InitPlan) OR owner_id = (InitPlan)` — and an OR with a per-statement\n * constant arm cannot use the owner index, so a user's owner-scoped list or\n * count scanned the whole table (78 ms against 2.8 ms at 1M rows). Written `TO`\n * this role, the policy is not in a user's plan at all.\n *\n * It holds no privilege and cannot log in: being in it only decides which\n * policies apply, and those still test `rebase.uid() IS NULL` or the `admin`\n * role. Admin requests switch to a request role that inherits it\n * ({@link adminRequestRoleFor}); a connection that is itself subject to RLS\n * inherits it for the server context. One fixed name, so the policy text is the\n * same in every deployment and every generated migration. FROZEN.\n */\nexport const REBASE_ADMIN_ROLE = \"rebase_admin\";\n\n/**\n * The role the admin request roles ({@link adminRequestRoleFor}) inherit and\n * nothing else does, so an admin-only grant can apply to admin REQUESTS alone.\n *\n * {@link REBASE_ADMIN_ROLE} cannot do that job: the connection inherits it for\n * the server context, and so would any process on it that does not switch\n * roles. Its policies therefore keep their test (`rebase.uid() IS NULL` or the\n * `admin` role) — and any policy expression that is not a constant is a\n * security barrier, behind which Postgres will not evaluate a non-leakproof\n * operator as an index condition. An admin's `tags && $1`, `name ~ $1` or\n * jsonb filter scanned the whole table where the owner's used the index.\n *\n * Each admin-only grant gets a companion `TO` this role `USING (true)`.\n * Postgres folds the OR of the permissive policies to `true` for a member, the\n * barrier goes, and an admin request plans as the owner's does; restrictive\n * policies still apply. Membership is the boundary: only the admin request\n * roles hold it, granted `WITH INHERIT TRUE, SET FALSE`, and only from\n * PostgreSQL 16, whose per-grant INHERIT keeps the connection (which holds\n * those roles `WITH INHERIT FALSE`) out. A boot that finds the connection with\n * its privileges revokes every membership, and the companions admit nobody.\n * One fixed name, as {@link REBASE_ADMIN_ROLE}. FROZEN.\n */\nexport const REBASE_ADMIN_REQUEST_ROLE = \"rebase_admin_request\";\n\n/**\n * The role an admin request runs as, for a signed-in request role: it inherits\n * that role (its grants and every policy written for it) and\n * {@link REBASE_ADMIN_ROLE}. One per request role rather than the shared\n * `rebase_admin` itself, because roles belong to the cluster: a project with a\n * request role of its own (`rls.requestRole`) would otherwise share its admin\n * access with every other project on the cluster. FROZEN derivation.\n */\nexport function adminRequestRoleFor(requestRole: string): string {\n return `${requestRole}_admin`;\n}\n\n/**\n * Whether a request with these roles passes `rolesOverlap([\"admin\"])` — the\n * test `string_to_array(rebase.roles(), ',') && ARRAY['admin']` makes of the\n * comma-joined `app.user_roles`, so a role name with a comma in it is split\n * exactly as Postgres splits it.\n */\nexport function holdsAdminRole(roles: readonly string[]): boolean {\n return roles.join(\",\").split(\",\").includes(\"admin\");\n}\n\n/**\n * Whether the caller is a GUEST — signed in through anonymous sign-in rather\n * than with an account.\n *\n * A different question from {@link ANONYMOUS_USER_ID}, and the two are easy to\n * confuse: that sentinel means \"no session at all\", while this means \"a session\n * with nobody behind it\". Anonymous sign-in mints a real user row with a real\n * uid, so before this reached the database the two kinds of caller were one\n * principal inside every policy.\n */\nexport const RLS_IS_ANONYMOUS_SQL = `${REBASE_SCHEMA}.is_anonymous()`;\n\n/** The request's JWT claims as `jsonb`, or `{}`. */\nexport const RLS_JWT_SQL = `${REBASE_SCHEMA}.jwt()`;\n\n/**\n * The pre-1.0 spellings, for recognising policies and hand-written SQL that\n * predate the move.\n *\n * Kept because policies outlive the server that wrote them: a database migrated\n * by an older release still holds `auth.uid()` in its policy bodies until the\n * next push or boot recompiles them, and anything that reads policies back has\n * to recognise both eras or report the framework's own output as foreign drift.\n * Also used to give a project whose `securityRules` contain raw `auth.uid()` a\n * message naming the replacement, instead of a parse failure.\n */\nexport const LEGACY_RLS_SCHEMA = \"auth\";\nexport const LEGACY_RLS_UID_SQL = `${LEGACY_RLS_SCHEMA}.uid()`;\nexport const LEGACY_RLS_ROLES_SQL = `${LEGACY_RLS_SCHEMA}.roles()`;\nexport const LEGACY_RLS_JWT_SQL = `${LEGACY_RLS_SCHEMA}.jwt()`;\n\n/**\n * Rewrites the pre-1.0 function calls in a fragment of policy SQL.\n *\n * Deliberately anchored on a word boundary and the schema qualifier, so a column\n * called `auth_uid` or a table named `auth` is left alone.\n */\nexport function rewriteLegacyRlsFunctions(sql: string): string {\n return sql.replace(\n /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/gi,\n (_match, fn: string) => `${REBASE_SCHEMA}.${fn.toLowerCase()}()`\n );\n}\n\n/** Whether a fragment of SQL still calls the pre-1.0 functions. */\nexport function usesLegacyRlsFunctions(sql: string): boolean {\n return /\\bauth\\.(uid|jwt|roles)\\s*\\(\\s*\\)/i.test(sql);\n}\n","/**\n * Row-level security rules for a collection.\n *\n * 325 lines of RLS policy contract that used to sit in the middle of\n * `collections.ts`, between the admin panel's table view-models and the auth\n * collection config. It has no relationship to the shape of a collection — it is\n * the most-read part of the BaaS surface, and it now reads on its own.\n *\n * A rule is compiled to Postgres `CREATE POLICY` DDL and, for the structured\n * flavour, independently evaluated in JavaScript, so the admin UI's idea of what\n * a user may do derives from the same expression the database enforces.\n *\n * Note that rule *names* are not what you write: an unnamed rule compiles to\n * `<table>_<op>_<sha1[0:7]>`, plus an injected `default_admin` baseline. Derive\n * them with `getPolicyNamesForRule`/`getEffectiveSecurityRules` rather than\n * matching on `rule.name`.\n */\nimport type { PolicyCondition } from \"./policy\";\n\n/**\n * SQL operation that a policy applies to.\n * @group Models\n */\nexport type SecurityOperation = \"select\" | \"insert\" | \"update\" | \"delete\" | \"all\";\n\n/**\n * Who a rule's `access` shortcut admits.\n *\n * - `\"public\"` — every caller who reaches the database, signed in or not.\n * - `\"authenticated\"` — a signed-in caller: the `rebase.uid()` is neither the\n * server context's `NULL` nor an anonymous visitor's sentinel (see\n * `policy.authenticated()`). On a project with anonymous sign-in this\n * includes guests: a guest session has a real uid.\n * - `\"registered\"` — a signed-in caller who has an account: `\"authenticated\"`\n * minus guest sessions (see `policy.registered()`). What most rules meaning\n * \"a signed-in person\" want on a project with anonymous sign-in enabled.\n *\n * @group Models\n */\nexport type SecurityRuleAccess = \"public\" | \"authenticated\" | \"registered\";\n\n/**\n * Flexible Row Level Security rule for a collection.\n *\n * Built on PostgreSQL Row Level Security. Rules can range from\n * simple convenience shortcuts to fully custom SQL expressions, giving you the\n * full power of PostgreSQL Row Level Security.\n *\n * The authenticated user's identity is available in raw SQL via:\n * - `rebase.uid()` — the user's ID\n * - `rebase.roles()` — comma-separated app role IDs\n * - `rebase.jwt()` — full JWT claims as JSONB\n *\n * These are set automatically per-transaction by the backend.\n *\n * **How rules combine:** PostgreSQL evaluates all matching policies for an\n * operation. Permissive rules are OR'd together (any one passing is enough).\n * Restrictive rules are AND'd (all must pass). This is standard PostgreSQL RLS behavior.\n *\n * **Mutual exclusivity:** `ownerField`, `access` and raw SQL\n * (`using`/`withCheck`) cannot be combined with each other, and a structured\n * `condition`/`check` combines only with `access`\n * ({@link ConditionalAccessSecurityRule}). The type system enforces this —\n * attempting to set conflicting fields will produce a compile-time error.\n *\n * **Which form to reach for:** prefer the structured {@link StructuredSecurityRule}\n * (`condition`/`check`) or the shortcuts (`ownerField`, `access`, `roles`). These\n * are engine-agnostic and evaluated identically by the database and the admin UI,\n * so the UI never shows an action the database will reject. Raw SQL\n * ({@link RawSQLSecurityRule}) keeps full PostgreSQL power but is Postgres-only\n * and server-authoritative (the UI cannot evaluate arbitrary SQL locally).\n *\n * @group Models\n */\nexport type SecurityRule =\n | OwnerSecurityRule\n | PublicSecurityRule\n | AuthenticatedSecurityRule\n | RegisteredSecurityRule\n | ConditionalAccessSecurityRule\n | CheckedAccessSecurityRule\n | StructuredSecurityRule\n | RawSQLSecurityRule\n | RawSQLCheckOnlySecurityRule\n | RolesOnlySecurityRule\n | RedactedSecurityRule;\n\n/**\n * Shared fields for all SecurityRule variants.\n * @group Models\n */\nexport interface SecurityRuleBase {\n /**\n * Optional human-readable name for the policy.\n * If not provided, one will be auto-generated from the table name and operation.\n * Must be unique per table.\n *\n * When using `operations` (array), each generated policy will have the\n * operation name appended, e.g. `\"owner_access_select\"`, `\"owner_access_update\"`.\n */\n name?: string;\n\n /**\n * Which SQL operation this policy applies to.\n * Use this when the policy targets a single operation or all operations.\n *\n * For multiple specific operations, use `operations` (array) instead.\n * If neither is specified, defaults to `\"all\"`.\n *\n * @default \"all\"\n */\n operation?: SecurityOperation;\n\n /**\n * Array of SQL operations this policy applies to.\n * The compiler will generate one PostgreSQL policy per operation, sharing\n * the same configuration.\n *\n * This reduces boilerplate when the same rule applies to multiple (but not all)\n * operations.\n *\n * Takes precedence over `operation` (singular) if both are specified.\n *\n * @example\n * // Same rule for select and update\n * { operations: [\"select\", \"update\"], ownerField: \"user_id\" }\n *\n * @example\n * // Equivalent to operation: \"all\"\n * { operations: [\"all\"], ownerField: \"user_id\" }\n */\n operations?: readonly SecurityOperation[];\n\n /**\n * Whether this policy is `\"permissive\"` (default) or `\"restrictive\"`.\n *\n * - **permissive**: Multiple permissive policies for the same operation are\n * OR'd together — if *any* passes, access is granted.\n * - **restrictive**: Restrictive policies are AND'd with all permissive\n * policies — they act as additional gates that *must* also pass.\n *\n * This is the standard PostgreSQL RLS model.\n *\n * @default \"permissive\"\n */\n mode?: \"permissive\" | \"restrictive\";\n\n /**\n * **Shortcut.** Restrict this rule to users that have one of these\n * application-level roles.\n *\n * **Important:** These are NOT native PostgreSQL database roles — names\n * like `public`, `anon` or `authenticated` belong to {@link pgRoles} and\n * produce a condition no user can satisfy if used here. These are\n * application roles managed by Rebase, stored as an inline `roles TEXT[]`\n * column on the users table, and injected into each transaction as\n * `app.user_roles` — which `rebase.roles()` reads.\n *\n * There is no roles registry: a role exists once it is assigned to a user.\n *\n * Generates a safe array-overlap condition — the user passes if they hold\n * *any* of the listed roles:\n * `string_to_array(rebase.roles(), ',') && ARRAY['<role1>', '<role2>']`\n *\n * (Note: this is a true set intersection, NOT a regex/substring match, so\n * a role named `admin` never matches `nonadmin` or `superadmin`.)\n *\n * Can be combined with `ownerField`, `access`, `condition`, or raw\n * `using`/`withCheck`. When combined, the role check is AND'd with the\n * other condition.\n *\n * @example\n * // Only admins can delete\n * { operation: \"delete\", roles: [\"admin\"] }\n *\n * @example\n * // Admins have unfiltered read access to all rows\n * { operation: \"select\", roles: [\"admin\"], using: \"true\" }\n */\n roles?: readonly string[];\n\n // ── Advanced: native PostgreSQL role targeting ───────────────────────\n\n /**\n * **Advanced.** Native PostgreSQL database roles the policy applies to.\n *\n * By default, all generated policies target the `public` role (i.e.\n * every database connection). This is correct for most setups where\n * a single database role is used for all connections.\n *\n * **Important:** These are NOT the same as the application-level\n * {@link roles} (admin, editor, viewer, etc.) — those are enforced in the\n * USING/WITH CHECK clauses via `rebase.roles()`. This field controls the\n * PostgreSQL `TO` clause in `CREATE POLICY ... TO role_name`.\n *\n * Use this if you have dedicated PostgreSQL roles (e.g. `app_read`,\n * `app_write`) and want policies to target specific ones.\n *\n * @default [\"public\"]\n *\n * @example\n * // Only apply this policy when connected as `app_role`\n * { operation: \"select\", access: \"public\", pgRoles: [\"app_role\"] }\n */\n pgRoles?: readonly string[];\n}\n\n/**\n * Security rule that grants access based on row ownership.\n * Generates a USING/WITH CHECK clause like: `<column> = rebase.uid()`\n *\n * Cannot be combined with `using`, `withCheck`, or `access`.\n *\n * @example\n * { operation: \"all\", ownerField: \"user_id\" }\n *\n * @group Models\n */\nexport interface OwnerSecurityRule extends SecurityRuleBase {\n /** The property (column) that stores the owner's user ID. */\n ownerField: string;\n access?: never;\n using?: never;\n withCheck?: never;\n condition?: never;\n check?: never;\n}\n\n/**\n * Security rule that grants unrestricted row access (no row filtering).\n * Generates `USING (true)`.\n *\n * This means \"no row-level filter\", NOT \"anonymous/unauthenticated access\" on\n * its own: when the API requires a token (`AUTH_REQUIRE`, the default) a\n * caller without one is refused before RLS is consulted. This only controls\n * which *rows* a caller who reached the database sees.\n *\n * Cannot be combined with `using`, `withCheck`, or `ownerField`. To narrow the\n * rows, add a `condition` — that is a {@link ConditionalAccessSecurityRule}.\n *\n * For \"any signed-in caller\", see {@link AuthenticatedSecurityRule}.\n *\n * @example\n * // Public read (every caller sees all rows)\n * { operation: \"select\", access: \"public\" }\n *\n * @group Models\n */\nexport interface PublicSecurityRule extends SecurityRuleBase {\n /** Grant unrestricted row access for this operation. */\n access: \"public\";\n ownerField?: never;\n using?: never;\n withCheck?: never;\n condition?: never;\n check?: never;\n}\n\n/**\n * Security rule that grants any signed-in caller row access, with no row\n * filter. Generates the signed-in test `policy.authenticated()` compiles to:\n * `rebase.uid()` is neither the server context's `NULL` nor an anonymous\n * visitor's sentinel.\n *\n * Older releases did not type this shape and compiled it to a policy that\n * denies every row; it is a new shape with its own policy name (see\n * `getPolicyNameHash`).\n *\n * Cannot be combined with `using`, `withCheck`, or `ownerField`. To narrow the\n * rows, add a `condition` — that is a {@link ConditionalAccessSecurityRule}.\n *\n * @example\n * // Any signed-in caller reads every row\n * { operation: \"select\", access: \"authenticated\" }\n *\n * @group Models\n */\nexport interface AuthenticatedSecurityRule extends SecurityRuleBase {\n /** Grant row access, with no row filter, to any signed-in caller. */\n access: \"authenticated\";\n ownerField?: never;\n using?: never;\n withCheck?: never;\n condition?: never;\n check?: never;\n}\n\n/**\n * Security rule that grants any signed-in caller who has an account row\n * access, with no row filter: {@link AuthenticatedSecurityRule} minus guest\n * sessions. Generates the test `policy.registered()` compiles to — signed in,\n * and `rebase.is_anonymous()` is false.\n *\n * On a project with anonymous sign-in, a guest (`POST /auth/anonymous`) has a\n * real uid and a real session, so `access: \"authenticated\"` admits anyone who\n * presses \"Continue as guest\". Reach for `\"registered\"` when the rule is about\n * a person who could be held responsible: writing a review, joining an\n * organization, spending money.\n *\n * A new shape with its own policy name (see `getPolicyNameHash`).\n *\n * Cannot be combined with `using`, `withCheck`, or `ownerField`. To narrow the\n * rows, add a `condition` — that is a {@link ConditionalAccessSecurityRule}.\n *\n * @example\n * // Only callers with an account may post a review\n * { operation: \"insert\", access: \"registered\" }\n *\n * @group Models\n */\nexport interface RegisteredSecurityRule extends SecurityRuleBase {\n /** Grant row access, with no row filter, to any signed-in caller who is not a guest. */\n access: \"registered\";\n ownerField?: never;\n using?: never;\n withCheck?: never;\n condition?: never;\n check?: never;\n}\n\n/**\n * Security rule that grants `access` on the rows matching a condition:\n * \"anyone (or any signed-in caller) may do this, on rows where …\".\n *\n * - `access: \"public\"` compiles to `USING (<condition>)` — no caller test.\n * - `access: \"authenticated\"` compiles to\n * `USING (<signed in> AND <condition>)`.\n * - `access: \"registered\"` compiles to\n * `USING (<signed in, not a guest> AND <condition>)`.\n *\n * The write clause is derived as a structured rule derives it: `WITH CHECK`\n * from `check`, falling back to `condition`, gated by `access` the same way.\n * With only `check` ({@link CheckedAccessSecurityRule}), the `USING` clause is\n * the `access` test alone.\n *\n * `condition` / `check` take a {@link PolicyExpression} or the\n * {@link PolicyShorthand} object form. `roles` ANDs an application-role test\n * on, as on every rule.\n *\n * A new shape: its policy names are hashed from their own input (see\n * `getPolicyNameHash`), so they never coincide with a name an older rule\n * shape compiles to.\n *\n * Cannot be combined with `ownerField` or raw `using`/`withCheck`.\n *\n * @example\n * // Anyone reads the published posts\n * { operation: \"select\", access: \"public\", condition: { status: \"published\" } }\n *\n * @example\n * // Signed-in callers may file a report, but only as an open one\n * { operation: \"insert\", access: \"authenticated\", check: { state: \"open\" } }\n *\n * @group Models\n */\nexport interface ConditionalAccessSecurityRule extends SecurityRuleBase {\n /** The callers the rule admits — see {@link SecurityRuleAccess}. */\n access: SecurityRuleAccess;\n\n /**\n * Which *existing* rows the callers may see / modify / delete (the `USING`\n * clause, ANDed with the `access` test).\n */\n condition: PolicyCondition;\n\n /**\n * Which *new/updated* row values the callers may write (the `WITH CHECK`\n * clause, ANDed with the `access` test). Defaults to `condition`.\n */\n check?: PolicyCondition;\n\n ownerField?: never;\n using?: never;\n withCheck?: never;\n}\n\n/**\n * {@link ConditionalAccessSecurityRule} with only a `check`: the callers named\n * by `access` may write rows matching `check`; the `USING` clause (for\n * `select` / `update` / `delete`) is the `access` test alone.\n *\n * @example\n * // Signed-in callers may insert reports, only as open ones\n * { operation: \"insert\", access: \"authenticated\", check: { state: \"open\" } }\n *\n * @group Models\n */\nexport interface CheckedAccessSecurityRule extends SecurityRuleBase {\n /** The callers the rule admits — see {@link SecurityRuleAccess}. */\n access: SecurityRuleAccess;\n\n /**\n * Which *new/updated* row values the callers may write (the `WITH CHECK`\n * clause, ANDed with the `access` test).\n */\n check: PolicyCondition;\n\n condition?: never;\n ownerField?: never;\n using?: never;\n withCheck?: never;\n}\n\n/**\n * Security rule expressed as a structured, engine-agnostic\n * {@link PolicyExpression}. This is the **recommended** way to write a\n * non-trivial condition: it compiles to PostgreSQL `USING`/`WITH CHECK` SQL\n * *and* is evaluated identically by the admin UI, so the UI can never show an\n * action the database will reject.\n *\n * Cannot be combined with `ownerField` or raw `using`/`withCheck`; combined\n * with `access` it is a {@link ConditionalAccessSecurityRule}.\n *\n * @example\n * // Rows of one organisation that are not deleted (shorthand form)\n * { operation: \"select\", condition: { orgId: \"acme\", deletedAt: null } }\n *\n * @example\n * // Owner, or any user holding the `moderator` role\n * {\n * operation: \"update\",\n * condition: policy.or(\n * policy.compare(policy.field(\"user_id\"), \"eq\", policy.authUid()),\n * policy.rolesOverlap([\"moderator\"])\n * )\n * }\n *\n * @group Models\n */\nexport interface StructuredSecurityRule extends SecurityRuleBase {\n /**\n * Structured condition for the `USING` clause — which *existing* rows are\n * visible / can be modified / deleted (SELECT, UPDATE, DELETE).\n *\n * A {@link PolicyExpression}, or the {@link PolicyShorthand} object form\n * (`{ status: \"published\" }` — each column equals its value).\n */\n condition: PolicyCondition;\n\n /**\n * Structured condition for the `WITH CHECK` clause — which *new/updated*\n * row values are allowed (INSERT, UPDATE). Defaults to `condition` when\n * omitted, mirroring PostgreSQL's own behavior. Takes the same two forms\n * as `condition`.\n */\n check?: PolicyCondition;\n\n ownerField?: never;\n access?: never;\n using?: never;\n withCheck?: never;\n}\n\n/**\n * Security rule using raw SQL expressions for full PostgreSQL RLS power.\n *\n * **Postgres-only and server-authoritative.** Arbitrary SQL cannot be\n * evaluated by the admin UI, so a rule using this form is treated as *unknown*\n * client-side (never silently allowed) and its effect on visible actions is\n * reflected from the server. For conditions that should also drive the UI\n * precisely, prefer the structured {@link StructuredSecurityRule}.\n *\n * Cannot be combined with `ownerField`, `access`, or structured `condition`.\n *\n * You can reference columns via `{column_name}` which will be resolved to\n * `table.column_name` in the generated Drizzle code.\n *\n * @example\n * // Rows published in the last 30 days are visible\n * { operation: \"select\", using: \"{published_at} > now() - interval '30 days'\" }\n *\n * @example\n * // Only the owner, or users with 'moderator' role\n * {\n * operation: \"select\",\n * using: \"{user_id} = rebase.uid() OR rebase.roles() ~ 'moderator'\"\n * }\n *\n * @group Models\n */\nexport interface RawSQLSecurityRule extends SecurityRuleBase {\n /**\n * Raw SQL expression for the `USING` clause.\n * This controls which *existing* rows are visible / can be modified / deleted.\n * Applied to SELECT, UPDATE, and DELETE.\n */\n using: string;\n\n /**\n * Raw SQL expression for the `WITH CHECK` clause.\n * This controls which *new/updated* row values are allowed.\n * Applied to INSERT and UPDATE.\n *\n * If not provided on INSERT/UPDATE policies, falls back to `using`\n * (which matches PostgreSQL's own default behavior).\n */\n withCheck?: string;\n\n ownerField?: never;\n access?: never;\n condition?: never;\n check?: never;\n}\n\n/**\n * Security rule with a raw SQL `WITH CHECK` clause and no `USING` clause — the\n * shape of every INSERT policy, which checks the row being written and has no\n * existing row to filter.\n *\n * On an operation that takes a `USING` clause, the missing one grants no rows,\n * as a Postgres policy without one does.\n *\n * @example\n * // Anyone may insert a row they own\n * { operation: \"insert\", withCheck: \"{owner_id} = rebase.uid()\" }\n *\n * @group Models\n */\nexport interface RawSQLCheckOnlySecurityRule extends SecurityRuleBase {\n /**\n * Raw SQL expression for the `WITH CHECK` clause.\n * This controls which *new/updated* row values are allowed.\n * Applied to INSERT and UPDATE.\n */\n withCheck: string;\n\n using?: never;\n ownerField?: never;\n access?: never;\n condition?: never;\n check?: never;\n}\n\n/**\n * Security rule that only filters by application roles, without any\n * row-level condition (USING/WITH CHECK).\n *\n * Useful for simple \"only admins can access this table\" rules where\n * no per-row filtering is needed.\n *\n * @example\n * // Only admins can delete\n * { operation: \"delete\", roles: [\"admin\"] }\n *\n * @group Models\n */\nexport interface RolesOnlySecurityRule extends SecurityRuleBase {\n ownerField?: never;\n access?: never;\n using?: never;\n withCheck?: never;\n condition?: never;\n check?: never;\n}\n/**\n * A rule whose SQL the server did not show this caller.\n *\n * `GET /api/schema/tables` serves a table's `rls.rules` to every caller who may\n * read the table's description, because the panel decides which controls to\n * offer from them. Raw SQL — a `using` / `withCheck` string, or a\n * `policy.raw(…)` node anywhere inside a `condition` / `check` — is served\n * only to administrators and `schema:read` holders: it is a description of\n * the authorization model, not of the data. Everyone else receives this\n * marker in the rule's place. It keeps what decides whom the rule concerns\n * (`operation` / `operations`, `mode`, `roles`, `access`) and says nothing\n * about which rows.\n *\n * Read-only: it is never authored. A table whose `rls` carries one is refused\n * when it is compiled, and no policy is ever generated from one.\n *\n * The client-side evaluator treats it exactly as it treats a raw rule it\n * cannot evaluate: *unknown*, never *allowed*. Panel gating (which resolves\n * unknown optimistically) offers the action and lets Postgres decide;\n * enforcement callers (which resolve unknown as deny) refuse.\n *\n * @example\n * // What a non-admin is served for `{ operation: \"update\", roles: [\"editor\"], using: \"owner_id = rebase.uid()\" }`\n * { operation: \"update\", roles: [\"editor\"], redacted: true }\n *\n * @group Models\n */\nexport interface RedactedSecurityRule extends SecurityRuleBase {\n /** The rule's clauses were withheld from this caller. */\n redacted: true;\n /** Who the rule admits, when the rule said so — see {@link SecurityRuleAccess}. */\n access?: SecurityRuleAccess;\n ownerField?: never;\n using?: never;\n withCheck?: never;\n condition?: never;\n check?: never;\n}\n\n/**\n * Whether a rule is the {@link RedactedSecurityRule} marker the server sends\n * in place of a rule whose SQL it withheld.\n *\n * @group Models\n */\nexport function isRedactedSecurityRule(rule: SecurityRule): rule is RedactedSecurityRule {\n return \"redacted\" in rule && rule.redacted === true;\n}\n","/**\n * First-class multi-tenancy: one declaration, every layer.\n *\n * A tenant-scoped collection was expert work. It took four separate,\n * hand-written pieces that nothing checked against each other — a column, an\n * `existsIn` or raw RLS rule, a value stamped on every insert by a callback,\n * and an index somebody had to remember. Miss the index and the table scans;\n * miss the stamp and the row is invisible the moment it is written; miss the\n * rule and every tenant reads every other tenant's rows, which is the failure\n * nothing surfaces until it is a disclosure.\n *\n * {@link CollectionTenantConfig} is the one place that says \"this collection\n * belongs to a tenant\", and the four pieces are derived from it:\n *\n * - the column is `NOT NULL` and gets a btree index (`planSchema`);\n * - a **restrictive** RLS policy is injected for every operation, so it\n * composes with (rather than replaces) whatever `securityRules` the\n * collection declares — tenancy narrows, it never grants;\n * - the write path stamps the caller's tenant on create, refuses a write that\n * names another tenant, and refuses an update that moves a row between\n * tenants;\n * - the OpenAPI document marks the field so a generated client can see it.\n *\n * @see CollectionTenantConfig\n * @group Models\n */\n\n/**\n * The caller's tenant comes from a claim on their session token.\n *\n * The single-tenant-per-user shape: an identity provider (or Rebase's own\n * custom-claims hook) puts the organization on the token, and every request\n * carries it. Compiles to a comparison against `rebase.jwt() ->> '<claim>'`,\n * which is the same value a hand-written rule would read — so the generated\n * policy and anything an author writes beside it agree by construction.\n *\n * @group Models\n */\nexport interface TenantClaimSource {\n /**\n * The claim's name on the access token, e.g. `\"org_id\"`.\n *\n * Custom claims survive verification and reach RLS as `rebase.jwt()`; the\n * identity claims (`uid`, `roles`, `aal`, `isAnonymous`) are written after\n * them when a token is minted and cannot be shadowed, so naming one of\n * those here is refused rather than quietly reading the identity.\n */\n claim: string;\n}\n\n/**\n * The caller's tenants come from rows of a membership table.\n *\n * The many-tenants-per-user shape — a `memberships` table with a user column\n * and a tenant column, which is how a person belongs to three organizations at\n * once. Compiles to a correlated `EXISTS` over that table (`policy.existsIn`),\n * so the database answers \"is the caller a member of this row's tenant?\" in the\n * same query rather than in an N+1 of lookups.\n *\n * Nothing is put on the token, so nothing has to be re-minted when somebody\n * joins or leaves a tenant — the next statement already sees the new row.\n *\n * @group Models\n */\nexport interface TenantMembershipSource {\n membership: {\n /** Slug of the table holding the memberships. */\n table: string;\n /** The property on it that holds the user id (compared to `rebase.uid()`). */\n userField: string;\n /** The property on it that holds the tenant id. */\n tenantField: string;\n };\n}\n\n/** Where the caller's tenant comes from. @group Models */\nexport type TenantSource = TenantClaimSource | TenantMembershipSource;\n\n/** Narrow a {@link TenantSource} to its claim form. @group Models */\nexport function isTenantClaimSource(source: TenantSource): source is TenantClaimSource {\n return typeof (source as TenantClaimSource).claim === \"string\";\n}\n\n/** Narrow a {@link TenantSource} to its membership form. @group Models */\nexport function isTenantMembershipSource(source: TenantSource): source is TenantMembershipSource {\n return typeof (source as TenantMembershipSource).membership === \"object\"\n && (source as TenantMembershipSource).membership !== null;\n}\n\n/**\n * The roles tenancy does not apply to, when the collection names none.\n *\n * `admin`, mirroring the security baseline every collection already carries\n * (`<table>_default_admin_read` / `_write`): the Studio, `dataAsAdmin` and a\n * support operator all run with it, and a tenancy rule that locked them out\n * would make the admin panel show an empty table on a collection full of rows.\n *\n * @group Models\n */\nexport const DEFAULT_TENANT_BYPASS_ROLES: readonly string[] = [\"admin\"];\n\n/**\n * Declare a collection tenant-scoped.\n *\n * ```ts\n * export const posts = buildCollection({\n * slug: \"posts\",\n * properties: {\n * orgId: { type: \"string\", validation: { required: true } },\n * title: { type: \"string\" }\n * },\n * tenant: { field: \"orgId\", from: { claim: \"org_id\" } }\n * });\n * ```\n *\n * The property has to exist — this says what a column *means*, it does not\n * conjure one into existence, exactly like `softDelete`. A config naming a\n * property the collection does not declare is refused at boot rather than at\n * the first read.\n *\n * ## What it composes with\n *\n * The injected policy is **restrictive**, so it is ANDed with every permissive\n * policy on the table: `securityRules`, `ownerField`, the injected admin\n * baseline. That is the only composition that is safe by construction — a\n * permissive tenancy policy would OR with the author's rules and a single\n * `access: \"public\"` rule would take the whole tenancy boundary off.\n *\n * Postgres-only. RLS is what enforces it, and an engine without row-level\n * security cannot be given this guarantee by an application-layer filter that\n * a raw query goes around.\n *\n * @group Models\n */\nexport interface CollectionTenantConfig<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * The property holding the tenant id.\n *\n * A `string` or `number` property, or a `reference` / `belongsTo` relation\n * to the tenants collection — in which case the foreign key the relation\n * already declares is the column, and no second one is created.\n *\n * The column is made `NOT NULL` and indexed: a nullable tenant column is a\n * row that belongs to nobody and is therefore invisible to everybody, and\n * an unindexed one turns every RLS-filtered read into a sequential scan.\n */\n field: Extract<keyof M, string> | string;\n\n /** Where the caller's tenant comes from. */\n from: TenantSource;\n\n /**\n * Roles that see and write across every tenant.\n *\n * Defaults to {@link DEFAULT_TENANT_BYPASS_ROLES}. An empty array means\n * \"nobody bypasses\" — the trusted server context still does, because it is\n * what runs migrations and the auth flows, and a policy that excluded it\n * would break the boot rather than protect a tenant.\n */\n bypassRoles?: readonly string[];\n}\n","import type { FilterValues, WhereFilterOp } from \"./filter-operators\";\nimport type { TableHooks } from \"../schema/hooks\";\nimport type { CompiledTable } from \"../schema/compiled\";\nimport type { TableDescriptor } from \"../schema/descriptor\";\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')\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}\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}\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)\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 * This process's realtime counts, for `/metrics`. Read at each scrape, so\n * it must be cheap. Absent on a provider with nothing to count, and the\n * series are then not emitted rather than reported as zeros.\n */\n counts?(): RealtimeCounts;\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 * What one realtime process is carrying. Counts only: a channel's name is\n * customer data and never leaves in a metric.\n * @group Backend\n */\nexport interface RealtimeCounts {\n /** Open sockets on this process. */\n sockets: number;\n /** Channels with a member on this process. */\n channels: number;\n /** Frames this process published to the channel bus, by frame kind. */\n busFramesPublished: Record<string, number>;\n /** Broadcasts and presence changes not published because no other instance had members. */\n busFramesSkipped: number;\n}\n\n// =============================================================================\n// COLLECTION REGISTRY INTERFACES\n// =============================================================================\n\n/**\n * The table registry a data driver builds for itself and returns on\n * `InitializedDriver.tableRegistry`: the compiled tables it serves, by\n * slug. The backend hands it the global hooks and later table hooks through\n * it; it never holds a collection.\n *\n * @group Backend\n */\nexport interface TableRegistryInterface {\n /** The table served at `/api/data/<slug>`, or `undefined`. */\n getTable(slug: string): { readonly descriptor: TableDescriptor } | undefined;\n\n /**\n * Take the global table hooks declared on `initializeRebaseBackend({ hooks })`.\n * Optional so a registry for a driver that runs no hooks still\n * type-checks; a project declaring global hooks over a registry without\n * it is refused at boot.\n */\n setGlobalHooks?(hooks: TableHooks): void;\n\n /**\n * Replace one table's own hooks after boot (`backend.setTableHooks`).\n * Returns whether this registry serves the table.\n */\n setTableHooks?(slug: string, hooks: TableHooks): boolean;\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 * One connection pool a driver holds, as `/metrics` reports it — see\n * {@link SQLAdmin.poolStats}.\n *\n * @group Admin\n */\nexport interface DatabasePoolStats {\n /** Which pool: `primary`, `read` (the replica), `session` (the direct pool for the SQL console). */\n pool: string;\n /** Connections open, busy or idle. */\n total: number;\n /** Open connections nobody holds. */\n idle: number;\n /** Callers queued for a connection. Above zero for long is a pool too small for its load. */\n waiting: number;\n}\n\n/**\n * A sample of the database server behind a source — see\n * {@link SQLAdmin.sampleHealth}. A field is absent when it could not be read\n * (a role without the privilege, an engine without the notion), never zero.\n *\n * @group Admin\n */\nexport interface DatabaseHealthSample {\n /** Client connections on the server, by state (`active`, `idle`, `idle in transaction`, …). */\n connections?: Record<string, number>;\n /** The server's `max_connections`. */\n maxConnections?: number;\n /** The size of this source's database, in bytes. */\n sizeBytes?: number;\n /** How far the read replica is behind the primary, in seconds, when the source has one. */\n replicaLagSeconds?: number;\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 * Ask the database whether it answers, on a connection of its own.\n *\n * For the health check. `executeSql(\"SELECT 1\")` waits for a pooled\n * connection, so a pool that is merely busy (every connection serving a\n * slow request) failed a readiness probe that gives a few seconds — and an\n * orchestrator took a working pod out of service, sending its load to the\n * others or, with one pod, to nobody. Implementations open a connection\n * outside the pool, run the cheapest round trip, and throw if that does not\n * finish within `timeoutMs`. Optional: without it the health check asks\n * through `executeSql` as before.\n */\n probe?(timeoutMs: number): Promise<void>;\n\n /**\n * The connection pools this source holds besides the one the server\n * opened for it — the read replica's, the SQL console's direct one —\n * for `/metrics`. Synchronous and free: counts the pools already keep.\n */\n poolStats?(): DatabasePoolStats[];\n\n /**\n * Sample the server behind this source: connections against\n * `max_connections`, the database's size, the replica's lag. Run every 30\n * seconds by the metrics probe, so the control plane can watch a database\n * it may not be able to reach.\n */\n sampleHealth?(): Promise<DatabaseHealthSample>;\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 schema management.\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`, `isSchemaAdmin`, `isBranchAdmin`)\n * to safely narrow the type before calling methods.\n *\n * @group Admin\n */\nexport type DatabaseAdmin = Partial<SQLAdmin> & 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 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 /** The driver's table registry. */\n tableRegistry: TableRegistryInterface;\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\"`).\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 ensureTableSchema}: 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 ensureTableSchema?(\n tables: readonly CompiledTable[],\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 ensureTableSchema}.\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 ensureTablePolicies?(\n tables: readonly CompiledTable[],\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 schema version this database was last provisioned\n * from, or `null` when nothing has ever stamped it.\n *\n * The companion to {@link stampTablesSchemaVersion}: 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 readTablesSchemaVersion?(\n driverResult?: InitializedDriver\n ): Promise<string | null>;\n\n /**\n * Record the schema version this process just applied.\n *\n * Called only by the process that provisions, and only after both\n * {@link ensureTableSchema} and {@link ensureTablePolicies} 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 stampTablesSchemaVersion?(\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 /** The driver's table registry: what the backend hands global and table hooks to. */\n tableRegistry?: TableRegistryInterface;\n\n /**\n * The descriptors of the tables the driver derived from the live database\n * schema, read from the catalogue (columns as Postgres types, relations\n * from foreign keys, row-level security from `pg_policies`): what the\n * server serves, and `GET /api/schema/tables` describes, for a project\n * that declares no tables. Set by drivers that introspect (`baas` mode);\n * `undefined` means the driver never looked.\n */\n tables?: import(\"../schema/descriptor\").TableDescriptor[];\n\n /**\n * Tables the driver found while deriving {@link tables} 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 /**\n * Serve these tables from now on, without a restart: what a live schema\n * apply (`/api/admin/schema/apply`) calls once its DDL has run, with\n * every compiled table the edited schema holds (hooks included).\n *\n * A driver that can MUST re-read the tables it stores from its own\n * database (a new table, a new or retyped column, a new relation and its\n * junction), keep the hooks the compiled tables carry, provision whatever\n * it provisions at boot for a table it did not serve before (change\n * capture, grants), stop serving a table the list no longer holds, and\n * swap all of it at once: a request sees the tables before the call or\n * those after it. A driver whose tables are unchanged by the list (the\n * edit touched another database's) MUST NOT read its catalogue again.\n *\n * Absent on a driver that cannot: the apply then says the change is\n * applied and served after a restart (`serving` on the result).\n * Rejecting leaves the driver serving the tables it served before.\n */\n refreshTables?(tables: readonly CompiledTable[]): Promise<TableRefreshOutcome>;\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 * What a driver did with the tables a live schema apply handed it\n * ({@link InitializedDriver.refreshTables}).\n *\n * - `served` — it serves them now.\n * - `restart` — it keeps serving the tables it opened with until the process\n * restarts; `reason` says why, in a sentence the Studio shows.\n *\n * @group Backend\n */\nexport type TableRefreshOutcome =\n | { status: \"served\" }\n | { status: \"restart\"; reason: string };\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","/**\n * The vocabulary a live schema change is described in.\n *\n * Declared here, and nowhere else, because two packages that must not import\n * each other both need it: `@rebasepro/server-postgres` decides what a change\n * means and renders the files it needs, while `@rebasepro/server` commits those\n * files and serves the routes. Neither can reach the other — the server is\n * engine-agnostic by design — so the shared kernel holds the shapes and the\n * driver is detected structurally through {@link SchemaEditingAdmin}.\n *\n * Nothing here executes anything. These are the nouns.\n */\nimport type { CompiledTable } from \"../schema/compiled\";\nimport type { TableDescriptor } from \"../schema/descriptor\";\n\n/**\n * What a change will do to a live database.\n *\n * - `safe` — the boot-time ensure path expresses it, and the result matches the\n * configuration.\n * - `diverges` — the ensure path applies *something*, but the database will not\n * match what the configuration declares, and nothing reports it. This is the\n * category worth having: adding a required property to a populated table\n * yields a nullable column, and adding a value to an existing enum yields\n * nothing at all. Both read as success.\n * - `needs-migration` — the ensure path cannot express it. Dropping anything,\n * changing a type, moving a primary key.\n */\nexport type SchemaChangeVerdict = \"safe\" | \"diverges\" | \"needs-migration\";\n\nexport type SchemaChangeKind =\n | \"add-collection\"\n | \"remove-collection\"\n | \"add-property\"\n | \"remove-property\"\n | \"change-property-type\"\n | \"rename-column\"\n | \"add-enum-value\"\n | \"remove-enum-value\"\n | \"change-required\"\n | \"change-primary-key\"\n | \"rename-table\"\n /** A property key renamed while keeping its column: no data moves. */\n | \"rename-property\"\n /** A relation's kind, foreign key or link column changes. */\n | \"change-relation\"\n /** A UNIQUE constraint, an index or an update trigger appears or goes. */\n | \"change-constraint\"\n /** A column's DEFAULT is set, changed or dropped. */\n | \"change-default\"\n /** The proposed collections cannot be planned at all. */\n | \"invalid-collection\"\n /** A collection's row-level security policies change. */\n | \"change-security-rules\";\n\nexport interface SchemaChange {\n kind: SchemaChangeKind;\n verdict: SchemaChangeVerdict;\n /** Collection slug. */\n collection: string;\n /** Property name, where the change is to one. */\n property?: string;\n /** One line, specific: what changed and what it will do. */\n detail: string;\n /** What to do instead, when the verdict is not `safe`. */\n remedy?: string;\n /**\n * What \"Edit source only\" leaves behind for this change: the collection is\n * committed and the database is not touched. Absent on a change that may\n * not be written source-only at all — one that would leave a project that\n * does not start, or reads its data as the wrong type.\n */\n sourceOnly?: string;\n /** The same, in a few words for a commit subject: `column products.sku kept`. */\n kept?: string;\n}\n\nexport interface ClassifiedSchemaChanges {\n changes: SchemaChange[];\n /** The worst verdict present, or `safe` for an empty diff. */\n verdict: SchemaChangeVerdict;\n /** True only when every change is `safe` — the one case an editor may apply. */\n applicable: boolean;\n}\n\n/**\n * Where a project's generated schema artifacts live, relative to the **project**\n * root — which is the repository root only when the project is the whole\n * repository.\n *\n * Here rather than in the Postgres package because it is a contract, not an\n * engine detail: `@rebasepro/server` has to derive these for a project in a\n * subdirectory, and it cannot import a driver to do it.\n */\nexport interface SchemaCommitPaths {\n /** Drizzle schema, imported by the backend. */\n schemaFile: string;\n}\n\n/**\n * The SQL `db push` and `db generate` render — `schema.sql`, `policies.sql` and\n * the rest — is not here, and must not come back. Both commands regenerate it\n * from the collections before reading it, so nothing ever read a committed\n * copy; it lives in the gitignored `.rebase/sql/`. When the commit carried it,\n * it carried a second copy besides: these paths are from the project root,\n * while the CLI writes beside the backend, so a live edit left `drizzle/` and\n * `backend/drizzle/` disagreeing about the schema.\n */\nexport const DEFAULT_COMMIT_PATHS: SchemaCommitPaths = {\n schemaFile: \"backend/src/schema.generated.ts\"\n};\n\n/** One file the commit writes, as content rather than as a path on a disk. */\nexport interface SchemaChangeFile {\n path: string;\n contents: string;\n /** The commit removes this file — a deleted collection. `contents` is ignored. */\n deleted?: boolean;\n}\n\n/**\n * Everything a change needs written and run.\n *\n * Computed without touching a disk or a network. The database is *read* — what\n * a change means depends on what is already there, and a plan that guessed\n * would be guessing about whether the statements it returns will be accepted.\n */\nexport interface SchemaChangePlan {\n /** Every file the commit writes — collection source and generated artifacts. */\n files: SchemaChangeFile[];\n /** The additive DDL this change adds, in dependency order. */\n statements: string[];\n classified: ClassifiedSchemaChanges;\n /** A commit message describing the change rather than announcing one. */\n message: string;\n /**\n * Constraints the configuration asks for that these statements do not\n * carry, and why.\n *\n * Almost always empty. When it is not, it is the part the person confirming\n * needs to read: the change will apply, and the database will still not\n * enforce something the configuration says — a required property over a\n * table that already holds rows with no value for it. Optional so a plan\n * from an engine that does not distinguish these cases stays valid.\n */\n withheldConstraints?: WithheldSchemaConstraint[];\n}\n\n/** A constraint a plan asks for and does not apply. */\nexport interface WithheldSchemaConstraint {\n /** `schema.table.column`. */\n target: string;\n kind: \"not-null\" | \"unique\";\n /** What is in the way, naming the obstacle rather than the rule. */\n reason: string;\n /** What would make it applicable. */\n remedy: string;\n}\n\n/**\n * An admin that can plan a schema change.\n *\n * Planning only. Applying is `executeSql`, which every SQL admin already has,\n * and committing belongs to whatever holds the repository — keeping those three\n * apart is what lets the same plan be committed locally on a developer's machine\n * and through a GitHub App from a cloud tenant.\n *\n * @group Admin\n */\nexport interface SchemaEditingAdmin {\n /**\n * Decide what the change means and render everything it needs.\n *\n * Rejects when the change is not applicable, carrying the classification so\n * a caller can say which change was the problem.\n *\n * @param before The tables the running server serves, compiled.\n * @param after The edited definitions, compiled (`compileSchemaDefs`).\n */\n planSchemaChange(\n before: readonly CompiledTable[],\n after: readonly CompiledTable[],\n options?: {\n paths?: Partial<SchemaCommitPaths>;\n /**\n * Plan a commit of the source alone — \"Edit source only\": never\n * rejects an unapplicable change, carries no statements, and its\n * message names what is left in the database.\n */\n sourceOnly?: boolean;\n }\n ): Promise<SchemaChangePlan>;\n\n /**\n * What it would take to bring the database's existing columns in line with\n * the collections, beyond what boot does on its own.\n *\n * Boot is additive: it never relaxes a constraint and never drops a column,\n * because nobody reads its plan. This is the reviewed counterpart. It\n * plans `DROP NOT NULL` for every column the collections declare optional\n * and the database still requires, lists every column no collection\n * declares, and drops only the ones named in `drop`. Read-only; applying\n * is `executeSql`, gated by the caller on the plan's `digest`.\n *\n * Optional so a driver that cannot answer stays a valid admin.\n */\n planSchemaReconcile?(\n /** The tables the running server serves, compiled. */\n tables: readonly CompiledTable[],\n options?: {\n /** Undeclared columns to drop, as `<collection slug>.<column>`. */\n drop?: string[];\n }\n ): Promise<SchemaReconcilePlan>;\n\n /**\n * The tables of one Postgres schema that no declared table maps — what\n * \"Import an existing table\" offers — each described as introspection\n * reads it, ready to adopt (`adoptTable`). Junction tables and Rebase's\n * own are left out. Only `SELECT`s.\n *\n * Optional so a driver that cannot answer stays a valid admin.\n *\n * @param schema The Postgres schema to read.\n * @param mapped The SQL names of the tables already declared in it.\n */\n describeUnmappedTables?(schema: string, mapped: ReadonlySet<string>): Promise<UnmappedTable[]>;\n}\n\n/**\n * A table the database has and no declared table maps, as \"Import an\n * existing table\" reads it.\n *\n * @group Schema\n */\nexport interface UnmappedTable {\n /** The Postgres schema holding it. */\n schema: string;\n /** The SQL table. */\n table: string;\n /** Row-level security is on (`relrowsecurity`). */\n rlsEnabled: boolean;\n /** How many policies the database holds on it. */\n policies: number;\n /**\n * The table as introspection describes it — columns as their Postgres\n * types, defaults, keys, foreign keys to declared tables as `belongsTo`,\n * enums, the policies as rules — which `adoptTable` writes as its\n * `defineTable` source. Absent when it cannot be imported.\n *\n * Its `rls` is never weaker than what the database enforces: a table whose\n * row-level security is off, or that has no policy, is described\n * `\"admin-only\"` ({@link rlsRaised} says so).\n */\n descriptor?: TableDescriptor;\n /** Set when {@link descriptor}'s `rls` is `\"admin-only\"` because the database protects the table with no rule: the sentence the import shows. */\n rlsRaised?: string;\n /** Why it cannot be imported, when it cannot (no primary key, …). */\n unimportable?: string;\n /** What introspection noted: what a push would not reproduce exactly, and decisions the file states. */\n notes: string[];\n}\n\n/** A column that exists in a collection's table and that no property declares. */\nexport interface SchemaReconcileColumn {\n /** The collection slug whose table holds it. */\n collection: string;\n /** `schema.table`. */\n table: string;\n column: string;\n /** NOT NULL with no default: every insert through the API fails on it. */\n blocksInserts: boolean;\n /** Rows holding a value in it. Counted only for a column being dropped. */\n rowsWithValue?: number;\n}\n\n/**\n * The plan `planSchemaReconcile` returns.\n *\n * `digest` identifies exactly these statements. A caller applies a plan only\n * when handed back the digest the person reviewed, so what runs is what was\n * read, and a database that changed in between is planned and shown again.\n */\nexport interface SchemaReconcilePlan {\n /**\n * Columns whose NOT NULL this plan drops: those declared optional that the\n * database still requires, and those no property declares that block\n * every insert (`undeclared: true`) and are not being dropped. Their data\n * stays.\n */\n relaxed: Array<{ collection: string; table: string; column: string; undeclared?: boolean }>;\n /** Every column no collection declares, dropped or not. */\n undeclared: SchemaReconcileColumn[];\n /** The undeclared columns this plan drops: the ones `drop` named. */\n dropped: SchemaReconcileColumn[];\n /** In order: every `DROP NOT NULL`, then every `DROP COLUMN`. */\n statements: string[];\n /** Why a requested drop cannot be planned. A plan with problems is not applied. */\n problems: string[];\n digest: string;\n}\n","/**\n * The cross-instance transport for channel broadcast and presence, and the\n * contract anyone implementing one has to meet.\n *\n * These types live in `@rebasepro/types` rather than in the Postgres adapter on\n * purpose: a transport package should depend on the contract, not on the\n * database driver that happens to ship the default implementation. A\n * `@rebasepro/channel-bus-<something>` package needs this file and nothing else.\n *\n * Why a transport exists at all: entity/collection realtime already spans\n * instances (CDC, or per-mutation LISTEN/NOTIFY). Channel broadcast and presence\n * did not — they fanned out from per-process maps, so two clients served by\n * different replicas could not see each other, and nothing errored. The bus is\n * the missing hop, and deliberately *only* that hop: which local clients receive\n * a frame stays in the realtime service, so a transport never has to know what a\n * subscription, a WebSocket or a presence roster is.\n */\n\n/**\n * A frame in flight between instances.\n *\n * `sid` identifies the publishing instance. The realtime service drops frames\n * carrying its own `sid` on arrival — local fan-out already happened before the\n * publish — so a transport that echoes a publisher's own messages back to it is\n * still correct, merely wasteful.\n *\n * Keys are spelled out rather than abbreviated. The one shipped transport with a\n * size limit has a pointer path for anything that would approach it, so shaving\n * bytes off key names buys nothing worth the opacity.\n */\nexport type ChannelBusFrame =\n /** A broadcast carrying its payload. */\n | {\n kind: \"broadcast\";\n sid: string;\n channel: string;\n event: string;\n /** Originating client, echoed so receivers can skip it if it is theirs. */\n from?: string;\n /** Sequence number, present only on retained channels. */\n seq?: number;\n payload: unknown;\n }\n /**\n * A broadcast too large for the transport to carry inline: the body is\n * already durable in `rebase.channel_messages`, so the frame carries only\n * its address and each receiver reads it back. Only ever emitted for\n * retained channels, and only by a transport with a finite\n * {@link ChannelBus.maxFrameBytes}.\n */\n | {\n kind: \"broadcast_ref\";\n sid: string;\n channel: string;\n from?: string;\n seq: number;\n }\n /** A presence join/leave/update, small by construction. */\n | {\n kind: \"presence_diff\";\n sid: string;\n channel: string;\n joins: Record<string, Record<string, unknown>>;\n leaves: Record<string, Record<string, unknown>>;\n }\n /**\n * Which channels an instance has members in, so the others can skip\n * publishing to channels nobody else is listening on (see\n * {@link ChannelBus.publishesOnDemand}). `add` is a channel's first local\n * member. A full list comes as `list` parts, the last with `done`, and\n * replaces what was known. `hello` asks everyone for theirs. `channel` is\n * always `\"__peers\"`: a transport drops frames without one.\n */\n | {\n kind: \"channels\";\n sid: string;\n channel: string;\n add?: string[];\n list?: string[];\n done?: boolean;\n hello?: boolean;\n };\n\n/** Receives frames published by *other* instances. */\nexport type ChannelBusHandler = (frame: ChannelBusFrame) => void | Promise<void>;\n\n/**\n * A cross-instance transport.\n *\n * ## What an implementation must guarantee\n *\n * - **`start()` rejects if the transport is unusable.** The caller falls back to\n * in-process delivery when it does. Resolving while disconnected produces a\n * cluster that believes it is connected and silently is not, which is the\n * exact failure this whole mechanism exists to remove.\n * - **`publish()` reaches every *other* instance, or rejects.** Delivery back to\n * the publisher is permitted but pointless (see {@link ChannelBusFrame.sid}).\n * - **`stop()` is idempotent** and releases everything, including anything\n * holding the event loop open.\n * - **A malformed message never throws out of the transport.** Parsing happens\n * inside the implementation; drop and log what you cannot understand, so one\n * bad frame cannot take the listener down.\n *\n * ## What it does *not* have to guarantee\n *\n * - **Ordering.** Retained channels carry `seq`, and the client SDK orders by\n * it. Unsequenced broadcasts are cursor-grade traffic where order is not\n * meaningful.\n * - **Durability.** A frame lost in transit is a missed live update; retained\n * channels repair themselves through the client's `channel_history` replay.\n * - **Exactly-once.** Duplicates are tolerated — retained frames are deduped by\n * `seq`, and presence diffs are idempotent by construction.\n */\nexport interface ChannelBus {\n /**\n * Identifies the transport in logs and in `getChannelBusKind()`. Use your\n * own name; the framework only compares against `\"memory\"` to decide\n * whether publishing is worth attempting at all.\n */\n readonly kind: string;\n\n /**\n * Publish only to channels another instance has members in.\n *\n * For a transport where each publish costs something (the Postgres bus: a\n * query on the primary), the service gossips over the bus which channels each\n * instance serves, and a frame nobody else is waiting for is not published\n * at all. An instance alone publishes nothing. Unset: every frame is published.\n */\n readonly publishesOnDemand?: boolean;\n\n /**\n * Largest frame this transport will carry, in bytes of encoded JSON, or\n * `Infinity` when there is no meaningful ceiling.\n *\n * A broadcast that exceeds it is published as a `broadcast_ref` pointer when\n * the channel is retained, and refused with an error to the sender when it\n * is not. Implementations with no limit should return `Infinity` rather than\n * a large number, so the pointer path is never taken needlessly.\n */\n readonly maxFrameBytes: number;\n\n /** Connect and begin delivering remote frames to `handler`. */\n start(handler: ChannelBusHandler): Promise<void>;\n\n /** Publish a frame to the other instances. */\n publish(frame: ChannelBusFrame): Promise<void>;\n\n /** Disconnect and release resources. Idempotent. */\n stop(): Promise<void>;\n}\n\n/**\n * Which transport to use, for the two that ship with the Postgres adapter.\n *\n * To use one that does not ship here — a Redis package, or your own class —\n * pass the {@link ChannelBus} instance itself instead of a config object.\n *\n * There are deliberately only two built in, and neither adds a service to a\n * deployment. Rebase deploys as Postgres + backend + frontend; a bus that\n * required a message broker would put a second stateful service into every\n * `docker-compose.yml` the CLI scaffolds, for a feature most applications never\n * use. Measured across two backend instances against one Postgres container,\n * the Postgres bus carried ~10k cross-instance messages/second with no losses,\n * and stayed flat out to eight instances — comfortably past what live-cursor\n * collaboration generates. The extension point below is the answer for anyone\n * who does outgrow it.\n */\nexport type ChannelBusConfig =\n /**\n * In-process only — the historical behaviour. Broadcast and presence reach\n * the clients connected to *this* instance and no further.\n */\n | { type: \"memory\" }\n /**\n * Postgres LISTEN/NOTIFY, reusing infrastructure the deployment already has.\n *\n * `pg_notify` caps a payload at 8000 bytes, so a broadcast larger than that\n * is delivered cross-instance only on a *retained* channel, where the\n * notification carries a pointer (`seq`) instead of the message and each\n * receiver reads the body back from `rebase.channel_messages`. An oversized\n * broadcast on an ephemeral channel is refused rather than silently\n * delivered to half the cluster.\n *\n * NOTE: `LISTEN` needs a session-mode connection. Behind PgBouncer in\n * transaction mode this must point at the database directly\n * (`DATABASE_DIRECT_URL`), not at the pooler.\n */\n | {\n type: \"postgres\";\n /** Direct connection for the LISTEN client. Defaults to `DATABASE_DIRECT_URL`. */\n connectionString?: string;\n /**\n * How long to coalesce outgoing frames into a single notification, in\n * milliseconds. Defaults to 10.\n *\n * A notify is a query on your primary database, so under load this is\n * the difference between one query per message and one per window. The\n * window is leading-edge: a frame arriving when none is open goes out\n * immediately, so an idle channel pays no added latency and only a\n * sustained stream is batched.\n *\n * Set to 0 to disable coalescing and send every frame on its own.\n */\n batchWindowMs?: number;\n };\n\n/**\n * What `realtime.bus` accepts: a built-in transport by name, or any\n * {@link ChannelBus} instance.\n *\n * ```typescript\n * realtime: { bus: { type: \"postgres\" } } // shipped\n * realtime: { bus: new MyRedisChannelBus(url) } // a separate package, or your own\n * ```\n */\nexport type ChannelBusSetting = ChannelBusConfig | ChannelBus;\n\n/**\n * Whether `setting` is an already-constructed transport rather than a request\n * for a built-in one.\n *\n * Structural rather than nominal so that an instance from a *different copy* of\n * `@rebasepro/types` — an entirely normal outcome of a separately versioned\n * transport package — is still recognised.\n */\nexport function isChannelBusInstance(setting: ChannelBusSetting | undefined): setting is ChannelBus {\n return typeof (setting as ChannelBus | undefined)?.publish === \"function\";\n}\n","import { ALL_WHERE_FILTER_OPS, WhereFilterOp } from \"./filter-operators\";\n\n/**\n * Describes the capabilities and features supported by a data source (driver).\n *\n * Each driver (Postgres, Firebase, etc.) declares which features it\n * supports. The admin uses this descriptor to:\n * - Show/hide editor tabs (e.g. Relations for SQL, Subcollections for Firebase)\n * - Filter the property type picker (e.g. `relation` for SQL, `reference` for Firebase)\n * - Toggle driver-specific form controls (e.g. `columnType` for SQL)\n *\n * @group Models\n */\nexport interface DataSourceCapabilities {\n /** Unique driver key (e.g. \"postgres\", \"firestore\") */\n key: string;\n\n /** Human-readable label for the UI (e.g. \"PostgreSQL\", \"Firebase / Firestore\") */\n label: string;\n\n // ── Feature flags ─────────────────────────────────────────────────\n /** Does this source support SQL-style relations (JOINs)? */\n supportsRelations: boolean;\n\n /** Does this source support nested subcollections? */\n supportsSubcollections: boolean;\n\n /** Does this source support Row Level Security policies? */\n supportsRLS: boolean;\n\n /** Does this source support document references (Firebase-style)? */\n supportsReferences: boolean;\n\n /** Does this source support SQL column type annotations? */\n supportsColumnTypes: boolean;\n\n /** Does this source support real-time listeners? */\n supportsRealtime: boolean;\n\n /**\n * Does this source store vectors natively?\n *\n * `VectorProperty` carries a `dimensions` and is pgvector-shaped. It was\n * the one driver-specific property kind with no flag to gate it, so unlike\n * every other field in this descriptor there was not even a runtime answer\n * to appeal to — a Firestore collection could declare an embedding column\n * and no driver would do anything with it.\n */\n supportsVectors: boolean;\n\n /**\n * Canonical filter operators this engine can execute.\n *\n * The admin UI intersects this set with the property-type defaults and\n * any per-property narrowing (`property.ui.filterOperators`) to decide\n * which operators to offer in filter fields — so an engine that cannot\n * run `ilike` (e.g. Firestore) never shows a \"Contains\" filter that\n * would throw at query time.\n */\n filterOperators: readonly WhereFilterOp[];\n\n /**\n * Relation kinds this engine's driver can compile into a filter.\n *\n * Only `belongsTo` puts a column on the row being filtered; the others are\n * answered with a correlated subquery over the junction or the target\n * table, which not every driver can build. An engine with no relations at\n * all declares none.\n *\n * The admin uses this to decide whether a relation column offers a filter\n * control. Offering one an engine cannot answer is not cosmetic: a driver\n * that drops the key it cannot resolve *widens* the read to every row, and\n * one that fails closed answers a control the admin itself put on screen\n * with a 400.\n *\n * Optional, so a third-party driver registered before this existed still\n * compiles. Omitted means {@link DEFAULT_FILTERABLE_RELATION_KINDS} — the\n * one kind that is a plain column comparison, which every relational\n * driver can do. The subquery kinds are a real capability and have to be\n * claimed rather than assumed: assuming them wrongly is the widening.\n */\n filterableRelationKinds?: readonly string[];\n\n /**\n * Can a filter address a *column of the related row* — `applications.status`\n * — rather than only the related row's id?\n *\n * A separate capability from {@link filterableRelationKinds} because it is\n * a separate subquery: the id filter stops at the junction, one of these\n * reaches the target table and compares one of its columns. A driver can\n * do the first and not the second.\n *\n * Optional and defaulting to **false**, for the reason the relation kinds\n * default narrow: an unclaimed capability that the admin assumes is there\n * produces a control whose query the driver answers by dropping the key —\n * and a dropped filter key widens the read to every row.\n *\n * Meaningless without {@link supportsRelations}; a driver with no relations\n * has nothing to reach through.\n */\n supportsRelationFieldFilters?: boolean;\n\n /**\n * Can a sort key be an aggregate over a to-many relation — \"oldest waiting\n * first\", \"busiest first\"?\n *\n * Compiled as a correlated scalar subquery in `ORDER BY`, which a document\n * store cannot express at all. Optional and defaulting to **false**.\n *\n * A wrongly claimed sort capability fails differently from a wrongly\n * claimed filter one, and worse in one respect: a driver that cannot\n * resolve the key drops the `ORDER BY` and answers 200 with rows in\n * whatever order the database pleased, which reads as a sorted list. Paging\n * over that repeats and skips rows.\n */\n relationAggregateSorts?: boolean;\n\n // ── Admin capability flags ───────────────────────────────────────\n /** Does this source support SQL admin operations (SQL editor, EXPLAIN, etc.)? */\n supportsSQLAdmin: boolean;\n\n /** Does this source support schema admin (unmapped tables, table metadata)? */\n supportsSchemaAdmin: boolean;\n}\n\n/**\n * Subset of DataSourceCapabilities containing only feature flags.\n * Useful when you only need to check capabilities without UI metadata.\n * @group Models\n */\nexport type DataSourceFeatures = Omit<DataSourceCapabilities, \"key\" | \"label\">;\n\n/**\n * The default data-source key, used when a collection does not name a\n * `dataSource`. Shared by the frontend router and the backend driver\n * registry so both agree on \"the default database\".\n * @group Models\n */\nexport const DEFAULT_DATA_SOURCE_KEY = \"(default)\";\n\n/**\n * How the *frontend* reaches a data source.\n *\n * - `\"server\"` — through the Rebase backend (the `RebaseClient`). The backend\n * holds the actual database adapter and routes by data-source key. This is\n * the default and covers Postgres, the only server engine.\n * - `\"direct\"` — straight from the client to the external backend via its own\n * SDK driver (e.g. Firestore). The Rebase backend is not in the data path.\n * - `\"custom\"` — a developer-supplied {@link DataDriver}, transport unspecified.\n *\n * @group Models\n */\nexport type DataSourceTransport = \"server\" | \"direct\" | \"custom\";\n\n/**\n * Declarative definition of a data source — a named place data lives.\n *\n * Declared once and shared front and back: the frontend uses it to decide\n * transport (client vs direct driver), the backend uses the same `key` to\n * resolve a database adapter, and the editor derives capabilities from\n * `engine`. Collections reference a definition by its `key` via\n * `collection.dataSource`.\n *\n * @group Models\n */\nexport interface DataSourceDefinition {\n /**\n * Unique identifier for this data source. Collections point at it via\n * `dataSource`. Defaults to {@link DEFAULT_DATA_SOURCE_KEY}.\n */\n key: string;\n\n /**\n * The engine backing this data source (e.g. `\"postgres\"`,\n * `\"firestore\"`, or a custom id). Determines the\n * {@link DataSourceCapabilities} surfaced in the editor.\n */\n engine: string;\n\n /**\n * How the frontend reaches this source. Optional — when omitted it is\n * inferred: `\"direct\"` if the definition carries a client-side driver,\n * `\"server\"` otherwise.\n */\n transport?: DataSourceTransport;\n\n /**\n * The physical database/schema/Firestore-database within the engine.\n * Threaded to drivers/adapters as the existing `databaseId` runtime\n * parameter. Defaults to the engine's own default.\n */\n databaseId?: string;\n\n /** Human-readable label for the UI. */\n label?: string;\n}\n\n/**\n * The resolved data source for a collection: the single source of truth that\n * the frontend router, backend registry, and editor all derive from.\n * Produced by `resolveDataSource(collection, registry)`.\n *\n * @group Models\n */\nexport interface ResolvedDataSource {\n /** Data-source key (routing key, shared front + back). */\n key: string;\n /** Engine backing the source (drives capabilities). */\n engine: string;\n /** Frontend transport. */\n transport: DataSourceTransport;\n /** Within-engine instance, if any (the `databaseId` runtime param). */\n databaseId?: string;\n /** Capabilities derived from {@link engine}. */\n capabilities: DataSourceCapabilities;\n}\n\n/**\n * Relation kinds assumed filterable when a driver does not say.\n *\n * `belongsTo` alone: its filter is a comparison on a column of the row being\n * filtered, the one shape that needs no query construction a driver might not\n * have. Everything else is a correlated subquery over another table.\n *\n * @group Models\n */\nexport const DEFAULT_FILTERABLE_RELATION_KINDS: readonly string[] = [\"belongsTo\"];\n\n// ── Built-in driver capabilities ─────────────────────────────────────\n\n/** @group Models */\nexport const POSTGRES_CAPABILITIES: DataSourceCapabilities = {\n key: \"postgres\",\n label: \"PostgreSQL\",\n supportsRelations: true,\n supportsSubcollections: false,\n supportsRLS: true,\n supportsReferences: false,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // `via` is absent: its join path is authored source → target with no\n // stated inverse, so the driver has nothing to reverse into a filter.\n filterableRelationKinds: [\"belongsTo\", \"manyToMany\", \"hasMany\", \"hasOne\"],\n supportsRelationFieldFilters: true,\n relationAggregateSorts: true,\n supportsSQLAdmin: true,\n supportsSchemaAdmin: true\n};\n\n/** @group Models */\nexport const FIREBASE_CAPABILITIES: DataSourceCapabilities = {\n key: \"firestore\",\n label: \"Firebase / Firestore\",\n supportsRelations: false,\n supportsSubcollections: true,\n supportsRLS: false,\n supportsReferences: true,\n supportsColumnTypes: false,\n supportsRealtime: true,\n supportsVectors: false,\n // Firestore has no SQL pattern matching — the driver throws on the LIKE\n // family, so the UI must never offer it.\n filterOperators: ALL_WHERE_FILTER_OPS.filter(op =>\n op !== \"like\" && op !== \"ilike\" && op !== \"not-like\" && op !== \"not-ilike\"\n // Firestore matches one element or any of a list; no query asks for all of them, or for none outside one.\n && op !== \"array-contains-all\" && op !== \"array-contained-by\"),\n // No relations at all — a document store links by reference. Nothing to\n // reach through, so neither of the two relation-reaching features either.\n filterableRelationKinds: [],\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: false,\n supportsSchemaAdmin: false\n};\n\n/**\n * Fallback capabilities when the driver is unknown.\n * Enables everything so nothing is hidden unexpectedly.\n * @group Models\n */\nexport const DEFAULT_CAPABILITIES: DataSourceCapabilities = {\n key: \"(default)\",\n label: \"Default\",\n supportsRelations: true,\n supportsSubcollections: true,\n supportsRLS: true,\n supportsReferences: true,\n supportsColumnTypes: true,\n supportsRealtime: true,\n supportsVectors: true,\n filterOperators: ALL_WHERE_FILTER_OPS,\n // The exception to this descriptor's \"enable everything\" rule. The other\n // flags hide a tab or a picker when they are wrong; this one decides\n // whether a query is sent that an unknown driver may answer by dropping\n // the condition — which returns every row rather than none.\n filterableRelationKinds: DEFAULT_FILTERABLE_RELATION_KINDS,\n // Narrow for the same reason, and more sharply. An unknown driver that is\n // assumed to compile these answers by dropping the key: the filter widens\n // the read to every row, and the sort comes back unordered while looking\n // sorted. Both have to be claimed.\n supportsRelationFieldFilters: false,\n relationAggregateSorts: false,\n supportsSQLAdmin: true,\n supportsSchemaAdmin: true\n};\n\nconst BUILT_IN_CAPABILITIES: ReadonlyMap<string, DataSourceCapabilities> = new Map([\n [\"postgres\", POSTGRES_CAPABILITIES],\n [\"firestore\", FIREBASE_CAPABILITIES],\n [\"(default)\", DEFAULT_CAPABILITIES]\n]);\n\n/**\n * Capabilities registered at runtime, on `globalThis` rather than in a module\n * local: a third-party driver inlines its own copy of this package and\n * registers through it, while the app and the server read through theirs. A\n * module local made the registration land in a copy nobody else reads.\n * See `module-state-across-copies.test.ts`.\n */\nconst REGISTERED_CAPABILITIES_KEY = Symbol.for(\"@rebasepro/types.dataSourceCapabilities.v1\");\n\ntype GlobalWithCapabilities = typeof globalThis & {\n [REGISTERED_CAPABILITIES_KEY]?: Map<string, DataSourceCapabilities>;\n};\n\nfunction registeredCapabilities(): Map<string, DataSourceCapabilities> {\n const g = globalThis as GlobalWithCapabilities;\n let registered = g[REGISTERED_CAPABILITIES_KEY];\n if (!registered) {\n registered = new Map();\n g[REGISTERED_CAPABILITIES_KEY] = registered;\n }\n return registered;\n}\n\n/**\n * Look up capabilities for a given engine key.\n * If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.\n * @group Models\n */\nexport function getDataSourceCapabilities(engine?: string): DataSourceCapabilities {\n if (!engine) return POSTGRES_CAPABILITIES; // postgres is the default engine\n return registeredCapabilities().get(engine) ?? BUILT_IN_CAPABILITIES.get(engine) ?? DEFAULT_CAPABILITIES;\n}\n\n/**\n * Register custom capabilities for a third-party driver.\n * @group Models\n */\nexport function registerDataSourceCapabilities(capabilities: DataSourceCapabilities): void {\n registeredCapabilities().set(capabilities.key, capabilities);\n}\n","/**\n * The resource graph: one declaration site for every named thing a project needs.\n *\n * ## The rule\n *\n * **Every named resource is declared with a constructor in config code.** A\n * database, a bucket, a topic and whatever kind comes next are all spelled the\n * same way, so \"where do I declare my second one\" has one answer instead of one\n * answer per kind.\n *\n * ```ts\n * export const main = database(\"main\");\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * export const signups = topic<SignupEvent>(\"signups\");\n * ```\n *\n * ## Declaration is not binding\n *\n * A declaration says a resource *exists* and what shape it has. It never says\n * how to reach it — that is a property of the environment, not of the project,\n * and it differs between a laptop, a self-hosted box and a tenant in the cloud.\n * Binding lives in `@rebasepro/server`'s boot path, where each kind registers\n * the resolver that reads its environment variables, keyed off the logical\n * name declared here.\n *\n * This split is the whole point. Before it, storage topology was hand-written\n * into `rebase.json` while database topology lived in TypeScript, and the\n * boundary between them was a fact about what the control plane could read\n * before a build — a platform implementation detail that a developer had no way\n * to derive. Worse, storage could be declared in *both* places, and the merge\n * silently kept the JSON's engine and discarded the code's.\n *\n * ## Why a registry rather than a fixed union\n *\n * Kinds register themselves. Adding pub/sub, a cache or a search index must not\n * require editing a manifest schema, a validator and three switch statements —\n * that cost is exactly why the last two kinds ended up in different homes.\n */\n\n/** How a client reaches a resource. */\nexport type ResourceTransport =\n /** Through the backend. The default, and the only one that needs no client SDK. */\n | \"server\"\n /** A provider SDK talks to the resource directly; the backend is not in the path. */\n | \"direct\";\n\n/**\n * A resource kind, as registered.\n *\n * `engines` is an allowlist rather than documentation. An unrecognised engine\n * used to be a free string that passed every check and failed later, further\n * from the typo that caused it — `\"s2\"` for `\"s3\"` reached the runtime. Anything\n * genuinely outside the list is spelled `custom:<id>`, which says so at the call\n * site instead of looking like a typo.\n */\nexport interface ResourceKindSpec {\n /** The kind's name, as it appears in a declaration and in the graph. */\n kind: string;\n /**\n * Which definition of this kind this is. Bump it whenever anything else in\n * the spec changes.\n *\n * Two copies of this package can meet in one process — a published driver\n * inlines it into its dist, and the runtime image ships its own — and the\n * registry is shared between them on purpose. Without a revision the only\n * thing the registry can do with two specs that differ is refuse, and a\n * refusal at driver load is a pod that never boots: every bundle built with\n * a driver older than the change dies on the first image that carries it.\n * With one, the higher revision wins whichever copy loads first, and the\n * older copy is told so. Missing means 0, which is what every copy shipped\n * before revisions existed reports.\n *\n * Only copies that know about revisions honour them. A copy published\n * BEFORE they existed still compares the whole literal and throws, so a\n * kind that has shipped in such a copy cannot change its literal at all —\n * not even to add this field. Correct those kinds with `amendResourceKind`.\n */\n revision?: number;\n /** Engines this kind ships with. `custom:<id>` is always additionally valid. */\n engines: readonly string[];\n /** Used when a declaration names none. */\n defaultEngine: string;\n /**\n * Environment variable base names this kind binds from, in the order a\n * binder should try them. A resource keyed `analytics` reads\n * `<BASE>__ANALYTICS`; the default-keyed resource reads `<BASE>` unsuffixed,\n * so a single-resource project configured the obvious way declares nothing.\n */\n envBases: readonly string[];\n /**\n * The subset of `envBases` that matters for a given engine.\n *\n * The binder reads every base and takes whichever is set — harmless, and it\n * keeps binding tolerant. A GENERATOR cannot be that relaxed: `rebase eject\n * infra` writing S3_BUCKET, GCS_BUCKET, STORAGE_BUCKET and\n * STORAGE_PUBLIC_URL for a `local` bucket hands somebody four variables of\n * which three are noise, and a config file full of irrelevant keys is one\n * nobody reads carefully.\n *\n * Keyed by engine; an engine with no entry falls back to all of them, which\n * is the honest answer for one this package has never heard of.\n */\n envBasesByEngine?: Readonly<Record<string, readonly string[]>>;\n /** Option keys this kind accepts beyond the common ones, for validation. */\n optionKeys?: readonly string[];\n /**\n * Whether a project implicitly has one of these even when it declares\n * nothing. True for databases — a backend without one is not a backend —\n * and false for topics, where zero is the normal number.\n */\n implicitDefault?: boolean;\n}\n\n/** The key a resource takes when a project declares only one of its kind. */\nexport const DEFAULT_RESOURCE_KEY = \"(default)\";\n\n/** A declared resource, as it appears in the graph. */\nexport interface ResourceDeclaration {\n kind: string;\n /** Unique within its kind. What a binder looks up and what an env suffix is built from. */\n key: string;\n engine: string;\n transport: ResourceTransport;\n label?: string;\n /** Kind-specific options, validated against the kind's `optionKeys`. */\n options: Readonly<Record<string, unknown>>;\n /**\n * What in the project reaches this resource, as `<what>:<name>` — a\n * `collection:posts` routed to a database, a `property:posts.cover` stored\n * in a bucket, a `function:report` importing a handle.\n *\n * Recorded by the derive step, never by a constructor: a declaration says\n * a resource exists, and only a reader that has evaluated the rest of the\n * project can say who uses it. It is the map a host needs to split a\n * monolith into units later, and the map a console needs to answer \"what\n * breaks if I remove this\". Absent when nothing was recorded, which is\n * different from an empty list.\n */\n usedBy?: readonly string[];\n}\n\n/**\n * The value a constructor returns.\n *\n * Carries its own declaration so config code can hold it and pass it around,\n * and stringifies to its key so it drops into the places that still take one.\n * Collections name a data source by string today; a handle works there without\n * the collection API having to change, which keeps this a config redesign\n * rather than a rewrite of the data layer.\n */\nexport interface ResourceHandle extends ResourceDeclaration {\n toString(): string;\n}\n\nconst BRAND = Symbol.for(\"@rebasepro/types.resource\");\n\n/** Whether a value is a resource handle rather than a plain string key. */\nexport function isResourceHandle(value: unknown): value is ResourceHandle {\n return typeof value === \"object\" && value !== null && BRAND in value;\n}\n\n/**\n * A reference to a resource where a key is expected: the handle a constructor\n * returned, or the key spelled as a string.\n *\n * The handle is the point. `dataSource: analytics` is the same name spelled\n * once — rename the export and every use follows, jump-to-definition lands on\n * the declaration, and the derive step can record who uses what. The string\n * form stays because a key has to survive serialisation: the runtime and the\n * admin UI read collections as plain data, where a handle cannot travel.\n */\nexport type ResourceRef = string | ResourceHandle;\n\n/** The key a resource reference names, whether it is a handle or already a key. */\nexport function resourceKeyOf(ref: ResourceRef): string {\n return isResourceHandle(ref) ? ref.key : ref;\n}\n\n/**\n * Replace every resource handle inside a value with its key, deeply.\n *\n * Applied where authored config becomes data: `defineCollection`, the\n * collection loaders, the derive step. Past that point a collection is plain\n * data that serialises, compares with `===` and reaches the admin UI over the\n * wire, so a handle must not survive into it. Plain objects and arrays are\n * walked; anything else — a function, a Date, a class instance — is a leaf and\n * is returned as it is, which is what keeps callbacks and validators intact.\n */\nexport function resolveResourceRefs<T>(value: T): T {\n if (isResourceHandle(value)) return value.key as T;\n // Identity-preserving: a value with no handle inside comes back as the\n // same object, not a copy. Collections point at each other through\n // `target: () => authors`, and a loader that cloned every collection would\n // leave those closures returning the originals while everything else\n // held the copies. A collection that `defineCollection` already\n // normalised passes through here untouched.\n if (Array.isArray(value)) {\n let changed = false;\n const out = value.map(item => {\n const next = resolveResourceRefs(item);\n if (next !== item) changed = true;\n return next;\n });\n return (changed ? out : value) as T;\n }\n if (value !== null && typeof value === \"object\") {\n const proto = Object.getPrototypeOf(value);\n if (proto === Object.prototype || proto === null) {\n let changed = false;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n const next = resolveResourceRefs(v);\n if (next !== v) changed = true;\n out[k] = next;\n }\n return (changed ? out : value) as T;\n }\n }\n return value;\n}\n\n/**\n * The process-wide registry.\n *\n * Keyed off `globalThis` through a shared symbol rather than held in a module\n * local, because a module local is per *copy* of this package. A project that\n * ends up with two copies of `@rebasepro/types` — which a partially-linked\n * `node_modules` produces, and which has already caused a phantom\n * \"JWT secret not configured\" bug in this repo — would otherwise register into\n * one registry and read from the other, and see an empty graph with nothing\n * anywhere to explain it.\n *\n * `declarations` is that shared map, and stays shared: it is what a project\n * writes and what every copy has to be able to read.\n *\n * `kinds` is NOT, and the distinction is the whole point of `KINDS_KEY` below.\n */\ninterface Registry {\n /** Kinds this copy and its peers agree on — the versioned map. */\n kinds: Map<string, ResourceKindSpec>;\n /** Kinds written by a copy that predates the versioned map. Read-only here. */\n legacyKinds: Map<string, ResourceKindSpec>;\n declarations: Map<string, ResourceDeclaration>;\n}\n\nconst GLOBAL_KEY = Symbol.for(\"@rebasepro/types.resourceRegistry\");\n\n/**\n * Where kinds live, versioned — and why the version is in the symbol.\n *\n * Sharing one kinds map across copies means the copy that registers SECOND is\n * the one that runs the comparison. That copy is whatever the bundle happens to\n * carry, which for a driver is a build of this package frozen at its release —\n * so the rule enforced is the rule that shipped THEN, not the one written here.\n *\n * `revision` (390bb03cd, applied to `database` in 346df48e2) was supposed to\n * settle a disagreement between two copies, and it settles it only when the\n * copy doing the arithmetic knows what `revision` is. 0.17.0–0.17.3 do not:\n * they deep-equal the spec and throw. The runtime registers at import and a\n * driver is imported after it, so the old copy is always second, always the\n * judge, and always throws — verified by the bundle corpus on 2026-09-07,\n * which reported v0.17.3's message verbatim (\"Two packages cannot define the\n * same kind.\", no revision clause) while the runtime it ran on was 0.18.\n *\n * So copies that understand `revision` keep their kinds here, under a symbol\n * no released copy looks at, and the legacy map is left to whoever still wants\n * it. An old copy then registers into a map nobody contests, finds no existing\n * entry, and cannot throw — in any load order, which is what the previous fix\n * only claimed. Bumping this suffix again is how a future change to the\n * REGISTRATION PROTOCOL is made; a change to a kind's own definition is still\n * `revision`, among peers that share this map.\n */\nconst KINDS_KEY = Symbol.for(\"@rebasepro/types.resourceKinds.v2\");\n\nfunction registry(): Registry {\n const g = globalThis as Record<symbol, unknown>;\n let shared = g[GLOBAL_KEY] as { kinds: Map<string, ResourceKindSpec>; declarations: Map<string, ResourceDeclaration> } | undefined;\n if (!shared) {\n // `kinds` is created but never written by this copy: an older copy's\n // own `registry()` returns this object as-is once it exists, and would\n // throw on `undefined.get` if the property were absent.\n shared = { kinds: new Map(), declarations: new Map() };\n g[GLOBAL_KEY] = shared;\n }\n let kinds = g[KINDS_KEY] as Map<string, ResourceKindSpec> | undefined;\n if (!kinds) {\n kinds = new Map();\n g[KINDS_KEY] = kinds;\n }\n return { kinds, legacyKinds: shared.kinds, declarations: shared.declarations };\n}\n\n/**\n * Every kind visible to this copy: the versioned map, plus anything only a\n * legacy copy registered.\n *\n * The fallback is not for Rebase's own kinds — this copy defines all of those —\n * but for a third-party driver built against an older `@rebasepro/types` that\n * registers a kind of its own. Dropping it would make that kind invisible and\n * turn `declareResource` into \"unknown resource kind\" for something genuinely\n * registered.\n */\nfunction visibleKinds(): Map<string, ResourceKindSpec> {\n const { kinds, legacyKinds } = registry();\n if (legacyKinds.size === 0) return kinds;\n const merged = new Map(legacyKinds);\n for (const [k, v] of kinds) merged.set(k, v);\n return merged;\n}\n\n/**\n * Corrections this copy applies on top of a registered kind.\n *\n * Deliberately a module local — per COPY of this package — where the registry\n * above is deliberately shared. A published driver inlines this package into\n * its dist, and the copy it carries compares the shared registry's entry for a\n * kind against its own literal by `JSON.stringify` and throws if they differ\n * (see `registerResourceKind` before revisions existed). That code is in the\n * field and cannot be changed, so the registered literal of any kind that has\n * ever shipped is frozen: change one enumerable key and every bundle built with\n * an older driver dies at driver load on the next image. What a kind actually\n * binds can still be corrected — here, read through `resourceKind()` and\n * everything built on it, invisible to the older copy, which keeps binding the\n * way it did when it was published.\n */\ntype KindAmendment = Partial<Pick<ResourceKindSpec, \"envBases\" | \"envBasesByEngine\" | \"optionKeys\">>;\nconst amendments = new Map<string, KindAmendment>();\n\n/**\n * Correct a registered kind without touching its registered literal.\n *\n * Use this, never an edit to the literal, for a kind that has shipped in a\n * published package. The amendment applies to reads through this copy only.\n */\nexport function amendResourceKind(kind: string, amendment: KindAmendment): void {\n amendments.set(kind, { ...amendments.get(kind), ...amendment });\n}\n\n/** A registered kind as this copy sees it: the shared literal plus this copy's amendments. */\nfunction effectiveKind(spec: ResourceKindSpec): ResourceKindSpec {\n const amendment = amendments.get(spec.kind);\n return amendment ? { ...spec, ...amendment } : spec;\n}\n\n/** `kind:key`, the graph's primary key. */\nfunction declarationId(kind: string, key: string): string {\n return `${kind}:${key}`;\n}\n\n/**\n * Register a resource kind.\n *\n * Idempotent for an identical spec. When a spec for the same kind is already\n * registered and differs, the `revision` decides: the higher one is kept and\n * the other copy is warned about, in either load order. Two different specs at\n * the SAME revision are a genuine conflict — two packages defining one kind, or\n * a change that forgot to bump — and still throw.\n *\n * Both copies in that comparison are peers on `KINDS_KEY`, which is what makes\n * the rule enforceable: a copy old enough not to know `revision` writes to the\n * legacy map instead and never reaches this function's arithmetic. Registering\n * a kind an older copy already put in the legacy map is therefore not a\n * conflict — it is the ordinary case, and `visibleKinds` prefers this one.\n */\nexport function registerResourceKind(spec: ResourceKindSpec): void {\n const kinds = registry().kinds;\n const existing = kinds.get(spec.kind);\n if (!existing) {\n kinds.set(spec.kind, spec);\n return;\n }\n if (JSON.stringify(existing) === JSON.stringify(spec)) return;\n\n const have = existing.revision ?? 0;\n const incoming = spec.revision ?? 0;\n if (have === incoming) {\n throw new Error(\n `Resource kind \"${spec.kind}\" is already registered with a different definition at revision ${have}. ` +\n \"Two packages cannot define the same kind; a newer definition of the same kind must carry a higher `revision`.\"\n );\n }\n const [kept, dropped] = incoming > have ? [spec, existing] : [existing, spec];\n if (kept === spec) kinds.set(spec.kind, spec);\n // No logger below @rebasepro/server, and this runs in browsers too.\n console.warn(\n `[resources] Resource kind \"${spec.kind}\" is registered twice, at revisions ${dropped.revision ?? 0} and ` +\n `${kept.revision ?? 0}; keeping revision ${kept.revision ?? 0}. The older copy is usually @rebasepro/types ` +\n \"inlined in a driver built before the kind changed — rebuild the project with a current driver to remove it.\"\n );\n}\n\n/** Every registered kind, for validators and for `rebase doctor`. */\nexport function resourceKinds(): ResourceKindSpec[] {\n return [...visibleKinds().values()].map(effectiveKind);\n}\n\n/** One registered kind, or undefined. */\nexport function resourceKind(kind: string): ResourceKindSpec | undefined {\n const spec = visibleKinds().get(kind);\n return spec && effectiveKind(spec);\n}\n\n/** Options every kind accepts. */\nexport interface DeclareOptions {\n engine?: string;\n transport?: ResourceTransport;\n label?: string;\n [option: string]: unknown;\n}\n\nconst COMMON_OPTION_KEYS = [\"engine\", \"transport\", \"label\"] as const;\n\n/** Whether an engine is one the kind knows, or an explicit `custom:` opt-out. */\nexport function isValidEngine(spec: ResourceKindSpec, engine: string): boolean {\n return engine.startsWith(\"custom:\") || spec.engines.includes(engine);\n}\n\n/**\n * Declare a resource. The primitive every kind's constructor is built from.\n *\n * Redeclaring the same `kind:key` with a *different* shape throws rather than\n * merging. Merging is what the old storage path did, and it silently discarded\n * one of the two engines — a declaration accepted and then ignored, which is\n * the failure this whole model exists to remove. Redeclaring it identically is\n * fine: a config module evaluated twice must not be an error.\n */\nexport function declareResource(\n kind: string,\n key: string = DEFAULT_RESOURCE_KEY,\n options: DeclareOptions = {}\n): ResourceHandle {\n const spec = resourceKind(kind);\n if (!spec) {\n const known = [...visibleKinds().keys()].sort().join(\", \") || \"none\";\n throw new Error(\n `Unknown resource kind \"${kind}\". Registered kinds: ${known}. ` +\n \"Call registerResourceKind() before declaring one.\"\n );\n }\n\n if (!key || typeof key !== \"string\" || key.trim() === \"\") {\n throw new Error(`A ${kind} needs a non-empty key.`);\n }\n\n const engine = options.engine ?? spec.defaultEngine;\n if (!isValidEngine(spec, engine)) {\n throw new Error(\n `Unknown ${kind} engine \"${engine}\" for \"${key}\". ` +\n `Known engines: ${spec.engines.join(\", \")}. ` +\n `An engine this build does not ship is spelled \"custom:${engine}\", ` +\n \"which says so at the call site rather than failing later.\"\n );\n }\n\n const allowed = new Set<string>([...COMMON_OPTION_KEYS, ...(spec.optionKeys ?? [])]);\n const unknown = Object.keys(options).filter(k => !allowed.has(k));\n if (unknown.length > 0) {\n throw new Error(\n `Unknown option(s) on ${kind} \"${key}\": ${unknown.join(\", \")}. ` +\n `A ${kind} accepts: ${[...allowed].sort().join(\", \")}.`\n );\n }\n\n const extra: Record<string, unknown> = {};\n for (const k of spec.optionKeys ?? []) {\n if (options[k] !== undefined) extra[k] = options[k];\n }\n\n const declaration: ResourceDeclaration = {\n kind,\n key,\n engine,\n transport: options.transport ?? \"server\",\n ...(options.label !== undefined ? { label: options.label } : {}),\n options: Object.freeze(extra)\n };\n\n const id = declarationId(kind, key);\n const previous = registry().declarations.get(id);\n if (previous) {\n if (JSON.stringify(previous) !== JSON.stringify(declaration)) {\n throw new Error(\n `${kind} \"${key}\" is declared twice with different configuration. ` +\n \"Declare it once and export it — two declarations of one resource is \" +\n \"the ambiguity this model exists to remove, so it is refused rather \" +\n \"than merged.\"\n );\n }\n } else {\n registry().declarations.set(id, declaration);\n }\n\n const handle = {\n ...declaration,\n toString() { return key; },\n [BRAND]: true as const\n };\n return handle as ResourceHandle;\n}\n\n/** Every declared resource, in declaration order, optionally filtered by kind. */\nexport function declaredResources(kind?: string): ResourceDeclaration[] {\n const all = [...registry().declarations.values()];\n return kind ? all.filter(r => r.kind === kind) : all;\n}\n\n/**\n * Forget every declaration, keeping registered kinds.\n *\n * For tests and for a CLI that evaluates more than one project in a process.\n * Kinds survive because they are registered by module import, which will not\n * happen a second time.\n */\nexport function resetDeclaredResources(): void {\n registry().declarations.clear();\n}\n\n/**\n * The env-var suffix a resource's bindings use: `__ANALYTICS` for `analytics`,\n * and nothing at all for the default-keyed one.\n *\n * The default takes no suffix so that a project with one database configured\n * through plain `DATABASE_URL` keeps working having declared nothing — the\n * overwhelmingly common project must not have to say so.\n */\nexport function resourceEnvSuffix(key: string): string {\n if (key === DEFAULT_RESOURCE_KEY) return \"\";\n return `__${key.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\").replace(/^_+|_+$/g, \"\")}`;\n}\n\n/**\n * Two resources of a kind whose keys differ but whose env suffixes do not.\n *\n * `media-files` and `media_files` both become `__MEDIA_FILES`, so one would\n * silently read the other's configuration. Returned rather than thrown so the\n * caller can report it with the rest of a validation pass.\n */\nexport function findEnvSuffixCollision(keys: readonly string[]): { a: string; b: string; suffix: string } | null {\n const seen = new Map<string, string>();\n for (const key of keys) {\n const suffix = resourceEnvSuffix(key);\n const previous = seen.get(suffix);\n if (previous !== undefined && previous !== key) return { a: previous, b: key, suffix };\n seen.set(suffix, key);\n }\n return null;\n}\n\n/**\n * The whole graph, as recorded in a manifest and read by a host.\n *\n * `version` is the graph format, not the project's. A host reading a graph it\n * does not understand must say so rather than provision half of it.\n */\nexport interface ResourceGraph {\n version: 1;\n resources: ResourceDeclaration[];\n}\n\n/** The current graph format version. */\nexport const RESOURCE_GRAPH_VERSION = 1 as const;\n\n/**\n * Build a graph from the current declarations, sorted for a stable diff.\n *\n * `usedBy` maps a `kind:key` id to the things that reach it. The derive step\n * supplies it after evaluating collections; a runtime building the graph at\n * boot passes nothing and gets declarations alone, which is all it binds from.\n */\nexport function buildResourceGraph(usedBy?: ReadonlyMap<string, readonly string[]>): ResourceGraph {\n const resources = declaredResources().slice().sort(\n (a, b) => a.kind.localeCompare(b.kind) || a.key.localeCompare(b.key)\n ).map(r => {\n const users = usedBy?.get(declarationId(r.kind, r.key));\n return users && users.length > 0 ? { ...r, usedBy: [...users].sort() } : r;\n });\n return { version: RESOURCE_GRAPH_VERSION, resources };\n}\n\n/** `kind:key`, the id `usedBy` maps are keyed by. Exported for the derive step. */\nexport function resourceId(kind: string, key: string): string {\n return declarationId(kind, key);\n}\n\n/**\n * The environment variables worth writing for a resource, given its engine.\n *\n * Falls back to every base the kind reads when the engine is unknown — a\n * `custom:` engine gets the full list rather than an empty one, because\n * guessing narrow would silently omit the variable it actually needs.\n */\nexport function envBasesForResource(declaration: ResourceDeclaration): readonly string[] {\n const spec = resourceKind(declaration.kind);\n if (!spec) return [];\n return spec.envBasesByEngine?.[declaration.engine] ?? spec.envBases;\n}\n","/**\n * Describes a named storage backend — a place files live.\n *\n * Declared once and shared front + back: the frontend uses it to decide\n * transport (HTTP proxy vs direct SDK), the backend uses the same `key`\n * to resolve a StorageController, and collection properties reference\n * a definition by its `key` via `StorageConfig.storageSource`.\n *\n * This mirrors the {@link DataSourceDefinition} pattern used for databases.\n *\n * @group Models\n */\n\n/**\n * The default storage source key, used when a property does not specify\n * a `storageSource`. Shared by the frontend and backend registries so\n * both agree on \"the default storage backend\".\n * @group Models\n */\nexport const DEFAULT_STORAGE_SOURCE_KEY = \"(default)\";\n\n/**\n * How the *frontend* reaches a storage backend.\n *\n * - `\"server\"` — through the Rebase backend REST API (`/api/storage`).\n * The backend holds the actual `StorageController` and routes by\n * storage-source key. This is the default and covers Local, S3, GCS,\n * and any other server-mediated engine.\n * - `\"direct\"` — straight from the client to the external backend via\n * its own SDK (e.g. Firebase Storage via `@firebase/storage`).\n * The Rebase backend is **not** in the upload/download path.\n *\n * @group Models\n */\nexport type StorageSourceTransport = \"server\" | \"direct\";\n\n/**\n * Declarative definition of a storage source — a named place files live.\n *\n * Declared once and shared front and back: the frontend uses it to decide\n * transport (client HTTP proxy vs direct provider SDK), the backend uses\n * the same `key` to resolve a `StorageController`, and collection\n * properties reference a definition by its `key` via\n * `StorageConfig.storageSource`.\n *\n * @group Models\n */\nexport interface StorageSourceDefinition {\n /**\n * Unique identifier for this storage source. Collection properties\n * point at it via `StorageConfig.storageSource`.\n * Defaults to {@link DEFAULT_STORAGE_SOURCE_KEY}.\n */\n key: string;\n\n /**\n * The engine backing this storage source (e.g. `\"local\"`, `\"s3\"`,\n * `\"gcs\"`, `\"firebase\"`, `\"azure\"`, or a custom id).\n */\n engine: string;\n\n /**\n * The credential set this source signs with, when several sources share one.\n *\n * ## What it is for\n *\n * Every binding a bucket needs is read per key — `S3_BUCKET__MEDIA`,\n * `S3_ACCESS_KEY_ID__MEDIA`, and so on. That is right for the bucket *name*,\n * which is different for every source by definition, and wrong for the\n * credentials, which usually are not: fifteen buckets on one MinIO install\n * meant fifteen copies of the same endpoint, access key and secret — ninety\n * variables where eighteen would do, and one key rotation became fifteen\n * paired edits where a single missed one fails at upload time with an opaque\n * signing error.\n *\n * Naming an account here lets the *account-scoped* bindings fall back to\n * `<BASE>__<ACCOUNT>` when no per-key value is set. The bucket name never\n * falls back: it is what distinguishes one source from another.\n *\n * ## Why it does not fall back to the bare variable\n *\n * A source with no `account` reads only its own suffixed names, exactly as\n * before — so every project that predates this is wire-identical. The\n * unsuffixed `S3_ACCESS_KEY_ID` belongs to the *default* source, and letting\n * a named bucket inherit it would mean a typo'd key silently signs with\n * another source's credentials. Two forms, both explicit, opt-in.\n */\n account?: string;\n\n /**\n * How the frontend reaches this storage. Defaults to `\"server\"`.\n *\n * When `\"direct\"`, the client uses a provider-specific SDK\n * (e.g. `@firebase/storage`) and the backend does not proxy\n * upload/download traffic for this source.\n */\n transport: StorageSourceTransport;\n\n /**\n * Serve unqualified uploads — a storage property naming no `storageSource`\n * — from this source.\n *\n * Declared, never inferred. A source without it never becomes the default:\n * the default keeps its own configuration whatever else is declared.\n */\n default?: boolean;\n\n /** Human-readable label for the UI (e.g. \"Firebase Storage\", \"S3 Media\"). */\n label?: string;\n\n /**\n * Delete, on a schedule, the files in this source that no row names.\n *\n * Absent, nothing is swept. See {@link OrphanSweepOptions}.\n */\n orphanSweep?: OrphanSweepOptions;\n}\n\n/**\n * A scheduled sweep of a storage source's unreferenced files.\n *\n * Deleting a row leaves the files it named in the bucket, because a key is not\n * owned by one row: another row, a version in row history, or app code holding\n * the key in a plain string may still name it. So nothing is deleted with the\n * row. The sweep is the same scan as `rebase storage orphans --delete`: every\n * row of every collection and every history entry is read, a file still named\n * anywhere is kept, a file newer than the grace period is kept, and each one is\n * checked again right before it is deleted. A collection the scan cannot read\n * keeps everything, that run.\n *\n * It runs as a cron job, `storage-orphan-sweep-<source>`, so it shows in the\n * admin's cron list with its history, runs on one instance per slot, and can be\n * triggered or paused like any other job.\n *\n * @group Models\n */\nexport interface OrphanSweepOptions {\n /**\n * How old an unreferenced file must be before it is deleted, in hours. At\n * least 24, because an upload is written before the row that names it is\n * saved. Defaults to 168 (a week).\n */\n olderThanHours?: number;\n /** When to run, as a cron expression in UTC. Defaults to daily at 04:17. */\n schedule?: string;\n}\n\n/**\n * A resolved storage source: the single source of truth that the frontend\n * router and backend registry both derive from.\n *\n * @group Models\n */\nexport interface ResolvedStorageSource {\n /** Storage source key (routing key, shared front + back). */\n key: string;\n /** Engine backing the source. */\n engine: string;\n /** Frontend transport. */\n transport: StorageSourceTransport;\n /** Human-readable label. */\n label?: string;\n}\n\n/**\n * The environment-variable suffix for a storage or data source key.\n *\n * `\"\"` for the default source — so a single-bucket project keeps configuring\n * plain `S3_BUCKET` — and `__<KEY>` for every named one, uppercased with\n * non-alphanumerics collapsed to underscores: `media-cdn` → `S3_BUCKET__MEDIA_CDN`.\n *\n * The rule derives the variable name from the declared key rather than\n * discovering keys by scanning the environment. Scanning would have to guess how\n * `S3_BUCKET__MEDIA_CDN` splits into a key; deriving cannot be ambiguous, and a\n * typo surfaces as a missing source at boot instead of a silently ignored\n * variable.\n *\n * It lives in this package, with no dependencies, because four things must agree\n * on it exactly: the CLI (validating a build), the runtime (reading its own\n * environment), the control plane (writing a tenant's Secret), and the docs. A\n * second implementation of a naming convention is a second chance to disagree.\n *\n * @group Models\n */\nexport function storageEnvSuffix(key: string, defaultKey: string = DEFAULT_STORAGE_SOURCE_KEY): string {\n if (!key || key === defaultKey) return \"\";\n const normalized = key\n .replace(/[^A-Za-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .toUpperCase();\n if (!normalized) {\n throw new Error(\n `Source key \"${key}\" cannot be turned into an environment variable name. ` +\n \"Use a key containing at least one letter or digit.\"\n );\n }\n return `__${normalized}`;\n}\n\n/**\n * Two distinct keys that collapse onto the same variable name, or `null`.\n *\n * `media-cdn` and `media_cdn` are different source keys but the same suffix, so\n * without this one of them silently reads the other's configuration. Returns the\n * offending pair rather than throwing, so each caller can raise it in its own\n * idiom — a `BundleError` at boot, a build failure in the CLI, a rejected deploy\n * in a control plane.\n *\n * @group Models\n */\nexport function findStorageSuffixCollision(\n keys: string[],\n defaultKey: string = DEFAULT_STORAGE_SOURCE_KEY\n): { a: string; b: string; suffix: string } | null {\n const seen = new Map<string, string>();\n for (const key of keys) {\n const suffix = storageEnvSuffix(key, defaultKey);\n const existing = seen.get(suffix);\n if (existing !== undefined && existing !== key) {\n return { a: existing, b: key, suffix };\n }\n seen.set(suffix, key);\n }\n return null;\n}\n","/**\n * The kinds Rebase ships, and the constructors a project declares them with.\n *\n * Each kind is registered rather than hardcoded, so a fourth one arrives\n * without editing a manifest schema, a validator and a switch statement. That\n * cost is precisely why databases and buckets ended up declared in different\n * files with different rules — the cheapest thing to do was always to bolt the\n * new kind onto whichever home was nearest.\n *\n * A kind owns its engine list. `custom:<id>` is always accepted, so a build\n * that ships an engine this package has never heard of says so at the call site\n * instead of looking like a typo of one that exists.\n */\nimport {\n DEFAULT_RESOURCE_KEY,\n declareResource,\n declaredResources,\n amendResourceKind,\n registerResourceKind,\n type DeclareOptions,\n type ResourceDeclaration,\n type ResourceHandle\n} from \"./resources\";\nimport { DEFAULT_DATA_SOURCE_KEY, type DataSourceDefinition } from \"./data_source\";\nimport { DEFAULT_STORAGE_SOURCE_KEY, type OrphanSweepOptions, type StorageSourceDefinition } from \"./storage_source\";\n\n// ── database ─────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // There is no single frozen literal for this kind, which is why it carries a\n // revision. 0.17.0 and 0.17.1 shipped `optionKeys: [\"databaseId\",\n // \"migrations\"]`; 0.17.2 added \"extensions\" to the literal itself, before the\n // rule against that existed. So two different objects are inlined in drivers\n // that are in the field, and no choice of literal can equal both: a runtime\n // that matched one threw `already registered with a different definition` at\n // the other and refused to boot. Two tenants crash-looped for six and a half\n // days on exactly that.\n //\n // `revision` is what resolves it. An older copy — whichever literal it\n // carries — is at revision 0, loses to this one, and warns instead of\n // throwing. Corrections still go in the amendment below; this number moves\n // only when the literal itself has to, and every published copy predating the\n // move is thereby handled.\n //\n // The same goes for `engines`. Only \"postgres\" has a server driver — MongoDB\n // support was removed after 0.30.1 — but \"mongodb\" stays in this list because\n // removing it is an edit to the literal every published copy compares. The\n // server refuses a `database()` declared with an engine it has no driver\n // for, naming the engine, so the stale entry cannot be booted.\n revision: 1,\n kind: \"database\",\n engines: [\"postgres\", \"mongodb\", \"firestore\", \"sqlite\"],\n defaultEngine: \"postgres\",\n envBases: [\"DATABASE_URL\", \"REBASE_DRIVER\", \"REBASE_DB_POOL_MAX\"],\n optionKeys: [\"databaseId\", \"migrations\", \"extensions\"],\n implicitDefault: true\n});\n// What a database actually binds from. The 0.17.3 list named two variables\n// the resolver never read and omitted five it does (25f1a97e3).\namendResourceKind(\"database\", {\n // `rls` added by amendment, never to the literal above: every published\n // copy compares that literal, and an edit to it is what took two tenants\n // down for six days (see the comment on `revision`).\n optionKeys: [\"databaseId\", \"migrations\", \"extensions\", \"rls\"],\n envBases: [\n \"DATABASE_URL\",\n \"DATABASE_READ_URL\",\n \"DATABASE_DIRECT_URL\",\n \"DATABASE_POOLED\",\n \"ADMIN_CONNECTION_STRING\",\n \"REBASE_DRIVER\",\n \"DB_POOL_MAX\",\n \"DB_POOL_IDLE_TIMEOUT\",\n \"DB_POOL_CONNECT_TIMEOUT\"\n ]\n});\n\n/** Options a database accepts beyond the common ones. */\nexport interface DatabaseOptions extends DeclareOptions {\n /**\n * The physical database or schema within the engine, when it differs from\n * the engine's own default. Threaded to drivers as `databaseId`.\n */\n databaseId?: string;\n /** Directory of migration files, relative to the config directory. */\n migrations?: string;\n /**\n * Server extensions Rebase may install on this database.\n *\n * A permission, not a request: naming one grants leave to run\n * `CREATE EXTENSION IF NOT EXISTS <name>`, and Rebase issues it only when\n * something in the schema actually needs it. Naming an extension nothing\n * needs installs nothing.\n *\n * It has to be said out loud because installing an extension is a decision\n * with a deployment behind it — the image has to ship the library, the role\n * has to be allowed to install it, and a managed provider has to have it on\n * an allow-list. Rebase cannot see any of that from inside the connection,\n * so the answer comes from whoever chose the database.\n *\n * Today `vector` is the one that matters: a `{ type: \"vector\" }` property\n * compiles to a `VECTOR(n)` column, which does not exist until pgvector is\n * installed. Without this, Rebase creates the column and lets Postgres\n * refuse, naming the option.\n *\n * ```ts\n * export const main = database({ extensions: [\"vector\"] });\n * ```\n *\n * `pg_trgm` and `unaccent` are not on this list and need no permission: a\n * `search` block installs them unasked, because they are contrib modules\n * present in every Postgres distribution. pgvector is a separate build that\n * a stock `postgres:18` does not carry.\n */\n extensions?: string[];\n /**\n * How row-level security runs on this database — the request role and\n * everything around it. Every default is what Rebase did before the option\n * existed. Declared here rather than only on the driver because the policy\n * settings shape the SQL `rebase db generate` writes, and the CLI reads\n * this declaration as the server does. The `REBASE_RLS_*` variables win.\n *\n * ```ts\n * export const main = database({ rls: { requestRole: \"acme_user\" } });\n * ```\n *\n * See `PostgresRlsConfig` in `@rebasepro/server-postgres` for each setting,\n * and the forms only code can give (a function for the role or identity).\n */\n rls?: DatabaseRlsOptions;\n}\n\n/**\n * The data-only `rls` settings a database declaration takes. The driver's own\n * `rls` block (`PostgresRlsConfig`) accepts these and the function forms.\n */\nexport interface DatabaseRlsOptions {\n requestRole?: string | { anonymous: string; signedIn: string };\n provisionRole?: \"auto\" | \"never\";\n grants?: \"schema\" | \"managed\" | \"none\";\n policyTarget?: \"public\" | \"requestRole\";\n adminPolicies?: \"adminRole\" | \"public\";\n defaultPolicies?: boolean;\n /**\n * `false` serves this database's declared tables even when it does not\n * enforce their `rls` (row-level security off, declared policies\n * missing): for a database whose schema something else owns and whose\n * access the app enforces. A table's own `rlsRequired` wins. Default\n * `true`: such a table is withheld (503 TABLE_WITHHELD).\n */\n required?: boolean;\n inheritRoles?: string[];\n identity?: \"rebase\" | \"supabase\";\n sharedRole?: \"warn\" | \"refuse\" | \"ignore\";\n}\n\n/** A database handle. Collections point at it via `dataSource`. */\nexport type DatabaseHandle = ResourceHandle;\n\n/**\n * Declare a database.\n *\n * ```ts\n * export const main = database(); // the default one\n * export const analytics = database(\"analytics\"); // reads DATABASE_URL__ANALYTICS\n * export const withPgv = database({ extensions: [\"vector\"] }); // the default one, configured\n * ```\n *\n * The third form exists because the default database has no name to pass, and\n * the alternative was `database(\"(default)\", { … })` — writing out an internal\n * sentinel to reach the options. A key is a string and options are an object,\n * so the two can never be confused for one another.\n */\nexport function database(options?: DatabaseOptions): DatabaseHandle;\nexport function database(key?: string, options?: DatabaseOptions): DatabaseHandle;\nexport function database(\n keyOrOptions: string | DatabaseOptions = DEFAULT_RESOURCE_KEY,\n options: DatabaseOptions = {}\n): DatabaseHandle {\n return typeof keyOrOptions === \"string\"\n ? declareResource(\"database\", keyOrOptions, options)\n : declareResource(\"database\", DEFAULT_RESOURCE_KEY, keyOrOptions);\n}\n\n/**\n * The extensions the project's databases gave Rebase leave to install.\n *\n * A flat union rather than a per-database answer, because the surfaces that ask\n * — `rebase db push` and the boot schema-ensure — drive one connection and\n * generate one `schema.sql` for every collection regardless of `dataSource`.\n * Splitting the permission by data source would be a distinction the rest of\n * that pipeline does not make, and a false precision is worse than none.\n *\n * Empty for a project that declared nothing, which is every project that has\n * not opted in — so this reads as a refusal by default, on purpose.\n */\nexport function declaredDatabaseExtensions(): readonly string[] {\n const names = new Set<string>();\n for (const declaration of declaredResources(\"database\")) {\n const declared = declaration.options.extensions;\n if (!Array.isArray(declared)) continue;\n for (const name of declared) {\n if (typeof name === \"string\" && name.trim()) names.add(name.trim());\n }\n }\n return [...names].sort();\n}\n\n/** The `rls` options a database declaration gave, `{}` when it gave none or was never declared. */\nexport function declaredDatabaseRls(key: string = DEFAULT_DATA_SOURCE_KEY): DatabaseRlsOptions {\n const declaration = declaredResources(\"database\").find((d) => d.key === key);\n const rls = declaration?.options.rls;\n return rls && typeof rls === \"object\" ? rls as DatabaseRlsOptions : {};\n}\n\n/**\n * The policy settings every compile path must agree on — the boot's policy\n * ensure, `rebase db generate`, the drift check — read from the one place all\n * of them can see: the database declaration, with `REBASE_RLS_POLICY_TARGET` /\n * `REBASE_RLS_ADMIN_POLICIES` / `REBASE_RLS_DEFAULT_POLICIES` over it. Defaults\n * are what Rebase compiled before these existed, except `adminPolicies`, whose\n * default (`\"adminRole\"`) changed what the server-or-admin policies are `TO`.\n *\n * Browser-safe: where there is no `process`, only the declaration counts.\n */\nexport function declaredRlsPolicyShape(dataSource: string = DEFAULT_DATA_SOURCE_KEY): {\n policyTarget: \"public\" | \"requestRole\";\n adminPolicies: \"adminRole\" | \"public\";\n defaultPolicies: boolean;\n} {\n const declared = declaredDatabaseRls(dataSource);\n const env = typeof process !== \"undefined\" ? process.env : undefined;\n const envTarget = env?.REBASE_RLS_POLICY_TARGET?.trim();\n const envAdmin = env?.REBASE_RLS_ADMIN_POLICIES?.trim();\n const envDefaults = env?.REBASE_RLS_DEFAULT_POLICIES?.trim().toLowerCase();\n return {\n policyTarget: envTarget === \"requestRole\" || envTarget === \"public\"\n ? envTarget\n : declared.policyTarget === \"requestRole\" ? \"requestRole\" : \"public\",\n adminPolicies: envAdmin === \"adminRole\" || envAdmin === \"public\"\n ? envAdmin\n : declared.adminPolicies === \"public\" ? \"public\" : \"adminRole\",\n defaultPolicies: envDefaults === \"false\" ? false : envDefaults === \"true\" ? true : declared.defaultPolicies !== false\n };\n}\n\n// ── bucket ───────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // FROZEN at the 0.17.3 literal, for the reason given on `database`.\n kind: \"bucket\",\n engines: [\"local\", \"s3\", \"gcs\", \"azure\", \"firebase\"],\n defaultEngine: \"local\",\n envBases: [\"S3_BUCKET\", \"GCS_BUCKET\", \"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n envBasesByEngine: {\n local: [\"STORAGE_BUCKET\"],\n s3: [\"S3_BUCKET\", \"STORAGE_ENDPOINT\", \"STORAGE_REGION\", \"STORAGE_PUBLIC_URL\"],\n gcs: [\"GCS_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n azure: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"],\n firebase: [\"STORAGE_BUCKET\", \"STORAGE_PUBLIC_URL\"]\n },\n optionKeys: [\"publicRead\", \"prefix\", \"account\"],\n implicitDefault: false\n});\n// What a bucket actually binds from, per engine (25f1a97e3), plus `default`:\n// the registry no longer promotes a lone named bucket, so a project needs a way\n// to say which one serves unqualified uploads. The literal above is frozen, so\n// the new option key arrives here.\namendResourceKind(\"bucket\", {\n // `orphanSweep` arrived the same way, after `default`.\n optionKeys: [\"publicRead\", \"prefix\", \"account\", \"default\", \"orphanSweep\"],\n envBases: [\n \"STORAGE_TYPE\",\n \"STORAGE_PATH\",\n \"S3_BUCKET\",\n \"S3_REGION\",\n \"S3_ACCESS_KEY_ID\",\n \"S3_SECRET_ACCESS_KEY\",\n \"S3_ENDPOINT\",\n \"S3_FORCE_PATH_STYLE\",\n \"GCS_BUCKET\",\n \"GCS_PROJECT_ID\",\n \"GCS_KEY_FILENAME\",\n // The largest file the source accepts, read for every engine.\n \"STORAGE_MAX_FILE_SIZE\"\n ],\n envBasesByEngine: {\n local: [\"STORAGE_TYPE\", \"STORAGE_PATH\", \"STORAGE_MAX_FILE_SIZE\"],\n s3: [\n \"STORAGE_TYPE\",\n \"S3_BUCKET\",\n \"S3_REGION\",\n \"S3_ACCESS_KEY_ID\",\n \"S3_SECRET_ACCESS_KEY\",\n \"S3_ENDPOINT\",\n \"S3_FORCE_PATH_STYLE\",\n \"STORAGE_MAX_FILE_SIZE\"\n ],\n gcs: [\"STORAGE_TYPE\", \"GCS_BUCKET\", \"GCS_PROJECT_ID\", \"GCS_KEY_FILENAME\", \"STORAGE_MAX_FILE_SIZE\"],\n azure: [],\n firebase: []\n }\n});\n\n/** Options a bucket accepts beyond the common ones. */\nexport interface BucketOptions extends DeclareOptions {\n /**\n * Whether objects are world-readable by default.\n *\n * Declared rather than inferred from the engine, because the two have\n * disagreed before: a private object served through a cacheable public URL\n * is a data leak that nothing errors on.\n */\n publicRead?: boolean;\n /**\n * @deprecated Never applied: every object lands at the root of its bucket,\n * whatever this says, so two sources declaring one bucket share one\n * namespace. Give each source a bucket of its own (`S3_BUCKET__<KEY>`,\n * `GCS_BUCKET__<KEY>`, or `STORAGE_PATH__<KEY>` for a local one), or put\n * the folder in each storage property's `storagePath`. The backend warns\n * once at boot when it is set. Will be removed in a future release.\n */\n prefix?: string;\n /**\n * Serve unqualified uploads — a storage property with no `storageSource` —\n * from this bucket.\n *\n * Without it, declaring `bucket(\"media\")` leaves the default source where\n * it was: on its own `STORAGE_PATH` / `./uploads`, or the bucket the\n * unsuffixed `S3_BUCKET` / `GCS_BUCKET` names. Mark a named bucket to make\n * it the default instead; the files the default held before stay where\n * they are and are no longer served through it.\n */\n default?: boolean;\n /**\n * The credential set this bucket signs with, when several share one.\n *\n * `bucket(\"media\", { engine: \"s3\", account: \"minio\" })` keeps reading its own\n * `S3_BUCKET__MEDIA` — the bucket name is what distinguishes one source from\n * another and never falls back — while the provider-level variables\n * (`S3_ACCESS_KEY_ID`, `S3_SECRET_ACCESS_KEY`, `S3_ENDPOINT`, `S3_REGION`,\n * `S3_FORCE_PATH_STYLE`) fall back to `__MINIO` when no per-key value is set.\n *\n * Fifteen buckets on one install go from ninety variables to eighteen, and\n * rotating the key becomes one edit. A per-bucket value still wins, so a\n * single source can move to another provider without breaking the rest off\n * their shared account.\n */\n account?: string;\n /**\n * Delete, on a schedule, the files in this bucket that no row names:\n * `true` for the defaults, or `{ olderThanHours, schedule }`. See\n * {@link OrphanSweepOptions}.\n *\n * ```ts\n * export const voice = bucket(\"voice\", { engine: \"gcs\", orphanSweep: { olderThanHours: 72 } });\n * ```\n */\n orphanSweep?: boolean | OrphanSweepOptions;\n}\n\n/** A bucket handle. Storage properties point at it via `storageSource`. */\nexport type BucketHandle = ResourceHandle;\n\n/**\n * Declare a bucket.\n *\n * ```ts\n * export const uploads = bucket({ engine: \"s3\" }); // the default one\n * export const media = bucket(\"media\", { transport: \"direct\" });\n * ```\n *\n * `transport: \"direct\"` means a provider SDK talks to the bucket and the\n * backend is not in the upload path.\n *\n * The options-only form exists for the same reason `database`'s does: the\n * default bucket has no name to pass, and without it the only way to configure\n * one was `bucket(\"(default)\", { … })` — writing out an internal sentinel to\n * reach the options. Passing options where a key belongs used to throw \"a\n * bucket needs a non-empty key\", which names neither the mistake nor the fix.\n */\nexport function bucket(options?: BucketOptions): BucketHandle;\nexport function bucket(key?: string, options?: BucketOptions): BucketHandle;\nexport function bucket(\n keyOrOptions: string | BucketOptions = DEFAULT_RESOURCE_KEY,\n options: BucketOptions = {}\n): BucketHandle {\n return typeof keyOrOptions === \"string\"\n ? declareResource(\"bucket\", keyOrOptions, options)\n : declareResource(\"bucket\", DEFAULT_RESOURCE_KEY, keyOrOptions);\n}\n\n// ── topic ────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n // FROZEN at the 0.17.3 literal, for the reason given on `database`.\n kind: \"topic\",\n // `jobs` is the durable local implementation: a topic fans out to one job\n // row per subscription, so each subscriber retries on its own schedule and\n // a failure is a row somebody can look at rather than a lost message.\n engines: [\"jobs\"],\n defaultEngine: \"jobs\",\n envBases: [\"REBASE_TOPIC_URL\"],\n optionKeys: [\"delivery\", \"maxAttempts\"],\n implicitDefault: false\n});\n// Nothing. A topic on the `jobs` engine is rows in the project's own database\n// and binds from no variable of its own. The literal above says\n// `REBASE_TOPIC_URL` — a name nothing in either repository read, which\n// `rebase status` then printed as a variable somebody could set — and it has to\n// keep saying it, because a driver ≤ 0.17.3 compares that object and throws.\n// The gate in `resource-env-bases.test.ts` covers every registered kind through\n// the amended view, so a phantom name fails a build rather than reaching a\n// developer.\namendResourceKind(\"topic\", { envBases: [] });\n\n/**\n * How hard the runtime tries to deliver.\n *\n * Only `at-least-once` is implemented, and it is the honest name for what a\n * retrying queue does: a handler must tolerate seeing the same event twice.\n * `at-most-once` is listed so a future transport can offer it without the\n * option changing shape, and is refused today rather than silently upgraded.\n */\nexport type TopicDelivery = \"at-least-once\" | \"at-most-once\";\n\n/** Options a topic accepts beyond the common ones. */\nexport interface TopicOptions extends DeclareOptions {\n delivery?: TopicDelivery;\n /** Attempts per subscription before a message is left failed. Default 5. */\n maxAttempts?: number;\n}\n\n/**\n * What a subscription does with an event.\n *\n * `attempt` counts from 1. Worth branching on: the first delivery and the\n * fourth are the same call, but the fourth is where it is worth logging loudly.\n * `signal` is aborted when the attempt runs past the job queue's `timeoutMs`.\n */\nexport type TopicHandler<T> = (\n event: T,\n context: { attempt: number; topic: string; subscription: string; signal: AbortSignal }\n) => Promise<void> | void;\n\n/** A declared subscription, as recorded in the graph and wired at boot. */\nexport interface TopicSubscription<T = unknown> {\n topic: string;\n name: string;\n handler: TopicHandler<T>;\n maxAttempts?: number;\n}\n\n/**\n * What a topic publishes through.\n *\n * Installed by `@rebasepro/server` at boot. Absent — in the CLI evaluating\n * config to derive the graph, or in a unit test — publishing throws a message\n * naming the cause, rather than resolving and dropping the event. A publish\n * that silently does nothing is the failure mode a queue exists to prevent.\n */\nexport interface TopicRuntime {\n publish(topic: string, event: unknown): Promise<void>;\n}\n\n/**\n * Declared handlers and installed runtimes, for topics and queues — on\n * `globalThis` under a shared symbol, never in module locals.\n *\n * A module local is one per COPY of this package, and two copies in one\n * process is the normal layout rather than an accident: `@rebasepro/server`\n * inlines this package into its own dist, while `config/resources.ts` imports\n * it from `node_modules`. With locals, a project's `.handler()` and\n * `.subscription()` went into the project's copy and the worker read the\n * server's empty one (`Job queue started {\"tasks\":0}`), and the runtime the\n * server installed was invisible to the project's `enqueue`/`publish` — so\n * every queue and topic threw \"no runtime is installed\" inside a running\n * backend. The CLI deriving the graph had the same split. Same mechanism and\n * reasoning as `registry()` in resources.ts; `module-state-across-copies.test.ts`\n * loads two copies to hold it, and scans for any other module-level state that\n * would split the same way.\n *\n * The version is in the symbol: a change to this object's SHAPE takes a new\n * suffix, so no copy ever reads a shape it does not know.\n */\nconst WORK_KEY = Symbol.for(\"@rebasepro/types.workRegistry.v1\");\n\ninterface WorkRegistry {\n topicRuntime: TopicRuntime | null;\n subscriptions: TopicSubscription[];\n queueRuntime: QueueRuntime | null;\n queueConsumers: Map<string, QueueConsumer>;\n}\n\ntype GlobalWithWork = typeof globalThis & { [WORK_KEY]?: WorkRegistry };\n\nfunction work(): WorkRegistry {\n const g = globalThis as GlobalWithWork;\n let shared = g[WORK_KEY];\n if (!shared) {\n shared = { topicRuntime: null, subscriptions: [], queueRuntime: null, queueConsumers: new Map() };\n g[WORK_KEY] = shared;\n }\n return shared;\n}\n\n/**\n * Where `@rebasepro/server` publishes its client once it has booted (its\n * `singleton.ts`). Read only to tell the two causes of a missing runtime apart.\n */\nconst SERVER_INSTANCE_SLOT = Symbol.for(\"@rebasepro/server:singleton-instance\");\n\ntype GlobalWithServer = typeof globalThis & { [SERVER_INSTANCE_SLOT]?: unknown };\n\n/**\n * Why there is no runtime to send through, as far as this process can tell.\n *\n * Outside a backend — the CLI evaluating config, a script, a unit test — the\n * answer is that there is nothing to deliver to. Inside one it is not: the\n * backend installs a runtime at boot for what `config/resources.ts` declared,\n * so a missing one there means boot never saw the declaration, or the backend\n * carries a copy of this package too old to share the slot it installs into.\n * Saying \"outside a backend\" to somebody whose backend is running sends them\n * looking for the wrong thing.\n */\nfunction missingRuntimeCause(kind: \"queue\" | \"topic\"): string {\n const backendUp = (globalThis as GlobalWithServer)[SERVER_INSTANCE_SLOT] != null;\n if (!backendUp) {\n return \"This works inside a running Rebase backend; this looks like code running outside one \" +\n \"(a build, a script, or a test without a harness).\";\n }\n return `A Rebase backend is running in this process but installed no ${kind} runtime. It installs one at boot ` +\n `when config/resources.ts declares a ${kind}, so either this ${kind} is declared somewhere boot does not ` +\n \"read, or the backend's copy of @rebasepro/types predates the shared runtime slot this copy reads — keep \" +\n \"@rebasepro/server and @rebasepro/types on the same version.\";\n}\n\n/** Install the transport topics publish through. Called by the server at boot. */\nexport function setTopicRuntime(runtime: TopicRuntime | null): void {\n work().topicRuntime = runtime;\n}\n\n/** Every declared subscription, for the worker to wire and the graph to record. */\nexport function declaredSubscriptions(topic?: string): TopicSubscription[] {\n const { subscriptions } = work();\n return topic ? subscriptions.filter(s => s.topic === topic) : subscriptions.slice();\n}\n\n/** Forget declared subscriptions. For tests, alongside `resetDeclaredResources`. */\nexport function resetDeclaredSubscriptions(): void {\n work().subscriptions.length = 0;\n}\n\n/** A topic handle, carrying its payload type. */\nexport interface TopicHandle<T> extends ResourceHandle {\n /**\n * Publish an event.\n *\n * Resolves once the event is durably recorded for every subscription, not\n * once they have run. Enqueued inside a transaction that rolls back, it was\n * never published.\n */\n publish(event: T): Promise<void>;\n /**\n * Declare a subscription.\n *\n * The name is its identity: it is what the job row records, what a retry\n * counts against, and what a second subscription must not collide with.\n */\n subscription(name: string, handler: TopicHandler<T>, options?: { maxAttempts?: number }): void;\n}\n\n/**\n * Declare a topic.\n *\n * ```ts\n * export const signups = topic<{ userId: string }>(\"signups\");\n * signups.subscription(\"send-welcome\", async (event) => { … });\n * await signups.publish({ userId });\n * ```\n */\nexport function topic<T = unknown>(key: string, options: TopicOptions = {}): TopicHandle<T> {\n if (options.delivery === \"at-most-once\") {\n throw new Error(\n `Topic \"${key}\" asks for at-most-once delivery, which no shipped transport implements. ` +\n \"The durable queue behind topics retries, so it is at-least-once and a handler must \" +\n \"tolerate seeing an event twice. Refused rather than quietly given the other guarantee.\"\n );\n }\n const handle = declareResource(\"topic\", key, options);\n\n return {\n ...handle,\n toString() { return key; },\n async publish(event: T): Promise<void> {\n const runtime = work().topicRuntime;\n if (!runtime) {\n throw new Error(\n `Cannot publish to topic \"${key}\": no topic runtime is installed. ${missingRuntimeCause(\"topic\")}`\n );\n }\n await runtime.publish(key, event);\n },\n subscription(name: string, handler: TopicHandler<T>, subOptions: { maxAttempts?: number } = {}): void {\n if (!name || name.trim() === \"\") {\n throw new Error(`A subscription on topic \"${key}\" needs a non-empty name.`);\n }\n const { subscriptions } = work();\n if (subscriptions.some(s => s.topic === key && s.name === name)) {\n throw new Error(\n `Topic \"${key}\" already has a subscription named \"${name}\". ` +\n \"The name is what a job row records and what a retry counts against, so two \" +\n \"cannot share one.\"\n );\n }\n subscriptions.push({\n topic: key,\n name,\n handler: handler as TopicHandler<unknown>,\n ...(subOptions.maxAttempts !== undefined ? { maxAttempts: subOptions.maxAttempts } : {})\n });\n }\n } as TopicHandle<T>;\n}\n\n// ── cron ─────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"cron\",\n // The in-process scheduler, claiming each slot in `rebase.cron_claims` so\n // several instances of one deployment run a slot once. It is the only\n // engine because it is the only one that exists; an external scheduler\n // (a platform's cron, a Kubernetes CronJob) would be a second engine that\n // triggers the same handler over HTTP, and it can register itself.\n engines: [\"scheduler\"],\n defaultEngine: \"scheduler\",\n // Code, not configuration: a cron binds from no variable. It is in the\n // graph so a host knows a project's schedules BEFORE running it, which is\n // what lets a console show them and a placement decision read them.\n envBases: [],\n optionKeys: [\"schedule\", \"timezone\", \"description\", \"enabled\", \"timeoutSeconds\", \"catchUpWindowSeconds\"],\n implicitDefault: false\n});\n\n/** What a cron declaration records, beyond its handler. */\nexport interface CronResourceOptions extends DeclareOptions {\n /** Five-field cron expression, e.g. `0 3 * * *`. */\n schedule: string;\n /**\n * IANA zone the schedule is read in, e.g. `Europe/Madrid`.\n *\n * Without it the schedule is read in the process's own zone, which is\n * whatever the host happens to be set to — UTC in nearly every container,\n * the developer's own on a laptop. \"3 AM\" then means two different hours\n * either side of a deploy. Naming the zone makes the declaration mean one\n * thing everywhere.\n */\n timezone?: string;\n description?: string;\n enabled?: boolean;\n timeoutSeconds?: number;\n catchUpWindowSeconds?: number;\n}\n\n/**\n * Declare a cron, as the scheduler's `defineCron` does on its way through.\n *\n * Projects do not call this: `defineCron` in `@rebasepro/server` does, so a\n * cron file is both the handler and the declaration — one file, one name, and\n * the graph derived from it says what a host needs to know without evaluating\n * the handler. Exported so the derive step and the scheduler spell the\n * declaration identically.\n */\nexport function declareCron(name: string, options: CronResourceOptions): ResourceHandle {\n if (typeof options.schedule !== \"string\" || options.schedule.trim() === \"\") {\n throw new Error(`Cron \"${name}\" needs a schedule — a five-field cron expression such as \"0 3 * * *\".`);\n }\n return declareResource(\"cron\", name, options);\n}\n\n// ── function ─────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"function\",\n // Mounted by this runtime at `/api/functions/<name>`. A host that runs a\n // function elsewhere — an edge runtime, say — is a second engine, and the\n // bundle's `portable` analysis already says which ones could move.\n engines: [\"http\"],\n defaultEngine: \"http\",\n envBases: [],\n optionKeys: [\"portable\", \"requires\", \"file\"],\n implicitDefault: false\n});\n\n/**\n * What a function declaration records.\n *\n * Recorded by the derive step from the bundler's static analysis rather than\n * by evaluating the function module: a function's handler is a Hono app that\n * only needs to exist at request time, and evaluating it at build time would\n * run its module-scope code in a process with none of its environment.\n */\nexport interface FunctionResourceOptions extends DeclareOptions {\n /** Path inside the project, so a host can point at the file. */\n file?: string;\n /** `false` when the source imports a Node built-in or a package that needs one. */\n portable?: boolean;\n /** Why it is not portable — one short phrase per reason. */\n requires?: string[];\n}\n\n/** Declare a function. Called by the derive step, not by projects. */\nexport function declareFunction(name: string, options: FunctionResourceOptions = {}): ResourceHandle {\n return declareResource(\"function\", name, options);\n}\n\n// ── queue ────────────────────────────────────────────────────────────────────\n\nregisterResourceKind({\n kind: \"queue\",\n // Same durable queue topics ride on: a row per job, claimed with\n // `FOR UPDATE SKIP LOCKED`, retried on a backoff, kept when it gives up.\n engines: [\"jobs\"],\n defaultEngine: \"jobs\",\n envBases: [],\n optionKeys: [\"maxAttempts\"],\n implicitDefault: false\n});\n\n/** Options a queue accepts beyond the common ones. */\nexport interface QueueOptions extends DeclareOptions {\n /** Attempts before a job is left failed. Default 5. */\n maxAttempts?: number;\n}\n\n/**\n * What a queue's handler receives. `attempt` counts from 1; `signal` is\n * aborted when the attempt runs past the job queue's `timeoutMs`.\n */\nexport type QueueHandler<T> = (\n payload: T,\n context: { attempt: number; queue: string; jobId: string; signal: AbortSignal }\n) => Promise<void> | void;\n\n/** Per-job options at enqueue time. */\nexport interface QueueEnqueueOptions {\n /** Earliest time the job may run. Defaults to now. */\n runAt?: Date;\n /** Attempts for this job, overriding the queue's. */\n maxAttempts?: number;\n}\n\n/**\n * What a queue enqueues through.\n *\n * Installed by `@rebasepro/server` at boot, alongside the topic runtime.\n * Absent — config evaluated by the CLI, a unit test — enqueueing throws with\n * the cause named, rather than resolving and dropping the job.\n */\nexport interface QueueRuntime {\n enqueue(queue: string, payload: unknown, options?: QueueEnqueueOptions): Promise<{ id: string }>;\n}\n\n/** Install the transport queues enqueue through. Called by the server at boot. */\nexport function setQueueRuntime(runtime: QueueRuntime | null): void {\n work().queueRuntime = runtime;\n}\n\n/** A queue's handler, as recorded for the worker to wire. */\nexport interface QueueConsumer<T = unknown> {\n queue: string;\n handler: QueueHandler<T>;\n}\n\n/** Every declared queue handler, for the worker to wire. */\nexport function declaredQueueConsumers(): QueueConsumer[] {\n return [...work().queueConsumers.values()];\n}\n\n/** Forget declared queue handlers. For tests, alongside `resetDeclaredResources`. */\nexport function resetDeclaredQueueConsumers(): void {\n work().queueConsumers.clear();\n}\n\n/** A queue handle, carrying its payload type. */\nexport interface QueueHandle<T> extends ResourceHandle {\n /**\n * Put a job on the queue.\n *\n * Resolves once the job is durably recorded, not once it has run. A row\n * insert, so enqueued inside a transaction that rolls back it was never\n * enqueued.\n */\n enqueue(payload: T, options?: QueueEnqueueOptions): Promise<{ id: string }>;\n /**\n * Declare the handler.\n *\n * One per queue: a queue is a work list with one consumer, which is what\n * separates it from a topic. Work that several things must react to is a\n * topic with several subscriptions.\n */\n handler(fn: QueueHandler<T>): void;\n}\n\n/**\n * Declare a queue.\n *\n * ```ts\n * export const thumbnails = queue<{ key: string }>(\"thumbnails\");\n * thumbnails.handler(async ({ key }) => { … });\n * await thumbnails.enqueue({ key }, { runAt: new Date(Date.now() + 60_000) });\n * ```\n *\n * The difference from a topic is the number of consumers: a queue has one, a\n * topic fans out to every subscription. Both ride on the durable job queue, so\n * declaring either turns it on.\n */\nexport function queue<T = unknown>(key: string, options: QueueOptions = {}): QueueHandle<T> {\n const handle = declareResource(\"queue\", key, options);\n\n return {\n ...handle,\n toString() { return key; },\n async enqueue(payload: T, enqueueOptions?: QueueEnqueueOptions): Promise<{ id: string }> {\n const runtime = work().queueRuntime;\n if (!runtime) {\n throw new Error(\n `Cannot enqueue on queue \"${key}\": no queue runtime is installed. ${missingRuntimeCause(\"queue\")}`\n );\n }\n return runtime.enqueue(key, payload, enqueueOptions);\n },\n handler(fn: QueueHandler<T>): void {\n const { queueConsumers } = work();\n if (queueConsumers.has(key)) {\n throw new Error(\n `Queue \"${key}\" already has a handler. A queue has exactly one consumer; ` +\n \"work that several things react to is a topic with several subscriptions.\"\n );\n }\n queueConsumers.set(key, { queue: key, handler: fn as QueueHandler<unknown> });\n }\n } as QueueHandle<T>;\n}\n\n// ── Handing declarations to the readers ──────────────────────────────────────\n\n/**\n * One declaration, as the data layer's definition.\n *\n * There is exactly one of these per kind, and everything that needs a\n * definition goes through it — the frontend, the managed runtime's boot path,\n * and an ejected project's own entrypoint. That is not tidiness: the mapping\n * used to exist twice, once here and once in `@rebasepro/server`'s\n * `graphToStorageSources`, and the two disagreed. The server's copy carried a\n * bucket's `account`; this one dropped it, so a bucket declared with shared\n * credentials resolved them on the managed runtime and resolved *nothing* in an\n * ejected backend — the source was skipped and every upload to it answered 501.\n *\n * A field-by-field map is one line away from that failure at all times, so\n * there is now one line to keep right instead of two to keep equal.\n */\nexport function resourceToDataSource(declaration: ResourceDeclaration): DataSourceDefinition {\n return {\n // The graph and the data layer spell \"the unnamed one\" identically\n // today, but they are separate constants and nothing stops them\n // drifting. Mapped explicitly so a divergence is a compile error rather\n // than a default database that silently fails to bind.\n key: declaration.key === DEFAULT_RESOURCE_KEY ? DEFAULT_DATA_SOURCE_KEY : declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n ...(typeof declaration.options.databaseId === \"string\"\n ? { databaseId: declaration.options.databaseId }\n : {}),\n ...(declaration.label !== undefined ? { label: declaration.label } : {})\n };\n}\n\n/** One declaration, as the storage layer's definition. See {@link resourceToDataSource}. */\nexport function resourceToStorageSource(declaration: ResourceDeclaration): StorageSourceDefinition {\n return {\n key: declaration.key === DEFAULT_RESOURCE_KEY ? DEFAULT_STORAGE_SOURCE_KEY : declaration.key,\n engine: declaration.engine,\n transport: declaration.transport,\n // Carried, or the declaration's `account` is accepted at the call site\n // and lost on the way to the reader — a declared option that does\n // nothing, which is the exact failure this whole model exists to remove.\n ...(typeof declaration.options.account === \"string\"\n ? { account: declaration.options.account }\n : {}),\n ...(declaration.options.default === true ? { default: true } : {}),\n ...orphanSweepOf(declaration.options.orphanSweep),\n ...(declaration.label !== undefined ? { label: declaration.label } : {})\n };\n}\n\n/**\n * A bucket's `orphanSweep` option as a definition carries it: `true` is the\n * defaults, an object keeps only the fields of the right type. The runtime\n * checks the values (the grace-period floor, the schedule) and refuses a bad\n * one loudly; this only refuses to invent one.\n */\nfunction orphanSweepOf(option: unknown): { orphanSweep?: OrphanSweepOptions } {\n if (option === true) return { orphanSweep: {} };\n if (!option || typeof option !== \"object\") return {};\n const { olderThanHours, schedule } = option as Record<string, unknown>;\n return {\n orphanSweep: {\n ...(typeof olderThanHours === \"number\" ? { olderThanHours } : {}),\n ...(typeof schedule === \"string\" ? { schedule } : {})\n }\n };\n}\n\n/**\n * The declared databases, as definitions.\n *\n * Both the frontend and a project's own backend entrypoint read this. The\n * frontend needs to know which sources exist and how they are reached — a\n * `direct`-transport source is one the browser talks to itself — and it imports\n * the same config package the backend does. Without these it would mean writing\n * the list a second time, by hand, next to the declarations, which is precisely\n * the two-homes problem this model removed everywhere else.\n *\n * ```tsx\n * import \"../config/resources\"; // registers them\n * import { declaredDataSources, declaredStorageSources } from \"@rebasepro/types\";\n *\n * <Rebase dataSources={declaredDataSources()} storageSources={declaredStorageSources()} />\n * ```\n *\n * The import is what registers them, so a bundler that drops an unused module\n * would leave this empty — hence the side-effect import above rather than a\n * bare re-export.\n */\nexport function declaredDataSources(): DataSourceDefinition[] {\n return declaredResources(\"database\").map(resourceToDataSource);\n}\n\n/** The declared buckets, as definitions. */\nexport function declaredStorageSources(): StorageSourceDefinition[] {\n return declaredResources(\"bucket\").map(resourceToStorageSource);\n}\n","const YES = new Set([\"true\", \"1\", \"yes\", \"on\"]);\nconst NO = new Set([\"false\", \"0\", \"no\", \"off\"]);\n\n/**\n * Read a boolean environment variable — one spelling rule for every reader.\n *\n * `true`, `1`, `yes` and `on` are true; `false`, `0`, `no` and `off` are\n * false. Case and surrounding whitespace are ignored. Anything else — unset,\n * blank, or a value that spells neither — is `undefined`, so the caller's\n * default decides and a typo lands on the side the caller chose:\n *\n * ```ts\n * parseEnvBoolean(env.FORCE_LOCAL_STORAGE) === true // off unless said\n * parseEnvBoolean(env.REBASE_MCP_OPEN_REGISTRATION) !== false // on unless said\n * ```\n *\n * It exists because every reader used to spell this itself, and they\n * disagreed. The reader that mattered tested the raw string for truthiness —\n * `!process.env.FORCE_LOCAL_STORAGE` — and every non-empty string is truthy,\n * so `FORCE_LOCAL_STORAGE=false`, written to say \"there is no durable volume\n * here\", switched the production storage guard off and sent uploads to a\n * container filesystem the next redeploy erased. Beside it, `=== \"true\"` made\n * `DISABLE_DB_ROLE_SWITCHING=1` do nothing and `!== \"false\"` made\n * `REBASE_MCP_OPEN_REGISTRATION=0` leave registration open.\n *\n * The boot schemas in `@rebasepro/server` (`loadEnv`, `loadBootEnv`) accept a\n * strict subset — `true`, `false` and blank — and refuse any other value\n * before the server starts. On that subset they read exactly what this reads,\n * so a variable a schema declares and something else reads lazily cannot mean\n * two different things.\n *\n * It lives in this package, with no dependencies, for the reason\n * {@link storageEnvSuffix} does: the runtime, its drivers and the CLI all read\n * these variables, and a second parser is a second chance to disagree.\n *\n * @group Models\n */\nexport function parseEnvBoolean(value: string | undefined): boolean | undefined {\n if (value === undefined) return undefined;\n const spelled = value.trim().toLowerCase();\n if (YES.has(spelled)) return true;\n if (NO.has(spelled)) return false;\n return undefined;\n}\n","/**\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// ─── Refresh token delivery ──────────────────────────────────────────────────\n\n/**\n * The request header a client sends to the auth routes to say where it keeps\n * its refresh token. `json` asks for the token in the response body, and has\n * the token it presents read from the request body.\n *\n * It matters only on a server with `cookieAuth`, which otherwise puts the\n * token in an HttpOnly cookie and answers the body's with `\"\"`, so a client\n * with no cookie jar (Node, React Native), or one that keeps its own sign-in\n * apart from the page's cookie session, held nothing to renew with. A request\n * that sends it is answered as a server without `cookieAuth` answers: the\n * cookie is neither read nor set. So it can never turn a cookie the page's\n * script cannot read into a token it can.\n *\n * `@rebasepro/client` sends it on every auth request in `authFlowMode: \"json\"`.\n *\n * @group Auth\n */\nexport const AUTH_FLOW_HEADER = \"x-rebase-auth-flow\";\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 /**\n * Supports device sign-in (`POST /auth/device`): a terminal shows a code\n * and a link, and the person approves it in a browser where they are\n * signed in. Optional, as `emailOtp` is; absent reads as \"no\".\n */\n deviceLogin?: 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 * Public client ids, by provider id, for the providers whose sign-in a\n * browser starts with one (Apple's Services ID). Absent when none does.\n */\n providerClientIds?: Record<string, 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\" | \"device\";\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 * The auth table's own hooks (`onCreateUser`) are the adapter's to know: the\n * built-in adapter is configured with them (`authTableHooks`).\n *\n * @param values - Raw request body from the client.\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 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 describeUserCreationContract?(): 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 like 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","/**\n * Scopes — what a credential may do, named `resource:action`.\n *\n * One vocabulary for every way of reaching a Rebase backend: a person's\n * session, a service key, a personal key and an OAuth token for `/mcp` all\n * answer \"may this caller do X?\" with the same strings, so a grant reads the\n * same on a key, on a role and on a consent screen.\n *\n * A scope may carry a target — `data:read:posts` is `data:read` on the `posts`\n * collection only. The unqualified scope covers every target. Only the data\n * plane and app scopes take targets; see {@link SCOPE_TARGETS}.\n *\n * Two planes, held differently:\n *\n * - **The data plane** (`data:*`, `storage:*`, `functions:invoke`). Every\n * signed-in person holds all of it, because what a person may do with data\n * is decided row by row by the collection's `securityRules` and by storage\n * policies, never by a scope. On a key or a token these scopes narrow: a key\n * holding `data:read:posts` reaches nothing else, whatever RLS would allow.\n * - **The admin plane** (everything else). Nobody holds it implicitly. The\n * `admin` role holds all of it; any other role holds what the app declares\n * for it under `auth.roles` on the users collection.\n *\n * Apps declare their own scopes too (`auth.scopes`), named the same way —\n * `project:deploy`. Every signed-in person holds every app scope: like the data\n * plane, the function behind it decides whether the person may act, and the\n * scope exists so a key can be narrowed to that one action.\n *\n * @module\n */\n\n/** @group Auth */\nexport const DATA_PLANE_SCOPES = [\n \"data:read\",\n \"data:write\",\n \"data:delete\",\n \"storage:read\",\n \"storage:write\",\n \"storage:delete\",\n \"functions:invoke\"\n] as const;\n\n/** @group Auth */\nexport const ADMIN_SCOPES = [\n \"users:read\",\n \"users:write\",\n \"schema:read\",\n \"schema:write\",\n \"database:read\",\n \"database:write\",\n \"backups:read\",\n \"cron:read\",\n \"cron:write\",\n \"logs:read\",\n \"keys:read\",\n \"keys:write\"\n] as const;\n\n/** @group Auth */\nexport type DataPlaneScope = (typeof DATA_PLANE_SCOPES)[number];\n/** @group Auth */\nexport type AdminScope = (typeof ADMIN_SCOPES)[number];\n/** @group Auth */\nexport type BuiltInScope = DataPlaneScope | AdminScope;\n\n/** Every scope Rebase itself defines, in display order. @group Auth */\nexport const BUILT_IN_SCOPES: readonly BuiltInScope[] = [...DATA_PLANE_SCOPES, ...ADMIN_SCOPES];\n\n/**\n * Scopes no key may hold.\n *\n * A key that could manage keys could mint its own successor, widen itself, or\n * revoke the keys other integrations run on — and revoking it would undo none\n * of that. Managing keys is for a person (or the service key).\n *\n * @group Auth\n */\nexport const KEY_MANAGEMENT_SCOPES: readonly AdminScope[] = [\"keys:read\", \"keys:write\"];\n\n/** The one built-in role. It holds every scope and is the RLS `admin` role. @group Auth */\nexport const ADMIN_ROLE = \"admin\";\n\n/** What a scope's target names. @group Auth */\nexport type ScopeTargetKind = \"collection\" | \"bucket\" | \"function\";\n\n/**\n * The built-in scopes that accept a target, and what the target names.\n *\n * - `data:*` — a collection slug\n * - `storage:*` — a storage source id (`(default)` for the default source)\n * - `functions:invoke` — a custom function's name\n *\n * @group Auth\n */\nexport const SCOPE_TARGETS: Readonly<Partial<Record<BuiltInScope, ScopeTargetKind>>> = {\n \"data:read\": \"collection\",\n \"data:write\": \"collection\",\n \"data:delete\": \"collection\",\n \"storage:read\": \"bucket\",\n \"storage:write\": \"bucket\",\n \"storage:delete\": \"bucket\",\n \"functions:invoke\": \"function\"\n};\n\n/** A scope's wording, for the screens that ask a person to grant it. @group Auth */\nexport interface ScopeDescription {\n /** Short, imperative: what a holder may do. */\n label: string;\n /** One sentence on what that reaches, including anything surprising. */\n description: string;\n}\n\n/** @group Auth */\nexport const BUILT_IN_SCOPE_DESCRIPTIONS: Readonly<Record<BuiltInScope, ScopeDescription>> = {\n \"data:read\": {\n label: \"Read data\",\n description: \"Read rows from tables, through the caller's row-level security.\"\n },\n \"data:write\": {\n label: \"Create and update data\",\n description: \"Create and update rows in tables, through the caller's row-level security.\"\n },\n \"data:delete\": {\n label: \"Delete data\",\n description: \"Delete rows from tables, through the caller's row-level security.\"\n },\n \"storage:read\": {\n label: \"Read files\",\n description: \"List and download stored files.\"\n },\n \"storage:write\": {\n label: \"Upload files\",\n description: \"Upload files and create folders.\"\n },\n \"storage:delete\": {\n label: \"Delete files\",\n description: \"Delete stored files.\"\n },\n \"functions:invoke\": {\n label: \"Call functions\",\n description: \"Call the backend's custom functions. A function can do anything its code does.\"\n },\n \"users:read\": {\n label: \"See users\",\n description: \"List user accounts and their roles.\"\n },\n \"users:write\": {\n label: \"Manage users\",\n description: \"Create, edit and delete accounts, reset passwords and second factors, and assign roles up to the holder's own.\"\n },\n \"schema:read\": {\n label: \"See the schema\",\n description: \"Read the schema, plan schema changes and run the RLS audit.\"\n },\n \"schema:write\": {\n label: \"Change the schema\",\n description: \"Apply schema changes: edits schema files and alters the database.\"\n },\n \"database:read\": {\n label: \"Inspect the database\",\n description: \"List databases, tables, Postgres roles and branches.\"\n },\n \"database:write\": {\n label: \"Run SQL\",\n description: \"Run SQL as the database owner, outside row-level security, and create or delete branches.\"\n },\n \"backups:read\": {\n label: \"Download backups\",\n description: \"List and download database backups — every row, outside row-level security.\"\n },\n \"cron:read\": {\n label: \"See cron jobs\",\n description: \"List cron jobs and read their run history.\"\n },\n \"cron:write\": {\n label: \"Run cron jobs\",\n description: \"Trigger cron jobs and switch them on or off.\"\n },\n \"logs:read\": {\n label: \"Read server logs\",\n description: \"Read the server's request and application logs.\"\n },\n \"keys:read\": {\n label: \"See service keys\",\n description: \"List the project's service keys. Never grantable to a key.\"\n },\n \"keys:write\": {\n label: \"Manage service keys\",\n description: \"Create, change and revoke the project's service keys. Never grantable to a key.\"\n }\n};\n\n/**\n * An app-declared scope, under `auth.scopes` on the users collection.\n *\n * @example\n * ```ts\n * auth: {\n * enabled: true,\n * scopes: {\n * \"project:deploy\": { label: \"Deploy projects\", target: \"project\" }\n * }\n * }\n * ```\n *\n * @group Auth\n */\nexport interface ScopeDefinition {\n /** Short, imperative: what a holder may do. Shown wherever the scope is granted. */\n label: string;\n /** One sentence on what that reaches. */\n description?: string;\n /**\n * What a target names, when the scope accepts one — `\"project\"` lets a\n * key hold `project:deploy:<id>`. Unset, the scope takes no target.\n */\n target?: string;\n}\n\n/**\n * An app-declared role, under `auth.roles` on the users collection.\n *\n * A role is a name the database sees (RLS policies match it) and a bundle of\n * admin-plane and app scopes. Data-plane scopes are not role scopes: what a\n * person may do with data is the collection's `securityRules`, so listing\n * `data:write` here would read as a grant it is not, and is refused.\n *\n * @example\n * ```ts\n * auth: {\n * enabled: true,\n * roles: {\n * support: { name: \"Support\", scopes: [\"users:read\", \"users:write\", \"logs:read\"] },\n * developer: { name: \"Developer\", scopes: [\"schema:read\", \"database:read\", \"logs:read\", \"cron:read\"] }\n * }\n * }\n * ```\n *\n * @group Auth\n */\nexport interface RoleDefinition {\n /** Display name. Defaults to the role id. */\n name?: string;\n /** One sentence on who holds it. */\n description?: string;\n /** Admin-plane and app scopes the role holds. */\n scopes: readonly string[];\n}\n\n/**\n * The declared access model: the app's own scopes and roles beside the\n * built-in ones. What `scopesForRoles` and `validateScopes` read.\n *\n * @group Auth\n */\nexport interface AccessModel {\n roles: Readonly<Record<string, RoleDefinition>>;\n scopes: Readonly<Record<string, ScopeDefinition>>;\n}\n\n/** The access model of an app that declares nothing: built-ins only. @group Auth */\nexport const EMPTY_ACCESS_MODEL: AccessModel = { roles: {}, scopes: {} };\n\n/** A scope string split into its scope and optional target. @group Auth */\nexport interface ParsedScope {\n /** `resource:action`. */\n scope: string;\n /** The one collection, bucket, function or app resource it is narrowed to. */\n target?: string;\n}\n\nconst SCOPE_PART = /^[a-z][a-z0-9-]*$/;\n\n/**\n * Split `resource:action[:target]`. Returns null for anything else.\n *\n * The target is everything after the second colon, so a target may itself\n * contain colons. Resource and action are lower-case words.\n *\n * @group Auth\n */\nexport function parseScope(value: string): ParsedScope | null {\n if (typeof value !== \"string\") return null;\n const first = value.indexOf(\":\");\n if (first < 0) return null;\n const second = value.indexOf(\":\", first + 1);\n const resource = value.slice(0, first);\n const action = second < 0 ? value.slice(first + 1) : value.slice(first + 1, second);\n if (!SCOPE_PART.test(resource) || !SCOPE_PART.test(action)) return null;\n if (second < 0) return { scope: `${resource}:${action}` };\n const target = value.slice(second + 1);\n if (target.length === 0 || /\\s/.test(target)) return null;\n return { scope: `${resource}:${action}`, target };\n}\n\n/** @group Auth */\nexport function isBuiltInScope(scope: string): scope is BuiltInScope {\n return (BUILT_IN_SCOPES as readonly string[]).includes(scope);\n}\n\n/** @group Auth */\nexport function isDataPlaneScope(scope: string): scope is DataPlaneScope {\n return (DATA_PLANE_SCOPES as readonly string[]).includes(scope);\n}\n\n/** @group Auth */\nexport function isAdminScope(scope: string): scope is AdminScope {\n return (ADMIN_SCOPES as readonly string[]).includes(scope);\n}\n\n/** Does this list of roles include the built-in `admin` role? @group Auth */\nexport function hasAdminRole(roles: readonly string[] | null | undefined): boolean {\n return !!roles?.includes(ADMIN_ROLE);\n}\n\n/**\n * Why `name` cannot be written as a role, or `undefined` when it can.\n *\n * No naming pattern is imposed — an app may call its roles anything. What is\n * refused is a name that would be read back as *other* roles: a role travels as\n * one element of a Postgres `text[]` and as one entry of the comma-joined\n * `app.user_roles` setting that RLS policies split with\n * `string_to_array(…, ',')`. Written as `\"support,admin\"`, a role comes back as\n * `admin`; braces, quotes and backslashes are array-literal syntax, so they are\n * refused too, as are empty names and control characters.\n *\n * @group Auth\n */\nexport function roleNameProblem(name: unknown): string | undefined {\n if (typeof name !== \"string\") return \"is not a string\";\n if (name.trim() === \"\") return \"is empty\";\n if (/[,{}\"\\\\]/.test(name)) return \"contains , { } \\\" or \\\\\";\n // eslint-disable-next-line no-control-regex\n if (/[\\u0000-\\u001f\\u007f]/.test(name)) return \"contains a control character\";\n return undefined;\n}\n\n/**\n * Does a set of held scopes grant `scope`, optionally on one `target`?\n *\n * The unqualified grant covers every target. A qualified grant covers its own\n * target only, and never answers an unqualified question: a key holding\n * `data:read:posts` is not asked \"may you read data?\" and told yes.\n *\n * @group Auth\n */\nexport function scopeGrants(held: readonly string[], scope: string, target?: string): boolean {\n for (const entry of held) {\n if (entry === scope) return true;\n if (target !== undefined && entry === `${scope}:${target}`) return true;\n }\n return false;\n}\n\n/**\n * Does a set of held scopes grant `scope` on at least one target?\n *\n * For a surface that lists what is reachable — the collections an MCP client\n * may query — and filters per item afterwards.\n *\n * @group Auth\n */\nexport function scopeGrantsAny(held: readonly string[], scope: string): boolean {\n const prefix = `${scope}:`;\n return held.some(entry => entry === scope || entry.startsWith(prefix));\n}\n\n/**\n * The targets a held set narrows `scope` to: `\"all\"` when it holds the\n * unqualified scope, otherwise the listed targets (possibly none).\n *\n * @group Auth\n */\nexport function scopeTargets(held: readonly string[], scope: string): \"all\" | string[] {\n const prefix = `${scope}:`;\n const targets: string[] = [];\n for (const entry of held) {\n if (entry === scope) return \"all\";\n if (entry.startsWith(prefix)) targets.push(entry.slice(prefix.length));\n }\n return targets;\n}\n\n/**\n * Every scope a person holding `roles` has.\n *\n * The data plane and every app scope always; the whole admin plane with the\n * `admin` role; otherwise each declared role's scopes. A role nobody declared\n * adds nothing — it may still mean something to an RLS policy.\n *\n * @group Auth\n */\nexport function scopesForRoles(roles: readonly string[] | null | undefined, model: AccessModel = EMPTY_ACCESS_MODEL): string[] {\n const held = new Set<string>([...DATA_PLANE_SCOPES, ...Object.keys(model.scopes)]);\n if (hasAdminRole(roles)) {\n for (const scope of ADMIN_SCOPES) held.add(scope);\n return [...held];\n }\n for (const role of roles ?? []) {\n const definition = Object.prototype.hasOwnProperty.call(model.roles, role) ? model.roles[role] : undefined;\n for (const scope of definition?.scopes ?? []) held.add(scope);\n }\n return [...held];\n}\n\n/**\n * Every scope this access model knows, unqualified: the built-ins, then the\n * app's own.\n *\n * @group Auth\n */\nexport function knownScopes(model: AccessModel = EMPTY_ACCESS_MODEL): string[] {\n return [...BUILT_IN_SCOPES, ...Object.keys(model.scopes)];\n}\n\n/** Does this scope accept a target? @group Auth */\nexport function scopeAcceptsTarget(scope: string, model: AccessModel = EMPTY_ACCESS_MODEL): boolean {\n if (isBuiltInScope(scope)) return SCOPE_TARGETS[scope] !== undefined;\n const definition = Object.prototype.hasOwnProperty.call(model.scopes, scope) ? model.scopes[scope] : undefined;\n return definition?.target !== undefined;\n}\n\n/** How a scope string failed to validate. @group Auth */\nexport interface ScopeProblem {\n scope: string;\n reason: \"malformed\" | \"unknown\" | \"target-not-accepted\";\n}\n\n/**\n * Check a list of scope strings against an access model. Returns the\n * problems, empty when every entry is a known scope with an acceptable target.\n *\n * @group Auth\n */\nexport function validateScopes(values: readonly unknown[], model: AccessModel = EMPTY_ACCESS_MODEL): ScopeProblem[] {\n const known = new Set(knownScopes(model));\n const problems: ScopeProblem[] = [];\n for (const value of values) {\n const text = typeof value === \"string\" ? value : String(value);\n const parsed = typeof value === \"string\" ? parseScope(value) : null;\n if (!parsed) {\n problems.push({ scope: text, reason: \"malformed\" });\n } else if (!known.has(parsed.scope)) {\n problems.push({ scope: text, reason: \"unknown\" });\n } else if (parsed.target !== undefined && !scopeAcceptsTarget(parsed.scope, model)) {\n problems.push({ scope: text, reason: \"target-not-accepted\" });\n }\n }\n return problems;\n}\n\n/**\n * The entries of `requested` that `held` does not cover — what a credential\n * would hold beyond its minter. Empty means the request is within reach.\n *\n * `data:read:posts` is covered by `data:read`; `data:read` is not covered by\n * `data:read:posts`.\n *\n * @group Auth\n */\nexport function scopesBeyond(requested: readonly string[], held: readonly string[]): string[] {\n return requested.filter(entry => {\n const parsed = parseScope(entry);\n if (!parsed) return true;\n return !scopeGrants(held, parsed.scope, parsed.target);\n });\n}\n\n/**\n * Narrow `requested` to what `held` covers, entry by entry. What a personal\n * key holds today when its owner has lost a role since it was minted.\n *\n * @group Auth\n */\nexport function intersectScopes(requested: readonly string[], held: readonly string[]): string[] {\n const beyond = new Set(scopesBeyond(requested, held));\n return requested.filter(entry => !beyond.has(entry));\n}\n\n/**\n * How a scope is worded for a person: the built-in description, the app's\n * declared label, or the raw string when nothing describes it. A target is\n * named after the label.\n *\n * @group Auth\n */\nexport function describeScope(value: string, model: AccessModel = EMPTY_ACCESS_MODEL): ScopeDescription {\n const parsed = parseScope(value);\n if (!parsed) return { label: value, description: \"\" };\n let base: ScopeDescription | undefined;\n if (isBuiltInScope(parsed.scope)) {\n base = BUILT_IN_SCOPE_DESCRIPTIONS[parsed.scope];\n } else if (Object.prototype.hasOwnProperty.call(model.scopes, parsed.scope)) {\n const definition = model.scopes[parsed.scope];\n base = { label: definition.label, description: definition.description ?? \"\" };\n }\n const label = base?.label ?? parsed.scope;\n return {\n label: parsed.target !== undefined ? `${label}: ${parsed.target}` : label,\n description: base?.description ?? \"\"\n };\n}\n\n/** A role as a person managing access sees it. @group Auth */\nexport interface RoleSummary {\n id: string;\n name: string;\n description?: string;\n /** Admin-plane and app scopes. The `admin` role lists every admin-plane scope. */\n scopes: string[];\n /** True for `admin`, which the app does not declare. */\n builtIn: boolean;\n}\n\n/** A scope as a screen that grants it lists it. @group Auth */\nexport interface ScopeSummary {\n scope: string;\n label: string;\n description: string;\n /** What a target names, when the scope takes one. */\n target?: string;\n /** `data`, `admin` or `app`: which plane the scope belongs to. */\n plane: \"data\" | \"admin\" | \"app\";\n}\n\n/** The roles of an access model, `admin` first. @group Auth */\nexport function summarizeRoles(model: AccessModel = EMPTY_ACCESS_MODEL): RoleSummary[] {\n return [\n { id: ADMIN_ROLE, name: \"Admin\", description: \"Holds every scope. Row-level security does not limit it: it reads, changes and deletes every row.\", scopes: [...ADMIN_SCOPES], builtIn: true },\n ...Object.entries(model.roles).map(([id, definition]) => ({\n id,\n name: definition.name ?? id,\n ...(definition.description ? { description: definition.description } : {}),\n scopes: [...definition.scopes],\n builtIn: false\n }))\n ];\n}\n\n/** Every scope of an access model, described, in display order. @group Auth */\nexport function summarizeScopes(model: AccessModel = EMPTY_ACCESS_MODEL): ScopeSummary[] {\n const builtIn: ScopeSummary[] = BUILT_IN_SCOPES.map(scope => ({\n scope,\n ...BUILT_IN_SCOPE_DESCRIPTIONS[scope],\n ...(SCOPE_TARGETS[scope] ? { target: SCOPE_TARGETS[scope] } : {}),\n plane: isDataPlaneScope(scope) ? \"data\" : \"admin\"\n }));\n const app: ScopeSummary[] = Object.entries(model.scopes).map(([scope, definition]) => ({\n scope,\n label: definition.label,\n description: definition.description ?? \"\",\n ...(definition.target ? { target: definition.target } : {}),\n plane: \"app\"\n }));\n return [...builtIn, ...app];\n}\n","/**\n * The project manifest (`rebase.json`) and the build artifacts derived from it.\n *\n * Three separate documents live in this file, and keeping them distinct matters:\n *\n * 1. {@link RebaseProjectManifest} — `rebase.json`. **Authored** by the developer,\n * committed to the repository. Declares topology only: which runtime major the\n * project targets, and which apps *this repository* contributes to the project.\n * Tables, security rules, hooks and functions stay in TypeScript under\n * `backend/` — nothing that needs a type system belongs here.\n *\n * 2. {@link RebaseProjectLink} — the per-checkout link (`.rebase/cloud.json`).\n * **Not committed**, because it is per-developer like a git remote. Says which\n * deployed project this working copy points at, whether that is a Rebase Cloud\n * project or the base URL of a self-hosted backend.\n *\n * 3. {@link RebaseBundleManifest} — `manifest.json` inside a built bundle.\n * **Generated**, never hand-edited. It is the lockfile analogue: the exact\n * contract a built artifact claims to satisfy, which the runtime validates\n * before it boots and a control plane validates before it deploys.\n *\n * A repository declares only the apps it contains. The set of apps belonging to a\n * project is held by the project itself, which is what makes multi-repo projects\n * work: two repositories never need to know about each other, only about the\n * project.\n */\n\nimport type { StorageSourceDefinition } from \"./storage_source\";\nimport type { ResourceGraph } from \"./resources\";\nimport type { TableDescriptor } from \"../schema/descriptor\";\n\n/**\n * Which kind of thing an app is.\n *\n * - `backend` — the tables/hooks/functions that define the project's API.\n * Exactly one per *project* (not per repository); the registry enforces it.\n * - `static` — a pre-built client bundle (SPA, static site), served from the\n * backend process at its declared `path` or from a CDN. The admin panel is\n * one of these: it is an app in the user's repository like any other.\n *\n * That is the whole list. Ownership of the server process is a property of the\n * backend app ({@link RebaseBackendAppConfig.runtime}), not an app type.\n */\nexport type RebaseAppType = \"backend\" | \"static\";\n\n/**\n * The backend app: the project's API surface.\n *\n * Paths are relative to the directory holding `rebase.json`. The defaults match\n * the layout `rebase init` scaffolds, so a stock project may declare simply\n * `{ \"type\": \"backend\", \"runtime\": \"managed\" }`.\n */\nexport interface RebaseBackendAppConfig {\n type: \"backend\";\n /**\n * Who owns the process this backend runs in.\n *\n * - `managed` — the platform's runtime image boots this project's bundle.\n * You supply tables, functions, crons and schema; Rebase supplies the\n * server.\n * - `custom` — this repository builds its own image and entrypoint. The\n * escape hatch: full control, no managed-runtime guarantees.\n *\n * Independent of *where* it runs. Both run on Rebase Cloud and both\n * self-host — the destination lives in `.rebase/cloud.json`, not here. See\n * `infra/docker/docker-compose.selfhost.yml`, which boots a managed bundle on a\n * developer's own Docker host.\n *\n * This is authored rather than inferred on purpose. It is the single most\n * consequential fact about a deployment, and inferring it is what used to\n * land projects on the custom runtime without anyone choosing it.\n */\n runtime: \"managed\" | \"custom\";\n /**\n * Directory whose `index.ts` exports the project's tables and views\n * (`defineTable`, `defineAuthTable`, `defineView`) and, optionally,\n * `defaultRls`. Default `backend/schema`.\n *\n * When it has no `index.ts` the project declares no tables, and the runtime\n * introspects them from the live database at boot.\n *\n * Not `schema`: that key already names the *generated* Drizzle module, and\n * a manifest is read by tools of every age.\n *\n * Replaces `config` (the config package, whose `collections/` held\n * `defineCollection` files) and `usersCollection` (the auth table is the one\n * declared with `defineAuthTable`). Both are refused by the CLI with the\n * codemod in the message — see {@link LEGACY_LAYOUT_REMEDY}.\n */\n tables?: string;\n /** Directory of server functions. Default `backend/functions`. */\n functions?: string;\n /** Directory of cron job definitions. Default `backend/crons` when present. */\n crons?: string;\n /**\n * Path to the generated Drizzle schema module (tables/enums/relations).\n * Default `backend/src/schema.generated.ts`.\n */\n schema?: string;\n /**\n * Type server-side data from the generated `Database`. When `true`, every\n * `rebase generate-sdk` — `rebase dev`'s included, and the first one on a\n * fresh clone — writes the types and the `Register` declaration to\n * `backend/generated/`. `rebase generate-sdk --register` sets it.\n * Default `false`.\n */\n registerDatabase?: boolean;\n\n /**\n * `runtime: \"custom\"` only. Dockerfile path relative to the repository root.\n * Default `Dockerfile`.\n */\n dockerfile?: string;\n /**\n * `runtime: \"custom\"` only. Directory handed to `docker build` as the build\n * context, relative to the directory holding `rebase.json`. Default `.`.\n *\n * The one path in this file allowed to point **above** the project. Every\n * other one names something Rebase reads, and those must be inside the\n * project or a bundle cannot carry them; this names something Rebase never\n * opens. In a workspace repository it normally has to be the workspace root\n * (`\"..\"`), because the lockfile and sibling packages a Dockerfile copies do\n * not live beside `rebase.json`.\n *\n * {@link RebaseBackendAppConfig.dockerfile} stays relative to `rebase.json`\n * whatever this is — it names a file in this repository, and moving the\n * context should not rewrite it. `rebase build` re-expresses it against the\n * context when it prints the command, because `docker build -f` resolves\n * against the working directory rather than the context.\n */\n context?: string;\n /** `runtime: \"custom\"` only. Port the container listens on. Default 8080. */\n port?: number;\n}\n\n/**\n * A static client bundle — SPA or static site — built here and served at `path`.\n */\nexport interface RebaseStaticAppConfig {\n type: \"static\";\n /** Package directory containing the client sources. */\n root: string;\n /** Command that produces `output`. Run from the repository root. */\n build?: string;\n /** Directory of built assets, relative to the repository root. */\n output: string;\n /**\n * Public base path this app is served under. Default `/`.\n *\n * Several static apps run in one process, each at its own path — the API at\n * `/api`, a site at `/`, the admin at `/admin` — which is what keeps a\n * self-hosted deployment a single container.\n *\n * **This is a build-time input, not only a serving concern.** An app mounted\n * at `/admin` must be *built* for `/admin` (Vite's `base`), or `index.html`\n * loads and every asset 404s: a blank page with no server error. `rebase\n * build` passes it as `REBASE_APP_BASE` and asserts the emitted HTML honours\n * it. Changing this value requires rebuilding the app.\n *\n * **Or a full URL, to give the app a hostname of its own:**\n * `\"https://admin.example.com\"`, or `\"https://admin.example.com/cms\"` for a\n * path under it. The app then answers only on that hostname, and every app\n * without one keeps answering on all the others. The URL form is split by\n * {@link parseAppAddress}: the hostname travels as the bundle's\n * {@link RebaseBundleStatic.host}, and the path part is what the rules above\n * (and `REBASE_APP_BASE`) apply to. HTTPS only, with no port, query or\n * fragment — a hostname is served over TLS by the platform, not chosen per\n * request.\n *\n * On Rebase Cloud the deploy registers the hostname on the project. It is\n * live once its DNS records verify, which the deploy prints when they don't\n * yet.\n */\n path?: string;\n /**\n * Serve `index.html` for unmatched paths under `path` (client-side routing).\n * Default `true` — the overwhelmingly common case for a client app, and a\n * static *site* generator emits real files for its routes anyway.\n */\n spa?: boolean;\n /**\n * Where this app mounts the Rebase CMS, as a URL path — the address you\n * would type to reach it, not a path relative to `path`.\n *\n * The CMS is an ordinary React component in the developer's own app\n * (`<RebaseCMS basePath=\"/admin\">`), so its address is a *client-side\n * route*: nothing on the server, in the bundle, or in the control plane can\n * observe it. A project whose CMS sits at `/admin` inside a frontend that\n * also serves a product at `/` is indistinguishable, from the outside, from\n * one that has no CMS at all — which is exactly how a Rebase Cloud project\n * came to have no discoverable admin URL anywhere in its console.\n *\n * Declaring it is the only way that fact travels. It is carried into the\n * bundle manifest, recorded on the project's app row at deploy, and is what\n * lets the console (and `rebase apps list`) offer a link straight to it.\n *\n * Must be `path` itself or something beneath it, since the app serving that\n * URL is the one that has to answer for it. Absent means this app does not\n * mount the CMS — the common case for a marketing site or a product app.\n *\n * @example \"/\" — the whole app is the CMS, as `rebase init` scaffolds it\n * @example \"/admin\" — the CMS is one route of a larger app\n */\n cms?: string;\n /**\n * Paths on this app's address that a custom function answers instead of\n * the build: a sitemap, a feed, a server-rendered page.\n *\n * A static app cannot claim `/api`, so without this a function's response\n * lives only at `/api/functions/<name>`, and `/sitemap.xml` or\n * `/blog/<slug>` needs a custom runtime or a proxy in front. A route\n * serves the function's response, whatever its content type, at the\n * route's path, on this app's hostname when its `path` names one.\n *\n * The function sees the request as if it had been called at\n * `/api/functions/<name>`, with the same auth, scopes and rate limit, and\n * a wildcard route hands it the rest of the path: `/blog/*` sends\n * `/blog/hello` to the function's `/hello` route. Query string, method,\n * headers and body pass through, `Host` included.\n *\n * The most specific route wins: an exact path before a wildcard, and a\n * longer wildcard before a shorter one. A route wins over a file of the\n * same path in the build. The function's `Content-Security-Policy` is its\n * own when it sends one; otherwise the response gets this app's, so\n * {@link RebaseStaticAppConfig.frameAncestors} covers routed pages too.\n *\n * Served by the process that serves the project's functions, which is the\n * backend this app is folded into. A static app deployed on its own has\n * no functions to call, so `rebase cloud deploy` refuses one with routes.\n */\n routes?: RebaseStaticRoute[];\n /**\n * Origins allowed to frame this app, besides its own.\n *\n * A static app is served with `frame-ancestors 'self'`, so only a page on\n * its own origin can put it in an iframe. A CMS on `admin.example.com`\n * that previews the site on `www.example.com` needs the site to name it:\n * `[\"https://admin.example.com\"]`. Each entry is one origin: `https://`\n * with a hostname and an optional port, or `http://` for `localhost`,\n * `127.0.0.1` and `[::1]` while developing. No wildcards, no paths, no\n * keywords — `'self'` is always included.\n *\n * Applies to every response this app serves, and to its routes' responses\n * that carry no policy of their own.\n */\n frameAncestors?: string[];\n}\n\n/**\n * A path on a static app's address answered by a custom function instead of\n * the app's build. See {@link RebaseStaticAppConfig.routes}.\n */\nexport interface RebaseStaticRoute {\n /**\n * The URL path, absolute — not relative to the app's `path` — and inside\n * it. Either exact, `/sitemap.xml`, or a prefix ending in `/*`, `/blog/*`,\n * which matches `/blog` itself and every path beneath it.\n */\n path: string;\n /** The custom function that answers it, by name: `sitemap` for `/api/functions/sitemap`. */\n function: string;\n}\n\nexport type RebaseAppConfig = RebaseBackendAppConfig | RebaseStaticAppConfig;\n\n/**\n * Path prefixes the backend owns, which no static app may claim.\n *\n * One process — and, on the platform, one hostname — serves both the API and\n * however many static apps a project has. Mounting is longest-path-first, so an\n * app declaring `/api` would win against the API itself and every request to it\n * would be answered with that app's `index.html`: a 200 carrying HTML where the\n * caller expected JSON, from a project that looks deployed and healthy.\n *\n * Declared here rather than in either enforcer because both must agree. The CLI\n * checks it so a developer finds out while editing `rebase.json`; the control\n * plane checks it again at deploy intake, because the front door's correctness\n * cannot rest on a check that ran in somebody else's CLI — and a repository can\n * be deployed by a CLI older than this rule.\n */\nexport const RESERVED_BACKEND_PREFIXES = [\"/api\", \"/health\", \"/healthz\", \"/livez\", \"/readyz\", \"/metrics\"] as const;\n\n/**\n * Whether `path` collides with a prefix the backend owns.\n *\n * Compares at segment boundaries, so `/api` and `/api/v2` collide while\n * `/apidocs` does not — the same rule the router matches with, because a check\n * that is stricter than the router rejects paths that would have worked, and one\n * that is looser admits paths that will not.\n */\nexport function reservedPrefixFor(path: string): string | undefined {\n const normalized = path.endsWith(\"/\") && path !== \"/\" ? path.slice(0, -1) : path;\n return RESERVED_BACKEND_PREFIXES.find(\n reserved => normalized === reserved || normalized.startsWith(`${reserved}/`)\n );\n}\n\n/**\n * Where a static app answers: on one hostname or all of them, at a path.\n *\n * `host` absent is every hostname the project is served on.\n */\nexport interface AppAddress {\n host?: string;\n path: string;\n}\n\nexport type AppAddressResult =\n | { ok: true; address: AppAddress }\n | { ok: false; reason: string };\n\n/**\n * Split a static app's declared `path` into the hostname it claims and the path\n * under it.\n *\n * `\"/admin\"` is `{ path: \"/admin\" }`, returned as written: the path rules\n * (leading slash, no `..`, reserved prefixes) belong to the caller, which\n * applies them to the path part of either form. `\"https://admin.example.com/cms\"`\n * is `{ host: \"admin.example.com\", path: \"/cms\" }`.\n *\n * Shared because three parties must read the same value the same way: the CLI\n * while `rebase.json` is edited, the control plane at deploy intake (a bundle can\n * come from any CLI, or none), and the runtime choosing which app answers.\n */\nexport function parseAppAddress(value: string): AppAddressResult {\n if (!/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value)) {\n // A bare hostname is the likeliest mistake, and \"must start with /\" would\n // not say what was meant.\n if (!value.startsWith(\"/\") && isValidAppHost(value.toLowerCase().replace(/\\/.*$/, \"\"))) {\n return { ok: false, reason: `looks like a hostname — write it as a URL: \"https://${value}\"` };\n }\n return { ok: true, address: { path: value } };\n }\n\n // `new URL` forgives what a manifest should not: it strips tabs and newlines,\n // reads \"\\\" as \"/\", and drops a default \":443\". Each would make the address\n // mean something other than what was written, so these are judged on the\n // text, before the parser can tidy them away.\n // eslint-disable-next-line no-control-regex\n if (/[\\s\\\\\\u0000-\\u001f\\u007f]/.test(value)) {\n return { ok: false, reason: \"must not contain spaces, control characters or backslashes\" };\n }\n const authority = value.slice(value.indexOf(\"//\") + 2).split(/[/?#]/)[0];\n if (/:[^@]*$/.test(authority) && !authority.startsWith(\"[\")) {\n return { ok: false, reason: \"must not name a port — a hostname is served on 443\" };\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return { ok: false, reason: \"is not a valid URL\" };\n }\n if (url.protocol !== \"https:\") {\n return { ok: false, reason: `must use https — the platform serves every hostname over TLS: \"https://${url.host}${url.pathname === \"/\" ? \"\" : url.pathname}\"` };\n }\n if (url.username || url.password) return { ok: false, reason: \"must not contain credentials\" };\n if (url.port) return { ok: false, reason: \"must not name a port — a hostname is served on 443\" };\n // `new URL` drops an empty \"?\" or \"#\", so test the text as well.\n if (url.search || url.hash || /[?#]/.test(value)) {\n return { ok: false, reason: \"must not have a query or fragment\" };\n }\n if (!isValidAppHost(url.hostname)) {\n return { ok: false, reason: `names \"${url.hostname}\", which is not a public hostname` };\n }\n // The rules a path is held to are the caller's, so hand back what was\n // written after the host, not what `URL` normalised it to — a `..` resolved\n // away here would slip past the check that exists to refuse it.\n const authorityAndPath = value.slice(value.indexOf(\"//\") + 2);\n const slash = authorityAndPath.indexOf(\"/\");\n return { ok: true, address: { host: url.hostname, path: slash === -1 ? \"/\" : authorityAndPath.slice(slash) } };\n}\n\n/**\n * Whether `host` is a public DNS name an app can be given: lowercase labels of\n * letters, digits and hyphens, at least two of them, not an IP address and not\n * `localhost`. Internationalised names arrive here already in punycode.\n */\nexport function isValidAppHost(host: string): boolean {\n if (host.length === 0 || host.length > 253 || host !== host.toLowerCase()) return false;\n const labels = host.split(\".\");\n if (labels.length < 2) return false;\n const label = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;\n if (!labels.every(part => label.test(part))) return false;\n // An all-numeric last label is an IPv4 address, never a TLD.\n return !/^[0-9]+$/.test(labels[labels.length - 1]);\n}\n\n/** Whether `path` is `parent`, or a path beneath it, at segment boundaries. */\nfunction isPathUnder(path: string, parent: string): boolean {\n if (parent === \"/\") return true;\n return path === parent || path.startsWith(`${parent}/`);\n}\n\n/**\n * The characters a route's path may hold: unreserved and sub-delimiters, `:`,\n * `@` and `/`. A request path arrives percent-encoded and is matched as it\n * arrives, so a route written with a space, a `%` or a non-ASCII letter could\n * never match anything.\n */\nconst ROUTE_PATH_CHARACTERS = /^\\/[A-Za-z0-9\\-._~!$&'()+,;=:@/]*$/;\n\n/** A function's name as it appears in `/api/functions/<name>`: one path segment. */\nconst FUNCTION_NAME = /^[A-Za-z0-9_-][A-Za-z0-9_.-]*$/;\n\nexport type StaticRouteResult =\n | { ok: true; route: RebaseStaticRoute }\n | { ok: false; field?: \"path\" | \"function\"; reason: string };\n\n/**\n * Validate one of a static app's routes against the app's own path (the path\n * part of its address).\n *\n * Shared for the reason {@link parseAppAddress} is: the CLI checks a route\n * while `rebase.json` is edited, and the runtime checks it again when it loads\n * a bundle, which any program could have written. The rules:\n *\n * - `path` is absolute, with no `..`, empty segment or trailing slash, and\n * ends in `/*` or holds no `*` at all.\n * - No segment starts with a dot: `/.well-known` is the backend's, and a\n * static app serves no dot-file.\n * - It is not under a prefix the backend owns ({@link RESERVED_BACKEND_PREFIXES}),\n * because the API answers there on every hostname.\n * - It is inside the app's path, since the app is what answers there, and a\n * wildcard does not cover the whole app, which would leave nothing of the\n * build to serve.\n * - `function` is one path segment, as a function's file name is.\n */\nexport function validateStaticRoute(value: unknown, appPath: string): StaticRouteResult {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return { ok: false, reason: 'must be an object like { \"path\": \"/sitemap.xml\", \"function\": \"sitemap\" }' };\n }\n const { path, function: fn } = value as Record<string, unknown>;\n\n if (typeof path !== \"string\" || !path.startsWith(\"/\")) {\n return { ok: false, field: \"path\", reason: 'must be an absolute path like \"/sitemap.xml\" or \"/blog/*\"' };\n }\n const wildcard = path.endsWith(\"/*\");\n const prefix = wildcard ? path.slice(0, -2) || \"/\" : path;\n if (prefix.includes(\"*\")) {\n return { ok: false, field: \"path\", reason: 'may end in \"/*\" to match everything beneath a path, and holds no other \"*\"' };\n }\n if (!ROUTE_PATH_CHARACTERS.test(prefix)) {\n return {\n ok: false,\n field: \"path\",\n reason: \"may hold letters, digits, \\\"/\\\" and - . _ ~ ! $ & ' ( ) + , ; = : @ only — no spaces, \\\"?\\\", \\\"#\\\" or \\\"%\\\"\"\n };\n }\n if (prefix.includes(\"//\") || (prefix !== \"/\" && prefix.endsWith(\"/\"))) {\n return { ok: false, field: \"path\", reason: \"must have no empty segment and no trailing slash\" };\n }\n if (prefix.split(\"/\").some(segment => segment.startsWith(\".\"))) {\n return { ok: false, field: \"path\", reason: 'must have no segment starting with \".\" — the backend serves /.well-known, and an app serves no dot-file' };\n }\n const reserved = reservedPrefixFor(prefix);\n if (reserved) {\n return { ok: false, field: \"path\", reason: `cannot be \"${reserved}\" or nest under it — the backend serves that path on every hostname` };\n }\n if (!isPathUnder(prefix, appPath)) {\n return { ok: false, field: \"path\", reason: `must be inside this app's path, \"${appPath}\" — the app is what answers there` };\n }\n if (wildcard && prefix === appPath) {\n return { ok: false, field: \"path\", reason: `covers all of this app's path, \"${appPath}\", so nothing in its build would ever be served` };\n }\n\n if (typeof fn !== \"string\" || !FUNCTION_NAME.test(fn)) {\n return { ok: false, field: \"function\", reason: 'must name a custom function, as its file is named: \"sitemap\" for functions/sitemap.ts' };\n }\n return { ok: true, route: { path, function: fn } };\n}\n\n/**\n * Whether `route` answers `requestPath`, and with what path under its\n * function: `\"\"` for the route's own path, `/rest` beneath a wildcard.\n * `undefined` when it does not match.\n *\n * Compared as the path arrives, percent-encoding and all, and at segment\n * boundaries: `/blog/*` matches `/blog` and `/blog/x`, not `/blogroll`.\n */\nexport function matchStaticRoute(route: RebaseStaticRoute, requestPath: string): string | undefined {\n if (!route.path.endsWith(\"/*\")) return requestPath === route.path ? \"\" : undefined;\n const prefix = route.path.slice(0, -2);\n if (prefix === \"\") return requestPath === \"/\" ? \"\" : requestPath;\n if (requestPath === prefix) return \"\";\n return requestPath.startsWith(`${prefix}/`) ? requestPath.slice(prefix.length) : undefined;\n}\n\n/**\n * Order routes so the first match is the most specific: exact paths first,\n * then wildcards by the length of their prefix, longest first. Declaration\n * order breaks ties, which only equal wildcards can have.\n */\nexport function compareStaticRoutes(a: RebaseStaticRoute, b: RebaseStaticRoute): number {\n const aWild = a.path.endsWith(\"/*\");\n const bWild = b.path.endsWith(\"/*\");\n if (aWild !== bWild) return aWild ? 1 : -1;\n return aWild ? b.path.length - a.path.length : 0;\n}\n\nexport type FrameAncestorResult =\n | { ok: true; origin: string }\n | { ok: false; reason: string };\n\n/** Hosts plain `http://` is accepted for: a CMS running on the developer's own machine. */\nconst LOOPBACK_HOSTS = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\n\n/**\n * Validate one entry of a static app's `frameAncestors`: a single origin that\n * may frame the app.\n *\n * The value ends up inside a `Content-Security-Policy` header, so it is held\n * to the exact serialisation of an origin — `new URL(value).origin` has to\n * give it back unchanged. That leaves nothing that could close the directive\n * or open another one, and turns every near miss (a trailing slash, a\n * capital, a default port, a path) into a refusal that names the fix.\n *\n * `https://` with a public hostname, or `localhost`; plain `http://` only for\n * a loopback host. Never a wildcard or a keyword: this is a list of the\n * origins an operator chose, and `'self'` is always on it.\n */\nexport function parseFrameAncestor(value: unknown): FrameAncestorResult {\n const example = 'must be an origin like \"https://admin.example.com\"';\n if (typeof value !== \"string\" || value === \"\") return { ok: false, reason: example };\n if (value.includes(\"*\")) {\n return { ok: false, reason: \"must name one origin — wildcards are not accepted, so list each origin that may frame this app\" };\n }\n if (value.startsWith(\"'\")) {\n return { ok: false, reason: `${example} — keywords are not accepted, and 'self' is always allowed` };\n }\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return { ok: false, reason: example };\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") return { ok: false, reason: example };\n const loopback = LOOPBACK_HOSTS.has(url.hostname);\n if (url.protocol === \"http:\" && !loopback) {\n return { ok: false, reason: `must use https — plain http is accepted for localhost only: \"https://${url.host}\"` };\n }\n if (!loopback && !isValidAppHost(url.hostname)) {\n return { ok: false, reason: `names \"${url.hostname}\", which is not a public hostname` };\n }\n if (url.origin !== value) {\n return { ok: false, reason: `must be the origin alone — scheme, hostname and an optional port, lowercase, with nothing after it: \"${url.origin}\"` };\n }\n return { ok: true, origin: value };\n}\n\n/**\n * One declared storage source, as authored in `rebase.json`.\n *\n * The key comes from the enclosing record, so this is\n * {@link StorageSourceDefinition} minus its `key` — the same document the\n * runtime registry and the frontend router consume, expressed the way a JSON\n * object naturally expresses \"a set of named things\".\n */\nexport interface RebaseStorageSourceConfig {\n /** Engine backing this source: `local`, `s3`, `gcs`, or a custom id. */\n engine: string;\n /**\n * How the frontend reaches it. Default `server` (proxied through\n * `/api/storage`). `direct` means a provider SDK talks to the bucket and the\n * backend is not in the upload path.\n */\n transport?: \"server\" | \"direct\";\n /** Human-readable label for the console and the admin UI. */\n label?: string;\n}\n\n/**\n * `rebase.json` — the authored project manifest.\n */\nexport interface RebaseProjectManifest {\n /** JSON Schema URL, for editor completion. Ignored by the tooling. */\n $schema?: string;\n /**\n * The runtime contract **major** this project targets, as a semver range\n * (e.g. `^1`, `~1.4`, or an exact `1.4.2` to pin).\n *\n * The platform upgrades patches and minors underneath a project without\n * asking; it never crosses a major. See {@link RUNTIME_CONTRACT_VERSION}.\n *\n * Named `rebase` rather than `runtime` so that `runtime` means exactly one\n * thing — {@link RebaseBackendAppConfig.runtime}, who owns the process. It\n * reads like `engines` in a `package.json`, which is what it is.\n */\n rebase: string;\n /**\n * Apps this repository contributes, keyed by app name. The key is the app's\n * identity within the project: it is what `rebase deploy <app>` names, what\n * client credentials are issued against, and what a second repository must\n * not collide with.\n */\n apps: Record<string, RebaseAppConfig>;\n /**\n * Buckets are NOT declared here any more.\n *\n * They were, and the runtime merged this block with the declarations in\n * config code — a bucket named in both had one engine kept and the other\n * silently discarded. Two homes for one concept, with a merge to decide\n * between them, is the shape this whole model replaced.\n *\n * `bucket(\"media\", { engine: \"s3\" })` in the project's config declares one\n * now, and `rebase resources --write` generates `rebase.resources.json`,\n * which is what a host reads before a build. A `storage` block left in this\n * file is refused by the validator, by name, with the replacement in the\n * message — not ignored, because a key that still parses and does nothing\n * is the failure this removed.\n */\n /**\n * Repository-wide opt-out from anonymous CLI usage sharing.\n *\n * **Only `false` does anything.** It suppresses sharing for everyone who\n * clones this repository, overriding each developer's own answer — an\n * organisation setting policy for work done on its behalf, the same shape\n * as a committed `.npmrc`.\n *\n * `true` is deliberately ignored, and the CLI says so rather than obeying\n * quietly. This file is committed, so a `true` here would be one developer\n * answering a privacy question for every colleague who later clones the\n * repo — consent by proxy, which is the exact thing opt-in exists to\n * prevent. Individuals answer at `rebase init`, or with `rebase telemetry enable` / `disable`.\n */\n telemetry?: boolean;\n}\n\n/**\n * The per-checkout project link.\n *\n * Deliberately separate from `rebase.json`: the manifest is committed and shared,\n * while the link is per-developer. Keeping them in one file would mean either\n * committing someone's project id or gitignoring the topology.\n */\nexport interface RebaseProjectLink {\n /**\n * A Rebase Cloud project id, or the base URL of any running Rebase backend\n * (`https://api.example.com`). Both are first-class: every command that\n * accepts a project reference accepts either, so a self-hosted project has\n * the same tooling as a cloud one.\n */\n project: string;\n /** Organization slug. Cloud projects only. */\n org?: string;\n /** Explicit API base URL, when it differs from the project's default. */\n apiUrl?: string;\n}\n\n/**\n * Whether a project can run on the managed runtime, and if not, precisely why.\n *\n * The reasons are returned rather than summarised so tooling can print something\n * a developer can act on. \"Not eligible\" is never a dead end — it selects the\n * custom-runtime path, which still deploys.\n */\nexport interface ManagedCompatibility {\n eligible: boolean;\n reasons: string[];\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Bundle\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Version of the bundle *format* itself.\n *\n * Bumped only when the on-disk layout changes in a way an older runtime could\n * not read. A runtime accepts any bundle whose `bundleFormat` is less than or\n * equal to its own — old bundles keep booting on new runtimes, which is the\n * whole point of separating the artifact from the engine.\n *\n * - **1** — `mode: \"cms\" | \"baas\" | \"static\"`, `entry.static` a single directory\n * string, `entry.admin` for a bundled admin panel.\n * - **2** — `kind: \"backend\" | \"static\"`, `entry.static` a list of\n * {@link RebaseBundleStatic}, `entry.admin` removed. A format-1 runtime reading\n * one of these would find no `mode` and an array where it expects a string, so\n * the bump is what turns that into a refusal to boot instead of a bundle that\n * starts and serves nothing.\n * - **3** — the schema is `entry.tables` (the compiled `backend/schema`\n * directory, whose `index` exports the tables), beside `entry.resources`,\n * `entry.storage` and `entry.hooks`. There is no config package any more:\n * `entry.config`, `entry.collections` and `entry.usersCollection` are not\n * written. A format-2 runtime would find none of the keys it boots from and\n * introspect the database instead of serving the declared tables — so the\n * bump turns that into a refusal.\n *\n * **Format 2 bundles are refused, not upgraded.** Unlike 1 → 2, which was a\n * renaming, a format-2 bundle carries `config/collections` — `defineCollection`\n * objects — and a runtime that reads only `backend/schema` has nothing to read\n * them with. It refuses them at boot with {@link LEGACY_LAYOUT_REMEDY} in the\n * error: run the codemod on the project's source, then rebuild.\n */\nexport const BUNDLE_FORMAT_VERSION = 3;\n\n/**\n * What to do about a project on the `config/collections` layout — the words\n * every refusal of that layout ends with.\n *\n * Shared because two parties refuse it and must say the same thing: the CLI,\n * for a `rebase.json` that still names `config` or `usersCollection`, and the\n * runtime, for a format-2 / contract-1 bundle built from `config/collections`.\n */\nexport const LEGACY_LAYOUT_REMEDY =\n \"run `rebase migrate collections-to-tables` (in the Rebase repository: \" +\n \"tooling/scripts/migrate-collections-to-tables.mts), which rewrites config/collections as \" +\n \"backend/schema (and the admin presentation as frontend/src/cms), carries the collection \" +\n \"callbacks into the tables as hooks, moves resources.ts and storage.ts to backend/, and proves \" +\n \"the generated SQL unchanged; then rebuild\";\n\n/**\n * The runtime contract major.\n *\n * Distinct from the `@rebasepro/server` package version: the package may release\n * any number of minors and patches while this stays put. It changes only when\n * the bundle/runtime contract breaks compatibility, and a project's\n * `manifest.runtime` range is matched against *this*.\n *\n * ## v2 — tables, not collections\n *\n * The runtime reads the project's schema from `backend/schema` (bundle format\n * 3, `entry.tables`): `defineTable` / `defineAuthTable` / `defineView` exports\n * and `defaultRls`. It no longer loads `config/collections`, and it no longer\n * reads a config package's `collections` / `callbacks` exports or a\n * `usersCollection` module; global table hooks come from `backend/hooks.ts`,\n * `storageAuthorize` from `backend/storage.ts`, declared resources from\n * `backend/resources.ts`.\n *\n * So, plainly: **a format-2 / contract-1 bundle — one built from\n * `config/collections` — is refused by a contract-2 runtime**, at boot, with\n * {@link LEGACY_LAYOUT_REMEDY} in the message. There is no in-runtime adapter\n * from collections to tables; the project's source is migrated once with the\n * codemod and rebuilt. On the managed tier that means the platform keeps such a\n * tenant on a contract-1 image until it is rebuilt — the release order below\n * applies unchanged.\n *\n * This has to be a major, and the reason is the managed tier: it moves projects\n * onto new images WITHOUT rebuilding them. Without the bump, one image rollout\n * would crash-loop every tenant whose bundle predates the change, in a wave,\n * with the cause in a container log nobody is watching. With it, an older\n * bundle on a newer runtime is refused by `readBundleManifest` with the remedy\n * in the message, and the platform keeps it on an image of its own major until\n * it is rebuilt. That is the whole purpose of this number.\n *\n * (Declared resources — `database()` / `bucket()` replacing\n * `RebaseBackendConfig.dataSources` / `.storageSources` — once took this number\n * to 2 and were taken back to 1 before launch, when there was no fleet for the\n * major to protect. They are part of v1.)\n *\n * **Release order matters and is not optional.** The control plane is the side\n * that rejects, so it ships FIRST: raise `SUPPORTED_RUNTIME_CONTRACT` in the\n * saas repo (it rejects only `contract >` its own, so it then accepts both),\n * deploy that, and only then release a runtime implementing v2. Shipping the\n * runtime first turns every deploy into a rejected intake blaming the tenant's\n * bundle.\n */\nexport const RUNTIME_CONTRACT_VERSION = 2;\n\n/** Where the runtime finds each part of the bundle. Paths are bundle-relative. */\nexport interface RebaseBundleEntrypoints {\n /**\n * Compiled `backend/schema` directory: its `index.js` exports the tables,\n * views and optional `defaultRls`. Absent when the project declares no\n * tables, which makes the runtime introspect the database instead.\n *\n * Not `schema`, which is the compiled *Drizzle* module below.\n */\n tables?: string;\n /** Compiled `backend/resources` module — the `database()` / `bucket()` / `topic()` declarations. */\n resources?: string;\n /** Compiled `backend/storage` module, exporting `storageAuthorize`. */\n storage?: string;\n /** Compiled `backend/hooks` module, exporting `hooks` (global table hooks). */\n hooks?: string;\n /** Compiled functions directory. */\n functions?: string;\n /** Compiled crons directory. */\n crons?: string;\n /** Compiled Drizzle schema module. */\n schema?: string;\n /**\n * A copy of the frontend's `src/cms/ui-config.json` — the presentation the\n * collection editor saved in development and the frontend ships as\n * `<RebaseCMS uiConfig>` — so the server knows it too: it is the workspace\n * baseline of what the server serves about presentation (the MCP views,\n * `GET /api/admin/ui-config`'s `shipped`).\n *\n * Optional and additive within format 3: absent when the project has no\n * such file, and on bundles built before it existed, which boot as before\n * (the server then knows only the preferences it stores).\n */\n uiConfig?: string;\n /**\n * Built static apps to serve from this process, in declaration order.\n *\n * A list rather than a single directory because one process serves several\n * apps at different paths — a site at `/` and the admin at `/admin`. The\n * runtime mounts them longest-path-first so the `/`-rooted app's catch-all\n * does not claim its siblings' URLs.\n */\n static?: RebaseBundleStatic[];\n}\n\n/** One built static app inside a bundle. */\nexport interface RebaseBundleStatic {\n /** Public base path, e.g. `/` or `/admin`. Always a path, never a URL. */\n path: string;\n /**\n * The one hostname this app answers on, lowercase, e.g. `admin.example.com`.\n *\n * Absent means every hostname the project is served on, which is what every\n * app was before this field existed. Present, the app answers only for\n * requests whose `Host` is exactly this — the path part of its address is\n * still `path`. At an equal `path`, an app naming the request's hostname\n * wins over one that does not.\n *\n * A runtime that predates this field ignores it and would mount two apps at\n * the same `path`, so a bundle carrying it must only ever reach a runtime\n * that reads it. The control plane enforces that at intake.\n */\n host?: string;\n /** Bundle-relative directory holding the built assets. */\n dir: string;\n /** Serve `index.html` for unmatched paths under `path`. */\n spa: boolean;\n /**\n * The app's name in `rebase.json`.\n *\n * `dir` is `static/<name>` and has been since folding was written, so this\n * is recoverable by string surgery — which is precisely why it is stated\n * instead. A control plane reconciling app rows against this list has to\n * match them by name, and a consumer that has to re-derive an identifier\n * from a path is one refactor away from matching nothing and registering a\n * duplicate app on every deploy.\n *\n * Optional because bundles built before this field exists do not carry it;\n * a reader that needs a name falls back to the last segment of `dir`.\n */\n name?: string;\n /**\n * Where this app mounts the Rebase CMS, as a URL path.\n *\n * Copied from the app's declaration — see {@link RebaseStaticAppConfig.cms}\n * for why a client-side route has to be declared to be knowable at all.\n */\n cms?: string;\n /**\n * Paths a custom function answers instead of the build, copied from the\n * app's declaration — see {@link RebaseStaticAppConfig.routes}.\n *\n * A runtime that predates this field ignores it and answers each path from\n * the build, which for an SPA is `index.html` with a 200. Nothing breaks\n * that worked before, but the route is not served until the runtime reads\n * it.\n */\n routes?: RebaseStaticRoute[];\n /**\n * Origins besides its own that may frame this app, copied from the app's\n * declaration — see {@link RebaseStaticAppConfig.frameAncestors}. A runtime\n * that predates this field serves `frame-ancestors 'self'`.\n */\n frameAncestors?: string[];\n}\n\n/**\n * A native module found in the dependency closure.\n *\n * Recorded rather than merely counted so a rejection can name the offending\n * package instead of saying \"something here is native\".\n */\nexport interface NativeDependency {\n name: string;\n /** Why it was flagged — a `.node` binary, a gyp build, or an install script. */\n reason: string;\n}\n\n/**\n * `manifest.json` — generated, and the document the runtime and control plane\n * both validate against.\n */\n/**\n * One custom function, as recorded in a built bundle.\n *\n * @see RebaseBundleManifest.functions\n */\nexport interface RebaseBundleFunction {\n /**\n * The filename without its extension — which is also the URL segment it\n * mounts at (`/api/functions/<name>`), the API-key permission that grants\n * it, and the name `REBASE_FUNCTIONS_ONLY` selects by. One identity, used\n * everywhere.\n */\n name: string;\n /** Path inside the bundle, so a host can point at the file. */\n file: string;\n /**\n * `false` when the function's own source imports a Node built-in or a\n * package that needs one.\n *\n * Descriptive, never a gate: nothing refuses to build or deploy on this. It\n * says where this function *could* run, not where it should.\n */\n portable: boolean;\n /**\n * Why it is not portable — one short phrase per reason, deduplicated.\n * Absent when it is.\n */\n requires?: string[];\n}\n\nexport interface RebaseBundleManifest {\n /** @see BUNDLE_FORMAT_VERSION */\n bundleFormat: number;\n runtime: {\n /** The `runtime` range copied from `rebase.json`. */\n range: string;\n /** Exact `@rebasepro/server` version this bundle was built against. */\n builtAgainst: string;\n /** Runtime contract major this bundle requires. */\n contract: number;\n };\n /**\n * Hash of the compiled table descriptors (`computeSchemaVersion`).\n *\n * This is the contract stamp. A generated SDK records the value it was built\n * from, a client sends it back, and a mismatch is what lets the platform say\n * \"this app was built against an older schema\" instead of failing mysteriously\n * at the first request. It covers tables only — a hook's code does not\n * change a client's contract, so editing it must not invalidate every SDK.\n */\n schemaVersion: string;\n /** Which app in `rebase.json` this bundle was built from. */\n app: string;\n /**\n * What the runtime does with this bundle.\n *\n * - `backend` — boot the full server: database, auth and the data API, plus\n * any static apps in `entry.static`.\n * - `static` — no backend at all: serve `entry.static` and nothing else. No\n * database, no auth, no data sources. This is how a static app runs on the\n * same image as the backend.\n *\n * Replaces an earlier `mode: \"cms\" | \"baas\" | \"static\"`. The cms/baas\n * distinction was never a third kind of thing — it is simply whether\n * `entry.tables` is present, so it is derived rather than declared.\n */\n kind: \"backend\" | \"static\";\n entry: RebaseBundleEntrypoints;\n /** Table slugs contained in the bundle, for quick inspection. */\n tables?: string[];\n /**\n * Every custom function in the bundle, named and classified.\n *\n * Two things are recorded per function, and both are answers a host would\n * otherwise have to get by importing user code:\n *\n * - **What it is called.** That name is the function's identity everywhere —\n * the URL segment it mounts at, the `functions/<name>` API-key\n * permission, the value `REBASE_FUNCTIONS_ONLY` selects by. A host that\n * wants to give one slow function its own replica count currently has to\n * boot the bundle to discover what is in it.\n * - **Whether it needs Node.** Purely descriptive: a function that opens a\n * file or runs raw SQL is a fine function, and every deployment today is\n * a Node process. It is recorded because the question \"which of these\n * could run somewhere else\" has to be answerable from the artifact, and\n * because answering it per-file after the fact — across a codebase\n * already written — is the expensive version of the same question.\n *\n * Absent on a bundle built before this field existed, which is why every\n * consumer must treat it as optional rather than as an empty list.\n */\n functions?: RebaseBundleFunction[];\n hooks: {\n /**\n * Whether the dependency closure contains native code.\n *\n * The managed runtime refuses these: a prebuilt binary cannot be run on\n * an image the platform did not build it for, and the honest failure is\n * at deploy time rather than at 3am in a crash loop.\n */\n native: boolean;\n nativeModules?: NativeDependency[];\n };\n /**\n * What the bundle's config says about storage access control.\n *\n * Storage is not under RLS and its keys share one flat namespace, so a\n * deployment with file storage enabled and no access model serves every\n * user's files to every signed-in user. The runtime refuses to boot in that\n * state — which, on a hosted platform that enables storage from the *console*\n * rather than from the bundle, surfaces as a crash loop the developer cannot\n * read.\n *\n * Recording it here lets a host reject the deploy with the reason instead.\n * Absent on bundles built before this field existed.\n */\n storage?: {\n /** Whether `backend/storage` exports a `storageAuthorize` hook. */\n authorize: boolean;\n /**\n * Buckets, on bundles built before {@link RebaseBundleManifest.resources}.\n *\n * No longer written. A host reads `resources`, which carries every kind\n * in one list; this stays declared so a control plane can keep reading\n * the bundles a project shipped before it was rebuilt.\n */\n sources?: StorageSourceDefinition[];\n };\n /**\n * Everything the project declares it needs — databases, buckets, topics,\n * and whatever kind is registered next.\n *\n * Recorded so a host can tell, from the artifact alone and before starting\n * anything, what a deploy will need provisioned. That question used to be\n * answerable for buckets and for nothing else, because buckets were the\n * only kind written into an artifact — which is how a project's databases\n * became invisible to the platform that runs them.\n *\n * Absent on bundles built before this field existed.\n */\n resources?: ResourceGraph;\n deps: {\n /** Runtime dependencies of user code, as declared. */\n declared: Record<string, string>;\n /**\n * The dependency tree ships *inside* the bundle, already installed.\n *\n * Absent or false means the tree is declared but not present, and\n * whoever boots the bundle has to install it. On the managed runtime that\n * install runs in an init container on **every** pod start — the bundle\n * lives on a volume that is wiped each time — and it is the single\n * largest cost in a managed pod's life: 35–55 seconds of a 40–60 second\n * cold start. Since a pod restarts on every eviction, node failure, OOM\n * and runtime rollout, that number is not a startup detail. It is what an\n * outage costs.\n *\n * Vendoring moves the install to build time, where it happens once. It is\n * skipped when the closure contains native code, because a prebuilt\n * binary is only valid for the platform it was built for — see\n * {@link vendorTarget} for what \"the platform\" means here.\n */\n vendored?: boolean;\n /**\n * What {@link vendored} was resolved for, recorded so a mismatch can be\n * refused rather than discovered at import time.\n *\n * Cross-platform vendoring is safe for pure JavaScript and unsafe for\n * anything compiled, and the boundary between them is not always visible\n * in a dependency list: `esbuild` is pure-JS with a *platform-specific\n * optional dependency* holding the actual binary, so an install run on a\n * developer's Mac silently produces a tree that cannot run on the Linux\n * image. The install therefore resolves optional dependencies for the\n * target explicitly rather than for the machine it runs on, and records\n * the answer here.\n */\n vendorTarget?: {\n /** npm `--os`, e.g. `linux`. */\n os: string;\n /** npm `--cpu`, e.g. `x64`. */\n cpu: string;\n /** Node major the tree was resolved for. */\n node: string;\n };\n };\n build: {\n /** `@rebasepro/cli` version that produced this bundle. */\n cli: string;\n /** Node major the bundle was compiled on. */\n node: string;\n /** ISO-8601. */\n createdAt: string;\n };\n}\n\n/** The contract a running backend serves at `GET /api/meta/contract`. */\nexport interface RebaseProjectContract {\n /** Matches {@link RebaseBundleManifest.schemaVersion}. */\n schemaVersion: string;\n runtime: {\n /** `@rebasepro/server` version currently running. */\n version: string;\n contract: number;\n };\n /**\n * Every table, as `GET /api/schema/tables` serves an administrator: the\n * input to remote SDK generation (`rebase generate-sdk --from`). Hooks are\n * presence flags; private columns are absent.\n */\n tables: TableDescriptor[];\n}\n\n/** Header carrying the schema version an SDK was generated from. */\nexport const SCHEMA_VERSION_HEADER = \"x-rebase-schema\";\n","/**\n * Whether a static build's file name carries a content hash: the files the\n * runtime serves `immutable` for a year, and the ones `rebase build` writes\n * `.br` and `.gz` beside. One rule for both, so a file is never precompressed\n * and revalidated, or cached for a year and compressed on every request.\n *\n * Two shapes count:\n *\n * - **Vite's own**, `[name]-[hash]`: the last eight characters of the name,\n * after a `-`. They are base64url, an alphabet with `-` and `_` in it, so\n * about one hash in eight holds a `-` (`index-C-WpENHZ.js`,\n * `page10-D6Dq--fD.js`), and the last `-` is not where it starts.\n * - **A longer one** with no `-` in it, eight characters or more after the last\n * `-` (`[hash:12]`, another bundler's names).\n *\n * Either must hold a digit or a capital. That is the evidence of a hash: a\n * hand-written `vendor-analytics.js` is not taken for one, and gets revalidated\n * rather than pinned in every visitor's cache with no way to recall it.\n */\nexport function isContentHashedFileName(fileName: string): boolean {\n const dot = fileName.lastIndexOf(\".\");\n if (dot <= 0) return false;\n const stem = fileName.slice(0, dot);\n\n if (stem.length > 9 && stem[stem.length - 9] === \"-\" && looksLikeHash(stem.slice(-8))) return true;\n\n const dash = stem.lastIndexOf(\"-\");\n if (dash < 0) return false;\n const suffix = stem.slice(dash + 1);\n return suffix.length >= 8 && looksLikeHash(suffix);\n}\n\n/** Base64url throughout, with a digit or a capital somewhere in it. */\nfunction looksLikeHash(text: string): boolean {\n return /^[A-Za-z0-9_-]+$/.test(text) && /[0-9A-Z]/.test(text);\n}\n","import type { TableDescriptor } from \"../schema/descriptor\";\n\n/**\n * The schema version stamp.\n *\n * One function, used in three places that must agree or the whole drift-detection\n * story is noise: `rebase build` writes it into a bundle manifest, the runtime\n * serves it from the contract endpoint and stamps it into the database it\n * provisions, and a generated SDK records the value it was built from. If any\n * two of those computed it differently, every client would look permanently out\n * of date.\n *\n * It covers **tables only** — their compiled descriptors — so editing a hook's\n * code or a server function never invalidates every SDK in every repository.\n * That is a deliberate narrowing, not an oversight.\n *\n * Versions are prefixed `v2:` (descriptors, since 0.31); `v1:` versions were\n * computed from collections — see {@link LEGACY_SCHEMA_VERSION_PREFIX}.\n */\n\n/** Stable stringify: object keys sorted at every level, so key order cannot alter the hash. */\nfunction canonicalize(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value) ?? \"null\";\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalize).join(\",\")}]`;\n }\n const entries = Object.entries(value)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(\",\")}}`;\n}\n\n/**\n * The prefix of a version computed before 0.31, from collections.\n *\n * A database stamped with one was provisioned under the collection model. Its\n * version can never equal a descriptor version, so the first boot of a 0.31\n * runtime against it reports a mismatch once — and says why, and how to\n * restamp.\n */\nexport const LEGACY_SCHEMA_VERSION_PREFIX = \"v1:\";\n\n/**\n * Compute the canonical string a schema version hashes: the tables'\n * descriptors, ordered by slug, every object's keys sorted.\n *\n * A descriptor is the compiled table — every default applied, every name\n * derived, `rls` resolved against `defaultRls` — so the same source compiles to\n * the same descriptor before or after anything loads it, and a build-time\n * stamp can match the server that serves it. It is plain JSON by\n * construction: hooks appear only as presence flags (`hooks.afterRead: true`),\n * so editing what a hook does never moves the version, while adding or\n * removing one does.\n *\n * Ordered by slug, so the order the tables were exported in cannot alter it.\n *\n * Exposed separately so the hashing itself can differ by environment: Node has\n * `crypto`, and callers without it can still compare canonical forms directly.\n */\nexport function canonicalSchemaPayload(tables: readonly TableDescriptor[]): string {\n const ordered = [...tables].sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));\n return canonicalize(ordered);\n}\n\n/**\n * A short, non-cryptographic digest of the canonical payload.\n *\n * FNV-1a style, 64 bits, as two 32-bit halves. This is an identity, not a\n * security boundary: nothing trusts a schema version to prove anything, it only\n * answers \"is this the same schema as before\". A hand-rolled hash keeps this\n * module free of `node:crypto`, so the identical function runs in the browser,\n * in the CLI, and in the runtime — which is the property that actually matters.\n */\nexport function computeSchemaVersion(tables: readonly TableDescriptor[]): string {\n const payload = canonicalSchemaPayload(tables);\n\n let h1 = 0x811c9dc5;\n let h2 = 0x01000193;\n\n for (let i = 0; i < payload.length; i++) {\n const code = payload.charCodeAt(i);\n h1 ^= code;\n // Multiply by the FNV prime using shifts to stay in 32-bit integer math.\n h1 = (h1 + ((h1 << 1) + (h1 << 4) + (h1 << 7) + (h1 << 8) + (h1 << 24))) >>> 0;\n h2 ^= code + i;\n h2 = (h2 + ((h2 << 1) + (h2 << 5) + (h2 << 9) + (h2 << 15) + (h2 << 24))) >>> 0;\n }\n\n const hex = (n: number): string => n.toString(16).padStart(8, \"0\");\n return `v2:${hex(h1)}${hex(h2)}`;\n}\n","/**\n * The modules an app Claude writes for show_app may import, and from each the\n * names the MCP view serves.\n *\n * An app imports the real package names, so the code reads — and pastes into\n * a project — like every other piece of Rebase code. Inside the view each\n * name is the package's own part: `\"*\"` serves the whole module, a list\n * serves exactly those exports. The one list three readers share, so none\n * can drift from the others:\n *\n * - the view's module registry (`@rebasepro/cms/mcp-view`), which hands an\n * app these exports and no others;\n * - the server's compiler for show_app, which refuses any other import\n * before the app opens, naming it;\n * - show_app's guide (`SHOW_APP_CODE_GUIDE` in `@rebasepro/server`), which a\n * test holds to this list.\n */\nexport const MCP_APP_MODULES = {\n \"react\": \"*\",\n // What JSX compiles to; never written by hand.\n \"react/jsx-runtime\": \"*\",\n // The UI kit whole: layout, inputs, dialogs, icons, SplitView, the KPI tiles and charts.\n \"@rebasepro/ui\": \"*\",\n // The project's rows, flat, as the person: read, counted, aggregated, written.\n \"@rebasepro/app\": [\n \"useRows\",\n \"useRow\",\n \"useRowCount\",\n \"useAggregate\",\n \"useRowWrites\"\n ],\n // The admin panel's own blocks and atoms, with the project's custom views, fields and actions.\n \"@rebasepro/cms\": [\n \"CollectionPanel\",\n \"CollectionToolbar\",\n \"CollectionSearchBar\",\n \"CollectionFiltersButton\",\n \"CollectionViewModeToggle\",\n \"CollectionAddButton\",\n \"RecordForm\",\n \"RecordDetail\",\n \"FormField\",\n \"FieldValue\",\n \"useSidePanel\"\n ]\n} as const satisfies Readonly<Record<string, \"*\" | readonly string[]>>;\n\n/** A module an app may import. */\nexport type McpAppModule = keyof typeof MCP_APP_MODULES;\n","/**\n * UI preferences: how a table is presented in the panel, stored as data.\n *\n * A table's schema lives in `backend/schema/*.ts`; how the panel presents it\n * (labels, icon, column order and widths, hidden columns, the default view\n * mode, enum labels and colours …) is a customization. Code customizations are\n * written with `customizeTable` in the frontend. What the collection editor and\n * the views change at runtime is stored as a {@link UiTablePreferences} delta —\n * for the whole workspace, or for one user — and folded in after the code\n * customizations, in this order:\n *\n * projected table → `tableCustomizations` (code) → workspace preferences → user preferences\n *\n * Every key here is one `customizeTable` accepts, with a JSON value only: no\n * function, component or resolver can arrive this way. Schema facts (column\n * types, validation, enum values, rules, `description`) are never stored here;\n * they are schema edits (`TablePatch`).\n *\n * @module\n */\nimport type { WhereFilterOp } from \"./filter-operators\";\n\n/**\n * Where a preference applies: to everybody in the workspace, or to one user.\n *\n * @group UI preferences\n */\nexport type UiPreferenceScope = \"workspace\" | \"user\";\n\n/**\n * The label (and colour) of one enum value. A colour is a chip colour key\n * (`\"green\"`, `\"orangeDark\"`).\n *\n * @group UI preferences\n */\nexport interface UiEnumLabel {\n label: string;\n color?: string;\n disabled?: boolean;\n}\n\n/**\n * How one field is presented: the data-only subset of a field customization.\n *\n * @group UI preferences\n */\nexport interface UiFieldPreferences {\n name?: string;\n hidden?: boolean;\n hiddenInForm?: boolean;\n disabled?: boolean;\n readOnly?: boolean;\n columnWidth?: number;\n span?: 1 | 2 | 3 | 4;\n multiline?: boolean;\n markdown?: boolean;\n previewAsTag?: boolean;\n clearable?: boolean;\n urlPreview?: boolean | \"image\" | \"video\" | \"audio\" | \"file\";\n mode?: \"date\" | \"date_time\";\n timezone?: string;\n enumLabels?: { [value: string]: string | UiEnumLabel };\n enumOrder?: (string | number)[];\n expanded?: boolean;\n minimalistView?: boolean;\n sortable?: boolean;\n canAddElements?: boolean;\n spreadChildren?: boolean;\n keyValue?: boolean;\n previewFields?: string[];\n fieldOrder?: string[];\n widget?: \"select\" | \"dialog\";\n includeId?: boolean;\n includeEntityLink?: boolean;\n referenceTo?: string;\n /** JSON-logic conditions (`{ disabled, hidden, readOnly, required … }`). */\n conditions?: { [key: string]: UiJsonValue };\n /** A JSON document's keys. */\n fields?: { [key: string]: UiFieldPreferences };\n /** An array's items. */\n of?: UiFieldPreferences;\n}\n\n/**\n * A JSON value, as conditions carry them.\n *\n * @group UI preferences\n */\nexport type UiJsonValue = string | number | boolean | null | UiJsonValue[] | { [key: string]: UiJsonValue };\n\n/**\n * The record slots of a table, each naming a field.\n *\n * @group UI preferences\n */\nexport interface UiDisplayPreferences {\n title?: string;\n subtitle?: string;\n image?: string;\n status?: string;\n date?: string;\n tags?: string;\n}\n\n/**\n * One sort: the field, the direction, and where nulls go.\n *\n * @group UI preferences\n */\nexport type UiSortTuple = [string, \"asc\" | \"desc\"] | [string, \"asc\" | \"desc\", \"first\" | \"last\"];\n\n/**\n * A filter on one field: an operator and its value, or several.\n *\n * @group UI preferences\n */\nexport type UiFilterCondition = [WhereFilterOp, UiJsonValue];\n\n/**\n * How one table is presented: the data-only subset of `customizeTable`'s\n * options. A stored preference is a delta: what it names replaces what the\n * code customization says, key by key (`fields` field by field).\n *\n * @group UI preferences\n */\nexport interface UiTablePreferences {\n name?: string;\n singularName?: string;\n icon?: string;\n group?: string;\n hideFromNavigation?: boolean;\n hideFromEntityViews?: boolean;\n defaultViewMode?: string;\n enabledViews?: string[];\n defaultSize?: \"xs\" | \"s\" | \"m\" | \"l\" | \"xl\";\n kanban?: { columnField: string; orderField?: string };\n fieldOrder?: string[];\n listFields?: string[];\n previewFields?: string[];\n display?: UiDisplayPreferences;\n hideIdFromCollection?: boolean;\n /** The default sort. */\n sort?: UiSortTuple | UiSortTuple[];\n /** The filter a visitor starts from. */\n defaultFilter?: { [field: string]: UiFilterCondition | UiFilterCondition[] };\n pagination?: boolean | number;\n inlineEditing?: boolean;\n selectionEnabled?: boolean;\n exportable?: boolean;\n openEntityMode?: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n defaultEntityAction?: \"view\" | \"edit\";\n sideDialogWidth?: number | string;\n defaultSelectedView?: string;\n formAutoSave?: boolean;\n alwaysApplyDefaultValues?: boolean;\n includeJsonView?: boolean;\n localChangesBackup?: \"manual_apply\" | \"auto_apply\" | false;\n hideIdFromForm?: boolean;\n /** Registered entity actions, by key. */\n entityActions?: string[];\n disableDefaultActions?: (\"edit\" | \"copy\" | \"delete\")[];\n /** Registered entity views, by key. */\n entityViews?: string[];\n /** Registered collection views, by key. */\n customViews?: string[];\n fields?: { [key: string]: UiFieldPreferences };\n}\n\n/**\n * Every key a {@link UiTablePreferences} may hold, as data: what the server\n * validates a stored preference by.\n *\n * @group UI preferences\n */\nexport const UI_PREFERENCE_TABLE_KEYS = [\n \"alwaysApplyDefaultValues\", \"customViews\", \"defaultEntityAction\", \"defaultFilter\", \"defaultSelectedView\", \"defaultSize\",\n \"defaultViewMode\", \"disableDefaultActions\", \"display\", \"enabledViews\", \"entityActions\", \"entityViews\",\n \"exportable\", \"fieldOrder\", \"fields\", \"formAutoSave\", \"group\", \"hideFromEntityViews\", \"hideFromNavigation\",\n \"hideIdFromCollection\", \"hideIdFromForm\", \"icon\", \"includeJsonView\", \"inlineEditing\", \"kanban\", \"listFields\",\n \"localChangesBackup\", \"name\", \"openEntityMode\", \"pagination\", \"previewFields\", \"selectionEnabled\",\n \"sideDialogWidth\", \"singularName\", \"sort\"\n] as const satisfies readonly (keyof UiTablePreferences)[];\n\n/**\n * Every key a {@link UiFieldPreferences} may hold, as data.\n *\n * @group UI preferences\n */\nexport const UI_PREFERENCE_FIELD_KEYS = [\n \"canAddElements\", \"clearable\", \"columnWidth\", \"conditions\", \"disabled\", \"enumLabels\", \"enumOrder\", \"expanded\",\n \"fieldOrder\", \"fields\", \"hidden\", \"hiddenInForm\", \"includeEntityLink\", \"includeId\", \"keyValue\", \"markdown\",\n \"minimalistView\", \"mode\", \"multiline\", \"name\", \"of\", \"previewAsTag\", \"previewFields\", \"readOnly\",\n \"referenceTo\", \"sortable\", \"span\", \"spreadChildren\", \"timezone\", \"urlPreview\", \"widget\"\n] as const satisfies readonly (keyof UiFieldPreferences)[];\n\n/** Compiles only when `T` is `never`. */\ntype AssertNever<T extends never = never> = T;\n/** An interface key the table list does not name fails to compile. */\ntype _EveryTableKeyIsListed = AssertNever<Exclude<keyof UiTablePreferences, typeof UI_PREFERENCE_TABLE_KEYS[number]>>;\n/** An interface key the field list does not name fails to compile. */\ntype _EveryFieldKeyIsListed = AssertNever<Exclude<keyof UiFieldPreferences, typeof UI_PREFERENCE_FIELD_KEYS[number]>>;\n\n/**\n * One problem with a preference delta: the path to the value, and what is\n * wrong with it.\n *\n * @group UI preferences\n */\nexport interface UiPreferenceProblem {\n path: string;\n message: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\nconst isStringList = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every(item => typeof item === \"string\");\n\ntype Check = (value: unknown, path: string, out: UiPreferenceProblem[]) => void;\n\nconst expect = (ok: (value: unknown) => boolean, what: string): Check => (value, path, out) => {\n if (!ok(value)) out.push({ path, message: `must be ${what}.` });\n};\nconst oneOf = (...allowed: readonly (string | number | boolean)[]): Check =>\n expect(value => allowed.some(a => a === value), allowed.map(a => JSON.stringify(a)).join(\" | \"));\nconst boolean = /*#__PURE__*/ expect(value => typeof value === \"boolean\", \"a boolean\");\nconst string = /*#__PURE__*/ expect(value => typeof value === \"string\", \"a string\");\nconst stringList = /*#__PURE__*/ expect(isStringList, \"a list of strings\");\nconst positiveNumber = /*#__PURE__*/ expect(value => typeof value === \"number\" && Number.isFinite(value) && value > 0, \"a positive number\");\n\nfunction isJson(value: unknown, depth = 0): boolean {\n if (depth > 32) return false;\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return true;\n if (typeof value === \"number\") return Number.isFinite(value);\n if (Array.isArray(value)) return value.every(item => isJson(item, depth + 1));\n if (isRecord(value)) return Object.values(value).every(item => isJson(item, depth + 1));\n return false;\n}\n\nconst enumLabels: Check = (value, path, out) => {\n if (!isRecord(value)) {\n out.push({ path, message: \"must map enum values to labels.\" });\n return;\n }\n for (const [key, label] of Object.entries(value)) {\n if (typeof label === \"string\") continue;\n if (!isRecord(label) || typeof label.label !== \"string\"\n || (label.color !== undefined && typeof label.color !== \"string\")\n || (label.disabled !== undefined && typeof label.disabled !== \"boolean\")\n || Object.keys(label).some(k => k !== \"label\" && k !== \"color\" && k !== \"disabled\")) {\n out.push({ path: `${path}.${key}`, message: \"must be a label, or `{ label, color?, disabled? }` with a chip colour key.\" });\n }\n }\n};\n\nconst fieldMap: Check = (value, path, out) => {\n if (!isRecord(value)) {\n out.push({ path, message: \"must map field keys to field preferences.\" });\n return;\n }\n for (const [key, field] of Object.entries(value)) fieldProblems(field, `${path}.${key}`, out);\n};\n\n/**\n * The checks, built on first use: module-level calls would keep this file in\n * every bundle that imports `@rebasepro/types`, whether it validates a\n * preference or not.\n */\nlet builtChecks: { field: Readonly<Record<typeof UI_PREFERENCE_FIELD_KEYS[number], Check>>; table: Readonly<Record<typeof UI_PREFERENCE_TABLE_KEYS[number], Check>> } | undefined;\nfunction checks(): NonNullable<typeof builtChecks> {\n builtChecks ??= { field: fieldChecks(), table: tableChecks() };\n return builtChecks;\n}\n\nconst fieldChecks = (): Readonly<Record<typeof UI_PREFERENCE_FIELD_KEYS[number], Check>> => ({\n name: string,\n hidden: boolean,\n hiddenInForm: boolean,\n disabled: boolean,\n readOnly: boolean,\n columnWidth: positiveNumber,\n span: oneOf(1, 2, 3, 4),\n multiline: boolean,\n markdown: boolean,\n previewAsTag: boolean,\n clearable: boolean,\n urlPreview: oneOf(true, false, \"image\", \"video\", \"audio\", \"file\"),\n mode: oneOf(\"date\", \"date_time\"),\n timezone: string,\n enumLabels,\n enumOrder: expect(value => Array.isArray(value) && value.every(item => typeof item === \"string\" || typeof item === \"number\"), \"a list of enum values\"),\n expanded: boolean,\n minimalistView: boolean,\n sortable: boolean,\n canAddElements: boolean,\n spreadChildren: boolean,\n keyValue: boolean,\n previewFields: stringList,\n fieldOrder: stringList,\n widget: oneOf(\"select\", \"dialog\"),\n includeId: boolean,\n includeEntityLink: boolean,\n referenceTo: string,\n conditions: expect(value => isRecord(value) && isJson(value), \"an object of JSON-logic rules\"),\n fields: fieldMap,\n of: (value, path, out) => fieldProblems(value, path, out)\n});\n\nconst tableChecks = (): Readonly<Record<typeof UI_PREFERENCE_TABLE_KEYS[number], Check>> => ({\n name: string,\n singularName: string,\n icon: string,\n group: string,\n hideFromNavigation: boolean,\n hideFromEntityViews: boolean,\n defaultViewMode: string,\n enabledViews: stringList,\n defaultSize: oneOf(\"xs\", \"s\", \"m\", \"l\", \"xl\"),\n kanban: expect(value => isRecord(value) && typeof value.columnField === \"string\"\n && (value.orderField === undefined || typeof value.orderField === \"string\")\n && Object.keys(value).every(k => k === \"columnField\" || k === \"orderField\"), \"`{ columnField, orderField? }`\"),\n fieldOrder: stringList,\n listFields: stringList,\n previewFields: stringList,\n display: expect(value => isRecord(value) && Object.entries(value).every(([slot, field]) =>\n [\"title\", \"subtitle\", \"image\", \"status\", \"date\", \"tags\"].includes(slot) && typeof field === \"string\"),\n \"an object naming a field for each of title, subtitle, image, status, date, tags\"),\n hideIdFromCollection: boolean,\n sort: expect(value => isSortTuple(value) || (Array.isArray(value) && value.length > 0 && value.every(isSortTuple)), \"`[field, \\\"asc\\\" | \\\"desc\\\"]` or a list of them\"),\n defaultFilter: expect(value => isRecord(value) && Object.values(value).every(condition =>\n isCondition(condition) || (Array.isArray(condition) && condition.length > 0 && condition.every(isCondition))),\n \"an object of `[operator, value]` conditions by field\"),\n pagination: expect(value => typeof value === \"boolean\" || (typeof value === \"number\" && Number.isInteger(value) && value > 0), \"a boolean or a page size\"),\n inlineEditing: boolean,\n selectionEnabled: boolean,\n exportable: boolean,\n openEntityMode: oneOf(\"side_panel\", \"full_screen\", \"split\", \"dialog\"),\n defaultEntityAction: oneOf(\"view\", \"edit\"),\n sideDialogWidth: expect(value => typeof value === \"string\" || (typeof value === \"number\" && value > 0), \"a width\"),\n defaultSelectedView: string,\n formAutoSave: boolean,\n alwaysApplyDefaultValues: boolean,\n includeJsonView: boolean,\n localChangesBackup: oneOf(\"manual_apply\", \"auto_apply\", false),\n hideIdFromForm: boolean,\n entityActions: stringList,\n disableDefaultActions: expect(value => Array.isArray(value) && value.every(item => item === \"edit\" || item === \"copy\" || item === \"delete\"), \"a list of \\\"edit\\\" | \\\"copy\\\" | \\\"delete\\\"\"),\n entityViews: stringList,\n customViews: stringList,\n fields: fieldMap\n});\n\nconst FILTER_OPS: readonly string[] = [\n \"<\", \"<=\", \"==\", \"!=\", \">=\", \">\", \"array-contains\", \"in\", \"not-in\", \"array-contains-any\", \"array-contains-all\",\n \"array-contained-by\", \"like\", \"ilike\", \"not-like\", \"not-ilike\", \"is-null\", \"is-not-null\"\n] satisfies readonly WhereFilterOp[];\n\nconst isSortTuple = (value: unknown): boolean => Array.isArray(value)\n && (value.length === 2 || value.length === 3)\n && typeof value[0] === \"string\"\n && (value[1] === \"asc\" || value[1] === \"desc\")\n && (value.length === 2 || value[2] === \"first\" || value[2] === \"last\");\n\nconst isCondition = (value: unknown): boolean => Array.isArray(value)\n && value.length === 2 && typeof value[0] === \"string\" && FILTER_OPS.includes(value[0]) && isJson(value[1]);\n\nconst isFieldKey = (key: string): key is typeof UI_PREFERENCE_FIELD_KEYS[number] =>\n (UI_PREFERENCE_FIELD_KEYS as readonly string[]).includes(key);\nconst isTableKey = (key: string): key is typeof UI_PREFERENCE_TABLE_KEYS[number] =>\n (UI_PREFERENCE_TABLE_KEYS as readonly string[]).includes(key);\n\nfunction fieldProblems(value: unknown, path: string, out: UiPreferenceProblem[]): void {\n if (!isRecord(value)) {\n out.push({ path, message: \"must be an object of field preferences.\" });\n return;\n }\n for (const [key, entry] of Object.entries(value)) {\n if (!isFieldKey(key)) {\n out.push({ path: `${path}.${key}`, message: `is not a field preference. A field preference is one of ${UI_PREFERENCE_FIELD_KEYS.join(\", \")}; schema facts (type, validation, enum values, description) are schema edits, and components are written in code.` });\n continue;\n }\n if (entry === undefined) continue;\n checks().field[key](entry, `${path}.${key}`, out);\n }\n}\n\n/**\n * Every problem with a table's preference delta as it arrived: a key that is\n * not a preference (a schema fact, a component, a misspelling) or a value of\n * the wrong shape. Empty when it may be stored.\n *\n * @group UI preferences\n */\nexport function uiTablePreferencesProblems(value: unknown): UiPreferenceProblem[] {\n const out: UiPreferenceProblem[] = [];\n if (!isRecord(value)) return [{ path: \"\", message: \"must be an object of table preferences.\" }];\n for (const [key, entry] of Object.entries(value)) {\n if (!isTableKey(key)) {\n out.push({ path: key, message: `is not a table preference. A table preference is one of ${UI_PREFERENCE_TABLE_KEYS.join(\", \")}; schema facts (columns, rules, description, history) are schema edits, and code (actions, components, callbacks) is written in code.` });\n continue;\n }\n if (entry === undefined) continue;\n checks().table[key](entry, key, out);\n }\n return out;\n}\n\n/**\n * Whether a value is a well-formed {@link UiTablePreferences} delta.\n *\n * @group UI preferences\n */\nexport function isUiTablePreferences(value: unknown): value is UiTablePreferences {\n return uiTablePreferencesProblems(value).length === 0;\n}\n\n/**\n * One delta over another: what `over` names replaces what `base` says, key by\n * key, and `fields` (and a field's nested `fields` / `of`) field by field.\n *\n * @group UI preferences\n */\nexport function mergeUiTablePreferences(base: UiTablePreferences, over: UiTablePreferences): UiTablePreferences {\n const out: UiTablePreferences = { ...base, ...over };\n if (base.fields || over.fields) out.fields = mergeFieldMaps(base.fields, over.fields);\n return out;\n}\n\nfunction mergeFieldMaps(\n base: UiTablePreferences[\"fields\"],\n over: UiTablePreferences[\"fields\"]\n): { [key: string]: UiFieldPreferences } {\n const out: { [key: string]: UiFieldPreferences } = { ...base };\n for (const [key, field] of Object.entries(over ?? {})) {\n out[key] = out[key] ? mergeField(out[key], field) : field;\n }\n return out;\n}\n\nfunction mergeField(base: UiFieldPreferences, over: UiFieldPreferences): UiFieldPreferences {\n const out: UiFieldPreferences = { ...base, ...over };\n if (base.fields || over.fields) out.fields = mergeFieldMaps(base.fields, over.fields);\n if (base.of && over.of) out.of = mergeField(base.of, over.of);\n if (base.enumLabels && over.enumLabels) out.enumLabels = { ...base.enumLabels, ...over.enumLabels };\n return out;\n}\n\n/**\n * The preferences of a workspace or a user, by table slug.\n *\n * @group UI preferences\n */\nexport interface UiPreferences {\n tables: { [slug: string]: UiTablePreferences };\n}\n","import type { VectorSearchParams } from \"./data_driver\";\nimport type { ComputedSortField, SearchMatch } from \"../types/search\";\nimport { WhereFilterOp, FieldPath, NonColumnFieldPath, FilterValues, NullsPlacement, OrderBySpec, OrderByTuple, RelationAggregateSort } from \"../types/filter-operators\";\n\n/**\n * The element type of an array column, and the column's own type otherwise.\n *\n * A generated SDK emits an `array` property as `Array<X>` and a to-many\n * relation as `Array<TargetRow>`, so this is what `array-contains` compares\n * against on either.\n */\nexport type ElementOf<T> = T extends readonly (infer E)[] ? E : T;\n\n/**\n * The `id` of a row-shaped element, and `never` for anything else.\n *\n * A to-many relation is emitted as `Array<TargetRow>`, but the filter compilers\n * compare a relation by **id** — `buildRelationFilterPredicate` in\n * `@rebasepro/server-postgres` unwraps a relation value down to its id — so\n * `where(\"tags\", \"array-contains\", tagId)` is the call that works, and the\n * element type alone would refuse it.\n */\nexport type IdOf<E> = E extends { id: infer I } ? I : never;\n\n/**\n * One member of an array column: its element, or — when the element is a row —\n * that row's id, which is what a relation filter is actually compared against.\n */\nexport type WhereElementOf<T> = ElementOf<T> | IdOf<ElementOf<T>>;\n\n/**\n * The value a given operator takes on a column of type `T`.\n *\n * `WhereValue<T>` was one value type for all sixteen operators, which made\n * `array-contains` uncallable from a generated SDK — it is the one operator\n * whose value is an *element* of the column rather than the column's own type,\n * so on `tags: string[]` it wanted a `string[]` and the documented\n * `.where(\"tags\", \"array-contains\", \"featured\")` was a compile error. The\n * spelling that did compile, `[\"featured\"]`, builds `@> ARRAY[$1]` with the\n * whole array bound as the single element and matches nothing: the correct\n * query rejected, the accepted query silently wrong.\n *\n * The branches mirror `buildSingleFilterCondition` in `@rebasepro/server-postgres`:\n *\n * - `array-contains` → one element of the column (or a related row's id).\n * - `in` / `not-in` / `array-contains-any` / `array-contains-all` /\n * `array-contained-by` → a list of elements; a bare element is read as the\n * one-element list, and `null` is a null check.\n * - `like` / `ilike` / `not-like` / `not-ilike` → a SQL pattern, always a\n * string. It matches a text column, or an enum by its label; on a number,\n * a date or any other column the Postgres driver refuses it with a 400\n * (`INVALID_FILTER_OPERATOR`).\n * - `is-null` / `is-not-null` → nothing; the value is ignored everywhere.\n * - everything else → the column's own type, or `null` for a null comparison.\n *\n * Distributes over `Op`, so a caller holding an unnarrowed `WhereFilterOp`\n * (a dynamic filter UI, say) gets the union of every branch and stays as\n * permissive as it was.\n */\nexport type WhereValueFor<Op extends WhereFilterOp, T> =\n Op extends \"array-contains\"\n ? WhereElementOf<T>\n : Op extends \"in\" | \"not-in\" | \"array-contains-any\" | \"array-contains-all\" | \"array-contained-by\"\n ? readonly WhereElementOf<T>[] | WhereElementOf<T> | null\n : Op extends \"like\" | \"ilike\" | \"not-like\" | \"not-ilike\"\n ? string\n : Op extends \"is-null\" | \"is-not-null\"\n ? null | undefined\n : T | null;\n\n/**\n * One `[operator, value]` condition on a column of type `T`, with the value\n * typed for the operator exactly as the fluent `where(column, op, value)` types\n * it — a union with one tuple per operator, so `[\"array-contains\", \"featured\"]`\n * on a `string[]` column compiles and `[\"array-contains\", [\"featured\"]]` (which\n * builds `@> ARRAY[$1]` and matches nothing) does not.\n */\nexport type WhereConditionFor<T> = { [Op in WhereFilterOp]: [Op, WhereValueFor<Op, T>] }[WhereFilterOp];\n\n/**\n * The object-form `where` for row type `M`: each column takes conditions typed\n * against that column, as the fluent form does.\n *\n * `FilterValues` typed the key and left the value `unknown`, so the very\n * shapes the fluent form was fixed to refuse — a wrong value type, an array\n * where `array-contains` wants one element — compiled in `find({ where })`,\n * the form `listen`, `observe`, `count` and `iterate` all take.\n *\n * A path that is not a column (`author.name`, `metadata->>tier`) has no type to\n * check against and stays `unknown`, as in {@link FieldPath}. An untyped `M`\n * (`Record<string, unknown>`, every key) collapses to plain `FilterValues`, so\n * an untyped client is exactly as permissive as before.\n */\nexport type WhereFor<M extends Record<string, unknown>> =\n string extends keyof M\n ? FilterValues<FieldPath<M>>\n : { [K in Extract<keyof M, string>]?: WhereConditionFor<M[K]> | WhereConditionFor<M[K]>[] }\n & FilterValues<NonColumnFieldPath>;\n\n/**\n * A group of conditions combined with `and`, `or`, or negated with `not`.\n *\n * ## `not`\n *\n * `not` negates the **conjunction** of its `conditions`: `not(a)` is `NOT a`,\n * and `not(a, b)` is `NOT (a AND b)`. One rule, stated here and applied\n * identically by the wire codec (`or(...)`/`and(...)`/`not(...)` in\n * `@rebasepro/common`), the REST `?not=` parameter and every driver compiler,\n * so a negation means the same thing whichever end writes it.\n *\n * Negation is not expressible by inverting the operators inside the group: SQL\n * three-valued logic makes `NOT (a AND b)` and `(NOT a) OR (NOT b)` differ the\n * moment a NULL is involved, and only one of them is what the caller wrote. It\n * compiles to a real `NOT (...)`.\n */\nexport interface LogicalCondition {\n type: \"and\" | \"or\" | \"not\";\n conditions: (FilterCondition | LogicalCondition)[];\n}\n\nexport interface FilterCondition {\n column: string;\n operator: WhereFilterOp;\n value: unknown;\n}\n\n/**\n * One {@link FilterCondition} on row type `M`: the column is one of `M`'s and\n * the value is typed for the operator against that column, exactly as the\n * fluent `where(column, op, value)` types it. A path that is not a column\n * (`author.name`, `metadata->>tier`) has nothing to check against and stays\n * `unknown`, as in {@link WhereFor}.\n *\n * An untyped `M` (`Record<string, unknown>`) collapses to plain\n * `FilterCondition`, so an untyped client is exactly as permissive as before.\n */\nexport type FilterConditionFor<M extends Record<string, unknown>> =\n | ColumnConditions<M>[keyof ColumnConditions<M>]\n | { column: NonColumnFieldPath; operator: WhereFilterOp; value: unknown };\n\n/**\n * Per column, the union of its typed conditions; an index-signature key (an\n * untyped row) maps to plain {@link FilterCondition}.\n *\n * A key-remapped mapped type rather than a conditional over `keyof M`, for the\n * reason {@link NumericKeyOf} gives: tsc measures the conditional form as\n * invariant in `M`, and a typed `SDKTableClient<Post>` stopped widening to\n * the wide `SDKTableClient`.\n */\ntype ColumnConditions<M extends Record<string, unknown>> = {\n [K in keyof M as K extends string ? K : never]: string extends K\n ? FilterCondition\n : { [Op in WhereFilterOp]: { column: K; operator: Op; value: WhereValueFor<Op, M[K]> } }[WhereFilterOp]\n};\n\n/**\n * A {@link LogicalCondition} whose every condition, at any depth, is a\n * {@link FilterConditionFor} row type `M`.\n *\n * `cond()` cannot know the row it will be used on, so it returns its column,\n * operator and value exactly as written; this is where they are checked.\n * `FindParams.logical` and the builders' `.where(group)` take it, so\n * `posts.where(or(cond(\"titel\", \"==\", 1)))` is a compile error on a typed\n * client rather than the server's 400.\n */\nexport interface LogicalConditionFor<M extends Record<string, unknown>> {\n type: \"and\" | \"or\" | \"not\";\n conditions: (FilterConditionFor<M> | LogicalConditionFor<M>)[];\n}\n\n/**\n * How one relation is loaded by {@link FindParams.include}.\n *\n * `true` loads the relation whole. The object form narrows it — the same four\n * knobs a top-level query has, applied to the rows *inside* one relation — and\n * `include` nests, so a query can ask for \"each post's five newest published\n * comments, each with its author\" in one request.\n *\n * ```ts\n * include: {\n * comments: {\n * limit: 5,\n * where: { published: [\"==\", true] },\n * orderBy: [\"created_at\", \"desc\"],\n * include: { author: true }\n * }\n * }\n * ```\n *\n * Nesting is bounded at {@link MAX_INCLUDE_DEPTH} hops. Each hop is another\n * batched query, and the bound is what stops one request from walking a\n * self-referencing relation forever.\n *\n * @group Data\n */\nexport interface IncludeOptions {\n /** Rows to load per parent row. Applied per parent, not across the page. */\n limit?: number;\n /** Filter the related rows, in the same dialect as {@link FindParams.where}. */\n where?: FilterValues<string>;\n /** An `and`/`or`/`not` group over the related rows. */\n logical?: LogicalCondition;\n /**\n * Sort the related rows — the tuple form, or the `field:direction[:nulls]`\n * shorthand the REST `?orderBy=` parameter uses.\n *\n * The string is accepted because this whole object travels over a query\n * string, where a tuple is three characters of JSON heavier for no gain.\n */\n orderBy?: OrderBySpec<string> | string;\n /** Columns of the *related* row to return. `id` is always included. */\n fields?: string[];\n /** Relations of the related row to load in turn. */\n include?: IncludeSpec;\n /**\n * Also serve how many related rows there are in all, per parent, under\n * the row's `_count` ({@link INCLUDE_COUNT_KEY}) — `{ tags: [...], _count:\n * { tags: 37 } }`. Counted by the same query that reads the rows, over the\n * same rows a read without `limit` would return (the include's `where`,\n * soft delete, row-level security), so `limit` caps what is sent and the\n * count says what was left out.\n *\n * To-many relations only: a to-one relation is a 400.\n *\n * @since 0.24\n */\n count?: boolean;\n}\n\n/**\n * The relations a read loads, as a list of (possibly dotted) names or as a\n * tree.\n *\n * - `[\"author\", \"comments.author\"]` — a dotted path is the same thing as the\n * nested object form, spelled flat. It is what the REST `?include=` parameter\n * carries, and the two forms compile to the same request.\n * - `[\"*\"]` — every relation the table declares, one hop deep, those\n * declared only for a record's tabs included — so on a list it can embed\n * every row of a to-many relation no column shows. Name the relations the\n * view renders instead; the admin panel does, and sends `*` only when it\n * cannot resolve a table's relations in the browser.\n * - `{ comments: { limit: 5, include: { author: true } } }` — the parametrised\n * form.\n *\n * A name that is not a relation of the table is a **400\n * `UNKNOWN_RELATION`**, not a silent omission: a read that quietly drops an\n * `include` answers 200 with the field missing, which is indistinguishable from\n * a row that genuinely has no related row.\n *\n * @group Data\n */\nexport type IncludeSpec = string[] | Record<string, true | IncludeOptions>;\n\n/**\n * What a read of one record by id takes besides the id — `findById` and\n * `listenById`.\n *\n * @group Data\n */\nexport interface ByIdReadOptions<Inc = IncludeSpec> {\n /**\n * Relations to load into the row, as {@link FindParams.include} loads them\n * into each row of a list. A to-many relation not named here is absent\n * from the row — not empty.\n */\n include?: Inc;\n}\n\n/**\n * An include checked against one generated table's relations: `R` is its\n * `Relations` map (relation name → the accessor it reaches) and `DB` the\n * generated `Database`, so a nested `include` is checked against the *target's*\n * relations in turn.\n *\n * A name, a dotted path starting with one, or `\"*\"`; or the tree, keyed by\n * relation name. A name that is not a relation is a 400 `UNKNOWN_RELATION`\n * from the server, and a compile error here.\n *\n * @group Data\n */\nexport type IncludeSpecFor<DB, R> =\n | readonly (Extract<keyof R, string> | \"*\" | `${Extract<keyof R, string>}.${string}`)[]\n | { [K in Extract<keyof R, string>]?: true | IncludeOptionsFor<DB, R[K]> };\n\n/**\n * {@link IncludeOptions} for a relation that reaches the generated table\n * `T`: its nested `include` is checked against `T`'s relations.\n *\n * @group Data\n */\nexport interface IncludeOptionsFor<DB, T> extends Omit<IncludeOptions, \"include\"> {\n include?: T extends keyof DB ? IncludeOf<DB[T], DB> : IncludeSpec;\n}\n\n/**\n * The include a generated `Database` entry takes — {@link IncludeSpecFor} over\n * its `Relations` — or the unchecked {@link IncludeSpec} for anything that does\n * not declare its relations (a hand-written row type, an older generated file).\n *\n * @group Data\n */\nexport type IncludeOf<Entry, DB> = Entry extends { Relations: infer R } ? IncludeSpecFor<DB, R> : IncludeSpec;\n\n/**\n * One argument of the fluent `.include(...)`: an element of the include list, a\n * whole list, or the tree.\n *\n * @group Data\n */\nexport type IncludeArgOf<Inc> = Inc extends readonly (infer E)[] ? E | Inc : Inc;\n\n/**\n * Hops an {@link IncludeSpec} may nest. `comments.author` is two.\n *\n * @group Data\n */\nexport const MAX_INCLUDE_DEPTH = 3;\n\n/**\n * Parameters for querying a table.\n *\n * ## How the filter parameters combine\n *\n * `where`, `logical`, and `searchString` are **independent** and, when more\n * than one is present, are combined with **AND** — every clause must match.\n * Concretely the backend builds:\n *\n * ```text\n * (where filters, AND-ed together)\n * AND (logical group)\n * AND (searchString matches, OR-ed across searchable columns)\n * ```\n *\n * So `where` does **not** conflict with or override `logical` — they stack.\n * If you need `where` fields OR-ed with each other, move them into `logical`\n * instead. There is no way to OR `where` against `logical`; express anything\n * that isn't a plain AND of the three groups inside a single `logical` tree.\n *\n * ## Pagination precedence\n *\n * `limit`/`offset` and `page` describe the same window two ways, so send one.\n * `page` is `offset = (page - 1) * (limit ?? DEFAULT_LIST_LIMIT)`. A read with\n * **both** is refused with `PAGE_WITH_OFFSET` — a 400 from the server, and a\n * `RebaseClientError` with that code from a client before any request — rather\n * than quietly applying one of them. `after` is refused beside either\n * (`CURSOR_WITH_OFFSET`).\n *\n * @group Data\n */\nexport interface FindParams<M extends Record<string, unknown> = Record<string, unknown>, Inc = IncludeSpec> {\n /**\n * Maximum number of items to return.\n *\n * Omit it and the backend applies {@link DEFAULT_LIST_LIMIT}, so a read is\n * never unbounded. Provide it and it must be a whole number between 1 and\n * {@link MAX_LIST_LIMIT}: the backend **rejects** anything else with a 400\n * rather than trimming it to fit, because a page quietly smaller than the\n * one you asked for is indistinguishable from having reached the end of the\n * table. To read past the ceiling, page with `offset` — or let\n * {@link SDKTableClient.iterate} / {@link SDKTableClient.findAll}\n * do it for you.\n */\n limit?: number;\n /**\n * Number of items to skip. Not with {@link FindParams.page}: the pair is\n * refused with `PAGE_WITH_OFFSET`.\n */\n offset?: number;\n /**\n * Page number (1-indexed), alternative to {@link FindParams.offset}: it\n * skips `(page - 1) * (limit ?? DEFAULT_LIST_LIMIT)` rows. Sent with\n * `offset`, the read is refused with `PAGE_WITH_OFFSET`.\n */\n page?: number;\n /**\n * Filter conditions keyed by field name.\n * Each value is a `[WhereFilterOp, value]` tuple or an array of tuples\n * for multiple conditions on the same field. Multiple fields, and multiple\n * tuples on one field, are **AND-ed**; also AND-ed with `logical` and\n * `searchString` when present (see the interface docs).\n *\n * @example\n * { status: [\"==\", \"active\"] }\n * { age: [\">=\", 18] }\n * { role: [\"in\", [\"admin\", \"editor\"]] }\n * { age: [[\">=\", 18], [\"<\", 65]] }\n */\n where?: WhereFor<M>;\n /**\n * Logical grouping conditions (AND/OR). Use this for anything `where`\n * can't express — notably OR-ing conditions. AND-ed with `where` and\n * `searchString` when present (see the interface docs).\n */\n logical?: LogicalConditionFor<M>;\n /**\n * Sort order as a `[field, direction]` tuple, or a list of them applied in\n * order of significance — the second key breaks ties on the first, and so on.\n *\n * @example orderBy: [\"created_at\", \"desc\"]\n * @example orderBy: [[\"roles\", \"asc\"], [\"created_at\", \"desc\"]]\n */\n orderBy?: OrderBySpec<FieldPath<M> | ComputedSortField>;\n /**\n * Relations to load into the response — see {@link IncludeSpec}.\n *\n * Not checked against `M` here: a relation name comes from the table's\n * `relations`, not from its columns, so nothing in a *hand-written* row type\n * can validate one. A **generated** `Database` narrows this to the\n * table's actual relation keys, recursively — see\n * {@link IncludeSpecFor}. The row a read returns still types each relation\n * as optional; the generated `RowWith<A, I>` names the row with the\n * included ones required.\n *\n * An unknown name is a 400 `UNKNOWN_RELATION`. It used to be ignored.\n */\n include?: Inc;\n\n /**\n * Columns to return, instead of all of them.\n *\n * A real column projection: only these columns are read from the database,\n * so a query that needs two fields of a wide row does not pay for the rest.\n * `excludeFromApi` still applies — naming such a column here does not\n * un-hide it — and the primary key is always returned, because a row that\n * cannot be addressed cannot be updated, deleted or paged past.\n *\n * A relation named in {@link FindParams.include} is loaded regardless of\n * whether it appears here; use {@link IncludeOptions.fields} to narrow the\n * columns *within* an included relation.\n */\n fields?: string[];\n\n /**\n * Collapse rows that are identical over the columns being returned.\n *\n * `SELECT DISTINCT` over the projection — so it is only meaningful\n * alongside {@link FindParams.fields}, and with the primary key in the\n * projection (which it always is) every row is already distinct. Pair it\n * with `fields` naming the columns you actually want the distinct values of.\n *\n * A distinct read is not counted, whichever door it goes through: over\n * HTTP its `meta.total` is absent, and in-process it is the rows up to the\n * end of the page — as for {@link FindParams.count} `\"none\"`. `hasMore`\n * is exact either way.\n */\n distinct?: boolean;\n\n /**\n * Continue from where a previous page ended — keyset (\"seek\") pagination.\n *\n * The value is the opaque `meta.nextCursor` of the previous response. It\n * encodes the sort keys the query was ordered by and the last row's values\n * for them, so a page picks up strictly after the last row served rather\n * than at a row *count* that concurrent writes have already moved.\n *\n * It has to describe the same query: `after` alongside a different\n * `orderBy` is a 400 `CURSOR_ORDER_MISMATCH` rather than a page of rows\n * seeked in an order nobody asked for. Mutually exclusive with `offset` and\n * `page` for the same reason.\n *\n * Multi-key sorts and nullable keys both work — the comparison is built\n * over every key, in order, with the NULL placement the sort declared.\n */\n after?: string;\n /**\n * Text search string, AND-ed with `where`/`logical`. This is the value\n * behind the query builder's `.search()` method.\n *\n * What it compiles to depends on the table. By default — matching\n * every table that has not said otherwise — it is a case-insensitive\n * substring match OR-ed across the table's top-level `string`\n * properties: it does not reach inside `map` or `array` properties, it does\n * not stem or rank, and it cannot use an index.\n *\n * A Postgres table that declares a `search` block instead gets a\n * ranked full-text match over exactly the fields it named, and rows come\n * back with a {@link FindParams.orderBy}-able `_score`.\n */\n searchString?: string;\n\n /**\n * Nearest-neighbour search over a `vector` property.\n *\n * Postgres only, and only for a table that declares a column of\n * type `vector`. Rows come back ordered by distance, closest first, each\n * carrying a `_distance`. Combines with `where` and `logical`, which are\n * applied as filters before the ordering — so this is \"the nearest rows\n * that also match\", not \"the nearest rows, then filtered\".\n *\n * Supplying the query vector is the caller's job: rebase stores and\n * searches embeddings, it does not compute them.\n */\n vectorSearch?: VectorSearchParams;\n\n /**\n * Ask each returned row to explain itself: which declared search fields\n * matched, with a highlighted snippet from each. Populates `_matches`.\n *\n * Off by default because it is not free — one `ts_headline` per declared\n * field per returned row, and `ts_headline` re-parses the document rather\n * than reading the index. Fine for a page of results, not for an export.\n *\n * Ignored unless the table declares a `search` block and the query\n * carries a `searchString`; there is nothing to explain otherwise.\n */\n searchExplain?: boolean;\n\n /**\n * Whether to count the whole matching set for `meta.total`.\n *\n * `\"exact\"`, the default, runs a `COUNT(*)` over every row the query\n * matches beside the page — and on a large table that count, not the page,\n * is most of what a list read costs: it reads every matching row to report\n * one number. `\"none\"` skips it. `meta.hasMore` is still exact (the read\n * asks for one row past the page and reports whether it came back), so\n * nothing that pages — `iterate()`, `findAll()`, a \"load more\" button —\n * needs the count.\n *\n * Without the count there is no `total` to report: over HTTP `meta.total`\n * is absent, and in-process it is the rows up to the end of this page\n * (`offset` + the page), the figure a driver that cannot count reports.\n * Sent as `?count=none`.\n */\n count?: \"exact\" | \"none\";\n}\n\n\n// =============================================================================\n// SDK-facing types — flat rows, no Entity wrapper\n// =============================================================================\n\n/**\n * Pagination metadata returned with table queries.\n * @group Data\n */\nexport interface PaginationMeta {\n /**\n * Every row the query matches, counted. Not counted — and absent from an\n * HTTP response — when the query asked for {@link FindParams.count}\n * `\"none\"`, and on a `distinct` read over HTTP.\n */\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n /**\n * The opaque cursor that continues this listing — pass it back as\n * {@link FindParams.after}.\n *\n * Present whenever there is a next page to describe (`hasMore` is true and\n * the page returned at least one row). Absent on the last page, and absent\n * on a query no cursor can describe (relevance ordering, whose scores are\n * computed per query and are not comparable between two of them).\n *\n * Opaque on purpose: it encodes the sort keys *and* the last row's values\n * for them, and a client that parsed it would be depending on an encoding\n * that exists to be changed.\n */\n nextCursor?: string;\n}\n\n/**\n * Paginated response from a table query (SDK-facing).\n * Returns flat rows instead of Entity-wrapped objects.\n *\n * @example\n * const { data, meta } = await rebase.data.posts.find();\n * console.log(data[0].title); // direct access — no .values\n * console.log(meta.total);\n *\n * @group Data\n */\nexport interface FindResult<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Flat rows matching the query, each carrying whatever the query computed\n * for it — see {@link QueryComputedFields}.\n */\n data: (M & QueryComputedFields)[];\n /** Pagination metadata */\n meta: PaginationMeta;\n}\n\n/**\n * Values a query attaches to a row that are not columns of it.\n *\n * Both are absent unless the query asked for the thing that produces them, so\n * both are optional — and reading one on a query that did not ask returns\n * `undefined` rather than a wrong number.\n *\n * They live here rather than on the row type because a generated row type\n * describes a *table*, and neither of these is in one. Without this, a caller\n * who sorted by relevance could not then read the relevance.\n *\n * A `type` alias, deliberately, not an `interface`. TypeScript grants an\n * implicit index signature to a type alias and withholds it from an interface,\n * so `Row & QueryComputedFields` stops being assignable to\n * `Record<string, unknown>` the moment this becomes an interface. Seven casts\n * in one downstream app broke on exactly that.\n *\n * @group Data\n */\nexport type QueryComputedFields = {\n /**\n * Relevance, when the table declares a {@link SearchConfig} and the\n * query carried a search string. Higher is better; the scale is not\n * comparable between two different search strings.\n */\n _score?: number;\n /**\n * Which declared fields matched, and the text around each hit. Present only\n * when the query asked for it — `.search(term, { explain: true })` — because\n * it costs a `ts_headline` per field per row.\n */\n _matches?: SearchMatch[];\n /**\n * Distance to the query vector, when the query used\n * {@link FindParams.vectorSearch}. Lower is closer, and the rows are\n * already ordered by it.\n */\n _distance?: number;\n};\n\n/**\n * One aggregate a query asks for.\n *\n * `count` alone counts rows; every other function names a column, and `count`\n * with a column counts its non-NULL values.\n *\n * - `countDistinct` counts the distinct non-NULL values of a column.\n * - `mode` is the most frequent value (ties go to the first in sort order).\n * - `percentile` is the continuous percentile `p` (0–1) of a number column:\n * `p: 0.5` is the median.\n * - `distinct` is the column's distinct non-NULL values, sorted, as an array —\n * for an array column, the distinct arrays; group by `unnest` for the\n * distinct elements.\n * - `fingerprint` is a short string that changes whenever a row it covers is\n * inserted, updated or deleted: compare it with the last one you saw to\n * know whether anything changed, without reading the rows. It may also\n * change when nothing did (a write that set a column to its own value), never\n * the other way round.\n *\n * `field` may also be a JSON path (`props->>players`): `sum`, `avg` and\n * `percentile` read the value there as a number (a value that is not one is\n * left out, as a filter leaves it out), the others as text.\n *\n * `where` counts only the rows it matches towards this one aggregate — SQL's\n * `count(*) FILTER (WHERE …)` — so several differently filtered aggregates\n * are one query over the rows the outer `where` chose.\n *\n * The result key is derived — `sum(total)` comes back as `sum_total`, a bare\n * `count()` as `count`, `countDistinct(sid)` as `count_distinct_sid` and\n * `percentile(fame, 0.95)` as `p95_fame` (see {@link AggregateAlias}) —\n * unless `as` names it, which two aggregates of one function need: two\n * filtered `count()`s would both be `count`. A name used twice, or the key of\n * a `groupBy` column, is refused (`INVALID_AGGREGATE_SELECT`) rather than\n * overwritten.\n *\n * @group Data\n */\nexport type AggregateSelect<M extends Record<string, unknown> = Record<string, unknown>> = (\n | { fn: \"count\"; field?: Extract<keyof M, string> | JsonFieldPath }\n | { fn: \"sum\" | \"avg\"; field: NumericKeyOf<M> | JsonFieldPath }\n | { fn: \"min\" | \"max\" | \"countDistinct\" | \"mode\" | \"distinct\"; field: Extract<keyof M, string> | JsonFieldPath }\n | { fn: \"percentile\"; field: NumericKeyOf<M> | JsonFieldPath; p: number }\n | { fn: \"fingerprint\" }\n) & {\n /** Only the rows matching this count towards this aggregate: `FILTER (WHERE …)`. */\n where?: WhereFor<M>;\n /** The key the aggregate comes back under, instead of the derived one. */\n as?: string;\n};\n\n/** A path inside a json/jsonb column: `props->>players`, `meta->a->>b`. @group Data */\nexport type JsonFieldPath = `${string}->>${string}`;\n\n/**\n * A transformed column to group by, where a plain column will not do:\n * `lower`/`upper` of a text column, the `year`/`month`/`day` of a timestamp\n * (served as `\"2026\"`, `\"2026-11\"`, `\"2026-11-08\"`), or `unnest` — one group\n * per element of an array column, so `count()` beside it counts the rows\n * holding each element.\n *\n * `year`/`month`/`day` read the instant in UTC, or in `timeZone` (an IANA\n * name, `\"Europe/Madrid\"`): \"per day\" for people in one place means their\n * days, and a UTC day splits their evening in two.\n *\n * Its key in each row is `<transform>_<field>` (`lower_artist`,\n * `unnest_tags`), which is also how `orderBy` names it.\n *\n * @group Data\n */\nexport type AggregateGroup<Field extends string = string> = {\n field: Field;\n transform: AggregateGroupTransform;\n /** `year`/`month`/`day` only: the IANA time zone the instant is read in. UTC when absent. */\n timeZone?: string;\n};\n\n/** What an {@link AggregateGroup} does to its column. @group Data */\nexport type AggregateGroupTransform = \"lower\" | \"upper\" | \"unnest\" | \"year\" | \"month\" | \"day\";\n\n/**\n * The columns of `M` that hold numbers — what `sum` and `avg` can add up. Any\n * column used to be accepted, and `sum` of a text column was a 400. An untyped\n * row (every key `string`) keeps every name.\n *\n * Written as the keys of a key-remapped mapped type, not as a conditional over\n * `keyof M`: tsc measures the conditional form as invariant in `M`, which made\n * a typed `SDKTableClient<Post>` unassignable to the wide\n * `SDKTableClient` that helpers taking any table accept. A mapped\n * type is related structurally, so a typed client still widens.\n */\nexport type NumericKeyOf<M extends Record<string, unknown>> = Extract<keyof {\n [K in keyof M as string extends K ? K : NonNullable<M[K]> extends number ? K : never]: M[K]\n}, string>;\n\n/**\n * One row of an aggregate result: the `groupBy` columns, plus one key per\n * {@link AggregateSelect} under its derived alias.\n *\n * `count`, `sum` and `avg` arrive as numbers — Postgres returns bigint and\n * numeric as strings, and they are parsed once at the driver rather than by\n * every caller. `min`/`max` keep the column's own type.\n *\n * @group Data\n */\nexport type AggregateRow = Record<string, unknown>;\n\n/**\n * What {@link SDKTableClient.aggregate} takes: the same narrowing a\n * `find()` takes, minus the parts of it that describe a *page* of rows.\n *\n * `limit` and `offset` page through the **groups**, as they page a listing's\n * rows, because grouping by a high-cardinality column is a whole table's worth\n * of rows in one response. Over HTTP a grouped aggregate with no `limit` gets\n * the listing default (50 groups) — read {@link AggregateResult.meta} to know\n * when there were more. Without `groupBy` there is one row: `limit` does nothing\n * there and `offset` is refused.\n *\n * `include`, `after` and the rest are absent on purpose: an aggregate has no\n * relations to load and no row to continue after.\n *\n * @group Data\n */\nexport interface AggregateParams<M extends Record<string, unknown> = Record<string, unknown>> {\n /** The aggregates to compute. At least one. */\n select: AggregateSelect<M>[];\n /**\n * Columns to group by — or a column transformed ({@link AggregateGroup}),\n * e.g. `{ field: \"artist\", transform: \"lower\" }`, or a JSON path\n * (`props->>music`, its text; its key in each row is the path as written).\n * Omit for a single row over everything that matches.\n */\n groupBy?: (Extract<keyof M, string> | JsonFieldPath | AggregateGroup<Extract<keyof M, string>>)[];\n /** Filter conditions, as {@link FindParams.where}. */\n where?: WhereFor<M>;\n /** An `and`/`or`/`not` group, AND-ed with `where`. */\n logical?: LogicalConditionFor<M>;\n /** Text search, AND-ed with the filters. */\n searchString?: string;\n /** Most groups to return. Grouped aggregates only. */\n limit?: number;\n /** Groups to skip, to page past `limit`. Grouped aggregates only. */\n offset?: number;\n /**\n * Sort the groups — by a `groupBy` column or by an aggregate's alias\n * (`\"count\"`, `\"sum_total\"`, see {@link AggregateAlias}). One\n * `[key, \"asc\" | \"desc\"]` tuple, or several applied in order. Groups the\n * sort leaves tied keep their `groupBy` order. Grouped aggregates only:\n * without `groupBy` there is one row, and over HTTP an `orderBy` beside it is\n * refused with `INVALID_AGGREGATE_WINDOW`. A key that is neither a group\n * column nor a selected aggregate is refused with `INVALID_ORDER_BY`.\n *\n * ```ts\n * await client.data.orders.aggregate({\n * select: [{ fn: \"sum\", field: \"total\" }],\n * groupBy: [\"status\"],\n * orderBy: [\"sum_total\", \"desc\"]\n * });\n * ```\n */\n orderBy?: OrderByTuple<AggregateOrderKey<M>> | OrderByTuple<AggregateOrderKey<M>>[];\n}\n\n/** What `refresh()` takes. @group Data */\nexport interface RefreshOptions {\n /** Keep serving the old rows while the new ones are computed (`REFRESH … CONCURRENTLY`). */\n concurrently?: boolean;\n}\n\n/**\n * The key an {@link AggregateSelect} comes back under: `count` for `count()`,\n * `<fn>_<field>` otherwise (`sum_total`, `max_created_at`).\n *\n * @group Data\n */\nexport type AggregateAlias<M extends Record<string, unknown> = Record<string, unknown>> =\n | \"count\"\n | \"fingerprint\"\n | `${\"count\" | \"min\" | \"max\" | \"count_distinct\" | \"mode\" | \"distinct\"}_${Extract<keyof M, string>}`\n | `${\"sum\" | \"avg\"}_${NumericKeyOf<M>}`\n | `p${number}_${NumericKeyOf<M>}`;\n\n/**\n * What {@link AggregateParams.orderBy} can sort the groups by: a column (to\n * group by) or an aggregate's alias.\n *\n * @group Data\n */\nexport type AggregateOrderKey<M extends Record<string, unknown> = Record<string, unknown>> =\n | Extract<keyof M, string>\n | `${AggregateGroupTransform}_${Extract<keyof M, string>}`\n | AggregateAlias<M>;\n\n/**\n * Where a grouped aggregate's page of groups sits: the `limit` it was cut at,\n * the `offset` it started from, and whether more groups follow.\n *\n * @group Data\n */\nexport interface AggregateMeta {\n limit: number;\n offset: number;\n hasMore: boolean;\n}\n\n/**\n * What {@link SDKTableClient.aggregate} resolves to: the rows, as an\n * array, carrying the page they are as `meta`.\n *\n * `meta` is present on a grouped aggregate that was cut at a `limit` — which,\n * over HTTP, is every grouped one, since the route applies the listing default\n * when none is given. `hasMore: true` means the groups did not all fit: page on\n * with `offset`, or raise `limit`. It is a non-enumerable property, so a spread,\n * `JSON.stringify` or `Object.keys` of the result sees only the rows.\n *\n * @group Data\n */\nexport interface AggregateResult extends Array<AggregateRow> {\n readonly meta?: AggregateMeta;\n}\n\n/**\n * Which column an iteration sorts by when it is asked to seek, for keyset\n * (\"seek\") pagination.\n *\n * Either the column name on its own — sorted ascending — or the column plus an\n * explicit direction. It is used only when the query names no `orderBy`; see\n * {@link PageWalkOptions.cursor}.\n *\n * @group Data\n */\nexport type CursorSpec<M extends Record<string, unknown> = Record<string, unknown>> =\n | (Extract<keyof M, string>)\n | { field: Extract<keyof M, string>; direction?: \"asc\" | \"desc\" };\n\n/**\n * How {@link SDKTableClient.iterate} / {@link SDKTableClient.findAll}\n * walk a table, layered on top of the normal `find()` parameters.\n *\n * @group Data\n */\nexport interface PageWalkOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Rows fetched per request. Defaults to 200; values below 1 are clamped up.\n * This is the request size, not a result cap — the iteration keeps going\n * until the server says there is nothing left.\n */\n pageSize?: number;\n /**\n * **Require** seeking: fail rather than fall back to offset paging.\n *\n * Every walk already seeks when it can. After the first page it hands the\n * server's `meta.nextCursor` back as `after`, so each page asks for rows\n * strictly after the last one seen — concurrent writes before that row\n * cannot shift the window, and the database never skips rows by count.\n * Where the server issues no cursor (a relevance-ordered search, a vector\n * search, a `distinct` read, a server that predates cursors), the default\n * walk pages by offset instead, which a concurrent insert or delete can\n * make skip or repeat a row.\n *\n * Passing `cursor` turns that fallback into an error: a listing with no\n * cursor throws `cursor-missing`, and a cursor that stops advancing throws\n * `cursor-stalled`. It also names the column to sort by when the query has\n * no `orderBy`; an explicit `orderBy` wins, and the cursor follows whatever\n * the query is sorted by, multi-key sorts and nullable keys included. The\n * row id breaks the final tie, so the order is always total.\n *\n * @example\n * for await (const job of client.data.jobs.iterate({ cursor: \"id\" })) { … }\n */\n cursor?: CursorSpec<M>;\n /**\n * Hard ceiling on the number of requests one walk may make, so a server\n * that never stops saying `hasMore` cannot spin forever. Defaults to\n * 10 000 pages; hitting it throws.\n */\n maxPages?: number;\n}\n\n/**\n * Parameters accepted by {@link SDKTableClient.iterate} — everything\n * `find()` takes except the window itself (`limit`, `offset`, `page`), which\n * the iterator owns, plus the walk options.\n *\n * `count` is accepted and ignored: no page of a walk is counted, since nothing\n * a walk returns carries a total (see {@link FindParams.count}).\n *\n * @group Data\n */\nexport type IterateParams<M extends Record<string, unknown> = Record<string, unknown>, Inc = IncludeSpec> =\n Omit<FindParams<M, Inc>, \"limit\" | \"offset\" | \"page\"> & PageWalkOptions<M>;\n\n/**\n * Parameters accepted by {@link SDKTableClient.findAll}: the iteration\n * parameters plus the ceiling that keeps a whole table from being pulled\n * into memory unnoticed.\n *\n * @group Data\n */\nexport type FindAllParams<M extends Record<string, unknown> = Record<string, unknown>, Inc = IncludeSpec> =\n IterateParams<M, Inc> & {\n /**\n * Most rows to materialise. Defaults to 10 000. Exceeding it **throws**\n * — a truncated array returned as if it were the whole answer is the\n * kind of quiet wrong that shows up months later in a report. Pass\n * `Infinity` to opt out deliberately, or use `iterate()` to stream.\n */\n maxRows?: number;\n };\n\n/**\n * Fluent Query Builder Interface for the SDK client.\n * Resolves to `FindResult<M>` (flat rows).\n *\n * @group Data\n */\nexport interface SDKQueryBuilderInterface<M extends Record<string, unknown> = Record<string, unknown>, Inc = IncludeSpec> {\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): this;\n /**\n * Filter on a relation path (`author.name`) or a JSON path\n * (`metadata->>tier`).\n *\n * A separate overload because the value cannot be typed: neither addresses\n * a column of `M`, so there is nothing in a generated row type to check\n * against — the driver resolves the path and refuses what it cannot. The\n * key is still constrained to a *path*, so a mistyped column name does not\n * fall through to here and lose its check.\n *\n * `find({ where })` has accepted both all along ({@link FieldPath}); the\n * builder did not, so the documented relation-path filters were compile\n * errors on a typed client.\n */\n where(column: NonColumnFieldPath, operator: WhereFilterOp, value: unknown): this;\n where(logicalCondition: LogicalConditionFor<M>): this;\n /**\n * Sort by a column, a relation or JSON path, `_score`, or an aggregate over\n * a to-many relation — the same key set {@link FindParams.orderBy} takes.\n */\n orderBy(\n column: FieldPath<M> | ComputedSortField | RelationAggregateSort,\n direction?: \"asc\" | \"desc\",\n nulls?: NullsPlacement\n ): this;\n limit(count: number): this;\n offset(count: number): this;\n search(searchString: string, options?: { explain?: boolean }): this;\n\n /**\n * Order rows by nearest-neighbour distance to `vector`, closest first.\n *\n * Postgres only, over a property declared as `type: \"vector\"`. Each row\n * comes back with a `_distance`. Any `where` on the same query filters\n * before the ordering; distance decides the order.\n *\n * The query embedding is the caller's to produce.\n */\n vectorSearch(\n property: Extract<keyof M, string>,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): this;\n /**\n * Load relations — names, dotted paths (`\"comments.author\"`), or the\n * parametrised tree. Repeated calls merge rather than replace.\n */\n include(...relations: IncludeArgOf<Inc>[]): this;\n /**\n * Return only these columns. A real projection: the columns are what is\n * read from the database, not what survives a trim of the response.\n */\n fields(...columns: Extract<keyof M, string>[]): this;\n /** `SELECT DISTINCT` over the projection — see {@link FindParams.distinct}. */\n distinct(enabled?: boolean): this;\n /** Continue after a previous page's `meta.nextCursor`. */\n after(cursor: string): this;\n find(): Promise<FindResult<M>>;\n /**\n * Aggregate the rows this query matches instead of returning them.\n *\n * The builder's `where`/`logical`/`search` narrow which rows are\n * aggregated; its `orderBy`, `include` and window do not apply and are\n * ignored, exactly as they are on the REST route. Page the groups with the\n * `limit`/`offset` passed here.\n */\n aggregate(params: Omit<AggregateParams<M>, \"where\" | \"logical\" | \"searchString\">): Promise<AggregateResult>;\n\n /**\n * Page through everything this query matches, one row at a time.\n *\n * The same walker {@link SDKTableClient.iterate} uses, so the ceiling\n * on `limit` is not a ceiling on what a query can read. `.limit()` set on\n * the builder becomes the **page size** here, not a total.\n */\n iterate(options?: PageWalkOptions<M>): AsyncIterableIterator<M>;\n\n /**\n * Collect everything this query matches into one array.\n *\n * {@link SDKTableClient.findAll}'s `maxRows` guard applies: an\n * unbounded collect is a memory hazard, so it stops and says so rather than\n * growing until the process dies.\n */\n findAll(options?: PageWalkOptions<M> & { maxRows?: number }): Promise<M[]>;\n\n count(): Promise<number>;\n listen(onUpdate: (data: FindResult<M>) => void, onError?: (error: Error) => void): () => void;\n}\n\n/**\n * SDK table client — returns flat rows, no Entity wrapper.\n *\n * This is the public API surface for app developers using\n * `createRebaseClient()`.\n *\n * Type parameters:\n * - `M` — the **Row** shape returned by reads (`find`, `findById`, `listen`).\n * - `I` — the **Insert** shape accepted by {@link create}. Defaults to\n * `Partial<M>`; the generated SDK supplies a dedicated `Insert` type where\n * required columns are required and auto-generated / read-only columns are\n * omitted, so `create({})` on a table with required fields is a compile error.\n * - `U` — the **Update** shape accepted by {@link update}. Defaults to\n * `Partial<M>`; the generated SDK supplies a dedicated `Update` type.\n *\n * @example\n * const { data: posts } = await rebase.data.posts.find();\n * console.log(posts[0].title); // flat access\n * console.log(posts[0].id); // id at top level\n *\n * const post = await rebase.data.posts.findById(1);\n * console.log(post?.title); // no .values needed\n *\n * @group Data\n */\n/**\n * A change expressed as an operation on the column's current value, rather than\n * as the value to store.\n *\n * `{ views: 5 }` says what the number becomes; `{ views: { $inc: 1 } }` says\n * what happens to it. The difference is the read the caller no longer has to\n * make — and the race that read opens. Two requests that each read `4`, add one\n * and write `5` lose an increment between them; `SET views = views + 1` cannot,\n * because the arithmetic happens inside the statement holding the row lock.\n *\n * Exactly one operator per field. `{ views: { $inc: 1, $push: \"x\" } }` is\n * refused rather than applied in an order the caller cannot see.\n *\n * @group Data\n */\n/**\n * The operator names, as a value.\n *\n * A runtime list beside the type because three layers have to *recognise* an\n * operation, not just accept one: the REST validator, the driver that compiles\n * it, and the offline queue that must refuse to apply one locally. Three copies\n * of four strings is three chances for one of them to miss an operator added to\n * the other two, and the failure is silent in the worst direction — an\n * unrecognised marker is written to the column as a JSON document.\n *\n * @group Data\n */\nexport const FIELD_OPERATORS = [\"$inc\", \"$push\", \"$pull\", \"$merge\"] as const;\n\n/**\n * The key of a {@link BatchRef}. Declared here, beside the field operators,\n * because the two share one namespace: a `$`-prefixed key in a write payload is\n * a marker, and every reader of that namespace has to know all of it.\n *\n * @group Data\n */\nexport const BATCH_REF_KEY = \"$ref\";\n\n/**\n * Whether a value is *trying* to be a field operation — including a misspelled\n * one, which is the case worth catching.\n *\n * Any `$`-prefixed key counts, because `{ $increment: 1 }` written to a number\n * column as a JSON document is the failure this exists to prevent.\n *\n * Except on a `map` (pass `propertyType`): a map's value is a JSON document,\n * and one may legitimately carry `$` keys — a JSON Schema's `$schema`, a\n * document exported from another database. There, only a single-key object whose key is one of\n * {@link FIELD_OPERATORS} is an operation, and anything else is data. A caller\n * that does not know the property type gets the strict reading.\n *\n * The one exception is `{ $ref: … }`, the batch's backward reference. It stands\n * where a *value* goes and is resolved to one before the row is written, so it\n * is not an operation on a column — reading it as a misspelled operator refused\n * every `$ref` in a batch with \"unknown field operator '$ref'\".\n *\n * @group Data\n */\nexport function isFieldOperation(value: unknown, propertyType?: string): boolean {\n if (typeof value !== \"object\" || value === null || Array.isArray(value) || value instanceof Date) {\n return false;\n }\n const keys = Object.keys(value);\n if (keys.length === 1 && keys[0] === BATCH_REF_KEY) return false;\n if (propertyType === \"map\") {\n return keys.length === 1 && (FIELD_OPERATORS as readonly string[]).includes(keys[0]);\n }\n return keys.some((key) => key.startsWith(\"$\"));\n}\n\n/** True when any value in a write payload is (or is attempting to be) one. @group Data */\nexport function hasFieldOperation(values: Record<string, unknown> | undefined): boolean {\n return !!values && Object.values(values).some((value) => isFieldOperation(value));\n}\n\nexport type FieldOperation =\n /** Add to a `number` column; negative to subtract. `SET col = col + n`. */\n | { $inc: number }\n /** Append one value, or each of an array of values, to an `array` column. */\n | { $push: unknown }\n /** Remove every occurrence of a value from an `array` column. */\n | { $pull: unknown }\n /** Shallow-merge an object into a `map` column. `SET col = col || …::jsonb`. */\n | { $merge: Record<string, unknown> };\n\n/**\n * The payload {@link SDKTableClient.update} accepts: plain values, field\n * operations, or both in one body.\n *\n * @group Data\n */\nexport type UpdateValues<U> = { [K in keyof U]?: U[K] | FieldOperationFor<U[K]> };\n\n/**\n * The field operations a column of type `T` takes: `$inc` on a number, `$push`\n * / `$pull` on an array, `$merge` on a map. Any operation on any column used to\n * compile — `update(id, { title: { $inc: 1 } })` — and the server answered 400.\n * A column whose type says nothing (`unknown`, an untyped client) takes them all.\n */\nexport type FieldOperationFor<T> =\n unknown extends T\n ? FieldOperation\n : | (NonNullable<T> extends number ? { $inc: number } : never)\n | (NonNullable<T> extends readonly unknown[] ? { $push: unknown } | { $pull: unknown } : never)\n | (NonNullable<T> extends readonly unknown[] ? never : NonNullable<T> extends Record<string, unknown> ? { $merge: Record<string, unknown> } : never);\n\n/**\n * Where an upsert looks for the row it might be replacing.\n *\n * The columns must carry a uniqueness guarantee the database can use as an\n * `ON CONFLICT` target — the primary key, a property with\n * `validation.unique`, or the columns of a declared `unique` index. Anything\n * else is refused with a 400 rather than sent to Postgres, which would answer\n * `there is no unique or exclusion constraint matching the ON CONFLICT\n * specification` from inside a transaction that has already done work.\n *\n * @group Data\n */\nexport interface UpsertOptions<M extends Record<string, unknown> = Record<string, unknown>> extends WriteOptions {\n /** Column names forming the conflict target. Defaults to the primary key. */\n onConflict?: readonly string[];\n /**\n * Replace a stored row only when it matches this filter, evaluated on the\n * stored row: `ON CONFLICT … DO UPDATE … WHERE`. A stored row it does not\n * match is left as it is, and nothing comes back for it. One statement,\n * so \"keep the higher score\" or \"only if newer\" cannot lose a race.\n *\n * ```ts\n * // Writes the score only when it beats the stored one.\n * const kept = await data.scores.upsert(\n * { day, sid, hype },\n * { where: { hype: [\"<\", hype] } }\n * ); // undefined when the stored score was higher\n * ```\n */\n where?: WhereFor<M>;\n /**\n * Leave a stored row on the conflict target as it is — `ON CONFLICT DO\n * NOTHING` — and return nothing for it. Insert-or-skip: an idempotent\n * claim, or a re-runnable import of rows that never change. Not with\n * `where`.\n */\n ignoreDuplicates?: boolean;\n}\n\n/**\n * The rows a filtered write ({@link SDKTableClient.updateWhere},\n * {@link SDKTableClient.deleteWhere}) addresses: the same `where` and\n * `logical` a `find()` takes, AND-ed.\n *\n * At least one condition. A filtered write with none would address every row,\n * which is the mistake this shape is most exposed to — a filter built from an\n * empty form, a key misspelled — so it is refused with `FILTER_REQUIRED`\n * rather than run. A field that is not a column is refused too, never dropped.\n *\n * @group Data\n */\nexport interface FilteredWriteParams<M extends Record<string, unknown> = Record<string, unknown>> {\n /** Filter conditions, as {@link FindParams.where}. */\n where?: WhereFor<M>;\n /** An `and`/`or`/`not` group, AND-ed with `where`. */\n logical?: LogicalConditionFor<M>;\n}\n\n/**\n * A placeholder standing for a value only the server will know: the id of a row\n * an earlier operation in the same batch creates.\n *\n * `{ \"$ref\": \"order.id\" }` reads the field `id` off the result of the operation\n * that named itself `ref: \"order\"`. Without it a batch cannot express the one\n * thing a cross-table batch exists for — writing a parent and its children\n * together — because the child's foreign key is not knowable until the parent\n * has been inserted, and splitting the two into separate requests is exactly\n * the non-atomic sequence the batch replaces.\n *\n * Only backward references resolve. `ref` names must be unique within a batch,\n * and an operation may not reference itself or anything after it.\n *\n * @group Data\n */\nexport interface BatchRef {\n /** `<ref name>.<field>`, e.g. `order.id`. */\n $ref: string;\n}\n\n/**\n * A row's values in a batch: the table's own columns, each of which may\n * instead be a {@link BatchRef} to a value an earlier operation produces.\n *\n * Homomorphic over the row type, so a column the row type requires is required\n * here too — a create in a batch is the same insert `create()` is. There used\n * to be an `& Record<string, unknown>` on the end, which let a misspelt column\n * compile and come back as a 400 `VALIDATION_UNKNOWN_FIELDS`.\n */\ntype BatchValues<T> = { [F in keyof T]: T[F] | BatchRef };\n\n/**\n * One entry of a batch request.\n *\n * `table` is the table's **accessor** on a typed client — the name\n * `client.data.<accessor>` takes, and the key of the generated `Database`\n * (`orderItems`). The client resolves it to the slug the route knows\n * (`order_items`) through its `tables` dictionary; a slug that is not an\n * accessor is sent as written.\n *\n * @group Data\n */\nexport type BatchOperation<DB = Record<string, unknown>> = {\n [K in Extract<keyof DB, string>]:\n | {\n op: \"create\";\n table: K;\n values: BatchValues<InsertOf<DB[K]>>;\n /** Name this row so a later operation can reference its columns. */\n ref?: string;\n }\n | {\n op: \"upsert\";\n table: K;\n values: BatchValues<InsertOf<DB[K]>>;\n /** See {@link UpsertOptions.onConflict}. Defaults to the primary key. */\n onConflict?: readonly string[];\n ref?: string;\n }\n | {\n op: \"update\";\n table: K;\n id: string | number | BatchRef;\n values: { [F in keyof UpdateOf<DB[K]>]?: UpdateOf<DB[K]>[F] | FieldOperationFor<UpdateOf<DB[K]>[F]> | BatchRef };\n ref?: string;\n }\n | {\n op: \"delete\";\n table: K;\n id: string | number | BatchRef;\n ref?: string;\n };\n}[Extract<keyof DB, string>];\n\n/**\n * What `POST /api/data/_batch` answers with.\n *\n * `data` is aligned to `operations`: the written row for a create, upsert or\n * update, and `null` for a delete — so an index into one is an index into the\n * other, whatever the batch mixed.\n *\n * @group Data\n */\nexport interface BatchResult<R = Record<string, unknown>> {\n data: (R | null)[];\n meta: { operations: number };\n}\n\n/**\n * Per-request options for a write.\n * @group Data\n */\nexport interface WriteOptions {\n /**\n * Names this write, so re-sending it is recognised instead of repeated.\n *\n * A client that does not see a response cannot know whether the write\n * committed. Retrying is therefore the only option, and without a key the\n * server has no way to tell a retry from a second, genuinely new write — so\n * it performs it again. On a table with a server-assigned id that is a\n * duplicate row, because the id the client chose was never used.\n *\n * A key names **one** request, not a job. It records the method, the path\n * and the body it was claimed for, so re-sending that exact request replays\n * its answer, while the same key on a different one is refused with\n * `IDEMPOTENCY_KEY_REUSED` (422) rather than silently answered with the\n * first request's result. Pass a fresh key — a uuid — per call; a reusable\n * business id shared by the create and the delete of one import means the\n * second of them never runs.\n *\n * Set by the offline queue on every replay. Honoured for 24 hours and scoped\n * to the authenticated user — an unauthenticated caller has no principal to\n * scope it to, so the key is ignored there. A retry sent while the first\n * attempt is still being answered gets `IDEMPOTENCY_KEY_IN_PROGRESS` (409)\n * and should be sent again. A server that cannot store keys ignores the\n * header rather than refusing the write.\n *\n * The in-process accessor (`context.data`, `rebase.data`) has no store to\n * keep keys in, and refuses one with `UNSUPPORTED_OPTION` rather than\n * writing as though it had been checked.\n */\n idempotencyKey?: string;\n\n /**\n * Whether the server should send the written row back.\n *\n * `false` sends `Prefer: return=minimal`, and the write answers `204 No\n * Content` — `200` carrying the ids only, for a batch. The row is the\n * default because it carries what the server decided: a serial id, an\n * `autoValue` timestamp, whatever `beforeSave` rewrote. A caller that\n * needs none of that is paying for a full row serialisation and, on\n * Postgres, a read-back per written row.\n *\n * Reach for it on imports and fire-and-forget writes. The method resolves\n * to `undefined` (or `[]`) when it is set, so a caller cannot accidentally\n * use a row the server never sent — and `create`, `update` and `upsert`\n * are typed `M | undefined` for a literal `returning: false`, so reading a\n * field off the result is a compile error rather than a `TypeError`.\n */\n returning?: boolean;\n\n /**\n * The version of the row this write was made against, so it is refused if\n * the row has moved on.\n *\n * The `ETag` from the read that produced the row — `etagOf(row)` on a row\n * from `findById`, or the `ETag` response header. A mismatch answers `412`\n * rather than writing, which is the difference between \"update the row I\n * read\" and \"overwrite whatever is there now\". Without it a read, an edit\n * and a write is last-writer-wins over everything the write did not send,\n * and the loser is told nothing.\n *\n * `\"*\"` asserts only that the row exists.\n *\n * Honoured on `update` and `delete` over HTTP. The in-process accessor\n * (`context.data`, `rebase.data`) cannot check a precondition yet, and\n * refuses one with `UNSUPPORTED_OPTION` rather than writing unconditionally.\n */\n ifMatch?: string;\n}\n\n\n/**\n * Options for {@link TrashClient.restore} and {@link TrashClient.restoreMany}.\n */\nexport interface RestoreOptions<M extends Record<string, unknown> = Record<string, unknown>> extends WriteOptions {\n /**\n * The table's soft-delete field, as declared in `softDelete`.\n * Defaults to `deletedAt`, the field `softDelete: true` uses; pass the\n * name a `softDelete: { field: \"archivedAt\" }` table declares.\n *\n * A restore is an ordinary update setting this field to `null`, which is\n * the one update the server lets reach a trashed row.\n */\n field?: keyof M & string;\n}\n\n/**\n * The trash of a table that declares `softDelete`: the rows a delete\n * stamped rather than removed. `client.data.<slug>.trash` in the browser,\n * `context.data.<slug>.trash` and `rebase.data.<slug>.trash` on the server.\n *\n * For a table that declares `softDelete`. On one that does not, `find`\n * and `count` answer for the live rows, `restore` is refused for a field the\n * table does not have, and `purge` is an ordinary delete.\n *\n * Where the data source cannot read a trash, every method is a stub that\n * throws when called.\n */\nexport interface TrashClient<M extends Record<string, unknown> = Record<string, unknown>, Inc = IncludeSpec> {\n /** The trashed rows matching `params` — `GET /data/<slug>?deleted=only`. */\n find(params?: FindParams<M, Inc>): Promise<FindResult<M>>;\n /** How many trashed rows match `params` — `GET /data/<slug>/count?deleted=only`. */\n count(params?: FindParams<M, Inc>): Promise<number>;\n /**\n * Bring a trashed row back: the update setting the soft-delete field to\n * `null` (`PATCH /data/<slug>/<id>`). Resolves with the restored row.\n */\n restore(id: string | number, options?: RestoreOptions<M>): Promise<M>;\n /** {@link TrashClient.restore} for several rows, as one transaction (`PATCH /data/<slug>/bulk`). */\n restoreMany(ids: (string | number)[], options?: RestoreOptions<M>): Promise<M[]>;\n /**\n * Delete a row for good — `DELETE /data/<slug>/<id>?hard=true`. It cannot\n * be restored afterwards. Needs the same permission an ordinary delete\n * does, and works on a live row as well as a trashed one.\n */\n purge(id: string | number, options?: WriteOptions): Promise<void>;\n /** {@link TrashClient.purge} for several rows, as one transaction (`POST /data/<slug>/bulk/delete?hard=true`). */\n purgeMany(ids: (string | number)[], options?: WriteOptions): Promise<void>;\n}\n\nexport interface SDKTableClient<\n M extends Record<string, unknown> = Record<string, unknown>,\n I = Partial<M>,\n U = Partial<M>,\n /** The include this table takes; {@link IncludeOf} for a generated `Database`. */\n Inc = IncludeSpec\n> {\n /**\n * Find multiple records with optional filtering, pagination, and sorting.\n *\n * ## What a list method returns\n *\n * Two shapes, and one rule that tells them apart: **a window is wrapped, a\n * whole answer is not.**\n *\n * - `find()` and `listen()` return {@link FindResult} — `{ data, meta }` —\n * because they hand back *one page*. `meta.total` and `meta.hasMore` are\n * the caller's only way to know there is more, so a bare array would lose\n * the answer to the question the call raises.\n * - `findAll()`, `createMany()` and `updateMany()` return a plain `M[]`,\n * because there is nothing left over to report: the walk finished, or the\n * batch is exactly the rows that were written. A `meta` there would be\n * `{ total: rows.length, hasMore: false }`, which says nothing.\n * - `iterate()` yields rows one at a time and never materialises a list at\n * all.\n *\n * So `data` is not a wrapper the SDK sometimes adds and sometimes forgets —\n * it is where the pagination metadata lives, and it is present exactly when\n * there is some.\n */\n find(params?: FindParams<M, Inc>): Promise<FindResult<M>>;\n\n /**\n * Walk every record matching a query, one row at a time, fetching pages as\n * the consumer consumes them.\n *\n * This is the pagination primitive: `find()` returns one window, `iterate()`\n * returns all of them without the caller hand-rolling the\n * `limit` / `offset += ` / \"am I done yet\" loop. Nothing is buffered — rows\n * are yielded as each page arrives, so a million-row walk costs one page of\n * memory. `break` stops the walk and no further requests are made.\n *\n * Termination is driven by the server's `meta.hasMore`, never by comparing\n * a page's length against the requested limit — a final page that happens\n * to be exactly full is indistinguishable that way, and a walk that stops\n * there drops rows. An empty page also ends the walk, and\n * {@link PageWalkOptions.maxPages} bounds a server that never stops saying\n * there is more.\n *\n * ## Consistency\n *\n * After the first page the walk **seeks**: it hands the server's\n * `meta.nextCursor` back as `after`, so each page asks for rows strictly\n * after the last one it saw, which concurrent writes cannot perturb. A\n * listing the server issues no cursor for — relevance, a vector search, a\n * `distinct` read — is paged by **offset** instead, which is only as stable\n * as the table is still: a row inserted or deleted ahead of the window\n * between two requests shifts every later one, so the walk can skip a row\n * or hand back the same one twice. Pass {@link PageWalkOptions.cursor} to\n * make seeking a requirement rather than a preference.\n *\n * @example\n * for await (const job of client.data.jobs.iterate({\n * where: { status: [\"==\", \"queued\"] },\n * cursor: \"id\",\n * pageSize: 500\n * })) {\n * await handle(job);\n * }\n */\n iterate(params?: IterateParams<M, Inc>): AsyncIterableIterator<M>;\n\n /**\n * {@link iterate}, collected into an array.\n *\n * Convenient when the result is known to be small and awkward to stream.\n * Because \"known to be small\" is an assumption and not a fact, the result is\n * capped — 10 000 rows by default — and going over the cap **throws**\n * rather than returning a short array that reads like a complete one. Raise\n * {@link FindAllParams.maxRows} when the data really is bigger, or switch to\n * `iterate()` and stream it.\n *\n * The consistency notes on {@link iterate} apply here too.\n *\n * @throws When more rows match than `maxRows` allows.\n *\n * @example\n * const overdue = await client.data.invoices.findAll({\n * where: { due_at: [\"<\", today] },\n * cursor: \"id\"\n * });\n */\n findAll(params?: FindAllParams<M, Inc>): Promise<M[]>;\n\n /**\n * Find a single record by its ID. `options.include` loads its relations,\n * as `find({ include })` does for each row of a list.\n */\n findById(id: string | number, options?: ByIdReadOptions<Inc>): Promise<M | undefined>;\n\n /**\n * Read one record by its ID, or throw if it is not there.\n *\n * The counterpart to {@link findById}, and the one most reads want. A row\n * fetched by an id that came from a link, a route parameter or another row\n * is expected to exist; when it does not, that is the error case, not a\n * value to thread through the rest of the function.\n *\n * `findById` returns `M | undefined`, so every caller had to prove the row\n * existed before touching a field:\n *\n * ```ts\n * const post = await rebase.data.posts.findById(id);\n * post.title; // TS18048: 'post' is possibly 'undefined'\n * const ok = (await rebase.data.posts.findById(id))!.title; // the `!` everyone reaches for\n * ```\n *\n * With `get`, the absent case is an exception with a code you can branch on,\n * and the happy path is typed as present:\n *\n * ```ts\n * const post = await rebase.data.posts.get(id); // M, not M | undefined\n * ```\n *\n * Same split as Prisma's `findUnique` / `findUniqueOrThrow`: two contracts,\n * both wanted, named so the choice is visible at the call site.\n *\n * @throws {RebaseApiError} `NOT_FOUND` (status 404) when no such row exists,\n * or is visible to the caller — row-level security makes a row the caller\n * may not read indistinguishable from one that is not there, deliberately.\n */\n get(id: string | number): Promise<M>;\n\n /**\n * Create a new record.\n * @param data The record data to create (the table's `Insert` shape).\n * @param id Optional specific id, sent as an `id` column. This is for tables\n * whose key *is* `id`: the value goes in as that column. For a table keyed\n * on anything else (a `sku`, a composite key), there is no `id` column to\n * receive it — put the key in `data` instead, where it belongs among the\n * columns.\n * @returns The created row — or nothing, with `returning: false`.\n */\n create(data: I, id: string | number | undefined, options: WriteOptions & { returning: false }): Promise<M | undefined>;\n create(data: I, id?: string | number, options?: WriteOptions): Promise<M>;\n\n /**\n * Write many records in a single request and a single transaction.\n *\n * Built for imports and ETL, where one call per row means one HTTP round\n * trip and one transaction per row. Every record still runs the normal\n * pipeline — callbacks, relations, row-level security — and the batch is\n * all-or-nothing: if any record is rejected, none of them land and the\n * error names the offending index.\n *\n * A record carrying its primary key updates that row; one without inserts.\n * With `{ upsert: true }` each record is written as INSERT ... ON CONFLICT\n * DO UPDATE on the primary key instead, which is what makes a re-runnable\n * import idempotent.\n *\n * Batches are capped server-side (1000 rows by default) because one batch\n * holds its locks for the whole transaction — chunk larger jobs.\n *\n * Pass {@link WriteOptions.idempotencyKey} on anything that may be retried.\n * A client that never sees the response cannot know whether the batch\n * committed, and without a key the server cannot tell the retry from a\n * second genuine import — so it performs it again, duplicating every row in\n * the batch rather than just one.\n *\n * With `upsert`, `ignoreDuplicates` and `where` say what happens to a row\n * already on the conflict target, as on {@link upsert}: left alone, or\n * replaced only when it matches. A row left alone is not in the answer.\n *\n * @returns The written rows, in the order given.\n *\n * @example\n * ```ts\n * for (const chunk of chunks(rows, 1000)) {\n * await client.data.products.createMany(chunk, { upsert: true });\n * }\n * ```\n */\n createMany(\n data: I[],\n options?: { upsert?: boolean; onConflict?: readonly string[]; where?: WhereFor<M>; ignoreDuplicates?: boolean } & WriteOptions\n ): Promise<M[]>;\n\n /**\n * Update an existing record by ID.\n * @param data The fields to update (the table's `Update` shape).\n * @param options Per-request write options — notably `idempotencyKey`.\n * @returns The updated row.\n * @throws {RebaseApiError} with status 404 when the record does not exist.\n *\n * `create`, `createMany`, `updateMany`, `delete` and `deleteMany` all took\n * {@link WriteOptions}; this one did not, so the single-row update was the\n * one write on the surface that could not be made idempotent. A client that\n * never sees the response retries, and without a key the server cannot tell\n * that retry from a second deliberate edit — which on a `PATCH` that\n * increments or appends is a second edit applied.\n */\n update(id: string | number, data: U | UpdateValues<U>, options: WriteOptions & { returning: false }): Promise<M | undefined>;\n update(id: string | number, data: U | UpdateValues<U>, options?: WriteOptions): Promise<M>;\n\n /**\n * Insert the row, or replace the one already occupying its key.\n *\n * `INSERT ... ON CONFLICT DO UPDATE`, in one statement — so unlike a\n * `findById` followed by `create`-or-`update` it cannot lose the race\n * between the two, and unlike `create` it does not fail when the row is\n * already there. That is what makes a re-runnable import idempotent\n * without a key.\n *\n * The conflict target defaults to the primary key. Pass `onConflict` to\n * upsert on a natural key instead — `[\"email\"]`, `[\"tenant_id\", \"slug\"]` —\n * and the columns must carry a uniqueness guarantee the database can use:\n * a property with `validation.unique`, or the columns of a declared\n * `unique` index. Anything else is a 400 rather than a Postgres error\n * raised half-way through a transaction.\n *\n * Refused (400 `INVALID_CONFLICT_TARGET`) on the auth table, whose\n * rows are the users: a create and an update of a user follow different\n * rules, and an upsert only learns which it is inside the write.\n *\n * The `on_create` timestamp of a row that already existed is left alone: a\n * conflict means the row's creation is a fact about the past, and a nightly\n * re-import that reset `createdAt` on everything it touched would take\n * every \"new this week\" query with it.\n *\n * `where` replaces a stored row only when it matches, and\n * `ignoreDuplicates` never replaces one ({@link UpsertOptions}): with\n * either, the call resolves to `undefined` when the stored row was left\n * as it was.\n *\n * @example\n * ```ts\n * await client.data.products.upsert(\n * { sku: \"LAMP-01\", name: \"Desk lamp\" },\n * { onConflict: [\"sku\"] }\n * );\n * ```\n */\n upsert(data: I, options: UpsertOptions<M> & { returning: false }): Promise<M | undefined>;\n upsert(data: I, options: UpsertOptions<M> & ({ where: WhereFor<M> } | { ignoreDuplicates: true })): Promise<M | undefined>;\n upsert(data: I, options?: UpsertOptions<M>): Promise<M>;\n\n /**\n * Update many records in a single request and a single transaction.\n *\n * The counterpart to {@link createMany}, and the reason it exists is the\n * same: one call per row means one HTTP round trip and one transaction per\n * row. Every record still runs the normal pipeline — callbacks, relations,\n * row-level security — and the batch is all-or-nothing, so a rejected\n * record leaves none of them written and the error names the offending\n * index.\n *\n * Each entry is `{ id, data }` rather than a flat row carrying its own key.\n * That is deliberate: on a table keyed on something other than `id` — a\n * `sku`, a composite key — a flat row cannot say whether a column is the\n * address or a value to write. Naming the address separately mirrors\n * single-row `update(id, data)` exactly and leaves nothing to infer.\n *\n * An id that matches no row fails the batch with a 404 rather than being\n * skipped, for the same reason `update()` does: silently updating four of\n * five rows is worse than updating none.\n *\n * Batches share `createMany`'s server-side cap (1000 rows by default),\n * because one batch holds its locks for the whole transaction.\n *\n * Pass {@link WriteOptions.idempotencyKey} on anything that may be retried.\n * An update replayed in full is naturally idempotent, but one interleaved\n * with another writer's is not — the key is what stops a lost ACK from\n * re-applying a stale batch over newer data.\n *\n * @returns The updated rows, in the order given.\n *\n * @example\n * ```ts\n * await client.data.orders.updateMany([\n * { id: \"o-1\", data: { status: \"shipped\" } },\n * { id: \"o-2\", data: { status: \"shipped\" } }\n * ]);\n * ```\n */\n updateMany(updates: { id: string | number; data: U | UpdateValues<U> }[], options?: WriteOptions): Promise<M[]>;\n\n /**\n * Update every record a filter matches, in one statement, and return the\n * records it updated.\n *\n * `UPDATE … SET … WHERE <filter> RETURNING *`: atomic, one round trip,\n * and the filter is evaluated by the statement that writes — so it is\n * also a compare-and-set. Field operations work as on {@link update}:\n *\n * ```ts\n * // Claim a save slot only if nobody wrote it since revision 7.\n * const [saved] = await data.saves.updateWhere(\n * { where: { who: [\"==\", who], rev: [\"==\", 7] } },\n * { body, rev: { $inc: 1 } }\n * ); // undefined when the revision moved on\n * ```\n *\n * Matching nothing is not an error: the answer is `[]`. Row-level\n * security applies as to any write. On a table whose writes run\n * per-row work — a save hook, history, tenancy, a `beforeQuery`, a trash,\n * per-field access — the matching rows are read under the caller's scope\n * and updated one by one through the full pipeline, in one transaction.\n *\n * The filter takes at least one condition ({@link FilteredWriteParams}).\n * Shares `createMany`'s row cap when it runs row by row.\n */\n updateWhere(query: FilteredWriteParams<M>, data: U | UpdateValues<U>, options?: WriteOptions): Promise<M[]>;\n\n /**\n * Delete every record a filter matches, in one statement, and return how\n * many went.\n *\n * `DELETE … WHERE <filter>`: atomic and one round trip, where a read\n * followed by {@link deleteMany} is two and can delete a row that changed\n * in between. Matching nothing is not an error — the answer is `0` — which\n * also makes it the delete for a row that may already be gone:\n *\n * ```ts\n * await data.passes.deleteWhere({ where: { token: [\"==\", token] } });\n * ```\n *\n * Per-row work (`beforeDelete`/`afterDelete`, history, a trash, a\n * `beforeQuery`) is honoured as {@link updateWhere} honours it: the\n * matching rows are deleted one by one through the pipeline, in one\n * transaction. The filter takes at least one condition\n * ({@link FilteredWriteParams}).\n */\n deleteWhere(query: FilteredWriteParams<M>, options?: WriteOptions): Promise<number>;\n\n /**\n * Delete a record by ID.\n * @throws {RebaseApiError} with status 404 when the record does not exist.\n *\n * Takes {@link WriteOptions} like every other write. It did not, so the one\n * mutation that cannot be made safe by repeating it — a delete replayed\n * after the row is gone answers 404, which an offline queue reads as a\n * permanent failure — was also the one that could not carry an\n * `idempotencyKey`.\n */\n delete(id: string | number, options?: WriteOptions): Promise<void>;\n\n /**\n * Delete many records in a single request and a single transaction.\n *\n * Takes ids. To delete by a condition, use {@link deleteWhere}, which\n * refuses an empty filter rather than emptying the table.\n *\n * `beforeDelete` and `afterDelete` fire per row, exactly as they do for\n * single deletes, and returning `false` from `beforeDelete` fails the batch\n * rather than quietly dropping one row from it. All-or-nothing, so an id\n * that matches no row 404s the whole call.\n *\n * Shares `createMany`'s row cap.\n *\n * @example\n * ```ts\n * await client.data.sessions.deleteMany([\"s-1\", \"s-2\"]);\n * ```\n */\n deleteMany(ids: (string | number)[], options?: WriteOptions): Promise<void>;\n\n /**\n * The low-level realtime subscription: raw server pushes, nothing else.\n *\n * **Prefer `observe()`** on a client from `@rebasepro/client`, which wraps\n * this one and is what a UI actually wants — it emits from the local\n * database first when offline is enabled, re-emits on local writes and\n * rollbacks, and de-duplicates emissions so a refresh that changes nothing\n * does not call back. `listen` does none of that; it forwards what the\n * socket sends.\n *\n * Always present. A client that cannot subscribe — one built with\n * `realtime: false`, or on a driver with no `listenCollection` — installs a\n * stub that throws a `RebaseClientError` naming the configuration that\n * would make it work. It used to be optional, which made every call site\n * either write `listen!(…)` or a null check the type system could not tell\n * apart from a real capability question; the answer to *that* question is\n * {@link isUnsupported}, and the answer for ordinary code is to just call\n * it.\n *\n * `observe()` degrades to a single fetch instead of throwing, which is the\n * other reason to reach for it instead.\n */\n listen(params: FindParams<M, Inc> | undefined, onUpdate: (response: FindResult<M>) => void, onError?: (error: Error) => void): () => void;\n\n /**\n * {@link listen} for a single row. Prefer `observeById()`. Every frame is\n * the row as `findById(id, options)` reads it, relations included.\n */\n listenById(id: string | number, onUpdate: (row: M | undefined) => void, onError?: (error: Error) => void, options?: ByIdReadOptions<Inc>): () => void;\n\n /**\n * The number of rows matching `params`, kept current: `onCount` is called\n * with the total once it is known, and again whenever a write changes it.\n * The live counterpart of {@link count} — a list's total, or a \"select all\n * N\" offer, that does not go stale while other people add and remove rows.\n * Only the filter (`where`, `logical`, `searchString`) counts; the window\n * and sort are ignored.\n *\n * Always present; on a client that cannot subscribe it is a stub that\n * throws, as {@link listen} is.\n */\n listenCount(params: FindParams<M, Inc> | undefined, onCount: (total: number) => void, onError?: (error: Error) => void): () => void;\n\n /**\n * The table's trash: list, count, restore and purge the rows a soft\n * delete stamped. See {@link TrashClient}.\n */\n trash: TrashClient<M, Inc>;\n\n /**\n * Count the number of records matching the given filter.\n *\n * Always present; see {@link listen} for what a transport that cannot serve\n * it does instead.\n */\n count(params?: FindParams<M, Inc>): Promise<number>;\n\n /**\n * `count`/`sum`/`avg`/`min`/`max` over the matching rows, optionally\n * grouped — the SDK half of `GET /<table>/aggregate`.\n *\n * The whole point is not to fetch rows in order to reduce them: \"revenue by\n * status\" over a million orders is one query and one row per status here,\n * and a `findAll()` plus a loop everywhere else — which is wrong under a\n * `limit` and unaffordable without one. It runs through the same\n * request-scoped handle as every other read, so RLS applies to the rows\n * being aggregated.\n *\n * ```ts\n * const rows = await rebase.data.orders.aggregate({\n * select: [{ fn: \"sum\", field: \"total\" }, { fn: \"count\" }],\n * groupBy: [\"status\"],\n * where: { created_at: [\">=\", startOfMonth] }\n * });\n * // [{ status: \"paid\", sum_total: 41822.5, count: 317 }, …]\n * ```\n *\n * Always present; a backend whose driver cannot aggregate answers 501\n * naming the capability rather than an empty result set, which would read\n * as \"nothing matched\".\n */\n aggregate(params: AggregateParams<M>): Promise<AggregateResult>;\n\n /**\n * Recompute a materialized view's rows from its query (`view:\n * { materialized: true }`), as `REFRESH MATERIALIZED VIEW` does.\n *\n * For a caller holding one of the view's `roles` (`dataAsAdmin` does);\n * refused for anyone else and for a table that is not a materialized\n * view. With `concurrently`, reads go on being served the old rows while\n * the new ones are computed — slower, and never a blocked read.\n *\n * ```ts\n * await rebase.dataAsAdmin.artist_stats.refresh({ concurrently: true });\n * ```\n */\n refresh(options?: RefreshOptions): Promise<void>;\n\n // Fluent Query Builder\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): SDKQueryBuilderInterface<M, Inc>;\n /** A relation path (`author.name`) or a JSON path (`metadata->>tier`). */\n where(column: NonColumnFieldPath, operator: WhereFilterOp, value: unknown): SDKQueryBuilderInterface<M, Inc>;\n where(logicalCondition: LogicalConditionFor<M>): SDKQueryBuilderInterface<M, Inc>;\n orderBy(\n column: FieldPath<M> | ComputedSortField | RelationAggregateSort,\n direction?: \"asc\" | \"desc\",\n nulls?: NullsPlacement\n ): SDKQueryBuilderInterface<M, Inc>;\n limit(count: number): SDKQueryBuilderInterface<M, Inc>;\n offset(count: number): SDKQueryBuilderInterface<M, Inc>;\n search(searchString: string, options?: { explain?: boolean }): SDKQueryBuilderInterface<M, Inc>;\n /**\n * Order rows by nearest-neighbour distance to `vector`, closest first.\n * Postgres only, over a `type: \"vector\"` property. See\n * {@link SDKQueryBuilderInterface.vectorSearch}.\n */\n vectorSearch(\n property: Extract<keyof M, string>,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): SDKQueryBuilderInterface<M, Inc>;\n include(...relations: IncludeArgOf<Inc>[]): SDKQueryBuilderInterface<M, Inc>;\n /** {@link SDKQueryBuilderInterface.fields} */\n fields(...columns: Extract<keyof M, string>[]): SDKQueryBuilderInterface<M, Inc>;\n /** {@link SDKQueryBuilderInterface.distinct} */\n distinct(enabled?: boolean): SDKQueryBuilderInterface<M, Inc>;\n /** {@link SDKQueryBuilderInterface.after} */\n after(cursor: string): SDKQueryBuilderInterface<M, Inc>;\n}\n\n\n/**\n * The unified data access object for the **SDK** — flat rows, no Entity wrapper.\n *\n * This is the symmetric developer-facing data API, identical in shape on both\n * sides of the stack:\n * - The frontend SDK client (`client.data.products.find()`)\n * - Backend framework callbacks & scripts (`context.data.products.find()`)\n *\n * Every accessor returns flat rows (the table's columns) via\n * {@link SDKTableClient} — access fields directly (`row.title`), never\n * `row.values.title`. (The admin panel's `Entity` view model is built from\n * these rows in `@rebasepro/cms-types`.)\n *\n * @example\n * // Frontend SDK\n * const { data: posts } = await client.data.posts.find();\n * console.log(posts[0].title); // flat — no .values\n *\n * // Backend callback — identical shape\n * callbacks: {\n * beforeSave: async ({ context }) => {\n * const product = await context.data.products.findById(id);\n * console.log(product?.price); // flat — no .values\n * }\n * }\n *\n * @group Data\n */\n/**\n * Extract the `Row` shape from a generated `Database[slug]` entry, falling\n * back to an open record when the entry is untyped.\n * @group Data\n */\nexport type RowOf<T> = T extends { Row: infer R extends Record<string, unknown> } ? R : Record<string, unknown>;\n\n/**\n * Extract the `Insert` shape from a generated `Database[slug]` entry (the\n * input accepted by `create`), falling back to `Partial<Row>`.\n * @group Data\n */\nexport type InsertOf<T> = T extends { Insert: infer I extends Record<string, unknown> } ? I : Partial<RowOf<T>>;\n\n/**\n * Extract the `Update` shape from a generated `Database[slug]` entry (the\n * input accepted by `update`), falling back to `Partial<Row>`.\n * @group Data\n */\nexport type UpdateOf<T> = T extends { Update: infer U extends Record<string, unknown> } ? U : Partial<RowOf<T>>;\n\n/**\n * The slugs a generated `Database` declares, from the `Slug` each entry\n * carries beside the accessor codegen chose for it.\n * @group Data\n */\nexport type SlugOf<DB> = {\n [K in keyof DB]: DB[K] extends { Slug: infer S extends string } ? S : never\n}[keyof DB];\n\n/** The generated `Database` entry whose `Slug` is `S`. */\ntype EntryOfSlug<DB, S extends string> = DB[{\n [K in keyof DB]: DB[K] extends { Slug: S } ? K : never\n}[keyof DB]];\n\n/**\n * `table(slug)` for a slug the registered `Database` declares: the same\n * typed client as the slug's accessor (`table(\"my-notes\")` is\n * `myNotes`). A slug it does not declare, or one computed at runtime, is\n * served by the untyped overload.\n */\ntype TypedSlugTable<DB> = {\n table<S extends SlugOf<DB>>(slug: S): SDKTableClient<\n RowOf<EntryOfSlug<DB, S>>,\n InsertOf<EntryOfSlug<DB, S>>,\n UpdateOf<EntryOfSlug<DB, S>>,\n IncludeOf<EntryOfSlug<DB, S>, DB>\n >;\n};\n\n/**\n * Note on the untyped branch below: its index signature is\n * `SDKTableClient`, NOT `SDKTableClient | ((slug: string) => …)`.\n *\n * The union looks like it is needed so `table` — a method on this same\n * object — satisfies the index signature. It is not, because `table` is\n * declared in a *separate* member of the intersection, and TypeScript only\n * requires named properties to be assignable to an index signature declared\n * alongside them. Including the function arm cost the documented accessor:\n *\n * rebase.dataAsAdmin.projects.find()\n * // ^ Property 'find' does not exist on type\n * // 'SDKTableClient | ((slug: string) => …)'\n *\n * Every project without a generated `Database` type lands on this branch, so\n * property-style access — the form used by the `@example` below, by the\n * scaffolded function template, and by the 0.13 migration note — did not\n * compile for any of them. Do not restore the arm; use `table(slug)` if a\n * caller genuinely needs the by-slug function.\n */\nexport type RebaseSdkData<DB = unknown> = (\n // Typed first, so a literal slug the `Database` declares picks this\n // overload; any other string falls through to the untyped one below.\n unknown extends DB ? unknown : TypedSlugTable<DB>\n) & {\n /**\n * Get a flat table accessor by slug.\n *\n * @example\n * const accessor = data.table(\"products\");\n * await accessor.find({ limit: 10 });\n */\n table<M extends Record<string, unknown> = Record<string, unknown>>(slug: string): SDKTableClient<M>;\n\n /**\n * A mixed list of writes across tables, as one transaction: the\n * in-process form of the HTTP client's `client.batch()`, with the same\n * operations, `$ref`s and answer. `table` is the accessor, as\n * everywhere on this object.\n *\n * Reserved, as `table` is: a table whose accessor is `batch` is\n * reached with `data.table(\"batch\")`.\n */\n batch(operations: BatchOperation<unknown extends DB ? Record<string, unknown> : DB>[]): Promise<BatchResult>;\n} & (\n // `unknown extends DB` rather than `DB extends Record<string, unknown>`:\n // the generated `Database` is an `interface`, and an interface has no\n // implicit index signature, so it never satisfied `Record<string,\n // unknown>` and a registered `Database` silently fell to the untyped arm.\n unknown extends DB\n ? {\n /**\n * Dynamic flat table accessor.\n * Access any table by its slug as a property.\n *\n * @example\n * data.products.find({ where: { status: [\"==\", \"published\"] } })\n */\n [tableSlug: string]: SDKTableClient;\n }\n : { [K in keyof DB]: SDKTableClient<RowOf<DB[K]>, InsertOf<DB[K]>, UpdateOf<DB[K]>, IncludeOf<DB[K], DB>> }\n);\n","import { RebaseApiError } from \"../errors\";\nimport type { EntityStatus } from \"../types/entities\";\nimport type { FilterValues } from \"../types/filter-operators\";\nimport type { OrderByTuple } from \"../types/filter-operators\";\nimport type { RebaseCallContext } from \"../call_context\";\nimport type { AggregateGroupTransform, IncludeSpec, LogicalCondition } from \"./data\";\nimport type { CollectionUpdateMeta } from \"../types/websockets\";\n\n\n/**\n * @internal\n */\nexport interface FetchOneProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n id: string | number;\n databaseId?: string;\n /**\n * See {@link FetchCollectionProps.withDeleted}. A soft-deleted row is a 404\n * here by default, so `findById` and `find` agree about which rows exist —\n * a row you cannot find in a listing and can still open by id is the kind\n * of inconsistency that makes a feature untrustworthy.\n */\n withDeleted?: boolean | \"only\";\n /**\n * Relations to load into the row (or into every frame of a listener), as\n * {@link FetchCollectionProps.include} loads them into each row of a list:\n * the target's own row under the relation's name. Absent means none — a\n * row carries its foreign keys and no relation. Without it on a listener a\n * to-many relation was absent from each frame, and the admin's record\n * form, opened by URL, showed it empty — so a save from it unlinked every\n * related row.\n */\n include?: IncludeSpec;\n}\n\n/**\n * @internal\n */\nexport type ListenOneProps<M extends Record<string, unknown> = Record<string, unknown>> =\n FetchOneProps<M>\n & {\n onUpdate: (row: Record<string, unknown> | null) => void,\n onError?: (error: Error) => void,\n }\n\n/**\n * Configuration for vector similarity search queries.\n * Vector search applies an ORDER BY distance expression and optionally\n * filters results by a distance threshold.\n */\nexport interface VectorSearchParams {\n /** Property name containing the vector column */\n property: string;\n /** Query vector to compare against */\n vector: number[];\n /** Distance function (default: \"cosine\") */\n distance?: \"cosine\" | \"l2\" | \"inner_product\";\n /** Only return results within this distance threshold */\n threshold?: number;\n}\n\n// ── List pagination bounds ────────────────────────────────────────────────\n//\n// Client-driven list reads (REST `GET /<collection>` and the WebSocket\n// `subscribe_collection` message) accept a client-supplied `limit`. Without\n// bounds, an ABSENT limit streams the entire table into memory — a trivial\n// OOM/DoS — and `limit=100000000` (or `limit=0`, historically an unlimited\n// bypass) is honoured verbatim. `resolveClientListLimit` is the single shared\n// enforcement point so every untrusted ingress behaves identically. Trusted\n// server-side callers build fetch options directly and are intentionally NOT\n// bounded here (migrations, admin exports, and CDC refetches may need the full\n// set).\n//\n// A limit the platform will not serve is REFUSED, not quietly shrunk. Clamping\n// answers a request for 100 000 rows with 1 000 of them, and a short page is\n// indistinguishable from \"that is all the data there is\" — which is how a CSV\n// export shipped 50 rows of a 100 000-row collection under a filename that read\n// like the whole thing. `meta.total`/`meta.hasMore` make truncation *detectable*\n// on the REST list response, but only for a caller who thinks to compare what it\n// asked for against what it got, and the WebSocket `collection_update` frame\n// carries neither — so signalling cannot be the answer on every surface and\n// rejecting is. An ABSENT limit still defaults: naming no window is not the same\n// as asking for one that cannot be served.\n\n/** Rows returned for a plain / text-search list read when the client sends no `limit`. */\nexport const DEFAULT_LIST_LIMIT = 50;\n/** Rows returned for a vector-search list read when the client sends no `limit`. */\nexport const DEFAULT_VECTOR_LIST_LIMIT = 10;\n/** Largest `limit` a client may ask for on any surface. Above it, the read is refused. */\nexport const MAX_LIST_LIMIT = 1000;\n\n/** Overridable bounds for {@link resolveClientListLimit}. */\nexport interface ListLimitBounds {\n /** Default page size for plain and text-search reads. */\n defaultLimit?: number;\n /** Default page size for vector-search reads. */\n vectorDefaultLimit?: number;\n /** Largest limit a client may ask for. A larger one is rejected, not clamped. */\n maxLimit?: number;\n}\n\n/**\n * Thrown by {@link resolveClientListLimit} for a `limit` the platform will not\n * serve. Carries an HTTP status so an ingress that speaks HTTP can forward it\n * verbatim, and `maxLimit` so one can be built without re-deriving the ceiling.\n *\n * @group Errors\n */\nexport class ListLimitError extends RebaseApiError {\n /** The ceiling that was exceeded — what the caller should page by instead. */\n readonly maxLimit: number;\n\n constructor(message: string, maxLimit: number) {\n super(message, { status: 400, code: \"INVALID_LIMIT\" });\n this.name = \"ListLimitError\";\n this.maxLimit = maxLimit;\n // Keeps `instanceof` working when this is compiled down for an older\n // target, where extending a builtin otherwise loses the prototype.\n Object.setPrototypeOf(this, ListLimitError.prototype);\n }\n}\n\n/**\n * Resolve a client-supplied list `limit` into a safe, always-defined value.\n *\n * - An absent / blank limit falls back to the mode default:\n * `vectorDefaultLimit` for a vector search, otherwise `defaultLimit`.\n * - A limit that is present must be an integer in `[1, maxLimit]`. Anything\n * else — `0`, a negative, `1.5`, `abc`, `100000000` — throws\n * {@link ListLimitError} rather than being coerced into range, because every\n * coercion answers a question the caller did not ask with a page it cannot\n * tell apart from the whole collection.\n *\n * The return is never `undefined` — no ingress that routes its client limit\n * through this can produce an unbounded read.\n *\n * @throws {ListLimitError} when a present `limit` is not an integer in range.\n */\nexport function resolveClientListLimit(\n rawLimit: number | string | null | undefined,\n opts: ListLimitBounds & { vectorSearch?: boolean } = {}\n): number {\n const maxLimit = opts.maxLimit ?? MAX_LIST_LIMIT;\n if (rawLimit != null && String(rawLimit).trim() !== \"\") {\n // `Number`, not `parseInt`: `parseInt(\"50rows\")` is 50, which silently\n // reads a typo as a window the caller never wrote.\n const parsed = typeof rawLimit === \"number\" ? rawLimit : Number(String(rawLimit).trim());\n if (!Number.isInteger(parsed) || parsed < 1) {\n throw new ListLimitError(\n `Invalid \\`limit\\`: ${String(rawLimit)}. Expected a whole number between 1 and ${maxLimit}.`,\n maxLimit\n );\n }\n if (parsed > maxLimit) {\n throw new ListLimitError(\n `\\`limit\\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows ` +\n \"per read and page through the rest with `offset` — answering with a smaller page would be \" +\n \"indistinguishable from there being no more rows.\",\n maxLimit\n );\n }\n return parsed;\n }\n return opts.vectorSearch\n ? (opts.vectorDefaultLimit ?? DEFAULT_VECTOR_LIST_LIMIT)\n : (opts.defaultLimit ?? DEFAULT_LIST_LIMIT);\n}\n\n/**\n * @internal\n */\nexport interface FetchCollectionProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n filter?: FilterValues<Extract<keyof M, string>>,\n /**\n * An `or(...)`/`and(...)` group, applied alongside `filter`.\n *\n * The REST layer parsed `?or=` into this and then had nowhere to put it, so\n * the group was dropped and the read ran unfiltered — returning every row\n * the caller's policies allowed rather than the ones they asked for.\n */\n logical?: LogicalCondition;\n limit?: number;\n offset?: number;\n startAfter?: unknown;\n /**\n * The sort, in either of two spellings:\n *\n * - a field name, whose direction is the separate `order` below — the\n * original single-column contract, which every existing driver reads;\n * - a list of `[field, direction]` tuples applied in order of significance,\n * which carries a multi-column sort and ignores `order` entirely.\n *\n * `normalizeDriverOrderBy` in `@rebasepro/common` collapses the pair to the\n * list form. A driver that has not been taught the list form should read it\n * through that helper rather than assume a string: handed an array, `String()`\n * would produce a field name like `roles,asc` and the sort would 400 (or,\n * with unknown-field warnings on, silently vanish).\n */\n orderBy?: string | OrderByTuple[];\n searchString?: string;\n /** Ask each row which declared search field matched — populates `_matches`. */\n searchExplain?: boolean;\n /** Direction for the string form of `orderBy`. Ignored when `orderBy` is a list. */\n order?: \"desc\" | \"asc\";\n /** Vector similarity search configuration */\n vectorSearch?: VectorSearchParams;\n /**\n * What to do about rows a soft delete has stamped.\n *\n * Unset (the default) hides them, which is the whole point of the feature:\n * a deleted row is deleted as far as the application is concerned. `true`\n * includes them alongside the live ones — a trash view, an admin audit.\n * `\"only\"` returns nothing but them, which is the trash view proper and is\n * not expressible as a filter, because the field is not part of the\n * caller's vocabulary.\n *\n * Ignored by tables that declare no `softDelete`: there is no stamp to look at, and\n * silently returning nothing for `\"only\"` on such a collection would be a\n * worse answer than ignoring it.\n */\n withDeleted?: boolean | \"only\";\n /**\n * Relations to load — see {@link IncludeSpec}.\n *\n * Absent means *no* relations, the same as it does over REST. It used to be\n * absent from this contract entirely, and the driver's own fetch then loaded\n * every relation of every row unconditionally: `find()` returned a row with\n * a foreign key and `listen()` returned the same row with a nested object\n * where that key was, for the same query.\n */\n include?: IncludeSpec;\n /** Columns to read, as a projection. See `FindParams.fields`. */\n fields?: string[];\n /** `SELECT DISTINCT` over the projection. See `FindParams.distinct`. */\n distinct?: boolean;\n}\n\n/**\n * @internal\n */\nexport type ListenCollectionProps<M extends Record<string, unknown> = Record<string, unknown>> =\n FetchCollectionProps<M> &\n {\n /**\n * Page number (1-indexed), as `FindParams.page`.\n *\n * A subscription could name a `limit` and an `offset` but not a `page`,\n * so a live list on page three had to compute the offset itself — and\n * the two spellings then disagreed about what a page was.\n */\n page?: number;\n /**\n * Subscribe to the count alone: the server reads no rows, and each\n * frame carries `rows: []` and `meta.total`. A server that predates it\n * ignores the key and answers with the rows asked for (so ask for\n * `limit: 1`) and the same `meta`. See `listenCount`.\n */\n countOnly?: boolean;\n onUpdate: (rows: Record<string, unknown>[], meta?: CollectionUpdateMeta) => void;\n onError?: (error: Error) => void;\n };\n\n/**\n * @internal\n */\nexport interface SaveProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n values: Partial<M>;\n id?: string | number; // can be empty for new entities\n previousValues?: Partial<M>;\n status: EntityStatus;\n /**\n * Write the row with INSERT ... ON CONFLICT DO UPDATE on the primary key\n * instead of choosing between insert and update up front.\n *\n * One statement, so it does not lose the race a read-then-write can, and it\n * succeeds whether or not the row is already there — what a re-runnable\n * import needs. Requires every primary key column to be present; without\n * them there is no conflict target and the row is inserted normally.\n */\n upsert?: boolean;\n\n /**\n * The columns the upsert matches a conflict on, instead of the primary key.\n *\n * The key is the only target that always exists, and it is the wrong one\n * for the write an upsert is usually reached for: \"this user, identified by\n * their email, exists with these values\". Keyed on the primary key that is\n * an insert, because the caller does not know the serial id — so the row is\n * duplicated on every run.\n *\n * Only column sets carrying a uniqueness guarantee are legal here; Postgres\n * refuses anything else with 42P10, from inside a transaction. The REST\n * layer checks the target against the collection's declarations first (see\n * `resolveConflictTarget`), so the answer is a 400 naming the available\n * targets rather than a 500 naming a constraint the caller never wrote.\n */\n onConflict?: readonly string[];\n\n /**\n * A check on the stored row an update addresses, run by the driver inside\n * the write's own transaction, before any hook runs and before anything is\n * written. See {@link RowPrecondition}. Honoured only by a driver that\n * declares {@link DataDriver.checksRowPreconditions}; ignored on a create.\n */\n precondition?: RowPrecondition;\n}\n\n/**\n * A check a caller makes on the row a write addresses, inside that write.\n *\n * The REST routes used to read the row in a transaction of their own before\n * writing it, to answer a missing row with their 404 and to compare\n * `If-Match`. Two transactions: the read loaded every declared relation of the\n * row, and two writes carrying the same tag could both pass the comparison,\n * because neither saw the other's write before making its own.\n *\n * @internal\n */\nexport interface RowPrecondition {\n /**\n * Lock the row before it is read, so no other write to it can land between\n * this check and this write. A conditional write (`If-Match`) sets it; a\n * plain existence check does not need it and does not pay for it.\n */\n lock?: boolean;\n /**\n * Judge the row as this caller reads it at the address written (their\n * policies, their `beforeQuery`, the trash hidden unless the write is a\n * restore or a purge) — `undefined` when there is none. Throw to refuse the\n * write; nothing has been written when this runs.\n */\n check(stored: Record<string, unknown> | undefined): void | Promise<void>;\n}\n\n/**\n * @internal\n */\nexport interface SaveManyProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n /**\n * The rows to write. A row carrying its primary key updates (or, with\n * `upsert`, inserts-or-updates) that row; one without inserts.\n */\n rows: Partial<M>[];\n /** Apply every row as INSERT ... ON CONFLICT DO UPDATE. See {@link SaveProps.upsert}. */\n upsert?: boolean;\n /** The conflict target for those upserts. See {@link SaveProps.onConflict}. */\n onConflict?: readonly string[];\n /**\n * With `upsert`: the stored row the conflict-update may write, as a filter\n * on its columns — `ON CONFLICT … DO UPDATE … WHERE`. A stored row it does\n * not match is left as it is and left out of the answer. What a \"keep the\n * best score\" or \"only if newer\" write needs, in one statement.\n */\n conflictWhere?: FilterValues<string>;\n /**\n * With `upsert`: leave a stored row on the conflict target untouched —\n * `ON CONFLICT DO NOTHING` — and leave it out of the answer. The\n * insert-or-skip an idempotent claim needs.\n */\n ignoreDuplicates?: boolean;\n}\n\n/**\n * The rows a filtered write ({@link DataDriver.updateWhere},\n * {@link DataDriver.deleteWhere}) addresses: the same `filter` and `logical`\n * a read takes, AND-ed. At least one condition — a filtered write with none\n * would address every row, and is refused (`FILTER_REQUIRED`).\n *\n * @internal\n */\nexport interface WriteFilterProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n filter?: FilterValues<string>;\n logical?: LogicalCondition;\n}\n\n/**\n * @internal\n */\nexport interface UpdateWhereProps<M extends Record<string, unknown> = Record<string, unknown>> extends WriteFilterProps<M> {\n /** What to set on every row the filter matches; field operations (`$inc`, …) included. */\n values: Partial<M>;\n}\n\n/**\n * @internal\n */\nexport interface DeleteWhereProps<M extends Record<string, unknown> = Record<string, unknown>> extends WriteFilterProps<M> {\n /** See {@link DeleteProps.hard}. */\n hard?: boolean;\n}\n\n/**\n * @internal\n */\nexport interface UpdateManyProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n /**\n * The rows to update, each named by its address.\n *\n * Distinct from {@link SaveManyProps.rows}, which carries keys *inside* the\n * values and is insert-shaped — `saveMany` passes `status: \"new\"` and no\n * `id`, so it cannot express \"update exactly this row\". This can, and it is\n * why bulk update is a separate driver method rather than a flag on that one.\n */\n updates: { id: string | number; values: Partial<M> }[];\n}\n\n/**\n * @internal\n */\nexport interface DeleteProps<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * The row's address, and nothing about its contents.\n *\n * The driver reads the row itself, under the caller's own scope, and that\n * read is what `beforeDelete` and `afterDelete` receive and what history\n * records. This used to carry `values`, and the driver took them as the\n * row — so over the WebSocket, which forwarded the client's frame, the\n * caller wrote the audit record of their own deletion and could get past a\n * `beforeDelete` that refused on a column by sending `values: {}`.\n */\n row: { id: string | number; path: string };\n /**\n * Issue a real `DELETE` on a table that declares `softDelete`.\n *\n * The row and every cascade behind it go. It needs the same permission an\n * ordinary delete does and nothing more: it is the same verb, and a second\n * access-control surface for one operation is a second thing to get wrong.\n * No effect on a collection without soft delete, where every delete is\n * already this one.\n */\n hard?: boolean;\n\n /**\n * A check on the stored row, inside the delete's own transaction, before\n * any hook runs. See {@link RowPrecondition}. Honoured only by a driver\n * that declares {@link DataDriver.checksRowPreconditions}.\n */\n precondition?: RowPrecondition;\n}\n\n/**\n * @internal\n */\nexport interface DeleteManyProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n ids: (string | number)[];\n /** See {@link DeleteProps.hard}. */\n hard?: boolean;\n}\n\n/**\n * Addressing ONE link of a many-to-many, to set the columns it carries.\n *\n * `path` is the relation on a row — `posts/1/tags` — and `targetId` the row on\n * the far side, so the pair names exactly one junction row. Not a `SaveProps`,\n * because a save at that address means \"write the target row\", and a link's own\n * columns are not the target's: two posts sharing a tag see one tag and two\n * different links.\n *\n * @internal\n */\nexport interface UpdateRelationPivotProps {\n /** The nested relation path, e.g. `posts/1/tags`. */\n path: string;\n /** The far side's key. */\n targetId: string | number;\n /** The junction columns to set, keyed by the property key `through.properties` declares. */\n pivot: Record<string, unknown>;\n}\n\n/**\n * One operation of a {@link DataDriver.batchWrite}.\n *\n * `path` rather than a slug, because a batch entry addresses rows exactly as\n * the single-row props do and a nested path is a legal address there.\n *\n * @internal\n */\nexport interface BatchWriteOperation<M extends Record<string, unknown> = Record<string, unknown>> {\n op: \"create\" | \"update\" | \"upsert\" | \"delete\";\n path: string;\n /** Required for `update` and `delete`. May be a `$ref` marker; see `batchWrite`. */\n id?: unknown;\n values?: Partial<M>;\n /** See {@link SaveProps.onConflict}. `upsert` only. */\n onConflict?: readonly string[];\n /** Names this operation's result, for a later `$ref`. */\n ref?: string;\n}\n\n/**\n * @internal\n */\nexport interface BatchWriteProps<M extends Record<string, unknown> = Record<string, unknown>> {\n operations: BatchWriteOperation<M>[];\n}\n\nexport type FilterCombinationValidProps = {\n path: string;\n databaseId?: string;\n filterValues: FilterValues<string>;\n sortBy?: [string, \"asc\" | \"desc\"];\n};\n\n/** Options of {@link DataDriver.sql}. */\nexport interface CallerSqlOptions {\n /** The statement's values, referenced as `$1`, `$2`, … in the query text. */\n params?: unknown[];\n /**\n * Run in a read-write transaction. Off by default: the statement runs\n * read-only, and an `INSERT`, `UPDATE` or `DELETE` fails with `25006`.\n */\n write?: boolean;\n}\n\n/**\n * The integration SPI for plugging a data backend into Rebase.\n *\n * Implement this interface to connect a custom backend (or use a built-in\n * driver such as the Firestore one) and register it on\n * `<Rebase dataSources>`. The SDK reads a driver through `buildSdkData`\n * (`@rebasepro/common`), and tables are routed to it by their `dataSource` key.\n *\n * For *consuming* data in application code, use `client.data` /\n * `context.data` instead — this interface is only for providing it.\n *\n * @group Datasource\n */\nexport interface DataDriver {\n\n /**\n * Key that identifies this driver\n */\n key?: string;\n\n /**\n * If the driver has been initialised\n */\n initialised?: boolean;\n\n /**\n * Fetch data from a collection\n * @param props\n * @return Promise of flat rows\n */\n fetchCollection<M extends Record<string, unknown> = Record<string, unknown>>(props: FetchCollectionProps<M>): Promise<Record<string, unknown>[]>;\n\n /**\n * Listen to a collection in a given path. If you don't implement this method\n * `fetchCollection` will be used instead, with no real time updates.\n * @param props\n * @return Function to cancel subscription\n */\n listenCollection?<M extends Record<string, unknown> = Record<string, unknown>>(props: ListenCollectionProps<M>): () => void;\n\n /**\n * Retrieve a single row given a path and a collection\n * @param props\n */\n fetchOne<M extends Record<string, unknown> = Record<string, unknown>>(props: FetchOneProps<M>): Promise<Record<string, unknown> | undefined>;\n\n /**\n * Get realtime updates on one row.\n * @param props\n * @return Function to cancel subscription\n */\n listenOne?<M extends Record<string, unknown> = Record<string, unknown>>(props: ListenOneProps<M>): () => void;\n\n /**\n * Let `<Rebase>` hear about changes this driver learns of that it did not\n * write itself — rows another process wrote, or ones an agent changed\n * through the driver's own backend.\n *\n * `<Rebase>` calls it once per driver it holds, while it is mounted, and\n * calls the function it returns when it unmounts. The driver calls\n * `onExternalChange(path)` with the path of each collection that changed\n * (the path the driver stores it under, as {@link FetchCollectionProps.path}\n * names it, or the collection's slug), and every view of that collection\n * whose data source cannot subscribe reads it again: the row hooks\n * (`useRows`, `useRow`, `useRowCount`, `useAggregate`) and the admin's\n * collection views. A view that subscribes through\n * {@link listenCollection} is left alone, so a driver that already pushes\n * the change there gains nothing from announcing it here.\n *\n * Writes made through `<Rebase>` itself need no announcement: they are\n * signalled as they succeed.\n *\n * Optional: a driver that learns of no outside changes leaves it out.\n *\n * @param onExternalChange call with a changed collection's path\n * @return stop calling `onExternalChange`\n */\n subscribeToExternalChanges?(onExternalChange: (path: string) => void): () => void;\n\n /**\n * Save a row to the specified path\n * @param props\n */\n save<M extends Record<string, unknown> = Record<string, unknown>>(props: SaveProps<M>): Promise<Record<string, unknown>>;\n\n /**\n * Save many rows as one unit of work.\n *\n * Every row runs the same pipeline as {@link save} — callbacks, relations\n * and row-level security all still apply — but they share a single\n * transaction, so the batch either lands whole or not at all. That, and the\n * single round trip, is what makes importing tens of thousands of rows\n * viable without dropping to raw SQL.\n *\n * Optional: drivers that cannot do this leave it undefined and callers fall\n * back to `save` per row.\n */\n saveMany?<M extends Record<string, unknown> = Record<string, unknown>>(props: SaveManyProps<M>): Promise<Record<string, unknown>[]>;\n\n /**\n * Update many rows in one transaction, each addressed by id.\n *\n * Optional for the same reason `saveMany` is: a driver that cannot make the\n * batch atomic should not pretend to. The REST layer reports\n * `BULK_UNSUPPORTED` rather than silently falling back to a loop of single\n * writes, which would be neither atomic nor one round trip — the two things\n * a caller reaches for a batch to get.\n */\n updateMany?<M extends Record<string, unknown> = Record<string, unknown>>(props: UpdateManyProps<M>): Promise<Record<string, unknown>[]>;\n\n /**\n * Update every row a filter matches, as one statement where nothing needs\n * the rows one by one (no hook, no history, no tenancy), and through the\n * per-row pipeline in one transaction where something does. Resolves to\n * the rows updated, which may be none: a filter matching nothing is not an\n * error, and is how a compare-and-set reports that it lost.\n *\n * Optional: a driver that cannot do it atomically leaves it undefined.\n */\n updateWhere?<M extends Record<string, unknown> = Record<string, unknown>>(props: UpdateWhereProps<M>): Promise<Record<string, unknown>[]>;\n\n /**\n * Delete every row a filter matches, under the same rules as\n * {@link updateWhere}. Resolves to how many rows went; none is not an\n * error.\n */\n deleteWhere?<M extends Record<string, unknown> = Record<string, unknown>>(props: DeleteWhereProps<M>): Promise<number>;\n\n /**\n * Recompute the rows of a collection that serves a materialized view —\n * see `SDKTableClient.refresh`. Optional: only a driver with views\n * has one.\n */\n refreshView?(path: string, options?: { concurrently?: boolean }): Promise<void>;\n\n /**\n * Delete the row `props.row` addresses.\n *\n * **Resolving means the row is gone because this call removed it.** A\n * delete that matched nothing must reject with a not-found error\n * (`ApiError.notFound`, `statusCode: 404`) rather than resolving quietly.\n *\n * The rule is here rather than in each driver because the two\n * implementations answered differently and each had a test pinning its own\n * habit: one threw, the other logged a warning and resolved. Three things\n * decide it in favour of rejecting.\n *\n * The REST layer already says 404 — `DELETE /api/data/<c>/<id>` reads the\n * row before removing it — so a quiet resolve made the driver API disagree\n * with the HTTP API about the same operation, and only in-process\n * `rebase.data` callers could see the difference.\n *\n * A caller cannot tell \"deleted\" from \"there was nothing there\" without it,\n * and those are different facts: one means the caller's model of the data\n * was right, the other that it was stale. Silence hands back the wrong one\n * and the caller carries on.\n *\n * And on a driver with row-level security, \"matched nothing\" is *also* how\n * a policy refusal arrives — Postgres filters `DELETE` through `USING`\n * rather than raising. A driver that resolves on zero rows therefore\n * reports a refused delete as a completed one, which is the defect\n * `explainZeroRowWrite` exists to prevent (see `write-denial.ts`).\n *\n * Conformance for both server drivers lives in\n * `packages/server/test/contract/delete-contract.ts`, run by each driver's\n * own suite against its own database. `packages/firebase`'s Firestore\n * driver does not honour it: `deleteDoc` resolves for a missing document\n * and reporting otherwise would cost a read on every delete. It runs in the\n * browser against Firestore's own semantics rather than behind\n * `rebase.data`, and that exception is stated here rather than left to be\n * discovered.\n */\n delete<M extends Record<string, unknown> = Record<string, unknown>>(props: DeleteProps<M>): Promise<void>;\n\n /**\n * Delete all entities from a collection.\n * @param path Collection path\n */\n deleteAll?(path: string): Promise<void>;\n\n /**\n * Set the columns ONE many-to-many link carries, leaving the membership\n * alone — `manyToMany`'s `through.properties`.\n *\n * `PATCH /api/data/<c>/<id>/<relation>/<targetId>` with a `_pivot` body\n * reaches this. The membership array cannot express it: sending one element\n * would unlink everything else, and re-sending the whole set to change one\n * value reintroduces the lost update the membership diff exists to avoid.\n *\n * Optional. A driver whose junctions carry nothing but the two keys leaves\n * it undefined, and the REST layer answers `RELATION_PIVOT_UNSUPPORTED`\n * rather than pretending the write landed.\n */\n updateRelationPivot?(props: UpdateRelationPivotProps): Promise<void>;\n\n /**\n * Delete many rows in one transaction, addressed by id.\n *\n * Ids; a filter is {@link deleteWhere}. Optional, as `saveMany` is.\n */\n deleteMany?<M extends Record<string, unknown> = Record<string, unknown>>(props: DeleteManyProps<M>): Promise<void>;\n\n /**\n * Apply a mixed list of writes across collections as one unit of work.\n *\n * The capability `saveMany` and `deleteMany` cannot express between them: a\n * batch that touches two tables. Sent as two requests those can\n * half-succeed, and the recovery — read back, work out which half landed,\n * undo it — is code nobody writes.\n *\n * Every operation runs the pipeline its single-row equivalent runs, in\n * order, in one transaction, under the caller's own role. Operations may\n * carry `{ \"$ref\": \"<name>.<field>\" }` markers in `values` or `id`, which\n * the driver resolves against the rows earlier operations wrote — the\n * driver, because inside the transaction is the only place those rows\n * exist. `@rebasepro/server` exports `resolveBatchRefs` so the resolution\n * is one implementation rather than one per driver.\n *\n * Resolves to one entry per operation, aligned to the input: the written\n * row for a create, update or upsert, and `null` for a delete.\n *\n * Optional for the same reason `saveMany` is: a driver that cannot make it\n * atomic must not pretend to. The REST layer answers `BATCH_UNSUPPORTED`\n * rather than falling back to a loop, which would be the non-atomic\n * sequence the caller reached for this to avoid.\n */\n batchWrite?<M extends Record<string, unknown> = Record<string, unknown>>(\n props: BatchWriteProps<M>\n ): Promise<(Record<string, unknown> | null)[]>;\n\n /**\n * Check if the given property is unique in the given collection\n * @param path Collection path\n * @param name of the property\n * @param value\n * @param id\n * @return `true` if there are no other fields besides the given entity\n */\n checkUniqueField(\n path: string,\n name: string,\n value: unknown,\n id?: string | number\n ): Promise<boolean>;\n\n /**\n * Count the number of entities in a collection\n */\n count?<M extends Record<string, unknown> = Record<string, unknown>>(props: FetchCollectionProps<M>): Promise<number>;\n\n /**\n * Run several reads as one: `work` is handed a driver whose reads all go\n * through a single read-only transaction that reads one snapshot, under\n * this driver's identity and row-level security, and its result is\n * returned.\n *\n * A list page is a read and a count, and each was a transaction of its\n * own — the second checkout, `BEGIN`, identity setup and `COMMIT` cost as\n * many round trips as the count itself. On one snapshot the two also\n * agree: `meta.total` describes the rows the page was taken from, and an\n * `ETag` the row the body was rendered from.\n *\n * Optional: a driver without it is called directly, read by read.\n */\n readTogether?<T>(work: (driver: DataDriver) => Promise<T>): Promise<T>;\n\n /**\n * Run one SQL statement as this driver's identity: in the caller's own\n * transaction, under the same row-level security as every read and write\n * on this driver, so the tables' policies decide which rows it sees and\n * changes. Read-only unless `write: true`.\n *\n * The query text must be the application's own. Every value — above all\n * anything a user sent — goes in `params` as `$1`, `$2`, …: identity rides\n * in session settings, and a statement able to change them is refused\n * (`SQL_NOT_ALLOWED`), as is more than one statement.\n *\n * Policies are what it shares with the SDK, and all it shares. Per-field\n * `access` rules, `afterRead`/`beforeQuery` hooks, validation, save hooks\n * and history are application code the SDK runs and this does not.\n *\n * Optional: an engine without row-level security has none. On the\n * server's own (unscoped) driver it is absent too — that one's raw SQL is\n * `admin.executeSql`, which runs as the owner.\n */\n sql?(query: string, options?: CallerSqlOptions): Promise<Record<string, unknown>[]>;\n\n /**\n * Every row a collection stores, as stored, a page at a time: soft-deleted\n * rows included, and past every read hook — no `beforeQuery`, no\n * `afterRead`, no per-field read rules.\n *\n * For whole-store sweeps run by the server itself, never for a read served\n * to anyone. `rebase storage orphans` reads it to find the files no row\n * names: read through `fetchCollection` instead, a `beforeQuery` scoping\n * rows to `context.user` (there is none in a sweep) or an `afterRead` that\n * rewrites a file field hides references, and the files they name are\n * reported as unused and deleted.\n *\n * Optional. A sweep reads a collection without read hooks through\n * `fetchCollection`, and refuses one with read hooks whose driver lacks\n * this, rather than trust what the hooks let through.\n */\n scanStoredRows?(props: {\n path: string;\n /** Rows per page. */\n pageSize?: number;\n }): AsyncIterable<Record<string, unknown>[]>;\n\n /**\n * Rows of a table this caller did not read through the driver, served as a\n * read of that table serves them: the columns the caller may not read\n * (`.private()`, `.access({ read })`, a withheld relation and its foreign\n * key) taken out, then the table's `afterRead` chain — global, the\n * table's, its columns' `.transform({ afterRead })` — run once, with this\n * driver's caller as `context`.\n *\n * For stored copies of rows served back to a caller: a history entry's\n * snapshots are the row as it was written, before any hook, and without\n * this they would hand a caller what every other read of the table masks.\n * The rows are the table's REST shape (column keys); a key the table has\n * no column for is the caller's to remove first — this takes out what the\n * table restricts, and cannot know what a dropped column held.\n *\n * A hook that throws fails the call: nothing is served unmasked.\n *\n * Optional. A server door that serves stored rows refuses to serve them\n * through a driver without it, rather than serve them unmasked.\n */\n serveStoredRows?(path: string, rows: Record<string, unknown>[]): Promise<Record<string, unknown>[]>;\n\n /**\n * Check if the given filter combination is valid\n * @param props\n */\n isFilterCombinationValid?(props: FilterCombinationValidProps): boolean;\n\n /**\n * Get the object to generate the current time in the driver\n */\n currentTime?: () => unknown;\n\n delegateToCMSModel?: (data: unknown) => unknown;\n\n cmsToDelegateModel?: (data: unknown) => unknown;\n\n /**\n * Flag to indicate if the driver has requested the initialization of the text search index\n */\n needsInitTextSearch?: boolean;\n\n // ── REST fetch capabilities ─────────────────────────────────────────\n\n /**\n * Optional REST-optimised fetch service. When present, the REST API\n * generator uses these methods instead of the generic `fetchOne` /\n * `fetchCollection` pipeline, enabling include-aware eager-loading.\n */\n restFetchService?: RestFetchService;\n\n /**\n * This driver reads the row an update or a delete addresses inside that\n * write's own transaction, and runs {@link SaveProps.precondition} /\n * {@link DeleteProps.precondition} on it there. A caller may then leave its\n * own read of the row out. A driver without it ignores the precondition,\n * so a caller must read the row itself.\n */\n readonly checksRowPreconditions?: boolean;\n\n // ── Admin capabilities ─────────────────────────────────────────────\n //\n // Admin operations are now modelled as capability-specific interfaces\n // (SQLAdmin, SchemaAdmin, BranchAdmin) in `@rebasepro/types/backend`.\n //\n // Drivers that support admin features should expose them here.\n // Consumers should use the `isSQLAdmin()`, `isSchemaAdmin()` etc.\n // type guards to safely narrow the type before calling methods.\n\n /**\n * Return the admin capabilities of this driver.\n * @see SQLAdmin\n * @see SchemaAdmin\n */\n admin?: import(\"../types/backend\").DatabaseAdmin;\n\n}\n\n/**\n * One aggregate as a driver is handed it: an `AggregateSelect` with its\n * derived `alias` (the key it comes back under).\n */\nexport interface DriverAggregate {\n fn: \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\" | \"countDistinct\" | \"mode\" | \"percentile\" | \"distinct\" | \"fingerprint\";\n /** Absent for `count()` and `fingerprint()`. A column, or a JSON path (`props->>players`). */\n field?: string;\n /** `percentile`'s fraction, 0–1. */\n p?: number;\n /** Only the rows matching this count towards the aggregate: SQL's `FILTER (WHERE …)`. */\n filter?: FilterValues<string>;\n alias: string;\n}\n\n/** A transformed group (`AggregateGroup`) as a driver is handed it, with the key it comes back under. */\nexport interface DriverAggregateGroup {\n field: string;\n transform: AggregateGroupTransform;\n /** `year`/`month`/`day`: the IANA time zone the date is read in. UTC when absent. */\n timeZone?: string;\n /** `<transform>_<field>`. */\n key: string;\n}\n\n/**\n * REST-optimised fetch service exposed by drivers that support\n * eager-loading of relations via `include`.\n *\n * The methods return flattened rows — exactly the table's columns, under their\n * own names and with the types the database returned — and included relations\n * inlined as plain nested rows. This is the shape served to app developers\n * through the REST API / SDK client.\n *\n * No synthesized `id`: identity is a primary key, which may be named anything\n * and span several columns, so an address is derived by whoever needs one (see\n * `buildCompositeId`) rather than written into the row on top of the data.\n *\n * @group DataDriver\n */\nexport interface RestFetchService {\n /**\n * Fetch a collection of flattened entities with optional relation includes.\n */\n fetchCollectionForRest(\n collectionPath: string,\n options?: {\n filter?: FilterValues<string>;\n /** An `or(...)`/`and(...)` group, applied alongside `filter`. */\n logical?: LogicalCondition;\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?: Record<string, unknown>;\n searchString?: string;\n /** Ask each row which declared search fields matched — populates `_matches`. */\n searchExplain?: boolean;\n databaseId?: string;\n vectorSearch?: VectorSearchParams;\n /** See {@link FetchCollectionProps.withDeleted}. */\n withDeleted?: boolean | \"only\";\n /**\n * Columns to read. A projection pushed into the SELECT, not a trim\n * of the response — `excludeFromApi` still applies on top, and the\n * primary key is always read whether or not it is named.\n */\n fields?: string[];\n /** `SELECT DISTINCT` over the projection. See `FindParams.distinct`. */\n distinct?: boolean;\n },\n include?: IncludeSpec\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * The opaque cursor that continues a listing after `row`.\n *\n * On the driver rather than the route because deriving it needs the\n * collection's primary key — which may be named anything and span several\n * columns — and that is the driver's knowledge. The route holds the last\n * row and the sort keys and asks for the string.\n *\n * `undefined` where no cursor can describe the page: an ordering with no\n * stored value to compare against (relevance), or a row missing a value for\n * one of the sort keys. The listing then reports no `nextCursor` and the\n * caller pages by offset, which is what it did before cursors existed.\n *\n * Optional: a driver that cannot seek simply never issues one, and\n * `meta.nextCursor` is absent for every read it serves.\n */\n cursorFor?(\n collectionPath: string,\n row: Record<string, unknown>,\n orderBy?: OrderByTuple[]\n ): string | undefined;\n\n /**\n * The aggregates of `AggregateSelect` (`count`, `sum`, `avg`, `min`,\n * `max`, `countDistinct`, `mode`, `percentile`, `distinct`, `fingerprint`)\n * over the rows a filter selects, optionally grouped by columns or by\n * transformed columns (`AggregateGroup`).\n *\n * Optional, and the REST route answers 501 where a driver does not\n * implement it — an aggregate is not a thing to approximate, and an empty\n * result set would read as \"nothing matched\".\n *\n * Any implementation **must apply the same row-level authorization as a\n * read**. An aggregate is an efficient way to learn about rows you cannot\n * select, and `count(*)` over a table whose policies would return nothing\n * has to be zero.\n *\n * Nor may it read what `afterRead` hides. An aggregate does not pass\n * through the callbacks, so on a collection any `afterRead` applies to\n * (global, collection or property) only `count` with no field and no\n * `groupBy` is served; anything else is refused with a 400.\n */\n aggregate?(\n collectionPath: string,\n options: {\n aggregates: DriverAggregate[];\n groupBy?: (string | DriverAggregateGroup)[];\n filter?: FilterValues<string>;\n logical?: LogicalCondition;\n searchString?: string;\n /** Groups to return. Applies to a grouped aggregate; one without `groupBy` is one row. */\n limit?: number;\n /** Groups to skip, for paging past `limit`. Grouped aggregates only. */\n offset?: number;\n /**\n * Sort for the groups, by a `groupBy` field or an aggregate's alias\n * (`count`, `sum_total`). Whatever it leaves tied is ordered by the\n * group keys, so the order is total and a page boundary falls in\n * the same place every time. Grouped aggregates only.\n */\n orderBy?: OrderByTuple[];\n /** See {@link FetchCollectionProps.withDeleted}. */\n withDeleted?: boolean | \"only\";\n }\n ): Promise<Record<string, unknown>[]>;\n\n /**\n * Fetch a single flattened entity with optional relation includes.\n */\n fetchOneForRest(\n collectionPath: string,\n id: string | number,\n include?: IncludeSpec,\n databaseId?: string,\n options?: {\n /** See `FetchCollectionProps.fields`. */\n fields?: string[];\n /** See {@link FetchOneProps.withDeleted}. */\n withDeleted?: boolean | \"only\";\n }\n ): Promise<Record<string, unknown> | null>;\n}\n","/**\n * Path prefix that marks an object as **public**. Files stored under this\n * prefix are served without any auth token via a stable, permanent,\n * CDN-cacheable URL (see {@link StorageSource.getSignedUrl}). Shared by the\n * client SDK and the backend so both agree on which objects are public.\n *\n * @group Models\n */\nexport const PUBLIC_STORAGE_PREFIX = \"public/\";\n\n/**\n * True when a storage **key** is public: it lies under\n * {@link PUBLIC_STORAGE_PREFIX}.\n *\n * The key is read exactly as it is — the canonical key within its bucket, the\n * one the server stores, serves, and hands a `storageAuthorize` hook as\n * `key` — and nothing is parsed out of it. That is the difference from\n * {@link isPublicStoragePath}, which reads a client-side *path* and so strips\n * a `scheme://` and a leading `default/` bucket segment first. On a key both are\n * wrong: `default/public/x` is a key in a folder called `default`, and a\n * request path `notes://public/x` names the key `notes:/public/x`. Neither is\n * public, and the server decides on this function so that it never says they\n * are.\n *\n * @group Models\n */\nexport function isPublicStorageKey(key: string | null | undefined): boolean {\n if (!key || !key.startsWith(PUBLIC_STORAGE_PREFIX)) return false;\n // A canonical key never carries a `..` segment; one that does is not a key\n // the server would serve, and is never public.\n return !key.split(/[\\\\/]/).includes(\"..\");\n}\n\n/**\n * True when a storage key or client-side path points at a public object\n * (lives under {@link PUBLIC_STORAGE_PREFIX}).\n *\n * For a path as a client holds it: a `scheme://` prefix and a single leading\n * `default/` bucket segment are stripped first. The server and a\n * `storageAuthorize` hook, which hold the canonical key, use\n * {@link isPublicStorageKey}.\n *\n * @group Models\n */\nexport function isPublicStoragePath(path: string | null | undefined): boolean {\n if (!path) return false;\n let p = path;\n const scheme = p.indexOf(\"://\");\n if (scheme !== -1) p = p.substring(scheme + 3);\n p = p.replace(/^\\/+/, \"\");\n\n // Defense-in-depth: a path containing traversal segments is never public,\n // so an attacker can't reach a private object via `public/../secret`.\n if (p.split(\"/\").some((seg) => seg === \"..\")) return false;\n\n // Public iff the object **key** starts with the public prefix. A single\n // leading `default/` bucket segment is tolerated (the default bucket).\n // A substring match is deliberately NOT used — a private object under a\n // folder literally named `public` (e.g. `reports/public/q3.pdf`) must stay\n // private. Named buckets: pass the key (not `bucket/key`) so the prefix is\n // anchored; otherwise it falls back to a private, token-scoped URL (safe).\n return p.startsWith(PUBLIC_STORAGE_PREFIX) || p.startsWith(`default/${PUBLIC_STORAGE_PREFIX}`);\n}\n\n/**\n * The path the storage routes address an object by, from a key or from the\n * `storageUrl` an upload returned (`<scheme>://<bucket>/<key>`, which is what a\n * property with `includeBucketUrl: true` keeps in its column).\n *\n * The routes address a source's objects by key. On S3 and GCS the bucket in a\n * `storageUrl` is always the source's own — the server refuses any other — so\n * it is dropped: sent along, `s3://acme-media/products/a.png` reached the\n * server as the key `acme-media/products/a.png`, the preview found nothing and\n * a delete reported success while the object stayed. It worked on local disk\n * only, because `local://default/<key>` happens to carry the one bucket\n * segment the routes recognise — which is kept, as is any other local bucket.\n *\n * A bare key whose first folder is `default` is sent behind that bucket\n * segment. The routes read one leading `default/` (in any case) as the bucket,\n * so the key `default/photo.png` sent as it is names the root `photo.png`:\n * {@link defaultBucketPath} is the spelling that names the key itself.\n *\n * Shared by every storage source that talks to those routes, so they address\n * an object alike.\n *\n * @group Models\n */\nexport function storageObjectPath(keyOrUrl: string, bucket?: string): string {\n let filePath = keyOrUrl;\n // Whether `filePath` already carries a bucket segment, rather than being a key.\n let bucketQualified = false;\n const scheme = /^(local|s3|gs):\\/\\//.exec(filePath);\n if (scheme) {\n filePath = filePath.substring(scheme[0].length);\n if (scheme[1] !== \"local\") {\n const slash = filePath.indexOf(\"/\");\n if (slash > 0) filePath = filePath.substring(slash + 1);\n } else {\n bucketQualified = true;\n }\n }\n if (bucket && filePath) {\n // Already behind its bucket, or not: `defaults/x` is not in `default`.\n if (!filePath.startsWith(`${bucket}/`)) filePath = `${bucket}/${filePath}`;\n bucketQualified = true;\n }\n return bucketQualified ? filePath : defaultBucketPath(filePath);\n}\n\n/**\n * The request path of a key in the default bucket: the key itself, unless the\n * routes would read its first folder as the bucket — a first folder named\n * `default`, matched as the routes match it (case-insensitively, and only when\n * something follows it). Then the bucket segment goes in front, so exactly the\n * one segment the routes strip is the one added.\n */\nfunction defaultBucketPath(key: string): string {\n const segments = key.split(\"/\");\n return segments.length > 1 && segments[0].toLowerCase() === \"default\" ? `default/${key}` : key;\n}\n\n/**\n * @group Models\n */\nexport interface UploadFileProps {\n file: File,\n key: string,\n metadata?: Record<string, unknown>,\n bucket?: string,\n /**\n * Store this object as **public**: it is placed under\n * {@link PUBLIC_STORAGE_PREFIX} and served via a stable, token-less,\n * permanent URL (safe to persist in a database and cache on a CDN).\n * Defaults to `false` (private, short-lived signed URLs).\n */\n public?: boolean,\n /**\n * Which property this file is being uploaded *for* — the collection's slug\n * and the property path within it (`coverImage`, `meta.avatar`,\n * `gallery` for an array of files).\n *\n * The server holds the upload to that property's own `storage.maxSize`\n * and `storage.acceptedFiles`. It holds every upload to the limits of the\n * properties whose `storagePath` its key falls in anyway, named or not;\n * naming the property adds that property's rule, which matters for a\n * property whose `storagePath` is a function the server cannot read.\n *\n * Advisory in one direction only. The rules are resolved from the server's\n * own registry by slug, so naming a property can make an upload *stricter*;\n * it can never widen anything.\n */\n context?: UploadPropertyContext\n}\n\n/**\n * The property an upload is destined for.\n *\n * @group Models\n */\nexport interface UploadPropertyContext {\n /** The collection's slug, as the server registered it. */\n collection: string;\n /** Dotted path to the property — `coverImage`, `meta.avatar`. */\n property: string;\n}\n\n/**\n * @group Models\n */\nexport interface UploadFileResult {\n /**\n * Storage key including the file name where the file was uploaded.\n */\n key: string;\n /**\n * Bucket where the file was uploaded\n */\n bucket: string;\n\n /**\n * Fully qualified storage URL for the uploaded file.\n *\n * For example: `s3://my-bucket/path/to/file.png`. Every controller in the\n * framework returns one — S3, GCS and local alike — and a caller that stores\n * the reference needs it, so it is part of the result rather than a maybe.\n */\n storageUrl: string;\n}\n\n/**\n * @group Models\n */\nexport interface DownloadConfig {\n /**\n * Temporal url that can be used to download the file\n */\n url: string | null;\n\n metadata?: DownloadMetadata;\n\n fileNotFound?: boolean;\n}\n\n/**\n * The full set of object metadata, including read-only properties.\n * @public\n */\nexport declare interface DownloadMetadata {\n /**\n * The bucket this object is contained in.\n */\n bucket: string;\n /**\n * The full path of this object.\n */\n fullPath: string;\n /**\n * The short name of this object, which is the last component of the full path.\n * For example, if path is 'full/path/image.png', name is 'image.png'.\n */\n name: string;\n /**\n * The size of this object, in bytes.\n */\n size: number;\n /**\n * Type of the uploaded file\n * e.g. \"image/jpeg\"\n */\n contentType: string;\n\n customMetadata: Record<string, unknown>;\n /**\n * Optional short-lived download token (for local/server-mediated storage).\n * Absent for public objects, which need no token.\n */\n token?: string;\n /**\n * Optional remaining lifetime of the token, in seconds.\n */\n tokenExpiresIn?: number;\n /**\n * True when this object is public: it is served without a token via a\n * stable, permanent, CDN-cacheable URL. When set, the client builds a\n * token-less URL and caches it indefinitely.\n */\n public?: boolean;\n}\n\n/**\n * What serving an object needs to know before deciding whether to read it.\n * See {@link StorageSource.statObject}.\n *\n * @group Models\n */\nexport interface StoredObjectInfo {\n /** The whole object's size in bytes. */\n size: number;\n /** The stored content type — the uploader's claim, not a sniffed one. */\n contentType: string;\n /**\n * The object's own modification time, in milliseconds since the epoch.\n * The routes build `ETag`, `Last-Modified` and the transform cache key from\n * it, so it must be the object's version, not the time of the read.\n */\n lastModified: number;\n}\n\n/**\n * An inclusive byte range, as `Range: bytes=start-end` names one.\n *\n * @group Models\n */\nexport interface StoredObjectRange {\n start: number;\n end: number;\n}\n\n/**\n * An object's bytes as a stream. See {@link StorageSource.getObjectStream}.\n *\n * @group Models\n */\nexport interface StoredObjectStream extends StoredObjectInfo {\n /** The bytes: the range when {@link range} is set, the whole object otherwise. */\n stream: ReadableStream<Uint8Array>;\n /**\n * The range {@link stream} holds — the one asked for — or absent when it\n * holds the whole object. A controller may answer a range with the whole\n * object, as HTTP lets a server do; the caller then serves it whole.\n */\n range?: StoredObjectRange;\n}\n\n/**\n * A write of bytes whose length is not known yet. See\n * {@link StorageSource.putObjectStream}.\n *\n * @group Models\n */\nexport interface PutObjectStreamProps {\n /** Read once, to its end. A controller cannot retry a stream it has consumed. */\n stream: ReadableStream<Uint8Array>;\n key: string;\n contentType?: string;\n bucket?: string;\n /** Refuse the write once the stream passes this many bytes. */\n maxBytes?: number;\n}\n\n/**\n * @group Models\n */\nexport interface PutObjectStreamResult extends UploadFileResult {\n /** How many bytes were written. */\n size: number;\n}\n\n/**\n * @group Models\n */\nexport interface StorageSource {\n /**\n * Upload an object, specifying a key\n * @param file\n * @param key\n * @param metadata\n * @param bucket\n */\n putObject: ({\n file,\n key,\n metadata,\n bucket\n }: UploadFileProps) => Promise<UploadFileResult>;\n\n /**\n * Convert a storage key or URL into a download configuration (signed URL equivalent)\n * @param keyOrUrl\n * @param bucket\n */\n getSignedUrl: (keyOrUrl: string, bucket?: string) => Promise<DownloadConfig>;\n\n /**\n * Get an object from a storage key.\n * It returns null if the object does not exist.\n * @param key\n * @param bucket\n */\n getObject: (key: string, bucket?: string) => Promise<File | null>;\n\n /**\n * Describe an object without reading its bytes, or `null` when there is no\n * such object. Server-side storage only.\n */\n statObject?: (key: string, bucket?: string) => Promise<StoredObjectInfo | null>;\n\n /**\n * Read an object, or one byte range of it, as a stream, or `null` when\n * there is no such object. Server-side storage only.\n *\n * The stream holds a file or a connection until it is read to the end or\n * cancelled, so a caller that decides not to read it must cancel it.\n */\n getObjectStream?: (key: string, options?: { bucket?: string; range?: StoredObjectRange }) => Promise<StoredObjectStream | null>;\n\n /**\n * Write an object from a stream, holding a chunk at a time however large it\n * is. Server-side storage only.\n *\n * Rejects with `ObjectTooLargeError` past `maxBytes`, and on that or any\n * other failure leaves no object at the key. The controller's upload limits\n * do not apply: this is how the server stores something of its own, and\n * `maxBytes` is its limit.\n */\n putObjectStream?: (props: PutObjectStreamProps) => Promise<PutObjectStreamResult>;\n\n /**\n * Delete an object.\n * @param key\n * @param bucket\n */\n deleteObject: (key: string, bucket?: string) => Promise<void>;\n\n /**\n * List the contents of a prefix.\n * @param prefix\n * @param options\n */\n listObjects: (prefix: string, options?: {\n bucket?: string,\n maxResults?: number,\n pageToken?: string\n }) => Promise<StorageListResult>;\n\n}\n\n/**\n * What the SDK's `putObject` takes. The server's controllers need a key; the\n * SDK does not: with none, the server names the object after the uploaded\n * file. And the SDK uploads any `Blob` — one that is not a `File` travels as a\n * file called \"blob\".\n *\n * @group Models\n */\nexport interface ClientUploadFileProps extends Omit<UploadFileProps, \"key\" | \"file\"> {\n file: Blob;\n key?: string;\n}\n\n/**\n * The SDK's storage source (`client.storage`). A {@link StorageSource} whose\n * upload takes {@link ClientUploadFileProps} — a wider argument, so it is\n * still a `StorageSource` wherever one is asked for.\n *\n * @group Models\n */\nexport interface ClientStorageSource extends Omit<StorageSource, \"putObject\"> {\n putObject: (props: ClientUploadFileProps) => Promise<UploadFileResult>;\n}\n\n/**\n * Result returned by list().\n * @public\n */\nexport declare interface StorageListResult {\n /**\n * References to prefixes (sub-folders). You can call list() on them to\n * get its contents.\n *\n * Folders are implicit based on '/' in the object paths.\n * For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a')\n * will return '/a/b' as a prefix.\n */\n prefixes: StorageReference[];\n /**\n * Objects in this directory.\n * You can call getMetadata() and getDownloadUrl() on them.\n */\n items: StorageReference[];\n /**\n * If set, there might be more results for this list. Use this token to resume the list.\n */\n nextPageToken?: string;\n}\n\n/**\n * Represents a reference to an S3-compatible storage object. Developers can\n * upload, download, and delete objects, as well as get/set object metadata.\n * @public\n */\nexport declare interface StorageReference {\n /**\n * Returns a s3:// URL for this object in the form\n * `s3://<bucket>/<path>/<to>/<object>`\n * @returns The s3:// URL.\n */\n toString(): string;\n\n /**\n * A reference to the root of this object's bucket, or null where the source\n * does not model one — the built-in local, S3 and GCS sources all leave it null.\n */\n root: StorageReference | null;\n /**\n * The name of the bucket containing this reference's object.\n */\n bucket: string;\n /**\n * The full path of this object.\n */\n fullPath: string;\n /**\n * The short name of this object, which is the last component of the full path.\n * For example, if path is 'full/path/image.png', name is 'image.png'.\n */\n name: string;\n\n /**\n * A reference pointing to the parent location of this reference, or null if\n * this reference is the root.\n */\n parent: StorageReference | null;\n\n /**\n * The object's size in bytes, as the listing read it. Set on the objects\n * of a listing from the built-in local, S3 and GCS sources; absent on\n * folders and from a source that cannot list it without a request per\n * object. Since 0.24.\n */\n size?: number;\n\n /**\n * When the object was last written, as an ISO 8601 timestamp — set where\n * {@link size} is.\n */\n updated?: string;\n\n /**\n * The object's stored content type, as the listing read it: set by local\n * storage and GCS. An S3 listing does not carry it, so on S3 it is absent\n * and `getSignedUrl()` (or the metadata route) still says.\n */\n contentType?: string;\n}\n","import { DEFAULT_STORAGE_SOURCE_KEY } from \"../types/storage_source\";\nimport type { StorageSource } from \"./storage\";\n\n// Storage references: a stored object named inside text. A module of its own,\n// apart from ./storage, because only the code that renders or rewrites text\n// needs it — an app bundles it only where it does, and not with every client\n// that uploads a file.\n\n/**\n * The scheme of a **storage reference**: a stored object named inside text.\n *\n * Text that embeds a file — a markdown body above all — cannot hold a private\n * object's URL: that URL carries a download token which expires in minutes,\n * after which every reader of the text gets a 401 for an image that is still in\n * the bucket. It holds a reference instead,\n * `rebase-storage:posts/cover.png` (`?storageId=media` for a named source),\n * and whoever renders the text exchanges each reference for a fresh URL with\n * {@link resolveStorageReferences} — `resolveStorageReferences(text, client)`\n * from `@rebasepro/client` on a site.\n *\n * @group Models\n */\nexport const STORAGE_REFERENCE_SCHEME = \"rebase-storage:\";\n\n/**\n * The object a storage reference names.\n *\n * @group Models\n */\nexport interface StorageReferenceTarget {\n /** The object's key in its storage source. */\n key: string;\n /** The named storage source holding it. Absent for the default source. */\n storageId?: string;\n}\n\n/**\n * `encodeURIComponent`, plus the five characters it leaves alone that end or\n * break a markdown link destination: `(`, `)`, `'`, `!` and `*`.\n */\nconst encodeReferencePart = (part: string): string =>\n encodeURIComponent(part).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);\n\n/**\n * A reference as it appears in text: the scheme, then the characters\n * {@link storageReference} writes. Kept beside {@link STORAGE_REFERENCE_SCHEME};\n * the test round-trips names chosen to break it.\n */\nconst STORAGE_REFERENCE_PATTERN = /rebase-storage:[A-Za-z0-9\\-._~%/?=&]+/g;\n\n/**\n * The reference for an object — what text stores in place of its URL.\n *\n * Every part is percent-encoded, so the reference contains no space,\n * parenthesis or quote and survives as one markdown link destination whatever\n * the file was called.\n *\n * @group Models\n */\nexport function storageReference(key: string, storageId?: string | null): string {\n const path = key.replace(/^\\/+/, \"\").split(\"/\").map(encodeReferencePart).join(\"/\");\n const named = storageId && storageId !== DEFAULT_STORAGE_SOURCE_KEY\n ? `?storageId=${encodeReferencePart(storageId)}`\n : \"\";\n return `${STORAGE_REFERENCE_SCHEME}${path}${named}`;\n}\n\n/**\n * Whether a string — an image's `src`, a link's `href` — is a storage reference.\n *\n * @group Models\n */\nexport function isStorageReference(value: string | null | undefined): value is string {\n return typeof value === \"string\" && value.startsWith(STORAGE_REFERENCE_SCHEME);\n}\n\n/**\n * The object a storage reference names, or `null` for anything else — a URL, a\n * bare key, or a reference whose key would climb out of its prefix.\n *\n * @group Models\n */\nexport function parseStorageReference(value: string | null | undefined): StorageReferenceTarget | null {\n if (!isStorageReference(value)) return null;\n const rest = value.slice(STORAGE_REFERENCE_SCHEME.length);\n const queryAt = rest.indexOf(\"?\");\n const rawPath = queryAt === -1 ? rest : rest.slice(0, queryAt);\n const query = queryAt === -1 ? \"\" : rest.slice(queryAt + 1);\n\n let key: string;\n let storageId: string | undefined;\n try {\n key = rawPath.split(\"/\").map(decodeURIComponent).join(\"/\");\n for (const pair of query.split(\"&\")) {\n const [name, raw] = pair.split(\"=\");\n if (name === \"storageId\" && raw) storageId = decodeURIComponent(raw);\n }\n } catch {\n return null;\n }\n if (!key || key.split(\"/\").some((segment) => segment === \"..\")) return null;\n return storageId && storageId !== DEFAULT_STORAGE_SOURCE_KEY ? { key, storageId } : { key };\n}\n\n/** The JSON in a JWT's payload segment, or `undefined` for anything else. */\nfunction jwtPayload(token: string): Record<string, unknown> | undefined {\n const segments = token.split(\".\");\n if (segments.length !== 3) return undefined;\n try {\n const base64 = segments[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const binary = atob(base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\"));\n const json = new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));\n const payload: unknown = JSON.parse(json);\n return payload && typeof payload === \"object\" && !Array.isArray(payload)\n ? payload as Record<string, unknown>\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The object a private file's download URL was minted for, or `null` for any\n * other URL.\n *\n * Text written before storage references stored such URLs —\n * `…/storage/file/posts/cover.png?token=…` — and their tokens expired minutes\n * later. The token still names the object it was minted for, so the URL can be\n * traded for a fresh one, or for a reference. Read without verifying the\n * token: it grants nothing here, it only says which object is meant, and the\n * key in the URL must agree with it. Host-agnostic, since a URL written\n * through one origin may be read through another.\n *\n * @group Models\n */\nexport function storageTargetOfDownloadUrl(url: string): StorageReferenceTarget | null {\n let parsed: URL;\n try {\n parsed = new URL(url, \"http://relative.invalid\");\n } catch {\n return null;\n }\n const marker = \"/storage/file/\";\n const at = parsed.pathname.indexOf(marker);\n const token = parsed.searchParams.get(\"token\");\n if (at === -1 || !token) return null;\n\n let key: string;\n try {\n key = parsed.pathname.slice(at + marker.length).split(\"/\").map(decodeURIComponent).join(\"/\");\n } catch {\n return null;\n }\n if (!key || key.split(\"/\").some((segment) => segment === \"..\")) return null;\n\n const payload = jwtPayload(token);\n if (payload?.purpose !== \"file-read\" || typeof payload.path !== \"string\") return null;\n // The token's path is `<bucket>/<key>`.\n const slash = payload.path.indexOf(\"/\");\n if (payload.path !== key && payload.path.slice(slash + 1) !== key) return null;\n\n const named = parsed.searchParams.get(\"storageId\")\n ?? (typeof payload.storageId === \"string\" ? payload.storageId : undefined);\n return named && named !== DEFAULT_STORAGE_SOURCE_KEY ? { key, storageId: named } : { key };\n}\n\n/**\n * A private file's download URL as it may appear in text. Parentheses are\n * allowed in the path, where an unencoded file name puts them; the query, a\n * token, has none, so the match ends where a markdown destination does.\n */\nconst DOWNLOAD_URL_PATTERN = /(?:https?:\\/\\/[^\\s()<>\"'\\]]+)?\\/storage\\/file\\/[^\\s<>\"'?#\\]]+\\?[^\\s()<>\"'#\\]]*/g;\n\n/** Each download URL in `text` that names an object, with its reference. */\nfunction downloadUrlsIn(text: string): Map<string, string> {\n const found = new Map<string, string>();\n if (!text.includes(\"/storage/file/\")) return found;\n for (const url of text.match(DOWNLOAD_URL_PATTERN) ?? []) {\n const target = storageTargetOfDownloadUrl(url);\n if (target) found.set(url, storageReference(target.key, target.storageId));\n }\n return found;\n}\n\n/**\n * Every object `text` names: its storage references, and the private files'\n * download URLs saved in it before references existed. An object named more\n * than once may be listed more than once.\n *\n * @group Models\n */\nexport function storageTargetsInText(text: string): StorageReferenceTarget[] {\n const references = text.includes(STORAGE_REFERENCE_SCHEME) ? text.match(STORAGE_REFERENCE_PATTERN) ?? [] : [];\n return [...references, ...downloadUrlsIn(text).values()]\n .map((reference) => parseStorageReference(reference))\n .filter((target): target is StorageReferenceTarget => target !== null);\n}\n\n/**\n * `text` with every private file's download URL replaced by the storage\n * reference for its object — for rewriting text saved before references, so\n * it stores what new text stores. Any other URL is left as it is.\n *\n * @group Models\n */\nexport function storageReferencesForDownloadUrls(text: string): string {\n const urls = downloadUrlsIn(text);\n if (urls.size === 0) return text;\n return text.replace(DOWNLOAD_URL_PATTERN, (url) => urls.get(url) ?? url);\n}\n\n/**\n * Where {@link resolveStorageReferences} gets URLs from: a function that\n * answers one, or anything shaped like a Rebase client — its `storage` for the\n * default source and `createStorageSource(id)` for a named one. Only a\n * source's `getSignedUrl` is read.\n *\n * @group Models\n */\nexport type StorageReferenceResolver =\n | ((target: StorageReferenceTarget) => Promise<string | null | undefined>)\n | {\n storage?: Pick<StorageSource, \"getSignedUrl\">;\n createStorageSource?(storageId: string): Pick<StorageSource, \"getSignedUrl\">;\n };\n\n/**\n * Exchange every storage reference in `text` for a URL, at the moment the text\n * is rendered.\n *\n * ```ts\n * const html = markdown.render(await resolveStorageReferences(post.body, client));\n * ```\n *\n * Each distinct object is asked for once — `getSignedUrl(key)` on its source —\n * so a private object gets a freshly minted download URL every time the text is\n * rendered. A reference that cannot be resolved (no such object, an unknown\n * source) is left as it was, so a missing object reads as a missing image\n * rather than as a failed render.\n *\n * A private file's download URL saved in the text before references existed\n * is renewed the same way: its expired token still names the object (see\n * {@link storageTargetOfDownloadUrl}). One that cannot be resolved is left as\n * it was.\n *\n * @group Models\n */\nexport async function resolveStorageReferences(\n text: string,\n from: StorageReferenceResolver\n): Promise<string> {\n if (!text) return text;\n const downloadUrls = downloadUrlsIn(text);\n if (!text.includes(STORAGE_REFERENCE_SCHEME) && downloadUrls.size === 0) return text;\n const resolve = typeof from === \"function\" ? from : resolverFromSources(from);\n const references = new Set([...(text.match(STORAGE_REFERENCE_PATTERN) ?? []), ...downloadUrls.values()]);\n const urls = new Map<string, string>();\n await Promise.all([...references].map(async (reference) => {\n const target = parseStorageReference(reference);\n if (!target) return;\n try {\n const url = await resolve(target);\n if (url) urls.set(reference, url);\n } catch {\n // Left as it was: one unreadable object must not fail the page.\n }\n }));\n if (urls.size === 0) return text;\n const renewed = downloadUrls.size === 0 ? text : text.replace(DOWNLOAD_URL_PATTERN, (saved) => {\n const reference = downloadUrls.get(saved);\n const url = reference === undefined ? undefined : urls.get(reference);\n return url === undefined ? saved : asLinkDestination(url);\n });\n return renewed.replace(STORAGE_REFERENCE_PATTERN, (reference) => {\n const url = urls.get(reference);\n return url === undefined ? reference : asLinkDestination(url);\n });\n}\n\n/**\n * A URL as one markdown link destination: whitespace, parentheses, angle\n * brackets and quotes percent-encoded, since any of them ends the destination\n * and turns the image into literal text. The URL means the same thing either\n * way.\n */\nconst asLinkDestination = (url: string): string =>\n url.replace(/[\\s()<>\"']/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`);\n\n/** A resolver over a client's storage sources, one source per named key. */\nfunction resolverFromSources(\n client: Exclude<StorageReferenceResolver, (target: StorageReferenceTarget) => unknown>\n): (target: StorageReferenceTarget) => Promise<string | null> {\n const named = new Map<string, Pick<StorageSource, \"getSignedUrl\"> | undefined>();\n return async ({ key, storageId }) => {\n let source = client.storage;\n if (storageId) {\n if (!named.has(storageId)) named.set(storageId, client.createStorageSource?.(storageId));\n source = named.get(storageId);\n }\n if (!source) return null;\n const config = await source.getSignedUrl(key);\n return config.fileNotFound ? null : config.url;\n };\n}\n","import type { AggregateGroup, AggregateGroupTransform, AggregateSelect } from \"./data\";\nimport type { DriverAggregate, DriverAggregateGroup } from \"./data_driver\";\n\n/** Every aggregate function, by its SDK name: what `?select=` accepts too. */\nexport const AGGREGATE_FUNCTIONS: readonly DriverAggregate[\"fn\"][] = [\n \"count\", \"sum\", \"avg\", \"min\", \"max\", \"countDistinct\", \"mode\", \"percentile\", \"distinct\", \"fingerprint\"\n];\n\n/** The functions that take no field. */\nexport const FIELDLESS_AGGREGATES: ReadonlySet<DriverAggregate[\"fn\"]> = new Set([\"count\", \"fingerprint\"]);\n\n/** Every `groupBy` transform. */\nexport const AGGREGATE_GROUP_TRANSFORMS: readonly AggregateGroupTransform[] = [\"lower\", \"upper\", \"unnest\", \"year\", \"month\", \"day\"];\n\n/** A function's name in its result key: the SDK's camelCase in SQL's spelling. */\nconst ALIAS_NAMES: Partial<Record<DriverAggregate[\"fn\"], string>> = { countDistinct: \"count_distinct\" };\n\n/**\n * `percentile`'s `p` as it reads in a key: `0.95` → `95`, `0.5` → `50`,\n * `0.995` → `99_5`.\n */\nfunction percentileLabel(p: number): string {\n return String(Math.round(p * 1000) / 10).replace(\".\", \"_\");\n}\n\n/**\n * The key an aggregate comes back under.\n *\n * `sum(total)` → `sum_total`, `count()` → `count`, `countDistinct(sid)` →\n * `count_distinct_sid`, `percentile(fame, 0.95)` → `p95_fame`. One function,\n * because the SDK, the REST parser and the HTTP client all derive it and have\n * to agree — a caller reading `row.sum_total` off an SDK result and off an HTTP\n * response is reading the same key or the SDK is broken.\n */\nexport function aggregateAlias(fn: string, field?: string, p?: number): string {\n if (fn === \"percentile\") return `p${percentileLabel(p ?? 0)}_${field ?? \"\"}`;\n const name = ALIAS_NAMES[fn as DriverAggregate[\"fn\"]] ?? fn;\n return field ? `${name}_${field}` : name;\n}\n\n/** `percentile`'s `p`, refused unless it is a fraction a key can name (0–1, at most three decimals). */\nexport function isPercentileFraction(p: unknown): p is number {\n return typeof p === \"number\" && Number.isFinite(p) && p >= 0 && p <= 1 && Math.abs(Math.round(p * 1000) - p * 1000) < 1e-9;\n}\n\n/**\n * An `AggregateSelect` as a driver is handed it — but for its `where`, which\n * the caller decodes into the driver's `filter` (this package has no filter\n * codec).\n */\nexport function toDriverAggregate(select: AggregateSelect<Record<string, unknown>>): DriverAggregate {\n const field = \"field\" in select ? select.field as string | undefined : undefined;\n const p = select.fn === \"percentile\" ? select.p : undefined;\n return {\n fn: select.fn,\n ...(field !== undefined ? { field } : {}),\n ...(p !== undefined ? { p } : {}),\n alias: select.as ?? aggregateAlias(select.fn, field, p)\n };\n}\n\n/** Whether `timeZone` names a time zone this runtime knows: an IANA name such as `Europe/Madrid`, or `UTC`. */\nexport function isTimeZoneName(timeZone: unknown): timeZone is string {\n if (typeof timeZone !== \"string\" || !/^[A-Za-z][A-Za-z0-9_+\\-/]*$/.test(timeZone)) return false;\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone });\n return true;\n } catch {\n return false;\n }\n}\n\n/** The key a group comes back under: the column's name, or `<transform>_<field>`. */\nexport function aggregateGroupKey(group: string | AggregateGroup | DriverAggregateGroup): string {\n return typeof group === \"string\" ? group : `${group.transform}_${group.field}`;\n}\n\n/** A `groupBy` entry as a driver is handed it. */\nexport function toDriverAggregateGroup(group: string | AggregateGroup): string | DriverAggregateGroup {\n return typeof group === \"string\"\n ? group\n : { field: group.field, transform: group.transform, ...(group.timeZone ? { timeZone: group.timeZone } : {}), key: aggregateGroupKey(group) };\n}\n","/**\n * The Postgres type of a column, as a tag.\n *\n * One member per type Rebase creates, 1:1 with the planner's own `PgType`: a\n * column says which Postgres type it is, and nothing downstream has to work it\n * out from a document-shaped \"string that is really a uuid\". `other` is a type\n * Rebase serves but does not create (`inet`, `citext`, `interval`, a range, a\n * domain, a PostGIS type, an array of one of those, …): what introspection\n * reports for such a column, and what `col.custom(sqlType)` declares. Its value\n * is passed through as the driver returns it.\n *\n * @group Schema\n */\nexport type ColumnType =\n | { kind: \"text\" }\n | { kind: \"varchar\"; length: number }\n | { kind: \"char\"; length: number }\n | { kind: \"uuid\" }\n | { kind: \"enum\"; values: readonly string[]; name?: string }\n | { kind: \"smallint\" }\n | { kind: \"integer\" }\n | { kind: \"bigint\" }\n | { kind: \"smallserial\" }\n | { kind: \"serial\" }\n | { kind: \"bigserial\" }\n | { kind: \"real\" }\n | { kind: \"doublePrecision\" }\n | { kind: \"numeric\"; precision?: number; scale?: number }\n | { kind: \"boolean\" }\n | { kind: \"timestamptz\" }\n | { kind: \"date\" }\n | { kind: \"time\" }\n | { kind: \"json\" }\n | { kind: \"jsonb\" }\n | { kind: \"vector\"; dimensions: number }\n | { kind: \"bytea\" }\n | { kind: \"array\"; of: ColumnType }\n | { kind: \"other\"; sqlType: string };\n\n/**\n * The tag of a {@link ColumnType}.\n *\n * @group Schema\n */\nexport type ColumnKind = ColumnType[\"kind\"];\n\n/** The kinds stored as text. */\nexport type TextColumnKind = \"text\" | \"varchar\" | \"char\";\n\n/** The kinds a JavaScript `number` is read from and written to. */\nexport type NumericColumnKind =\n | \"smallint\" | \"integer\" | \"bigint\"\n | \"smallserial\" | \"serial\" | \"bigserial\"\n | \"real\" | \"doublePrecision\" | \"numeric\";\n\n/** The kinds that hold an instant, a day or a time of day. */\nexport type TemporalColumnKind = \"timestamptz\" | \"date\" | \"time\";\n\nconst TEXT_KINDS: readonly ColumnKind[] = [\"text\", \"varchar\", \"char\"];\nconst NUMERIC_KINDS: readonly ColumnKind[] = [\n \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\", \"real\", \"doublePrecision\", \"numeric\"\n];\nconst TEMPORAL_KINDS: readonly ColumnKind[] = [\"timestamptz\", \"date\", \"time\"];\n\n/**\n * Whether a column type is stored as text (`text`, `varchar`, `char`).\n *\n * @group Schema\n */\nexport function isTextColumnType(type: ColumnType): boolean {\n return TEXT_KINDS.includes(type.kind);\n}\n\n/**\n * Whether a column type is read and written as a JavaScript `number`.\n *\n * @group Schema\n */\nexport function isNumericColumnType(type: ColumnType): boolean {\n return NUMERIC_KINDS.includes(type.kind);\n}\n\n/**\n * Whether a column type holds an instant, a day or a time of day.\n *\n * @group Schema\n */\nexport function isTemporalColumnType(type: ColumnType): boolean {\n return TEMPORAL_KINDS.includes(type.kind);\n}\n\n/**\n * Whether a column type is a JSON document (`json`, `jsonb`).\n *\n * @group Schema\n */\nexport function isJsonColumnType(type: ColumnType): boolean {\n return type.kind === \"json\" || type.kind === \"jsonb\";\n}\n\n/**\n * The SQL spelling of a column type, for messages and generated comments.\n *\n * Not the DDL renderer: an enum prints as `enum(a, b)` because its type name\n * belongs to the table it is planned in.\n *\n * @group Schema\n */\nexport function columnTypeLabel(type: ColumnType): string {\n switch (type.kind) {\n case \"varchar\": return `varchar(${type.length})`;\n case \"char\": return `char(${type.length})`;\n case \"enum\": return type.name ?? `enum(${type.values.join(\", \")})`;\n case \"doublePrecision\": return \"double precision\";\n case \"numeric\":\n if (type.precision === undefined) return \"numeric\";\n return type.scale === undefined ? `numeric(${type.precision})` : `numeric(${type.precision}, ${type.scale})`;\n case \"vector\": return `vector(${type.dimensions})`;\n case \"array\": return `${columnTypeLabel(type.of)}[]`;\n case \"other\": return type.sqlType;\n default: return type.kind;\n }\n}\n","import { resourceKeyOf } from \"../types/resources\";\nimport type { ResourceRef } from \"../types/resources\";\n\n/**\n * Who may read and who may write one column, by role.\n *\n * A list that is absent leaves that direction to the table's `rls`. An empty\n * list closes it to every caller, the server's own code aside. Enforced on\n * every door — REST, realtime, MCP, caller SQL, includes, filters and sorts —\n * never only in the panel.\n *\n * @group Schema\n */\nexport interface ColumnAccess {\n /** Roles that receive the column on a read. */\n read?: readonly string[];\n /** Roles that may write the column. */\n write?: readonly string[];\n}\n\n/**\n * Per-role access in its stored form, checked: `read` and `write` must each be\n * a list of non-empty role names, and nothing else may be given.\n *\n * Checked at runtime because a JavaScript caller writing\n * `.access({ read: \"admin\" })` would otherwise have the string spread into\n * one role per character, silently.\n *\n * @param where What is being configured, for the error: `column \"title\"`.\n *\n * @group Schema\n */\nexport function normalizeColumnAccess(access: unknown, where: string): ColumnAccess {\n const expected = \"Write `{ read?: [\\\"role\\\", …], write?: [\\\"role\\\", …] }`.\";\n if (typeof access !== \"object\" || access === null || Array.isArray(access)) {\n throw new Error(`The access of ${where} must be an object of role lists, got ${JSON.stringify(access)}. ${expected}`);\n }\n const stored: ColumnAccess = {};\n for (const [key, value] of Object.entries(access)) {\n if (key !== \"read\" && key !== \"write\") {\n throw new Error(`The access of ${where} has an unknown key \"${key}\". ${expected}`);\n }\n if (value === undefined) continue;\n if (!Array.isArray(value) || value.some(role => typeof role !== \"string\" || role.length === 0)) {\n throw new Error(`\\`access.${key}\\` of ${where} must be a list of role names, got ${JSON.stringify(value)}. ${expected}`);\n }\n const roles: string[] = value.filter((role): role is string => typeof role === \"string\");\n stored[key] = roles;\n }\n return stored;\n}\n\n/**\n * A value the server writes into a column on its own: the time, or the caller.\n *\n * @group Schema\n */\nexport interface ColumnStamp {\n /** `create` stamps on insert only; `update` stamps on every write. */\n on: \"create\" | \"update\";\n /** `now` is the current instant; `user` is the id of the caller. */\n value: \"now\" | \"user\";\n}\n\n/**\n * The DEFAULT of a column.\n *\n * - `literal` — a value, written as a DDL default and applied by the driver on\n * create, so every writer gets the same row.\n * - `sql` — an expression Postgres evaluates.\n * - `random-uuid` — `gen_random_uuid()`.\n * - `identity` — `GENERATED BY DEFAULT AS IDENTITY`.\n * - `database` — the database holds a default Rebase does not state and must\n * not drop; a create may omit the column.\n *\n * @group Schema\n */\nexport type ColumnDefault =\n | { kind: \"literal\"; value: unknown }\n | { kind: \"sql\"; expression: string }\n | { kind: \"random-uuid\" }\n | { kind: \"identity\" }\n | { kind: \"database\" };\n\n/** What every `.validate()` accepts. */\nexport interface BaseValidation {\n /** The API error when a `.notNull()` column is missing from a create. */\n requiredMessage?: string;\n}\n\n/**\n * Validation of a text column, checked by the API before a write.\n *\n * @group Schema\n */\nexport interface StringValidation extends BaseValidation {\n /** Minimum length. */\n min?: number;\n /** Maximum length. */\n max?: number;\n /** Exact length. */\n length?: number;\n /** A pattern the value must match. A `RegExp` is kept as its source and flags. */\n matches?: string | RegExp;\n /** Flags of `matches`, when it was given as a string. */\n matchesFlags?: string;\n /** The API error when `matches` fails. */\n matchesMessage?: string;\n /** The value must be an e-mail address. */\n email?: boolean;\n /** The value must be a URL. */\n url?: boolean;\n /** Lower-case the value before it is stored. */\n lowercase?: boolean;\n /** Upper-case the value before it is stored. */\n uppercase?: boolean;\n /** Trim surrounding whitespace before the value is stored. */\n trim?: boolean;\n}\n\n/**\n * Validation of a numeric column, checked by the API before a write.\n *\n * @group Schema\n */\nexport interface NumberValidation extends BaseValidation {\n /** Inclusive lower bound. */\n min?: number;\n /** Inclusive upper bound. */\n max?: number;\n /** Exclusive upper bound. */\n lessThan?: number;\n /** Exclusive lower bound. */\n moreThan?: number;\n /** The value must be greater than zero. */\n positive?: boolean;\n /** The value must be less than zero. */\n negative?: boolean;\n /** The value must be a whole number. */\n integer?: boolean;\n}\n\n/**\n * Validation of a temporal column. Bounds are ISO strings.\n *\n * @group Schema\n */\nexport interface DateValidation extends BaseValidation {\n /** Earliest accepted value. */\n min?: string | Date;\n /** Latest accepted value. */\n max?: string | Date;\n}\n\n/**\n * Validation of an array column.\n *\n * @group Schema\n */\nexport interface ArrayValidation extends BaseValidation {\n /** Fewest items accepted. */\n minItems?: number;\n /** Most items accepted. */\n maxItems?: number;\n /** Refuse an array holding the same value twice. */\n uniqueItems?: boolean;\n /**\n * For a JSON array of objects (`json.array(json.object({...}))`): refuse\n * two items with the same value in any one of these fields — each field\n * is unique across the items on its own (`[\"sku\"]`: no SKU twice). The\n * fields are keys of the item object; anything else is refused when the\n * schema compiles.\n */\n uniqueBy?: string[];\n}\n\n/**\n * Every validation rule a column can carry, as stored on its definition and\n * served on the wire: patterns are strings, date bounds are ISO strings.\n *\n * @group Schema\n */\nexport interface ColumnValidation {\n /** The API error when a `.notNull()` column is missing from a create. */\n requiredMessage?: string;\n /**\n * Lower bound: minimum length of text, inclusive minimum of a number, earliest\n * accepted value of a temporal column (an ISO string).\n */\n min?: number | string;\n /**\n * Upper bound: maximum length of text, inclusive maximum of a number, latest\n * accepted value of a temporal column (an ISO string).\n */\n max?: number | string;\n /** Exact length of a text value. */\n length?: number;\n /** A pattern a text value must match: a `RegExp`'s source, its flags in `matchesFlags`. */\n matches?: string;\n /** Flags of `matches` (`\"i\"`, `\"u\"`, …). No flags when omitted. */\n matchesFlags?: string;\n /** The API error when `matches` fails. */\n matchesMessage?: string;\n /** A text value must be an e-mail address. */\n email?: boolean;\n /** A text value must be a URL. */\n url?: boolean;\n /** Lower-case a text value before it is stored. */\n lowercase?: boolean;\n /** Upper-case a text value before it is stored. */\n uppercase?: boolean;\n /** Trim surrounding whitespace from a text value before it is stored. */\n trim?: boolean;\n /** Exclusive upper bound of a number. */\n lessThan?: number;\n /** Exclusive lower bound of a number. */\n moreThan?: number;\n /** A number must be greater than zero. */\n positive?: boolean;\n /** A number must be less than zero. */\n negative?: boolean;\n /** A number must be a whole number. */\n integer?: boolean;\n /** Fewest items an array accepts. */\n minItems?: number;\n /** Most items an array accepts. */\n maxItems?: number;\n /** Refuse an array holding the same value twice. */\n uniqueItems?: boolean;\n /** Fields of a JSON array's object items, each unique across the items. See {@link ArrayValidation.uniqueBy}. */\n uniqueBy?: string[];\n}\n\n/** The rules a builder method accepts, before they are normalized. */\nexport type ValidationInput = StringValidation | NumberValidation | DateValidation | ArrayValidation | BaseValidation;\n\nconst isoOf = (value: string | Date): string => (value instanceof Date ? value.toISOString() : value);\n\n/**\n * Validation rules in their stored form: a `RegExp` becomes its source and\n * flags, a `Date` bound becomes an ISO string. What a builder keeps is then\n * exactly what the wire carries.\n *\n * @group Schema\n */\nexport function normalizeValidation(rules: ValidationInput): ColumnValidation {\n const out: ColumnValidation = {};\n for (const [key, value] of Object.entries(rules)) {\n if (value === undefined) continue;\n if (key === \"matches\" && value instanceof RegExp) {\n out.matches = value.source;\n if (value.flags) out.matchesFlags = value.flags;\n continue;\n }\n if ((key === \"min\" || key === \"max\") && (value instanceof Date)) {\n out[key] = isoOf(value);\n continue;\n }\n // A list is copied, so the stored rules do not alias the caller's array.\n Object.assign(out, { [key]: Array.isArray(value) ? [...value] : value });\n }\n return out;\n}\n\n/**\n * How an image is resized before it is stored.\n *\n * @group Schema\n */\nexport interface StorageImageResize {\n /**\n * Largest width in pixels; a wider image is scaled down proportionally. No\n * width limit when omitted.\n */\n maxWidth?: number;\n /**\n * Largest height in pixels; a taller image is scaled down proportionally. No\n * height limit when omitted.\n */\n maxHeight?: number;\n /**\n * How the image fits `maxWidth` × `maxHeight`: `contain` (the default) scales\n * it to fit inside, keeping its aspect ratio; `cover` scales it to fill the box,\n * keeping its aspect ratio, and may crop.\n */\n mode?: \"contain\" | \"cover\";\n /** The stored image's format. `original` (the default) keeps the uploaded one. */\n format?: \"original\" | \"jpeg\" | \"png\" | \"webp\";\n /**\n * Quality of a lossy output (JPEG, WebP), 0–100: higher is sharper and larger.\n * 80 when omitted.\n */\n quality?: number;\n}\n\n/**\n * What `col.storage()` and `json.storage()` take.\n *\n * @group Schema\n */\nexport interface StorageOptions {\n /** The bucket, declared in `backend/resources.ts`. The default bucket when omitted. */\n source?: ResourceRef;\n /** Where files go, as a path template: `\"posts/heroes/\"`, `\"users/{id}/\"`. */\n path: string;\n /** MIME types accepted, with wildcards: `[\"image/*\", \"application/pdf\"]`. */\n accept?: readonly string[];\n /** Largest file accepted, in bytes or as `\"10MB\"`. */\n maxBytes?: number | string;\n /** Resize images before storing them. */\n imageResize?: StorageImageResize;\n /** Files are readable without a signed URL. */\n public?: boolean;\n /** The stored file name, as a template. The uploaded name when omitted. */\n fileName?: string;\n /** Metadata stored with every file. */\n metadata?: Record<string, unknown>;\n /** Store the bucket URL in front of the path. */\n includeBucketUrl?: boolean;\n /** Store the download URL instead of the path. */\n storeUrl?: boolean;\n}\n\n/**\n * The storage rules of a column, as stored and served: the bucket by its key,\n * the size limit in bytes.\n *\n * @group Schema\n */\nexport interface ColumnStorage {\n source?: string;\n path: string;\n accept?: readonly string[];\n maxBytes?: number;\n imageResize?: StorageImageResize;\n public?: boolean;\n fileName?: string;\n metadata?: Record<string, unknown>;\n includeBucketUrl?: boolean;\n storeUrl?: boolean;\n}\n\nconst BYTE_UNITS: Record<string, number> = {\n b: 1,\n kb: 1024,\n mb: 1024 ** 2,\n gb: 1024 ** 3,\n tb: 1024 ** 4\n};\n\n/**\n * A size in bytes, from a number or from `\"10MB\"` / `\"512 kb\"` / `\"1.5GB\"`.\n *\n * Binary multiples (1 MB = 1,048,576 bytes), the unit a storage limit is\n * enforced in. Throws on anything else: a limit that silently parsed to `NaN`\n * is a limit that is never applied.\n *\n * @group Schema\n */\nexport function parseByteSize(size: number | string): number {\n if (typeof size === \"number\") {\n if (!Number.isFinite(size) || size < 0) throw new Error(`A byte size must be a non-negative number, got ${size}.`);\n return size;\n }\n const match = /^\\s*(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|tb)?\\s*$/i.exec(size);\n if (!match) {\n throw new Error(`Cannot read \"${size}\" as a byte size. Write a number of bytes, or a size such as \"10MB\".`);\n }\n const unit = (match[2] ?? \"b\").toLowerCase();\n return Math.round(Number(match[1]) * BYTE_UNITS[unit]);\n}\n\n/**\n * Storage options in their stored form.\n *\n * @group Schema\n */\nexport function normalizeStorage(options: StorageOptions): ColumnStorage {\n if (typeof options.path !== \"string\" || options.path.length === 0) {\n throw new Error(\"A storage column needs a `path`: where its files go, e.g. `col.storage({ path: \\\"posts/heroes/\\\" })`.\");\n }\n const out: ColumnStorage = { path: options.path };\n if (options.source !== undefined) out.source = resourceKeyOf(options.source);\n if (options.accept !== undefined) out.accept = [...options.accept];\n if (options.maxBytes !== undefined) out.maxBytes = parseByteSize(options.maxBytes);\n if (options.imageResize !== undefined) out.imageResize = { ...options.imageResize };\n if (options.public !== undefined) out.public = options.public;\n if (options.fileName !== undefined) out.fileName = options.fileName;\n if (options.metadata !== undefined) out.metadata = { ...options.metadata };\n if (options.includeBucketUrl !== undefined) out.includeBucketUrl = options.includeBucketUrl;\n if (options.storeUrl !== undefined) out.storeUrl = options.storeUrl;\n return out;\n}\n\n/**\n * The distance a vector index is built for.\n *\n * `ip` is the inner product (pgvector's `vector_ip_ops`).\n *\n * @group Schema\n */\nexport type VectorMetric = \"cosine\" | \"l2\" | \"ip\";\n\n/**\n * The approximate-nearest-neighbour index of a `col.vector()` column.\n *\n * @group Schema\n */\nexport interface VectorIndexOptions {\n /** `hnsw` (the default) or `ivfflat`. */\n method?: \"hnsw\" | \"ivfflat\";\n /** The distance, or several: one index is built per metric. `cosine` by default. */\n metric?: VectorMetric | readonly VectorMetric[];\n /** HNSW: connections per layer. */\n m?: number;\n /** HNSW: size of the candidate list while building. */\n efConstruction?: number;\n /** IVFFlat: number of lists. */\n lists?: number;\n}\n","import type {\n ArrayValidation,\n BaseValidation,\n ColumnStorage,\n ColumnValidation,\n DateValidation,\n NumberValidation,\n StorageOptions,\n StringValidation,\n ValidationInput\n} from \"./column_options\";\nimport { normalizeStorage, normalizeValidation } from \"./column_options\";\nimport type { ColumnTransform } from \"./hooks\";\n\n/** What every node of a JSON shape may carry. */\ninterface JsonNodeBase {\n /** The key must be present in the document. */\n required?: boolean;\n /** The value written when the key is absent on create. */\n default?: unknown;\n /** What the value is, for OpenAPI and MCP. */\n description?: string;\n}\n\ntype JsonNode<Extra> = Extra & JsonNodeBase & (\n | {\n kind: \"string\";\n validate?: ColumnValidation;\n oneOf?: readonly string[];\n storage?: ColumnStorage;\n /**\n * The server writes the caller's user id into the field: on create\n * only (`\"createUser\"`, `.onCreateUser()`) or on every write\n * (`\"updateUser\"`, `.onUpdateUser()`).\n */\n stamp?: \"createUser\" | \"updateUser\";\n /** `\"user\"`: the field holds a user's id (`.userId()`). */\n semantic?: \"user\";\n }\n | { kind: \"number\"; validate?: ColumnValidation; oneOf?: readonly number[] }\n | { kind: \"boolean\" }\n | {\n kind: \"date\";\n validate?: ColumnValidation;\n /**\n * The server writes the current time into the field: on create only\n * (`\"create\"`, `.onCreateNow()`) or on every write (`\"update\"`,\n * `.onUpdateNow()`).\n */\n stamp?: \"create\" | \"update\";\n }\n | { kind: \"geopoint\" }\n | { kind: \"object\"; fields: Record<string, JsonNode<Extra>>; additional?: boolean }\n | { kind: \"array\"; of: JsonNode<Extra>; validate?: ColumnValidation }\n | { kind: \"oneOf\"; typeField: string; valueField: string; variants: Record<string, JsonNode<Extra>> }\n | { kind: \"unknown\" }\n);\n\n/**\n * The shape of a `json`/`jsonb` document, as served on the wire.\n *\n * It is what lets the server validate a nested field, stamp a nested date,\n * find the files a document references, and search a JSON path — and what lets\n * the panel build a form for the document without being told how.\n *\n * @group Schema\n */\nexport type JsonShape = JsonNode<unknown>;\n\n/**\n * A {@link JsonShape} as authored: the same tree, with field-level hooks on\n * its nodes. Hooks stay on the server.\n *\n * @group Schema\n */\nexport type JsonShapeDef = JsonNode<{ transform?: ColumnTransform }>;\n\n/**\n * The kind of one node of a JSON shape.\n *\n * @group Schema\n */\nexport type JsonKind = JsonShape[\"kind\"];\n\n/** A point on Earth, as a JSON document stores it. */\nexport interface JsonGeoPoint {\n /** Degrees north of the equator, −90 to 90 (south is negative). */\n latitude: number;\n /** Degrees east of Greenwich, −180 to 180 (west is negative). */\n longitude: number;\n}\n\ntype JsonValidationFor<K extends JsonKind> =\n K extends \"string\" ? StringValidation :\n K extends \"number\" ? NumberValidation :\n K extends \"date\" ? DateValidation :\n K extends \"array\" ? ArrayValidation :\n BaseValidation;\n\n/**\n * The value a JSON field's `.transform()` hooks receive and return: the\n * field's type, plus `undefined` while the field is not `.required()`.\n *\n * Read when `.transform()` is called: `.required().transform(…)` receives\n * `TData`, `.transform(…).required()` keeps `TData | undefined`.\n *\n * @group Schema\n */\nexport type JsonTransformValue<TData, TRequired extends boolean> = TRequired extends true ? TData : TData | undefined;\n\n/** The brand every JSON field builder carries, so one built by another copy of this package is still recognised. */\nexport const JSON_FIELD_BRAND = \"rebase.json-field\";\n\n/**\n * One field of a JSON document: `json.string()`, `json.object({...})`, ….\n *\n * Immutable: every modifier returns a new field.\n *\n * @group Schema\n */\nexport class JsonField<TData, TKind extends JsonKind = JsonKind, TRequired extends boolean = false> {\n\n /** Type-level only: the TypeScript type of the value. */\n declare readonly $data: TData;\n /** Type-level only: the node kind. */\n declare readonly $kind: TKind;\n /** Type-level only: whether the key must be present. */\n declare readonly $required: TRequired;\n\n readonly brand = JSON_FIELD_BRAND;\n\n constructor(\n /** The shape this field describes. */\n readonly shape: JsonShapeDef\n ) {}\n\n private with<D, K extends JsonKind, R extends boolean>(patch: Partial<JsonNodeBase> & Record<string, unknown>): JsonField<D, K, R> {\n return new JsonField<D, K, R>(Object.assign({}, this.shape, patch));\n }\n\n /** The key must be present in the document. */\n required(): JsonField<TData, TKind, true> {\n return this.with<TData, TKind, true>({ required: true });\n }\n\n /** The value written when the key is absent on create. */\n default(value: TData): JsonField<TData, TKind, TRequired> {\n return this.with<TData, TKind, TRequired>({ default: value });\n }\n\n /** What the value is, for OpenAPI and MCP. */\n describe(description: string): JsonField<TData, TKind, TRequired> {\n return this.with<TData, TKind, TRequired>({ description });\n }\n\n /** Rules the API checks before a write. */\n validate(rules: JsonValidationFor<TKind>): JsonField<TData, TKind, TRequired> {\n const input: ValidationInput = rules;\n return this.with<TData, TKind, TRequired>({ validate: normalizeValidation(input) });\n }\n\n /** A closed set of accepted values. */\n oneOf<const V extends readonly TData[], K extends \"string\" | \"number\">(\n this: JsonField<TData, K, TRequired>,\n values: V\n ): JsonField<V[number], K, TRequired> {\n return this.with<V[number], K, TRequired>({ oneOf: [...values] });\n }\n\n /** The server writes the current time into the field when the row is created. */\n onCreateNow(this: JsonField<string, \"date\", TRequired>): JsonField<string, \"date\", TRequired> {\n return this.with<string, \"date\", TRequired>({ stamp: \"create\" });\n }\n\n /** The server writes the current time into the field on every write. */\n onUpdateNow(this: JsonField<string, \"date\", TRequired>): JsonField<string, \"date\", TRequired> {\n return this.with<string, \"date\", TRequired>({ stamp: \"update\" });\n }\n\n /** The server writes the caller's user id into the field when the row is created. */\n onCreateUser(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n return this.with<string, \"string\", TRequired>({ stamp: \"createUser\" });\n }\n\n /** The server writes the caller's user id into the field on every write. */\n onUpdateUser(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n return this.with<string, \"string\", TRequired>({ stamp: \"updateUser\" });\n }\n\n /**\n * The field holds the id of a user. The panel offers a user picker for it,\n * and callers who may write the table may look users up to fill it.\n * Only on `json.string()`; anything else throws.\n */\n userId(this: JsonField<string, \"string\", TRequired>): JsonField<string, \"string\", TRequired> {\n if (this.shape.kind !== \"string\" || this.shape.storage !== undefined) {\n const what = this.shape.kind === \"string\" ? \"`json.storage()`\" : `a \\`json.${this.shape.kind}()\\` field`;\n throw new Error(`\\`.userId()\\` on ${what}: a user's id is held by \\`json.string()\\`.`);\n }\n return this.with<string, \"string\", TRequired>({ semantic: \"user\" });\n }\n\n /**\n * Field-level hooks. They run on the server only.\n *\n * The value is `TData | undefined` on a field not (yet) marked\n * `.required()` — the key can be absent from the document — and `TData` on\n * one that is; see {@link JsonTransformValue}. Chain `.required()` before\n * `.transform()` to get the narrower type.\n */\n transform(transform: ColumnTransform<JsonTransformValue<TData, TRequired>>): JsonField<TData, TKind, TRequired> {\n const erased: ColumnTransform = transform;\n return this.with<TData, TKind, TRequired>({ transform: erased });\n }\n}\n\n/** Any JSON field, whatever it holds. */\nexport type AnyJsonField = JsonField<unknown, JsonKind, boolean>;\n\n/** The TypeScript type a JSON field holds. */\nexport type JsonDataOf<F> = F extends JsonField<infer T, JsonKind, boolean> ? T : never;\n\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/** The TypeScript type of a `json.object({...})`: required keys required, the rest optional. */\nexport type JsonObjectOf<S extends Record<string, AnyJsonField>> = Simplify<\n { [K in keyof S as S[K] extends JsonField<unknown, JsonKind, true> ? K : never]: JsonDataOf<S[K]> } &\n { [K in keyof S as S[K] extends JsonField<unknown, JsonKind, true> ? never : K]?: JsonDataOf<S[K]> }\n>;\n\n/** One block of a `json.oneOf(...)`: its discriminator and its value. */\nexport type JsonOneOfOf<\n S extends Record<string, AnyJsonField>,\n TypeField extends string,\n ValueField extends string\n> = { [K in keyof S]: Simplify<Record<TypeField, K> & Record<ValueField, JsonDataOf<S[K]>>> }[keyof S];\n\nconst shapesOf = (fields: Record<string, AnyJsonField>): Record<string, JsonShapeDef> => {\n const out: Record<string, JsonShapeDef> = {};\n for (const [key, field] of Object.entries(fields)) out[key] = field.shape;\n return out;\n};\n\n/**\n * Builders for the shape of a `json`/`jsonb` document.\n *\n * ```ts\n * metadata: col.jsonb(json.object({\n * seoTitle: json.string().validate({ max: 60 }),\n * canonicalUrl: json.string().validate({ url: true }),\n * })),\n * content: col.jsonb(json.array(json.oneOf({\n * text: json.string(),\n * image: json.storage({ path: \"posts/content/\" }),\n * }))),\n * ```\n *\n * `col.jsonb().$type<T>()` on its own types the document statically; a shape also\n * tells the server what is inside it.\n *\n * @group Schema\n */\nexport const json = {\n /** A string. */\n string(): JsonField<string, \"string\"> {\n return new JsonField<string, \"string\">({ kind: \"string\" });\n },\n /** A number. */\n number(): JsonField<number, \"number\"> {\n return new JsonField<number, \"number\">({ kind: \"number\" });\n },\n /** A boolean. */\n boolean(): JsonField<boolean, \"boolean\"> {\n return new JsonField<boolean, \"boolean\">({ kind: \"boolean\" });\n },\n /** An instant, stored as an ISO string. */\n date(): JsonField<string, \"date\"> {\n return new JsonField<string, \"date\">({ kind: \"date\" });\n },\n /** A point on Earth: `{ latitude, longitude }`. */\n geopoint(): JsonField<JsonGeoPoint, \"geopoint\"> {\n return new JsonField<JsonGeoPoint, \"geopoint\">({ kind: \"geopoint\" });\n },\n /** The path of a stored file. Counted by the orphan sweep like a `col.storage()` column. */\n storage(options: StorageOptions): JsonField<string, \"string\"> {\n return new JsonField<string, \"string\">({ kind: \"string\", storage: normalizeStorage(options) });\n },\n /** An object with known keys. `additional: true` also accepts keys it does not name. */\n object<S extends Record<string, AnyJsonField>>(\n fields: S,\n options: { additional?: boolean } = {}\n ): JsonField<JsonObjectOf<S>, \"object\"> {\n const shape: JsonShapeDef = { kind: \"object\", fields: shapesOf(fields) };\n if (options.additional) shape.additional = true;\n return new JsonField<JsonObjectOf<S>, \"object\">(shape);\n },\n /** An array of one shape. */\n array<F extends AnyJsonField>(of: F): JsonField<JsonDataOf<F>[], \"array\"> {\n return new JsonField<JsonDataOf<F>[], \"array\">({ kind: \"array\", of: of.shape });\n },\n /**\n * A typed block: `{ type: \"<variant>\", value: <its shape> }`. The keys are\n * `type` and `value` unless `typeField` / `valueField` say otherwise.\n */\n oneOf<\n S extends Record<string, AnyJsonField>,\n const TypeField extends string = \"type\",\n const ValueField extends string = \"value\"\n >(\n variants: S,\n options: { typeField?: TypeField; valueField?: ValueField } = {}\n ): JsonField<JsonOneOfOf<S, TypeField, ValueField>, \"oneOf\"> {\n return new JsonField<JsonOneOfOf<S, TypeField, ValueField>, \"oneOf\">({\n kind: \"oneOf\",\n typeField: options.typeField ?? \"type\",\n valueField: options.valueField ?? \"value\",\n variants: shapesOf(variants)\n });\n },\n /** Anything. */\n unknown(): JsonField<unknown, \"unknown\"> {\n return new JsonField<unknown, \"unknown\">({ kind: \"unknown\" });\n }\n};\n\n/**\n * Whether a value is a JSON field builder, from this copy of the package or\n * another.\n *\n * @group Schema\n */\nexport function isJsonField(value: unknown): value is AnyJsonField {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === JSON_FIELD_BRAND;\n}\n\n/**\n * A JSON shape without its hooks: what the wire carries.\n *\n * @group Schema\n */\nexport function describeJsonShape(shape: JsonShapeDef): JsonShape {\n const { transform: _transform, ...rest } = shape;\n void _transform;\n switch (rest.kind) {\n case \"object\": {\n const fields: Record<string, JsonShape> = {};\n for (const [key, field] of Object.entries(rest.fields)) fields[key] = describeJsonShape(field);\n return { ...rest, fields };\n }\n case \"array\":\n return { ...rest, of: describeJsonShape(rest.of) };\n case \"oneOf\": {\n const variants: Record<string, JsonShape> = {};\n for (const [key, variant] of Object.entries(rest.variants)) variants[key] = describeJsonShape(variant);\n return { ...rest, variants };\n }\n default:\n return rest;\n }\n}\n","import type { ColumnKind, ColumnType, NumericColumnKind, TemporalColumnKind, TextColumnKind } from \"./column_type\";\nimport type {\n ArrayValidation,\n BaseValidation,\n ColumnAccess,\n ColumnDefault,\n ColumnStamp,\n ColumnStorage,\n ColumnValidation,\n DateValidation,\n NumberValidation,\n StorageOptions,\n StringValidation,\n ValidationInput,\n VectorIndexOptions\n} from \"./column_options\";\nimport { normalizeColumnAccess, normalizeStorage, normalizeValidation } from \"./column_options\";\nimport type { ColumnTransform } from \"./hooks\";\nimport type { JsonField, JsonGeoPoint, JsonKind, JsonShapeDef } from \"./json\";\n\n/**\n * Every Drizzle spelling Rebase refuses, with the instruction it shows.\n *\n * Each text is used twice: as a string-literal *type* placed where the\n * developer wrote the refused thing (a `this` parameter, a config key, an\n * argument), so TypeScript prints the instruction verbatim; and as the message\n * thrown at run time, for a JavaScript caller the types do not reach. See\n * `drizzle-alignment.md` for the table of Drizzle spellings.\n *\n * @group Schema\n */\nexport const DRIZZLE_REFUSALS = {\n /** `col.timestamp()` without `withTimezone: true`: Drizzle's timestamp WITHOUT time zone. */\n timestamp: \"Rebase stores instants as timestamptz: write `col.timestamp({ withTimezone: true })`. For a timestamp without time zone write `col.custom({ dataType: \\\"timestamp\\\" })`.\",\n /** `col.timestamp({ mode: \"date\" })`: Drizzle's Date-typed mode. */\n timestampMode: \"Rebase serves a timestamp as an ISO string: leave `mode` out or write `mode: \\\"string\\\"`.\",\n /** `col.timestamp({ precision })`. */\n timestampPrecision: \"Rebase does not state a timestamp's precision: leave `precision` out, or write `col.custom({ dataType: \\\"timestamp(3) with time zone\\\" })`.\",\n /** `col.date({ mode: \"date\" })`: Drizzle's Date-typed mode. */\n dateMode: \"Rebase serves a date as a `YYYY-MM-DD` string: leave `mode` out or write `mode: \\\"string\\\"`.\",\n /** `col.time({ withTimezone: true })`: a `timetz`. */\n timeZone: \"`col.time()` is a time without time zone: leave `withTimezone` out, or write `col.custom({ dataType: \\\"timetz\\\" })`.\",\n /** `col.time({ precision })`. */\n timePrecision: \"Rebase does not state a time's precision: leave `precision` out, or write `col.custom({ dataType: \\\"time(3)\\\" })`.\",\n /** `col.numeric({ mode: \"string\" | \"bigint\" })`: our value is a JSON number. */\n numericMode: \"Rebase reads and writes numeric as a JSON number: leave `mode` out or write `mode: \\\"number\\\"`. For exact decimals kept as text write `col.text()`.\",\n /** `col.bigint({ mode: \"bigint\" })`: our value is a JSON number. */\n bigintMode: \"Rebase serves bigint as a JSON number: write `{ mode: \\\"number\\\" }`. For exact 64-bit values write `col.numeric()` or `col.text()`.\",\n /** `col.varchar(\"name\")` / `col.varchar({ enum })` without a length. */\n varcharLength: \"`col.varchar()` needs a length (a bare varchar is unbounded in Postgres and Drizzle): write `col.varchar({ length: 255 })`, or `col.text()` for text of any length.\",\n /** `col.char(\"name\")` / `col.char({ enum })` without a length. */\n charLength: \"`col.char()` needs a length (a bare char is char(1) in Postgres and Drizzle): write `col.char({ length: 2 })`.\",\n /** `.generatedAlwaysAsIdentity()`: the planner creates BY DEFAULT identities only. */\n identityAlways: \"Rebase creates identity columns GENERATED BY DEFAULT: write `.generatedByDefaultAsIdentity()`.\",\n /** `.generatedByDefaultAsIdentity({ … })`: sequence options. */\n identityOptions: \"Rebase does not take sequence options: write `.generatedByDefaultAsIdentity()` with no argument.\",\n /** `.references(() => …)`: a foreign key is a `rel.belongsTo`. */\n references: \"A foreign key is a relation in Rebase: write `relations: { author: rel.belongsTo(() => users, { localKey: \\\"author_id\\\", onDelete: \\\"cascade\\\" }) }`. The relation's key is what `include` names.\",\n /** `.$defaultFn()` / `.$default()`: a run-time default function. */\n defaultFn: \"Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`…`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`.\",\n /** `.$onUpdate()` / `.$onUpdateFn()`: a run-time update function. */\n onUpdateFn: \"Rebase's schema is data, not code: write `.onUpdateNow()` for the time, `.onUpdateUser()` for the caller; anything else belongs in `hooks.beforeSave`.\",\n /** `.unique(name, { nulls })`: a named or NULLS NOT DISTINCT constraint. */\n uniqueName: \"Rebase derives constraint names and keeps NULLs distinct: write `.unique()`, or a unique index under `indexes`.\",\n /** `.generatedAlwaysAs(value)` with something other than a `sql` expression. */\n generatedValue: \"`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`…`)`.\",\n /** `.array(size)`. */\n arraySize: \"Postgres ignores array sizes: write `.array()`.\",\n /** `.notNull()` & co. before `.array()`. */\n arrayOrder: \"`.notNull()`, a default, `.primaryKey()`, `.readOnly()` and `.private()` before `.array()` would describe each item: write them after it, as in `col.text().array().notNull()`.\",\n /** `.array().array()`. */\n arrayOfArray: \"An array of arrays is not supported: use `col.jsonb()` for nested lists.\",\n /** `sql` with an interpolation. */\n sqlInterpolation: \"`sql` writes its text into the DDL verbatim: write the expression inline, without `${…}`.\",\n /** `col.bigint()` / `col.bigserial()` without `{ mode }`. */\n bigintModeMissing: \"`col.bigint()` and `col.bigserial()` take Drizzle's `{ mode: \\\"number\\\" }`: write `col.bigint({ mode: \\\"number\\\" })`.\",\n /** `col.numeric(10, 2)`: positional precision and scale. */\n numericPositional: \"`col.numeric()` takes a config object: write `col.numeric({ precision: 10, scale: 2 })`.\",\n /** `col.vector(1536)`: positional dimensions. */\n vectorPositional: \"`col.vector()` takes a config object: write `col.vector({ dimensions: 1536 })`.\",\n /** `col.enum(values, { name })`: a named enum type. */\n enumName: \"A named Postgres enum type is declared once with `pgEnum`: write `const postStatus = pgEnum(\\\"post_status\\\", [...])`, then `postStatus()` in the column.\",\n /** `col.custom(\"inet\")`: a lone string is the SQL column name. */\n customDataType: \"`col.custom()` names its Postgres type in a config object: write `col.custom({ dataType: \\\"inet\\\" })`, or `col.custom(\\\"ip\\\", { dataType: \\\"inet\\\" })` with a SQL column name.\",\n /** `pgEnum(name, { A: \"a\" })`: Drizzle's object form. */\n pgEnumObject: \"`pgEnum(name, values)` takes the list of labels: write `pgEnum(\\\"post_status\\\", [\\\"draft\\\", \\\"published\\\"])`.\"\n} as const;\n\ntype Refusal = typeof DRIZZLE_REFUSALS;\n\n/** The message of a Drizzle column type Rebase names only through `col.custom()`. */\ntype UnsupportedType<T extends string> =\n `Rebase has no \\`col.${T}()\\`: write \\`col.custom({ dataType: \"${T}\" })\\`. The value passes through as the driver returns it (a string).`;\n\nfunction unsupportedMessage<T extends string>(type: T): UnsupportedType<T> {\n return `Rebase has no \\`col.${type}()\\`: write \\`col.custom({ dataType: \"${type}\" })\\`. The value passes through as the driver returns it (a string).`;\n}\n\n/** The brand of a {@link sql} expression. */\nexport const SQL_BRAND = \"rebase.sql\";\n\n/**\n * A SQL expression written with the {@link sql} tag: `sql\\`now()\\``.\n *\n * @group Schema\n */\nexport interface SqlTemplate {\n /** Marks a value as written with the {@link sql} tag. */\n readonly brand: typeof SQL_BRAND;\n /** The expression, exactly as written between the backticks. */\n readonly text: string;\n}\n\n/**\n * A SQL expression for a default or a generated column, as Drizzle writes it:\n * `.default(sql\\`gen_short_id()\\`)`, `.generatedAlwaysAs(sql\\`lower(email)\\`)`.\n *\n * The text goes into the DDL verbatim, so it takes no interpolation: write the\n * expression inline.\n *\n * @group Schema\n */\nexport function sql(strings: TemplateStringsArray, ...values: Refusal[\"sqlInterpolation\"][]): SqlTemplate {\n if (values.length > 0 || strings.length !== 1) throw new Error(DRIZZLE_REFUSALS.sqlInterpolation);\n const text = strings[0] ?? strings.raw[0];\n if (text.trim().length === 0) throw new Error(\"`sql``` is empty: write the expression, e.g. sql`now()`.\");\n return { brand: SQL_BRAND, text };\n}\n\n/**\n * Whether a value is a {@link sql} expression, from this copy of the package or another.\n *\n * @group Schema\n */\nexport function isSqlTemplate(value: unknown): value is SqlTemplate {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === SQL_BRAND &&\n \"text\" in value && typeof value.text === \"string\";\n}\n\n/**\n * Everything a column builder has been told, as data.\n *\n * Wire-safe except for `transform` and the hooks inside `json`, which stay on\n * the server.\n *\n * @group Schema\n */\nexport interface ColumnDef {\n /** The Postgres type. */\n type: ColumnType;\n /** The SQL column name, when it is not the snake_case of the key. */\n column?: string;\n notNull: boolean;\n primaryKey: boolean;\n unique: boolean;\n default?: ColumnDefault;\n /** `GENERATED ALWAYS AS (<expression>) STORED`. */\n generatedAs?: string;\n readOnly: boolean;\n private: boolean;\n access?: ColumnAccess;\n stamp?: ColumnStamp;\n validate?: ColumnValidation;\n oneOf?: readonly (string | number)[];\n description?: string;\n storage?: ColumnStorage;\n /**\n * A meaning the Postgres type does not state: `\"geopoint\"` (`col.geopoint()`,\n * a `jsonb` point) or `\"user\"` (`.userId()`, a text or uuid column holding a\n * user's id).\n */\n semantic?: \"geopoint\" | \"user\";\n vectorIndex?: VectorIndexOptions | false;\n /** The shape of a `json`/`jsonb` document. */\n json?: JsonShapeDef;\n /** For an array column: the definition of each item. */\n element?: ColumnDef;\n /** Field-level hooks. Server only. */\n transform?: ColumnTransform;\n}\n\n/**\n * The type-level tag of a builder. A {@link ColumnKind}, or one of the two\n * builders whose meaning the Postgres type alone does not state.\n */\nexport type BuilderKind = ColumnKind | \"storage\" | \"geopoint\";\n\n/**\n * What the type system tracks about a column besides its data type.\n *\n * @group Schema\n */\nexport interface ColumnFlags {\n /** `NOT NULL`: never `null` on a row, required on create unless it has a default. */\n notNull: boolean;\n /** A create may omit it. */\n hasDefault: boolean;\n /** Clients may write it. */\n writable: boolean;\n /** It is served on the wire. */\n exposed: boolean;\n /** Part of the primary key. */\n primaryKey: boolean;\n}\n\n/** The flags of a column no modifier has touched: nullable, required-by-nobody, writable, served. */\nexport interface InitialColumnFlags extends ColumnFlags {\n notNull: false;\n hasDefault: false;\n writable: true;\n exposed: true;\n primaryKey: false;\n}\n\n/**\n * The value a column's `.transform()` hooks receive and return: the column's\n * type, plus `null` while the column is nullable.\n *\n * Read from the flags at the point `.transform()` is called, so the order of\n * the chain matters: `.notNull().transform(…)` (or `.primaryKey()` first)\n * receives `TData`; `.transform(…).notNull()` was typed before the column\n * became `NOT NULL` and keeps receiving `TData | null`. Write `.notNull()`\n * first.\n *\n * @group Schema\n */\nexport type ColumnTransformValue<TData, F extends ColumnFlags> = F[\"notNull\"] extends true ? TData : TData | null;\n\ntype SetFlag<F extends ColumnFlags, K extends keyof ColumnFlags, V extends boolean> = {\n [P in keyof ColumnFlags]: P extends K ? V : F[P]\n};\n\ntype WithDefault<F extends ColumnFlags> = SetFlag<F, \"hasDefault\", true>;\n\n/** The rules `.validate()` accepts for a kind of column. */\nexport type ValidationFor<K extends BuilderKind> =\n K extends TextColumnKind | \"storage\" ? StringValidation :\n K extends NumericColumnKind ? NumberValidation :\n K extends TemporalColumnKind ? DateValidation :\n K extends \"array\" ? ArrayValidation :\n BaseValidation;\n\n/** The value `.default()` accepts: what the column holds; a `Date` too, for a temporal column. */\nexport type DefaultValueFor<TData, K extends BuilderKind> = K extends TemporalColumnKind ? TData | Date : TData;\n\nconst STAMP_METHODS: Record<string, string> = {\n \"create:now\": \".onCreateNow\",\n \"update:now\": \".onUpdateNow\",\n \"create:user\": \".onCreateUser\",\n \"update:user\": \".onUpdateUser\"\n};\n\n/** The brand every column builder carries, so one built by another copy of this package is still recognised. */\nexport const COLUMN_BRAND = \"rebase.column\";\n\nconst baseDef = (type: ColumnType): ColumnDef => ({\n type,\n notNull: false,\n primaryKey: false,\n unique: false,\n readOnly: false,\n private: false\n});\n\n/**\n * One column of a table: `col.text()`, `col.uuid().primaryKey()`, ….\n *\n * Immutable — every modifier returns a new builder — so a column can be shared\n * between tables. Columns are nullable until `.notNull()` or `.primaryKey()`\n * says otherwise, as in SQL.\n *\n * @typeParam TData The TypeScript type of a value on the wire.\n * @typeParam TKind Which builder made it; decides which modifiers apply.\n * @typeParam F What has been said about it so far.\n *\n * @group Schema\n */\nexport class ColumnBuilder<TData, TKind extends BuilderKind = BuilderKind, F extends ColumnFlags = InitialColumnFlags> {\n\n /** Type-level only: the TypeScript type of a value. */\n declare readonly $data: TData;\n /** Type-level only: the builder kind. */\n declare readonly $kind: TKind;\n /** Type-level only: the flags. */\n declare readonly $flags: F;\n\n readonly brand = COLUMN_BRAND;\n\n constructor(\n /** Everything this column has been told. */\n readonly def: ColumnDef\n ) {}\n\n private with<D, K extends BuilderKind, G extends ColumnFlags>(patch: Partial<ColumnDef>): ColumnBuilder<D, K, G> {\n return new ColumnBuilder<D, K, G>({ ...this.def, ...patch });\n }\n\n /**\n * The patch that sets a stamp, refusing a second, different one: a column\n * holds one stamp, so `.onCreateNow().onUpdateNow()` would otherwise keep\n * whichever came last without a word.\n */\n private stamped(stamp: ColumnStamp, method: string): Partial<ColumnDef> {\n const current = this.def.stamp;\n if (current && (current.on !== stamp.on || current.value !== stamp.value)) {\n throw new Error(\n `\\`.${method}()\\` on a column that already has \\`${STAMP_METHODS[`${current.on}:${current.value}`]}()\\`: a column ` +\n \"holds one stamp. `.onUpdateNow()` alone also stamps the row when it is created.\"\n );\n }\n return { stamp };\n }\n\n // ── Every column ─────────────────────────────────────────────────────\n\n /**\n * Types the value without changing the column, as Drizzle's `$type`:\n * `col.jsonb().$type<{ seoTitle?: string }>()`, `col.integer().$type<UserId>()`.\n * Nothing is checked at run time; use `col.jsonb(json.object({...}))` for\n * a shape the server enforces.\n */\n $type<T>(): ColumnBuilder<T, TKind, F> {\n return this.with<T, TKind, F>({});\n }\n\n /** `NOT NULL`. The API requires the column on create unless it has a default. */\n notNull(): ColumnBuilder<TData, TKind, SetFlag<F, \"notNull\", true>> {\n return this.with<TData, TKind, SetFlag<F, \"notNull\", true>>({ notNull: true });\n }\n\n /**\n * Part of the primary key. Several columns marked this way form a composite\n * key, in declaration order.\n */\n primaryKey(): ColumnBuilder<TData, TKind, SetFlag<SetFlag<F, \"notNull\", true>, \"primaryKey\", true>> {\n return this.with<TData, TKind, SetFlag<SetFlag<F, \"notNull\", true>, \"primaryKey\", true>>({\n primaryKey: true,\n notNull: true\n });\n }\n\n /**\n * A single-column `UNIQUE` constraint. Its name is derived; Drizzle's\n * `.unique(name, { nulls })` arguments are refused.\n */\n unique(name?: Refusal[\"uniqueName\"], config?: Refusal[\"uniqueName\"]): ColumnBuilder<TData, TKind, F> {\n if (name !== undefined || config !== undefined) throw new Error(DRIZZLE_REFUSALS.uniqueName);\n return this.with<TData, TKind, F>({ unique: true });\n }\n\n /**\n * A default: a value, written as the column's DDL default and applied by\n * the driver on create, so a row comes out the same whoever inserts it — or\n * an expression Postgres evaluates, `.default(sql\\`gen_short_id()\\`)`.\n */\n default(value: DefaultValueFor<TData, TKind> | SqlTemplate): ColumnBuilder<TData, TKind, WithDefault<F>> {\n if (isSqlTemplate(value)) {\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"sql\", expression: value.text } });\n }\n const stored = value instanceof Date ? value.toISOString() : value;\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"literal\", value: stored } });\n }\n\n /** Refused: Drizzle's run-time default function. See {@link DRIZZLE_REFUSALS}. */\n $defaultFn(this: Refusal[\"defaultFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.defaultFn);\n }\n\n /** Refused: Drizzle's alias of `$defaultFn`. See {@link DRIZZLE_REFUSALS}. */\n $default(this: Refusal[\"defaultFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.defaultFn);\n }\n\n /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */\n $onUpdate(this: Refusal[\"onUpdateFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.onUpdateFn);\n }\n\n /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */\n $onUpdateFn(this: Refusal[\"onUpdateFn\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.onUpdateFn);\n }\n\n /**\n * Refused: a foreign key is a relation, `rel.belongsTo(() => users, {...})`\n * under `relations`, whose key is what `include` names.\n */\n references(this: Refusal[\"references\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.references);\n }\n\n /**\n * The database already holds a default for this column that Rebase does not\n * state. A create may omit the column, and a schema push leaves the default\n * alone.\n */\n dbDefault(): ColumnBuilder<TData, TKind, WithDefault<F>> {\n return this.with<TData, TKind, WithDefault<F>>({ default: { kind: \"database\" } });\n }\n\n /**\n * `GENERATED ALWAYS AS (<expression>) STORED`, as Drizzle writes it:\n * `.generatedAlwaysAs(sql\\`lower(email)\\`)`. Nobody writes the column.\n */\n generatedAlwaysAs(as: SqlTemplate | (() => SqlTemplate)): ColumnBuilder<TData, TKind, SetFlag<WithDefault<F>, \"writable\", false>> {\n const expression: unknown = typeof as === \"function\" ? as() : as;\n if (!isSqlTemplate(expression)) throw new Error(DRIZZLE_REFUSALS.generatedValue);\n return this.with<TData, TKind, SetFlag<WithDefault<F>, \"writable\", false>>({\n generatedAs: expression.text,\n readOnly: true\n });\n }\n\n /**\n * Client writes are refused on create and update. The database (a default,\n * a trigger) and the server's own code still fill it.\n */\n readOnly(): ColumnBuilder<TData, TKind, SetFlag<F, \"writable\", false>> {\n return this.with<TData, TKind, SetFlag<F, \"writable\", false>>({ readOnly: true });\n }\n\n /**\n * Never leaves the server: absent from every row on the wire, from the SDK\n * and from OpenAPI, and refused in filters and sorts. Hooks and server code\n * still see it.\n */\n private(): ColumnBuilder<TData, TKind, SetFlag<SetFlag<F, \"exposed\", false>, \"writable\", false>> {\n return this.with<TData, TKind, SetFlag<SetFlag<F, \"exposed\", false>, \"writable\", false>>({ private: true });\n }\n\n /**\n * Who may read and who may write the column, by role. Enforced on every\n * door into the table, not only in the panel. `read` and `write` are lists\n * of role names; anything else throws.\n */\n access(access: ColumnAccess): ColumnBuilder<TData, TKind, F> {\n return this.with<TData, TKind, F>({ access: normalizeColumnAccess(access, \"a column (`.access()`)\") });\n }\n\n /** What the column holds, for OpenAPI and MCP tool descriptions. */\n describe(description: string): ColumnBuilder<TData, TKind, F> {\n return this.with<TData, TKind, F>({ description });\n }\n\n /** Rules the API checks before a write. */\n validate(rules: ValidationFor<TKind>): ColumnBuilder<TData, TKind, F> {\n const input: ValidationInput = rules;\n return this.with<TData, TKind, F>({ validate: { ...this.def.validate, ...normalizeValidation(input) } });\n }\n\n /**\n * Field-level hooks: `beforeSave` returns the value to store, `afterRead`\n * the value to serve. They run on the server, for every caller.\n *\n * The value is `TData | null` on a column not (yet) marked `.notNull()` /\n * `.primaryKey()` — a nullable column hands the hook `null` — and `TData`\n * on one that is; see {@link ColumnTransformValue}. Chain `.notNull()`\n * before `.transform()` to get the narrower type.\n */\n transform(transform: ColumnTransform<ColumnTransformValue<TData, F>>): ColumnBuilder<TData, TKind, F> {\n const erased: ColumnTransform = transform;\n return this.with<TData, TKind, F>({ transform: erased });\n }\n\n // ── Text and numbers ─────────────────────────────────────────────────\n\n /**\n * A closed set of accepted values that is *not* a Postgres enum type: the\n * API refuses anything else and the SDK types the column as their union.\n * Use `col.enum()` when the database should enforce it too.\n *\n * On a number column. On a text column write Drizzle's spelling,\n * `col.text({ enum: [...] })`.\n */\n oneOf<const V extends readonly TData[], K extends TextColumnKind | NumericColumnKind>(\n this: ColumnBuilder<TData, K, F>,\n values: V\n ): ColumnBuilder<V[number], K, F> {\n const stored: (string | number)[] = [];\n for (const value of values) {\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n throw new Error(\"`.oneOf()` takes strings or numbers.\");\n }\n stored.push(value);\n }\n return this.with<V[number], K, F>({ oneOf: stored });\n }\n\n // ── uuid ─────────────────────────────────────────────────────────────\n\n /** `DEFAULT gen_random_uuid()`. */\n defaultRandom(this: ColumnBuilder<string, \"uuid\", F>): ColumnBuilder<string, \"uuid\", WithDefault<F>> {\n return this.with<string, \"uuid\", WithDefault<F>>({ default: { kind: \"random-uuid\" } });\n }\n\n // ── Integers ─────────────────────────────────────────────────────────\n\n /** `GENERATED BY DEFAULT AS IDENTITY`. Sequence options are refused. */\n generatedByDefaultAsIdentity<K extends \"smallint\" | \"integer\" | \"bigint\">(\n this: ColumnBuilder<number, K, F>,\n sequence?: Refusal[\"identityOptions\"]\n ): ColumnBuilder<number, K, WithDefault<F>> {\n if (sequence !== undefined) throw new Error(DRIZZLE_REFUSALS.identityOptions);\n return this.with<number, K, WithDefault<F>>({ default: { kind: \"identity\" } });\n }\n\n /** Refused: Rebase creates identity columns `GENERATED BY DEFAULT`. See {@link DRIZZLE_REFUSALS}. */\n generatedAlwaysAsIdentity(this: Refusal[\"identityAlways\"], ..._args: unknown[]): never {\n throw new Error(DRIZZLE_REFUSALS.identityAlways);\n }\n\n // ── Arrays ───────────────────────────────────────────────────────────\n\n /**\n * A Postgres array of this column's type, as Drizzle writes it:\n * `col.text().array()` is `TEXT[]`. What is chained before `.array()`\n * describes each item (`col.text({ enum: [...] }).array()`,\n * `col.integer().validate({ min: 0 }).array()`); column modifiers come\n * after it (`.array().notNull().default([])`). A leading SQL name\n * (`col.text(\"tag_list\").array()`) names the array column.\n */\n array(\n this: F extends InitialColumnFlags\n ? TKind extends \"array\" ? Refusal[\"arrayOfArray\"] : ColumnBuilder<TData, TKind, F>\n : Refusal[\"arrayOrder\"],\n size?: Refusal[\"arraySize\"]\n ): ColumnBuilder<TData[], \"array\"> {\n if (size !== undefined) throw new Error(DRIZZLE_REFUSALS.arraySize);\n if (!isColumnBuilder(this)) throw new Error(\"`.array()` is called on a column builder.\");\n const { column, ...item } = this.def;\n if (item.notNull || item.primaryKey || item.default !== undefined || item.readOnly || item.private) {\n throw new Error(DRIZZLE_REFUSALS.arrayOrder);\n }\n const def = arrayDef(item);\n if (column !== undefined) def.column = column;\n return new ColumnBuilder<TData[], \"array\">(def);\n }\n\n // ── Temporal ─────────────────────────────────────────────────────────\n\n /**\n * `DEFAULT now()`, as Drizzle's `defaultNow()`: a DDL default a client may\n * still override. `.onCreateNow()` is the server stamp the client cannot.\n */\n defaultNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>({ default: { kind: \"sql\", expression: \"now()\" } });\n }\n\n /** The server stamps the current time when the row is created (`DEFAULT now()`). */\n onCreateNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"create\", value: \"now\" }, \"onCreateNow\"));\n }\n\n /**\n * The server stamps the current time on every write: `DEFAULT now()`, a\n * `BEFORE UPDATE` trigger, and the driver's own stamp.\n */\n onUpdateNow<K extends TemporalColumnKind>(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"update\", value: \"now\" }, \"onUpdateNow\"));\n }\n\n // ── Acting user ──────────────────────────────────────────────────────\n\n /** The server writes the caller's id when the row is created. */\n onCreateUser<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"create\", value: \"user\" }, \"onCreateUser\"));\n }\n\n /** The server writes the caller's id on every write. */\n onUpdateUser<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, WithDefault<F>> {\n return this.with<string, K, WithDefault<F>>(this.stamped({ on: \"update\", value: \"user\" }, \"onUpdateUser\"));\n }\n\n /**\n * The column holds the id of a user. The panel offers a user picker for it,\n * and callers who may write the table may look users up to fill it (the\n * user picker's read answers them even though row-level security hides\n * other users' rows).\n *\n * Only on `col.text()`, `col.varchar()`, `col.char()` and `col.uuid()`;\n * anything else throws. It declares no foreign key: use\n * `rel.belongsTo(() => users)` when the database should enforce one.\n */\n userId<K extends TextColumnKind | \"uuid\">(\n this: ColumnBuilder<string, K, F>\n ): ColumnBuilder<string, K, F> {\n const kind = this.def.type.kind;\n if ((kind !== \"text\" && kind !== \"varchar\" && kind !== \"char\" && kind !== \"uuid\") || this.def.storage !== undefined) {\n const what = this.def.storage !== undefined ? \"`col.storage()`\" : `a \\`${kind}\\` column`;\n throw new Error(\n `\\`.userId()\\` on ${what}: a user's id is held by \\`col.text()\\`, \\`col.varchar()\\`, \\`col.char()\\` or \\`col.uuid()\\`.`\n );\n }\n return this.with<string, K, F>({ semantic: \"user\" });\n }\n\n // ── Storage ──────────────────────────────────────────────────────────\n\n /** The column holds several files: `TEXT[]` of paths. */\n multiple(this: ColumnBuilder<string, \"storage\", F>): ColumnBuilder<string[], \"array\", F> {\n const { storage, validate, ...rest } = this.def;\n return new ColumnBuilder<string[], \"array\", F>({\n ...rest,\n type: { kind: \"array\", of: { kind: \"text\" } },\n storage,\n element: { ...baseDef({ kind: \"text\" }), storage, validate }\n });\n }\n}\n\n/** Any column, whatever it holds. */\nexport type AnyColumn = ColumnBuilder<unknown, BuilderKind, ColumnFlags>;\n\n/**\n * The `columns` of a table: builders by key, in physical order.\n *\n * @group Schema\n */\nexport type ColumnsShape = Record<string, AnyColumn>;\n\n/** The SQL column name a builder's leading argument gives, checked. */\nfunction sqlName(name: string | undefined, builder: string): string | undefined {\n if (name === undefined) return undefined;\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(`\\`col.${builder}(name, …)\\`: the leading argument is the SQL column name, a non-empty string.`);\n }\n return name;\n}\n\n/** A fresh definition, named by the builder's leading argument when it has one. */\nfunction namedDef(type: ColumnType, name: string | undefined, builder: string): ColumnDef {\n const def = baseDef(type);\n const column = sqlName(name, builder);\n if (column !== undefined) def.column = column;\n return def;\n}\n\n/** Drizzle's `(name?, config?)` arguments, either of which may be left out. */\nfunction nameAndConfig<C>(first: string | C | undefined, second: C | undefined): [string | undefined, C | undefined] {\n return typeof first === \"string\" ? [first, second] : [undefined, first];\n}\n\n/** A config object, checked at run time: JavaScript callers bypass the types. */\nfunction configOf(value: unknown, builder: string): Record<string, unknown> {\n if (value === undefined) return {};\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`\\`col.${builder}()\\` takes an optional SQL column name and a config object, got ${JSON.stringify(value)}.`);\n }\n return { ...value };\n}\n\n/** The definition of an array of `item`: what `col.text().array()` builds. */\nfunction arrayDef(item: ColumnDef): ColumnDef {\n if (item.type.kind === \"array\") throw new Error(DRIZZLE_REFUSALS.arrayOfArray);\n const def = baseDef({ kind: \"array\", of: item.type });\n def.element = item;\n if (item.storage) def.storage = item.storage;\n return def;\n}\n\n/** A list of string labels: an enum's values, Drizzle's `{ enum: [...] }`. */\nfunction labelsOf(values: unknown, where: string): string[] {\n if (!Array.isArray(values) || values.length === 0 || values.some(value => typeof value !== \"string\")) {\n throw new Error(`${where} takes a non-empty list of strings, got ${JSON.stringify(values)}.`);\n }\n return values.filter((value): value is string => typeof value === \"string\");\n}\n\n/** A non-empty list of string labels, as a type. */\ntype Labels = readonly [string, ...string[]];\n\n/** What `col.text()` takes besides the name: Drizzle's `{ enum }`, a closed set of values. */\nexport interface TextConfig<E extends Labels = Labels> {\n /** The values the API accepts; the SDK types the column as their union. A Postgres enum type is `pgEnum`. */\n enum: E;\n}\n\n/** What `col.varchar()` / `col.char()` take besides the name. */\nexport interface StringConfig<E extends Labels = Labels> {\n /** The length in characters. Required: a bare varchar is unbounded and a bare char is char(1). */\n length: number;\n /** The values the API accepts, as `col.text({ enum })`. */\n enum?: E;\n}\n\n/** What `col.numeric()` takes besides the name. */\nexport interface NumericConfig {\n /** Total number of digits. */\n precision?: number;\n /** Digits after the decimal point. Needs a precision. */\n scale?: number;\n /** The value is a JSON number. Drizzle's `\"string\"` and `\"bigint\"` modes are refused. */\n mode?: \"number\" | Refusal[\"numericMode\"];\n}\n\n/** What `col.bigint()` / `col.bigserial()` take besides the name. */\nexport interface BigintConfig {\n /** `\"number\"`: the value is a JSON number. Drizzle's `\"bigint\"` mode is refused. */\n mode: \"number\" | Refusal[\"bigintMode\"];\n}\n\n/** What `col.timestamp()` takes besides the name. */\nexport interface TimestampConfig {\n /** `true`: the column is `TIMESTAMPTZ`, the only timestamp Rebase creates. */\n withTimezone: true;\n /** `\"string\"`: an ISO string on the wire, which it always is. */\n mode?: \"string\" | Refusal[\"timestampMode\"];\n /** Refused: Rebase does not state a timestamp's precision. */\n precision?: Refusal[\"timestampPrecision\"];\n}\n\n/** What `col.date()` takes besides the name. */\nexport interface DateConfig {\n /** `\"string\"`: `YYYY-MM-DD` on the wire, which it always is. */\n mode?: \"string\" | Refusal[\"dateMode\"];\n}\n\n/** What `col.time()` takes besides the name. */\nexport interface TimeConfig {\n /** `false` or omitted: `col.time()` is a time without time zone. */\n withTimezone?: false | Refusal[\"timeZone\"];\n /** Refused: Rebase does not state a time's precision. */\n precision?: Refusal[\"timePrecision\"];\n}\n\n/** What `col.vector()` takes besides the name. */\nexport interface VectorConfig {\n /** The number of dimensions. */\n dimensions: number;\n /** The approximate-nearest-neighbour index: HNSW cosine when omitted, none with `false`. */\n index?: VectorIndexOptions | false;\n}\n\n/** What `col.custom()` takes besides the name. */\nexport interface CustomConfig {\n /** The Postgres type, verbatim: `\"inet\"`, `\"citext\"`, `\"geometry(Point, 4326)\"`. */\n dataType: string;\n}\n\nconst checkMode = (value: unknown, allowed: string, message: string): void => {\n if (value !== undefined && value !== allowed) throw new Error(message);\n};\n\nfunction jsonColumn<T, K extends \"json\" | \"jsonb\">(kind: K, first: string | JsonField<T, JsonKind, boolean> | undefined, second: JsonField<T, JsonKind, boolean> | undefined): ColumnBuilder<T, K> {\n const [name, shape] = nameAndConfig(first, second);\n const def = namedDef({ kind }, name, kind);\n if (shape) def.json = shape.shape;\n return new ColumnBuilder<T, K>(def);\n}\n\nfunction jsonb(name?: string): ColumnBuilder<unknown, \"jsonb\">;\nfunction jsonb<T>(shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\">;\nfunction jsonb<T>(name: string, shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\">;\nfunction jsonb<T>(first?: string | JsonField<T, JsonKind, boolean>, second?: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"jsonb\"> {\n return jsonColumn<T, \"jsonb\">(\"jsonb\", first, second);\n}\n\nfunction json(name?: string): ColumnBuilder<unknown, \"json\">;\nfunction json<T>(shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\">;\nfunction json<T>(name: string, shape: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\">;\nfunction json<T>(first?: string | JsonField<T, JsonKind, boolean>, second?: JsonField<T, JsonKind, boolean>): ColumnBuilder<T, \"json\"> {\n return jsonColumn<T, \"json\">(\"json\", first, second);\n}\n\nconst lengthOf = (length: unknown, builder: string): number => {\n if (typeof length !== \"number\" || !Number.isInteger(length) || length <= 0) {\n throw new Error(`\\`col.${builder}({ length })\\` takes a positive whole number of characters, got ${String(length)}.`);\n }\n return length;\n};\n\nfunction text(name?: string): ColumnBuilder<string, \"text\">;\nfunction text<const E extends Labels>(config: TextConfig<E>): ColumnBuilder<E[number], \"text\">;\nfunction text<const E extends Labels>(name: string, config: TextConfig<E>): ColumnBuilder<E[number], \"text\">;\nfunction text(first?: string | TextConfig, second?: TextConfig): ColumnBuilder<string, \"text\"> {\n const [name, rawConfig] = nameAndConfig(first, second);\n const config = configOf(rawConfig, \"text\");\n const def = namedDef({ kind: \"text\" }, name, \"text\");\n if (config.enum !== undefined) def.oneOf = labelsOf(config.enum, \"`col.text({ enum })`\");\n return new ColumnBuilder<string, \"text\">(def);\n}\n\n/** `varchar` / `char`: Drizzle's `(name?, { length, enum? })`. A length is required. */\nfunction stringColumn<K extends \"varchar\" | \"char\">(kind: K, first: unknown, second: unknown): ColumnBuilder<string, K> {\n const name = typeof first === \"string\" ? first : undefined;\n const raw = typeof first === \"string\" ? second : first;\n if (raw === undefined || typeof raw === \"number\") throw new Error(kind === \"varchar\" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);\n const config = configOf(raw, kind);\n if (config.length === undefined) throw new Error(kind === \"varchar\" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);\n const length = lengthOf(config.length, kind);\n const def = namedDef(kind === \"varchar\" ? { kind: \"varchar\", length } : { kind: \"char\", length }, name, kind);\n if (config.enum !== undefined) def.oneOf = labelsOf(config.enum, `\\`col.${kind}({ enum })\\``);\n return new ColumnBuilder<string, K>(def);\n}\n\nfunction varchar(config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"varchar\">;\nfunction varchar<const E extends Labels>(config: StringConfig<E> & object): ColumnBuilder<E[number], \"varchar\">;\nfunction varchar(name: string, config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"varchar\">;\nfunction varchar<const E extends Labels>(name: string, config: StringConfig<E> & object): ColumnBuilder<E[number], \"varchar\">;\nfunction varchar(this: Refusal[\"varcharLength\"], ...rest: unknown[]): never;\nfunction varchar(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"varchar\"> {\n return stringColumn(\"varchar\", first, second);\n}\n\nfunction char(config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"char\">;\nfunction char<const E extends Labels>(config: StringConfig<E> & object): ColumnBuilder<E[number], \"char\">;\nfunction char(name: string, config: StringConfig<Labels> & { enum?: undefined } & object): ColumnBuilder<string, \"char\">;\nfunction char<const E extends Labels>(name: string, config: StringConfig<E> & object): ColumnBuilder<E[number], \"char\">;\nfunction char(this: Refusal[\"charLength\"], ...rest: unknown[]): never;\nfunction char(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"char\"> {\n return stringColumn(\"char\", first, second);\n}\n\nfunction enumColumn<const V extends Labels>(values: V): ColumnBuilder<V[number], \"enum\">;\nfunction enumColumn<const V extends Labels>(name: string, values: V): ColumnBuilder<V[number], \"enum\">;\nfunction enumColumn(this: Refusal[\"enumName\"], values: Labels, options: Readonly<Record<string, unknown>>): never;\nfunction enumColumn(this: unknown, first: string | Labels, second?: unknown): ColumnBuilder<string, \"enum\"> {\n if (typeof first === \"string\") {\n const values = labelsOf(second, \"`col.enum(name, values)`\");\n return new ColumnBuilder<string, \"enum\">(namedDef({ kind: \"enum\", values }, first, \"enum\"));\n }\n if (second !== undefined) throw new Error(DRIZZLE_REFUSALS.enumName);\n if (first.length === 0) throw new Error(\"`col.enum([...])` needs at least one value.\");\n return new ColumnBuilder<string, \"enum\">(baseDef({ kind: \"enum\", values: [...first] }));\n}\n\n/** `numeric`, Drizzle's `(name?, { precision, scale, mode })`. */\nfunction numericColumn(builder: string, first: unknown, second: unknown): ColumnBuilder<number, \"numeric\"> {\n if (typeof first === \"number\" || typeof second === \"number\") throw new Error(DRIZZLE_REFUSALS.numericPositional);\n const name = typeof first === \"string\" ? first : undefined;\n const config = configOf(typeof first === \"string\" ? second : first, builder);\n checkMode(config.mode, \"number\", DRIZZLE_REFUSALS.numericMode);\n const precision: unknown = config.precision;\n const scale: unknown = config.scale;\n if (scale !== undefined && precision === undefined) {\n throw new Error(`\\`col.${builder}({ precision, scale })\\`: a scale needs a precision.`);\n }\n for (const [what, value] of [[\"precision\", precision], [\"scale\", scale]] as const) {\n if (value !== undefined && (typeof value !== \"number\" || !Number.isInteger(value) || value < 0)) {\n throw new Error(`\\`col.${builder}()\\`: \\`${what}\\` is a whole number, got ${String(value)}.`);\n }\n }\n const type: ColumnType = typeof precision !== \"number\"\n ? { kind: \"numeric\" }\n : typeof scale !== \"number\" ? { kind: \"numeric\", precision } : { kind: \"numeric\", precision, scale };\n return new ColumnBuilder<number, \"numeric\">(namedDef(type, name, builder));\n}\n\nfunction numeric(name?: string, config?: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction numeric(config: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction numeric(this: Refusal[\"numericPositional\"], precision: number, scale?: number): never;\nfunction numeric(this: unknown, first?: string | number | NumericConfig, second?: number | NumericConfig): ColumnBuilder<number, \"numeric\"> {\n return numericColumn(\"numeric\", first, second);\n}\n\nfunction decimal(name?: string, config?: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction decimal(config: NumericConfig): ColumnBuilder<number, \"numeric\">;\nfunction decimal(first?: string | NumericConfig, second?: NumericConfig): ColumnBuilder<number, \"numeric\"> {\n return numericColumn(\"decimal\", first, second);\n}\n\n/** `bigint` / `bigserial`, Drizzle's `(name?, { mode })`. */\nfunction bigColumn<K extends \"bigint\" | \"bigserial\">(kind: K, first: unknown, second: unknown): ColumnBuilder<number, K> {\n const name = typeof first === \"string\" ? first : undefined;\n const raw = typeof first === \"string\" ? second : first;\n if (raw === undefined) throw new Error(DRIZZLE_REFUSALS.bigintModeMissing);\n checkMode(configOf(raw, kind).mode, \"number\", DRIZZLE_REFUSALS.bigintMode);\n return new ColumnBuilder<number, K>(namedDef(kind === \"bigint\" ? { kind: \"bigint\" } : { kind: \"bigserial\" }, name, kind));\n}\n\nfunction bigint(config: BigintConfig): ColumnBuilder<number, \"bigint\">;\nfunction bigint(name: string, config: BigintConfig): ColumnBuilder<number, \"bigint\">;\nfunction bigint(this: Refusal[\"bigintModeMissing\"], ...rest: unknown[]): never;\nfunction bigint(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<number, \"bigint\"> {\n return bigColumn(\"bigint\", first, second);\n}\n\nfunction bigserial(config: BigintConfig): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>;\nfunction bigserial(name: string, config: BigintConfig): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>;\nfunction bigserial(this: Refusal[\"bigintModeMissing\"], ...rest: unknown[]): never;\nfunction bigserial(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"bigserial\", WithDefault<InitialColumnFlags>>(bigColumn(\"bigserial\", first, second).def);\n}\n\nfunction timestamp(config: TimestampConfig): ColumnBuilder<string, \"timestamptz\">;\nfunction timestamp(name: string, config: TimestampConfig): ColumnBuilder<string, \"timestamptz\">;\nfunction timestamp(this: Refusal[\"timestamp\"], ...rest: unknown[]): never;\nfunction timestamp(this: unknown, first?: unknown, second?: unknown): ColumnBuilder<string, \"timestamptz\"> {\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"timestamp\");\n if (config.withTimezone !== true) throw new Error(DRIZZLE_REFUSALS.timestamp);\n checkMode(config.mode, \"string\", DRIZZLE_REFUSALS.timestampMode);\n if (config.precision !== undefined) throw new Error(DRIZZLE_REFUSALS.timestampPrecision);\n return new ColumnBuilder<string, \"timestamptz\">(namedDef({ kind: \"timestamptz\" }, name, \"timestamp\"));\n}\n\nfunction date(name?: string, config?: DateConfig): ColumnBuilder<string, \"date\">;\nfunction date(config: DateConfig): ColumnBuilder<string, \"date\">;\nfunction date(first?: string | DateConfig, second?: DateConfig): ColumnBuilder<string, \"date\"> {\n const [name, raw] = nameAndConfig(first, second);\n checkMode(configOf(raw, \"date\").mode, \"string\", DRIZZLE_REFUSALS.dateMode);\n return new ColumnBuilder<string, \"date\">(namedDef({ kind: \"date\" }, name, \"date\"));\n}\n\nfunction time(name?: string, config?: TimeConfig): ColumnBuilder<string, \"time\">;\nfunction time(config: TimeConfig): ColumnBuilder<string, \"time\">;\nfunction time(first?: string | TimeConfig, second?: TimeConfig): ColumnBuilder<string, \"time\"> {\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"time\");\n if (config.withTimezone !== undefined && config.withTimezone !== false) throw new Error(DRIZZLE_REFUSALS.timeZone);\n if (config.precision !== undefined) throw new Error(DRIZZLE_REFUSALS.timePrecision);\n return new ColumnBuilder<string, \"time\">(namedDef({ kind: \"time\" }, name, \"time\"));\n}\n\nfunction vector(config: VectorConfig): ColumnBuilder<number[], \"vector\">;\nfunction vector(name: string, config: VectorConfig): ColumnBuilder<number[], \"vector\">;\nfunction vector(this: Refusal[\"vectorPositional\"], dimensions: number, ...rest: unknown[]): never;\nfunction vector(this: unknown, first: unknown, second?: unknown): ColumnBuilder<number[], \"vector\"> {\n if (typeof first === \"number\") throw new Error(DRIZZLE_REFUSALS.vectorPositional);\n const name = typeof first === \"string\" ? first : undefined;\n const config = configOf(typeof first === \"string\" ? second : first, \"vector\");\n const dimensions: unknown = config.dimensions;\n const index: unknown = config.index;\n if (typeof dimensions !== \"number\" || !Number.isInteger(dimensions) || dimensions <= 0) {\n throw new Error(`\\`col.vector({ dimensions })\\` takes a positive whole number, got ${String(dimensions)}.`);\n }\n const def = namedDef({ kind: \"vector\", dimensions }, name, \"vector\");\n if (index === false) def.vectorIndex = false;\n else if (typeof index === \"object\" && index !== null) def.vectorIndex = { ...index };\n else if (index !== undefined) throw new Error(\"`col.vector({ index })` takes index options or `false`.\");\n return new ColumnBuilder<number[], \"vector\">(def);\n}\n\nfunction storage(options: StorageOptions): ColumnBuilder<string, \"storage\">;\nfunction storage(name: string, options: StorageOptions): ColumnBuilder<string, \"storage\">;\nfunction storage(first: string | StorageOptions, second?: StorageOptions): ColumnBuilder<string, \"storage\"> {\n const [name, options] = nameAndConfig(first, second);\n if (options === undefined) throw new Error(\"`col.storage()` takes its options: `col.storage({ path: \\\"posts/heroes/\\\" })`.\");\n const def = namedDef({ kind: \"text\" }, name, \"storage\");\n def.storage = normalizeStorage(options);\n return new ColumnBuilder<string, \"storage\">(def);\n}\n\nfunction custom<T = string>(config: CustomConfig): ColumnBuilder<T, \"other\">;\nfunction custom<T = string>(name: string, config: CustomConfig): ColumnBuilder<T, \"other\">;\nfunction custom(this: Refusal[\"customDataType\"], name: string): never;\nfunction custom<T = string>(this: unknown, first: string | CustomConfig, second?: CustomConfig): ColumnBuilder<T, \"other\"> {\n if (typeof first === \"string\" && second === undefined) throw new Error(DRIZZLE_REFUSALS.customDataType);\n const [name, raw] = nameAndConfig(first, second);\n const config = configOf(raw, \"custom\");\n if (typeof config.dataType !== \"string\") {\n throw new Error(\"`col.custom()` names its Postgres type: `col.custom({ dataType: \\\"inet\\\" })`.\");\n }\n return new ColumnBuilder<T, \"other\">(namedDef({ kind: \"other\", sqlType: customSqlType(config.dataType) }, name, \"custom\"));\n}\n\n/** A builder for a Drizzle column type Rebase serves only through `col.custom()`: refused with the spelling. */\nfunction unsupported<T extends string>(type: T): (this: UnsupportedType<T>, ..._args: unknown[]) => never {\n return () => {\n throw new Error(unsupportedMessage(type));\n };\n}\n\n/** A builder that takes only the optional SQL column name. */\nfunction simple<D, K extends ColumnKind>(kind: K & BuilderKind, type: ColumnType): (name?: string) => ColumnBuilder<D, K> {\n return (name?: string) => new ColumnBuilder<D, K>(namedDef(type, name, kind));\n}\n\n/**\n * The column builders, spelled as Drizzle's `pg-core` spells them: the\n * optional SQL column name first, then Drizzle's config object, then the\n * chain.\n *\n * ```ts\n * columns: {\n * id: col.uuid().primaryKey().defaultRandom(),\n * title: col.text().notNull().validate({ min: 3, max: 200 }),\n * slug: col.varchar({ length: 160 }).notNull().unique(),\n * status: postStatus().notNull().default(\"draft\"), // const postStatus = pgEnum(\"post_status\", [...])\n * tags: col.text().array().notNull().default([]),\n * heroImage: col.storage({ path: \"posts/heroes/\", accept: [\"image/*\"], maxBytes: \"10MB\" }),\n * createdAt: col.timestamp({ withTimezone: true }).notNull().defaultNow(),\n * }\n * ```\n *\n * @group Schema\n */\nexport const col = {\n /** `UUID`. */\n uuid: simple<string, \"uuid\">(\"uuid\", { kind: \"uuid\" }),\n /** `TEXT`. `col.text({ enum: [...] })` accepts only those values. */\n text,\n /** `VARCHAR(n)`: `col.varchar({ length: n })`. */\n varchar,\n /** `CHAR(n)`: `col.char({ length: n })`. */\n char,\n /**\n * A Postgres enum type of its own, created as `<table>_<column>`. A type\n * with a stated name, shared by several columns, is `pgEnum(name, values)`.\n */\n enum: enumColumn,\n /** `SMALLINT`. */\n smallint: simple<number, \"smallint\">(\"smallint\", { kind: \"smallint\" }),\n /** `INTEGER`. */\n integer: simple<number, \"integer\">(\"integer\", { kind: \"integer\" }),\n /** `BIGINT`, read and written as a JavaScript number: `col.bigint({ mode: \"number\" })`. */\n bigint,\n /** `SMALLSERIAL`. Prefer `col.smallint().generatedByDefaultAsIdentity()` in a new schema. */\n smallserial(name?: string): ColumnBuilder<number, \"smallserial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"smallserial\", WithDefault<InitialColumnFlags>>(namedDef({ kind: \"smallserial\" }, name, \"smallserial\"));\n },\n /** `SERIAL`. Prefer `col.integer().generatedByDefaultAsIdentity()` in a new schema. */\n serial(name?: string): ColumnBuilder<number, \"serial\", WithDefault<InitialColumnFlags>> {\n return new ColumnBuilder<number, \"serial\", WithDefault<InitialColumnFlags>>(namedDef({ kind: \"serial\" }, name, \"serial\"));\n },\n /** `BIGSERIAL`: `col.bigserial({ mode: \"number\" })`. Prefer an identity column in a new schema. */\n bigserial,\n /** `REAL`. */\n real: simple<number, \"real\">(\"real\", { kind: \"real\" }),\n /** `DOUBLE PRECISION`. */\n doublePrecision: simple<number, \"doublePrecision\">(\"doublePrecision\", { kind: \"doublePrecision\" }),\n /** `NUMERIC`, `NUMERIC(p)` or `NUMERIC(p, s)`: `col.numeric({ precision, scale })`. A JSON number. */\n numeric,\n /** Drizzle's alias of `col.numeric()`. */\n decimal,\n /** `BOOLEAN`. */\n boolean: simple<boolean, \"boolean\">(\"boolean\", { kind: \"boolean\" }),\n /** `TIMESTAMPTZ`: `col.timestamp({ withTimezone: true })`. An ISO string on the wire. */\n timestamp,\n /** `DATE`. `YYYY-MM-DD` on the wire. */\n date,\n /** `TIME`. `HH:MM:SS` on the wire. */\n time,\n /**\n * `JSONB`. `col.jsonb().$type<T>()` types the document;\n * `col.jsonb(json.object({...}))` also tells the server its shape, so\n * nested fields are validated, stamped and searchable.\n */\n jsonb,\n /** `JSON`. As `col.jsonb`, for a column that must keep the text it was given. */\n json,\n /**\n * `vector(dimensions)` (pgvector): `col.vector({ dimensions: 1536 })`. An\n * HNSW cosine index is created unless `index` says otherwise; `index: false`\n * creates none.\n */\n vector,\n /** `BYTEA`. Base64 on the wire. */\n bytea: simple<string, \"bytea\">(\"bytea\", { kind: \"bytea\" }),\n /** A point on Earth, stored as `JSONB` `{ latitude, longitude }`. */\n geopoint(name?: string): ColumnBuilder<JsonGeoPoint, \"geopoint\"> {\n const def = namedDef({ kind: \"jsonb\" }, name, \"geopoint\");\n def.semantic = \"geopoint\";\n return new ColumnBuilder<JsonGeoPoint, \"geopoint\">(def);\n },\n /**\n * The path of a stored file, as `TEXT` — or several with `.multiple()`. The\n * upload route enforces `accept` and `maxBytes`, and the orphan sweep counts\n * the file as referenced.\n */\n storage,\n /**\n * A column of a Postgres type no other builder names —\n * `col.custom({ dataType: \"inet\" })`, `col.custom({ dataType: \"citext\" })`,\n * `col.custom({ dataType: \"geometry(Point, 4326)\" })`. What\n * `rebase schema introspect` writes for a column of such a type, so a\n * project generated from an existing database keeps it.\n *\n * Rebase names the type in DDL, verbatim, and does nothing else with it: it\n * does not create, alter or drop the type's definition (an extension or a\n * `CREATE TYPE` the database already holds provides it), it does not\n * validate values, and it passes every value through exactly as the\n * driver returns it — a string for most types. `.$type<T>()` types it for\n * the SDK when the driver returns something else.\n */\n custom,\n /** Refused: write `col.custom({ dataType: \"interval\" })`. */\n interval: unsupported(\"interval\"),\n /** Refused: write `col.custom({ dataType: \"inet\" })`. */\n inet: unsupported(\"inet\"),\n /** Refused: write `col.custom({ dataType: \"cidr\" })`. */\n cidr: unsupported(\"cidr\"),\n /** Refused: write `col.custom({ dataType: \"macaddr\" })`. */\n macaddr: unsupported(\"macaddr\"),\n /** Refused: write `col.custom({ dataType: \"macaddr8\" })`. */\n macaddr8: unsupported(\"macaddr8\"),\n /** Refused: write `col.custom({ dataType: \"point\" })`. */\n point: unsupported(\"point\"),\n /** Refused: write `col.custom({ dataType: \"line\" })`. */\n line: unsupported(\"line\"),\n /** Refused: write `col.custom({ dataType: \"halfvec\" })`. */\n halfvec: unsupported(\"halfvec\"),\n /** Refused: write `col.custom({ dataType: \"sparsevec\" })`. */\n sparsevec: unsupported(\"sparsevec\"),\n /** Refused: write `col.custom({ dataType: \"bit\" })`. */\n bit: unsupported(\"bit\")\n};\n\n/**\n * A Postgres enum type with a stated name, as Drizzle declares one: call it in\n * a column, `status: postStatus().notNull()`, or with the SQL column name,\n * `postStatus(\"state\")`.\n *\n * @group Schema\n */\nexport interface PgEnum<V extends Labels> {\n /** A column of this enum type; the optional argument is the SQL column name. */\n (name?: string): ColumnBuilder<V[number], \"enum\">;\n /** The type's name in Postgres. */\n readonly enumName: string;\n /** Its labels, in order. */\n readonly enumValues: V;\n}\n\n/**\n * Declare a Postgres enum type by name, as Drizzle does:\n *\n * ```ts\n * export const postStatus = pgEnum(\"post_status\", [\"draft\", \"published\"]);\n * // columns: { status: postStatus().notNull().default(\"draft\") }\n * ```\n *\n * Every column of it shares the one type. Two declarations of the same name\n * must list the same labels.\n *\n * @group Schema\n */\nexport function pgEnum<const V extends Labels>(enumName: string, values: V): PgEnum<V>;\nexport function pgEnum(this: Refusal[\"pgEnumObject\"], enumName: string, values: Readonly<Record<string, string>>): never;\nexport function pgEnum<const V extends Labels>(this: unknown, enumName: string, values: V | Readonly<Record<string, string>>): PgEnum<V> {\n if (typeof enumName !== \"string\" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(enumName)) {\n throw new Error(`\\`pgEnum(name, values)\\`: the name is a plain SQL identifier, got ${JSON.stringify(enumName)}.`);\n }\n if (!isLabelTuple<V>(values)) throw new Error(DRIZZLE_REFUSALS.pgEnumObject);\n const labels = [...values];\n const factory = (name?: string): ColumnBuilder<V[number], \"enum\"> =>\n new ColumnBuilder<V[number], \"enum\">(namedDef({ kind: \"enum\", values: labels, name: enumName }, name, \"enum\"));\n return Object.assign(factory, { enumName, enumValues: values });\n}\n\nfunction isLabelTuple<V extends Labels>(values: V | Readonly<Record<string, string>>): values is V {\n return Array.isArray(values) && values.length > 0 && values.every(value => typeof value === \"string\");\n}\n\n/**\n * The type name `col.custom()` puts into DDL: trimmed, and refused when it is\n * empty or could end the statement it is written into.\n */\nfunction customSqlType(sqlType: string): string {\n const trimmed = typeof sqlType === \"string\" ? sqlType.trim() : \"\";\n if (trimmed.length === 0) throw new Error(\"`col.custom()` takes the Postgres type, e.g. `col.custom({ dataType: \\\"inet\\\" })`.\");\n if (/;|--|\\/\\*/.test(trimmed)) {\n throw new Error(`\\`col.custom({ dataType: ${JSON.stringify(sqlType)} })\\`: a type name holds no \\`;\\` and no comment.`);\n }\n return trimmed;\n}\n\n/**\n * Whether a value is a column builder, from this copy of the package or\n * another.\n *\n * @group Schema\n */\nexport function isColumnBuilder(value: unknown): value is AnyColumn {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === COLUMN_BRAND;\n}\n","import type { JoinStep, OnAction } from \"../types/relations\";\nimport type { OrderByTuple } from \"../types/filter-operators\";\nimport type { ColumnAccess } from \"./column_options\";\nimport { normalizeColumnAccess } from \"./column_options\";\nimport type { ColumnsShape } from \"./columns\";\n\n/**\n * A relation's target, as written: `() => users`.\n *\n * Typed `() => void` on purpose. A thunk typed by what it returns (generic\n * over the returned table, a structural table type, or `() => unknown`) makes\n * TypeScript resolve the returned table's type while it is still inferring the\n * table being defined, so two tables that point at each other — `posts.author`\n * → `users`, `users.posts` → `posts` — failed with TS7022/TS7024 unless one\n * thunk was annotated. A `void` return is the one form TypeScript never\n * resolves, so mutual and self relations need no annotation, in one file or\n * across files.\n *\n * What the thunk returns is checked when the schema is compiled instead: a\n * thunk that does not return a `defineTable` / `defineView` result is refused\n * by `compileTables`, naming the table and the relation.\n *\n * @group Schema\n */\nexport type TableThunk = () => void;\n\n/** The brand every relation builder result carries. */\nexport const RELATION_BRAND = \"rebase.relation\";\n\ninterface RelationDefBase {\n readonly brand: typeof RELATION_BRAND;\n /**\n * The table it points at, behind a thunk so two tables can point at each\n * other. Typed `() => unknown`: read it through `isTableDef` / `isViewDef`.\n */\n readonly target: () => unknown;\n}\n\n/**\n * Field-level access on a relation, accepted by every `rel.*`: who may read\n * the relation (`include` it, see its key) and who may write a link through it.\n * The same rules a column states with `.access()` / `.private()`, enforced by\n * the server on every door — an `include` the caller may not read is refused,\n * a nested write the caller may not make is refused.\n *\n * @group Schema\n */\nexport interface RelationAccessOptions {\n /**\n * Per-role read and write access to the relation. `read` lists the roles\n * that may include it; `write` the roles that may link or unlink through\n * it. Omitted: whoever the table's `rls` lets read or write the row.\n */\n access?: ColumnAccess;\n /**\n * `true` keeps the relation off the wire entirely: not includable, not in\n * the SDK or OpenAPI. Only server code traverses it. Not combined with\n * `access`.\n */\n private?: boolean;\n}\n\n/**\n * Options of `rel.belongsTo`.\n *\n * @group Schema\n */\nexport interface BelongsToOptions extends RelationAccessOptions {\n /**\n * The SQL column on this table holding the foreign key. `<relation>_id`\n * when omitted. A column in `columns` with this SQL name is bound to;\n * otherwise the column is derived from the target's key.\n */\n localKey?: string;\n /** The derived column is `NOT NULL`. A bound column says so itself. */\n notNull?: boolean;\n /** The derived column is `UNIQUE`, making this side one-to-one. */\n unique?: boolean;\n /** `RESTRICT` when the column is `NOT NULL`, `SET NULL` otherwise. */\n onDelete?: OnAction;\n /**\n * What the foreign key does when the referenced key changes. No `ON UPDATE`\n * clause when omitted, so Postgres's default applies: `NO ACTION`.\n */\n onUpdate?: OnAction;\n /** `false` skips the index on the foreign key that is otherwise created. */\n index?: boolean;\n /** `false` stores the key without a `FOREIGN KEY` constraint. */\n constraint?: boolean;\n}\n\n/**\n * Options of `rel.hasOne` and `rel.hasMany`.\n *\n * @group Schema\n */\nexport interface HasOptions extends RelationAccessOptions {\n /** The SQL column on the target that points back here. Derived from this table's slug when omitted. */\n foreignKey?: string;\n /** The SQL column on this table it points at, when that is not the primary key. */\n sourceKey?: string;\n}\n\n/**\n * Options of `rel.hasMany`.\n *\n * @group Schema\n */\nexport interface HasManyOptions extends HasOptions {\n /** The order related rows come back in when the caller names none. */\n orderBy?: OrderByTuple | readonly OrderByTuple[];\n}\n\n/**\n * Options of `rel.manyToMany`.\n *\n * @group Schema\n */\nexport interface ManyToManyOptions<P extends ColumnsShape = ColumnsShape> extends RelationAccessOptions {\n /** The junction table. The two table names, sorted and joined by `_`, when omitted. */\n through?: string;\n /** The junction column pointing at this table. */\n sourceKey?: string;\n /** The junction column pointing at the target. */\n targetKey?: string;\n /** Extra columns on the junction, read and written as `_pivot`. */\n pivot?: P;\n /** What happens to a link when either row is deleted. `CASCADE` when omitted. */\n onDelete?: OnAction;\n}\n\n/**\n * Options of `rel.via`.\n *\n * @group Schema\n */\nexport interface ViaOptions extends RelationAccessOptions {\n /** The joins from this table to the target, in order. */\n steps: readonly JoinStep[];\n /** `many` when omitted. */\n cardinality?: \"one\" | \"many\";\n}\n\n/** `rel.belongsTo(...)`. */\nexport interface BelongsToDef extends RelationDefBase, BelongsToOptions {\n readonly kind: \"belongsTo\";\n}\n\n/** `rel.hasOne(...)`. */\nexport interface HasOneDef extends RelationDefBase, HasOptions {\n readonly kind: \"hasOne\";\n}\n\n/** `rel.hasMany(...)`. */\nexport interface HasManyDef extends RelationDefBase, HasManyOptions {\n readonly kind: \"hasMany\";\n}\n\n/** `rel.manyToMany(...)`. */\nexport interface ManyToManyDef<P extends ColumnsShape = ColumnsShape> extends RelationDefBase, ManyToManyOptions<P> {\n readonly kind: \"manyToMany\";\n}\n\n/** `rel.via(...)`. */\nexport interface ViaDef extends RelationDefBase, ViaOptions {\n readonly kind: \"via\";\n}\n\n/**\n * A relation as authored: the result of one `rel.*` call.\n *\n * @group Schema\n */\nexport type RelationDef =\n | BelongsToDef\n | HasOneDef\n | HasManyDef\n | ManyToManyDef\n | ViaDef;\n\n/**\n * The `relations` of a table: `rel.*` results by relation name.\n *\n * @group Schema\n */\nexport type RelationsShape = Record<string, RelationDef>;\n\n/** The options with `access` checked and copied: a role list, never a string spread into characters. */\nfunction withCheckedAccess<O extends RelationAccessOptions>(kind: string, options: O): O {\n if (options.access === undefined) return options;\n return { ...options, access: normalizeColumnAccess(options.access, `a relation (\\`rel.${kind}(…, { access })\\`)`) };\n}\n\nfunction belongsTo(target: TableThunk): BelongsToDef;\nfunction belongsTo<const O extends BelongsToOptions>(target: TableThunk, options: O): BelongsToDef & O;\nfunction belongsTo(target: TableThunk, options: BelongsToOptions = {}): BelongsToDef {\n return { ...withCheckedAccess(\"belongsTo\", options), brand: RELATION_BRAND, kind: \"belongsTo\", target };\n}\n\n/**\n * The relation builders. All five kinds; the target is a thunk, so two tables\n * can point at each other whatever order their modules load in — and, being a\n * {@link TableThunk}, without a type annotation on either side.\n *\n * ```ts\n * relations: {\n * author: rel.belongsTo(() => users, { localKey: \"author_id\", notNull: true, onDelete: \"restrict\" }),\n * tags: rel.manyToMany(() => tags, { through: \"posts_tags\", pivot: { sortOrder: col.integer().default(0) } }),\n * }\n * ```\n *\n * @group Schema\n */\nexport const rel = {\n /**\n * This table holds the foreign key. Binds to the column in `columns` whose\n * SQL name is `localKey`, or derives that column and indexes it.\n */\n belongsTo,\n /** The target holds a unique foreign key pointing here. */\n hasOne(target: TableThunk, options: HasOptions = {}): HasOneDef {\n return { ...withCheckedAccess(\"hasOne\", options), brand: RELATION_BRAND, kind: \"hasOne\", target };\n },\n /** The target holds a foreign key pointing here. */\n hasMany(target: TableThunk, options: HasManyOptions = {}): HasManyDef {\n return { ...withCheckedAccess(\"hasMany\", options), brand: RELATION_BRAND, kind: \"hasMany\", target };\n },\n /**\n * Linked through a junction table, which is created with its own row-level\n * security. `pivot` columns are read and written as `_pivot`.\n */\n manyToMany<P extends ColumnsShape = Record<never, never>>(\n target: TableThunk,\n options: ManyToManyOptions<P> = {}\n ): ManyToManyDef<P> {\n return { ...withCheckedAccess(\"manyToMany\", options), brand: RELATION_BRAND, kind: \"manyToMany\", target };\n },\n /** A read-only traversal across several joins. */\n via(target: TableThunk, options: ViaOptions): ViaDef {\n if (!options.steps || options.steps.length === 0) {\n throw new Error(\"`rel.via(target, { steps })` needs at least one join step.\");\n }\n return { ...withCheckedAccess(\"via\", options), brand: RELATION_BRAND, kind: \"via\", target };\n }\n};\n\n/**\n * Whether a value is the result of a `rel.*` call.\n *\n * @group Schema\n */\nexport function isRelationDef(value: unknown): value is RelationDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === RELATION_BRAND;\n}\n","import type { User } from \"../users\";\nimport type { ResourceRef } from \"../types/resources\";\nimport type { SearchConfig } from \"../types/search\";\nimport type { RoleDefinition, ScopeDefinition } from \"../types/scopes\";\nimport type {\n AuthCollectionContext,\n AuthCollectionCreateResult,\n AuthCollectionResetResult\n} from \"../types/auth_hooks\";\nimport type { ColumnsShape } from \"./columns\";\nimport { isColumnBuilder } from \"./columns\";\nimport type { BelongsToDef, RelationsShape } from \"./relations\";\nimport { isRelationDef } from \"./relations\";\nimport type { TableHooks } from \"./hooks\";\nimport type { RlsPosture, TableIndex, TableTenant } from \"./table_options\";\nimport type { InsertOfColumns, RowOfColumns } from \"./infer\";\n\n/** The brand of a `defineTable` / `defineAuthTable` result. */\nexport const TABLE_BRAND = \"rebase.table\";\n/** The brand of a `defineView` result. */\nexport const VIEW_BRAND = \"rebase.view\";\n\n/**\n * What `defineTable` takes besides the name.\n *\n * @group Schema\n */\nexport interface TableConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> {\n /**\n * The name in the API, the SDK and in scopes. The table's name when\n * omitted. Captured as a literal type, so `TableSlugOf<typeof table>` reads it.\n */\n slug?: S;\n /** The SQL table name, when it is not the name the table is defined under. */\n table?: string;\n /** The Postgres schema. `public` when omitted. */\n schema?: string;\n /** A non-default Postgres database, declared in `backend/resources.ts`. */\n database?: ResourceRef;\n /** What the table holds, for OpenAPI and MCP tool descriptions. */\n description?: string;\n /**\n * The columns, in physical order. At least one must be `.primaryKey()`;\n * several form a composite key in declaration order.\n */\n columns: C;\n /** The relations, by name. */\n relations?: R;\n /**\n * The row-level security posture. Required: `\"admin-only\"`, `\"inherit\"`\n * (the project's `defaultRls`), or the rules to generate policies from.\n */\n rls: RlsPosture;\n /**\n * `false` generates only the declared rules, without the injected admin\n * baseline. Refused together with `rls: \"admin-only\"`. `true` keeps the\n * baseline even when the table's database switches it off for every\n * table (`database({ rls: { defaultPolicies: false } })`). Absent, the\n * database's declaration decides.\n */\n defaultPolicies?: boolean;\n /**\n * `false` serves the table even when the database does not enforce its\n * `rls`: row-level security off, or its declared policies missing. For a\n * table whose schema something else owns (Alembic, Prisma, a DBA) and\n * whose access the app enforces itself. The boot names every table it\n * serves this way. A boot that provisions still writes the declared\n * policies; this only stops a boot that provisions nothing from refusing\n * the table. `true` requires it even when the table's database says\n * `database({ rls: { required: false } })`. Absent, the database's\n * declaration decides (required by default).\n */\n rlsRequired?: boolean;\n /**\n * Scope every row to a tenant: a column key, or a `belongsTo` relation's\n * name, which stands for its foreign-key column (as the compiler reads it).\n */\n tenant?: TableTenant<NoInfer<Extract<keyof C, string> | BelongsToKeys<R>>>;\n /** Deleting stamps a timestamp column instead of removing the row. */\n softDelete?: boolean | { field?: NoInfer<Extract<keyof C, string>> };\n /** Record every write in the history table. */\n history?: boolean;\n /** Full-text search over these columns. */\n search?: SearchConfig;\n /**\n * Indexes, each with the query it serves. The keys are not inferred from:\n * without `NoInfer`, a key naming nothing made TypeScript infer a relation\n * of that name instead of refusing it.\n */\n indexes?: readonly TableIndex<NoInfer<Extract<keyof C, string> | Extract<keyof R, string>>>[];\n /** Server-side lifecycle hooks. */\n hooks?: TableHooks<RowOfColumns<C>, InsertOfColumns<C>, USER>;\n /** `false` accepts writes naming columns the table does not declare. */\n strictWrites?: false;\n /** Opaque data, served with the table's descriptor. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * The names of the `belongsTo` relations in `R`: the relations that own a\n * foreign-key column on this table, and so can stand for it.\n *\n * @group Schema\n */\nexport type BelongsToKeys<R extends RelationsShape> = {\n [K in Extract<keyof R, string>]: R[K] extends BelongsToDef ? K : never\n}[Extract<keyof R, string>];\n\n/**\n * A table as authored: the result of `defineTable`.\n *\n * `N` is the name it was defined under and `S` its slug — the `slug` it was\n * given, or the name when it was given none — both as literal types, so a\n * frontend holding only `typeof posts` knows the slug (`TableSlugOf`).\n *\n * @group Schema\n */\nexport interface TableDef<\n N extends string = string,\n C extends ColumnsShape = ColumnsShape,\n R extends RelationsShape = RelationsShape,\n S extends string = N\n> {\n readonly brand: typeof TABLE_BRAND;\n /** The name it was defined under. */\n readonly name: N;\n /** What it was defined with, as written. */\n readonly config: TableConfig<C, R, User, S>;\n /** Present when defined with `defineAuthTable`. */\n readonly auth?: AuthTableOptions;\n}\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertTableShape(builder: string, name: unknown, config: unknown): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new Error(`\\`${builder}(name, config)\\` needs the table's name as its first argument.`);\n }\n if (typeof config !== \"object\" || config === null) {\n throw new Error(`\\`${builder}(\"${name}\", config)\\` needs a config object.`);\n }\n const columns = \"columns\" in config ? config.columns : undefined;\n if (typeof columns !== \"object\" || columns === null || Object.keys(columns).length === 0) {\n throw new Error(`Table \"${name}\" declares no columns. Add \\`columns: { id: col.uuid().primaryKey().defaultRandom(), … }\\`.`);\n }\n for (const [key, column] of Object.entries(columns)) {\n if (!isColumnBuilder(column)) {\n throw new Error(`Column \"${key}\" of table \"${name}\" is not a \\`col.*\\` builder.`);\n }\n }\n const relations = \"relations\" in config ? config.relations : undefined;\n if (relations !== undefined) {\n if (typeof relations !== \"object\" || relations === null) {\n throw new Error(`\\`relations\\` of table \"${name}\" must be an object of \\`rel.*\\` results.`);\n }\n for (const [key, relation] of Object.entries(relations)) {\n if (!isRelationDef(relation)) {\n throw new Error(`Relation \"${key}\" of table \"${name}\" is not a \\`rel.*\\` result.`);\n }\n if (key in columns) {\n throw new Error(\n `Table \"${name}\" has both a column and a relation named \"${key}\". ` +\n \"A relation's key is what `include` names; give the foreign-key column its own key.\"\n );\n }\n }\n }\n for (const key of [\"schema\", \"table\"] as const) {\n const value: unknown = key in config ? Reflect.get(config, key) : undefined;\n if (value !== undefined && (typeof value !== \"string\" || !IDENTIFIER.test(value))) {\n throw new Error(`\\`${key}\\` of table \"${name}\" must be a plain SQL identifier, got ${JSON.stringify(value)}.`);\n }\n }\n}\n\nfunction assertRlsDeclared(builder: string, name: string, config: object): void {\n const rls = \"rls\" in config ? config.rls : undefined;\n const ok = rls === \"admin-only\" || rls === \"inherit\" || (Array.isArray(rls) && rls.length > 0);\n if (ok) return;\n const detail = Array.isArray(rls)\n ? \"`rls: []` grants nothing and says nothing. Write `rls: \\\"admin-only\\\"` to lock the table to admins.\"\n : \"Every table needs an explicit row-level security posture.\";\n throw new Error(\n `\\`${builder}(\"${name}\", …)\\` has no usable \\`rls\\`. ${detail} ` +\n \"Accepted: `\\\"admin-only\\\"`, `\\\"inherit\\\"` (the `defaultRls` exported from backend/schema/index.ts), \" +\n \"or a non-empty list of rules.\"\n );\n}\n\n/**\n * Define a Postgres table.\n *\n * The name is the SQL table and the API slug; `rls` is mandatory. The result\n * is what the backend reads from `backend/schema/index.ts` — it generates the\n * DDL and the policies, serves the REST, realtime and MCP surfaces, and types\n * the SDK.\n *\n * ```ts\n * export const posts = defineTable(\"posts\", {\n * columns: {\n * id: col.uuid().primaryKey().defaultRandom(),\n * title: col.text().notNull(),\n * },\n * rls: [\n * { operation: \"select\", access: \"public\" },\n * { operations: [\"insert\", \"update\", \"delete\"], roles: [\"editor\"] },\n * ],\n * });\n * ```\n *\n * @group Schema\n */\nexport function defineTable<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: TableConfig<C, R, User, S>): TableDef<N, C, R, S> {\n assertTableShape(\"defineTable\", name, config);\n assertRlsDeclared(\"defineTable\", name, config);\n return { brand: TABLE_BRAND, name, config };\n}\n\n/**\n * The auth half of `defineAuthTable`.\n *\n * @group Schema\n */\nexport interface AuthTableOptions {\n /** The roles a user can hold, each with the scopes it grants. */\n roles?: Record<string, RoleDefinition>;\n /** The scopes an API key or token can be granted. */\n scopes?: Record<string, ScopeDefinition>;\n /** Let users create personal API keys. */\n personalKeys?: boolean;\n /** Runs when an admin creates a user: hash the password, send the invitation. */\n onCreateUser?: (values: Record<string, unknown>, ctx: AuthCollectionContext) => Promise<AuthCollectionCreateResult>;\n /** Runs when an admin resets a user's password. */\n onResetPassword?: (uid: string, ctx: AuthCollectionContext) => Promise<AuthCollectionResetResult>;\n}\n\n/**\n * What `defineAuthTable` takes besides the name.\n *\n * @group Schema\n */\nexport interface AuthTableConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> extends TableConfig<C, R, USER, S> {\n /** Roles, scopes, personal keys and the user-lifecycle hooks. */\n auth?: AuthTableOptions;\n}\n\n/**\n * Define the table users are stored in.\n *\n * A `defineTable` that auth reads and writes: the columns auth needs are added\n * when the table does not declare them, a signed-in user can read their own\n * row, and the privilege columns (`roles`) can only be written by an admin —\n * whatever `rls` says. A project has at most one.\n *\n * @group Schema\n */\nexport function defineAuthTable<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: AuthTableConfig<C, R, User, S>): TableDef<N, C, R, S> {\n assertTableShape(\"defineAuthTable\", name, config);\n assertRlsDeclared(\"defineAuthTable\", name, config);\n const { auth, ...table } = config;\n return { brand: TABLE_BRAND, name, config: table, auth: auth ?? {} };\n}\n\n/**\n * What `defineView` takes besides the name.\n *\n * @group Schema\n */\nexport interface ViewConfig<\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n USER extends User = User,\n S extends string = string\n> {\n /** The defining `SELECT`. */\n query: string;\n /**\n * `true` stores the rows. Postgres cannot attach row policies to a\n * materialized view, so it is read through a gate that admits `roles`.\n */\n materialized?: boolean;\n /** Who may read a materialized view. `[\"admin\"]` when omitted. Not accepted on a plain view. */\n roles?: readonly string[];\n /** The columns the query returns. `.primaryKey()` marks the ones that identify a row. */\n columns: C;\n /** The name in the API. The view's name when omitted. Captured as a literal type, like a table's. */\n slug?: S;\n /** The SQL view name, when it is not the name the view is defined under. A plain SQL identifier. */\n table?: string;\n /** The Postgres schema. `public` when omitted. */\n schema?: string;\n /** A non-default Postgres database. */\n database?: ResourceRef;\n /** What the view holds, for OpenAPI and MCP. */\n description?: string;\n /** Relations to read through. No constraint is created for a view. */\n relations?: R;\n /** Indexes on a materialized view's stored rows. */\n indexes?: readonly TableIndex<NoInfer<Extract<keyof C, string>>>[];\n /** Read hooks. A view is never written. */\n hooks?: Pick<TableHooks<RowOfColumns<C>, RowOfColumns<C>, USER>, \"beforeQuery\" | \"afterRead\">;\n /** Opaque data, served with the view's descriptor. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * A view as authored: the result of `defineView`.\n *\n * @group Schema\n */\nexport interface ViewDef<\n N extends string = string,\n C extends ColumnsShape = ColumnsShape,\n R extends RelationsShape = RelationsShape,\n S extends string = N\n> {\n readonly brand: typeof VIEW_BRAND;\n /** The name it was defined under. */\n readonly name: N;\n /** What it was defined with, as written. */\n readonly config: ViewConfig<C, R, User, S>;\n}\n\n/**\n * Define a SQL view, served read-only.\n *\n * A plain view is created `WITH (security_invoker = true)`: the row-level\n * security of the tables it reads decides what each caller sees. A\n * materialized view stores its rows, so it is gated by `roles` instead.\n *\n * @group Schema\n */\nexport function defineView<\n const N extends string,\n C extends ColumnsShape,\n R extends RelationsShape = Record<never, never>,\n const S extends string = N\n>(name: N, config: ViewConfig<C, R, User, S>): ViewDef<N, C, R, S> {\n assertTableShape(\"defineView\", name, config);\n if (typeof config.query !== \"string\" || config.query.trim().length === 0) {\n throw new Error(`View \"${name}\" needs a \\`query\\`: the SELECT that defines it.`);\n }\n if (config.roles !== undefined && !config.materialized) {\n throw new Error(\n `View \"${name}\" lists \\`roles\\` but is not materialized. A plain view is governed by the row-level ` +\n \"security of the tables it reads; `roles` gates a materialized view only.\"\n );\n }\n return { brand: VIEW_BRAND, name, config };\n}\n\n/**\n * The slug of a table or view, from its type: `TableSlugOf<typeof posts>`.\n *\n * The `slug` it was defined with, or the name it was defined under when it was\n * given none — the table's API path, SDK accessor and what scopes name. Reads\n * any `{ name, config: { slug? } }` structurally, so `import type { posts }`\n * is enough; `string` for a table whose type is not literal.\n *\n * ```ts\n * const posts = defineTable(\"blog_posts\", { slug: \"posts\", … });\n * type S = TableSlugOf<typeof posts>; // \"posts\"\n * ```\n *\n * @group Schema\n */\nexport type TableSlugOf<T extends { readonly name: string }> =\n T extends { readonly config: { readonly slug?: infer S } }\n ? [Exclude<S, undefined>] extends [never]\n ? T[\"name\"]\n : Exclude<S, undefined> extends string ? Exclude<S, undefined> : T[\"name\"]\n : T[\"name\"];\n\n/**\n * A type compared member by member rather than through its type parameters.\n *\n * `TableConfig<C>` names `keyof C` (in `tenant`, `softDelete`, `indexes`), and\n * TypeScript measures a type parameter read through `keyof` as contravariant —\n * so `TableConfig<{ id: … }>` was refused where `TableConfig<ColumnsShape>`\n * was expected, although every member is assignable. Spelling the \"any\" types\n * out structurally makes the compiler compare the members, which is the\n * question actually being asked.\n */\ntype Structural<T> = { [K in keyof T]: T[K] };\n\n/**\n * Any table, whatever its columns: what a list of `defineTable` results is\n * typed as (`compileTables(defs)`, `backend/schema/index.ts`).\n *\n * @group Schema\n */\nexport interface AnyTableDef {\n readonly brand: typeof TABLE_BRAND;\n readonly name: string;\n readonly config: Structural<TableConfig<ColumnsShape, RelationsShape>>;\n readonly auth?: AuthTableOptions;\n}\n\n/**\n * Any view, whatever its columns.\n *\n * @group Schema\n */\nexport interface AnyViewDef {\n readonly brand: typeof VIEW_BRAND;\n readonly name: string;\n readonly config: Structural<ViewConfig<ColumnsShape, RelationsShape>>;\n}\n\n/**\n * Whether a value is the result of `defineTable` or `defineAuthTable`, from\n * this copy of the package or another.\n *\n * @group Schema\n */\nexport function isTableDef(value: unknown): value is AnyTableDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === TABLE_BRAND;\n}\n\n/**\n * Whether a value is the result of `defineAuthTable`.\n *\n * @group Schema\n */\nexport function isAuthTableDef(value: unknown): value is AnyTableDef & { auth: AuthTableOptions } {\n return isTableDef(value) && value.auth !== undefined;\n}\n\n/**\n * Whether a value is the result of `defineView`.\n *\n * @group Schema\n */\nexport function isViewDef(value: unknown): value is AnyViewDef {\n return typeof value === \"object\" && value !== null && \"brand\" in value && value.brand === VIEW_BRAND;\n}\n","import type { SecurityRule } from \"../types/security_rules\";\nimport type { SearchConfig } from \"../types/search\";\nimport type { ColumnDef } from \"./columns\";\nimport type { TableDescriptor } from \"./descriptor\";\nimport type { JsonShape } from \"./json\";\nimport type { BelongsToOptions, HasManyOptions, HasOptions, ManyToManyOptions, ViaOptions } from \"./relations\";\nimport type { RlsPosture, TableIndex, TableTenant } from \"./table_options\";\n\n/**\n * The edits the Studio's schema editor sends the server, one operation at a\n * time.\n *\n * Every operation names the table it edits by **slug** and carries only\n * wire-safe values: a column as its definition without functions, a relation\n * with its target as a slug, a posture or a rule as data. The server applies\n * the operations to `backend/schema/*.ts` — the `defineTable` call, its\n * `columns`, `relations`, `rls` and table-level keys — and nothing else:\n * presentation (labels, icons, column widths, view modes) is not a server edit.\n *\n * Whatever an operation does not name is left exactly as written: comments,\n * hooks, `.transform()` bodies, the other columns and rules.\n *\n * @group Schema\n */\nexport type TablePatch =\n | CreateTablePatch\n | AdoptTablePatch\n | DeleteTablePatch\n | AddColumnPatch\n | ChangeColumnPatch\n | RenameColumnPatch\n | RemoveColumnPatch\n | MoveColumnPatch\n | AddRelationPatch\n | ChangeRelationPatch\n | RemoveRelationPatch\n | SetRlsPatch\n | AddRulePatch\n | ReplaceRulePatch\n | RemoveRulePatch\n | SetTableOptionPatch;\n\n/**\n * The operation names of {@link TablePatch}.\n *\n * @group Schema\n */\nexport type TablePatchOp = TablePatch[\"op\"];\n\n/**\n * A column as the wire carries it: its definition without field-level hooks\n * (`.transform()` is code, and stays where it is written), the flags that are\n * `false` by default optional.\n *\n * @group Schema\n */\nexport type WireColumnDef = Omit<ColumnDef, \"transform\" | \"element\" | \"json\" | \"notNull\" | \"primaryKey\" | \"unique\" | \"readOnly\" | \"private\"> & {\n notNull?: boolean;\n primaryKey?: boolean;\n unique?: boolean;\n readOnly?: boolean;\n private?: boolean;\n /** An array column's item. */\n element?: WireColumnDef;\n /** The shape of a `json`/`jsonb` document, without hooks. */\n json?: JsonShape;\n};\n\n/**\n * A relation as the wire carries it: the `rel.*` builder's options, its kind,\n * and its target table by slug. `manyToMany` pivot columns are\n * {@link WireColumnDef}s, in the order they are declared.\n *\n * @group Schema\n */\nexport type WireRelation =\n | (BelongsToOptions & { kind: \"belongsTo\"; target: string })\n | (HasOptions & { kind: \"hasOne\"; target: string })\n | (HasManyOptions & { kind: \"hasMany\"; target: string })\n | (Omit<ManyToManyOptions, \"pivot\"> & { kind: \"manyToMany\"; target: string; pivot?: Record<string, WireColumnDef> })\n | (ViaOptions & { kind: \"via\"; target: string });\n\n/**\n * The table-level keys an edit may set or remove after creation, with the\n * value each takes. `slug`, `table`, `schema` and the table's name are not\n * here: renaming them moves data, which is a migration, not an edit.\n *\n * @group Schema\n */\nexport interface TableOptionValues {\n description: string;\n tenant: TableTenant;\n softDelete: boolean | { field?: string };\n history: boolean;\n search: SearchConfig;\n indexes: readonly TableIndex[];\n strictWrites: false;\n defaultPolicies: boolean;\n rlsRequired: boolean;\n metadata: Record<string, unknown>;\n}\n\n/**\n * A key of {@link TableOptionValues}.\n *\n * @group Schema\n */\nexport type TableOptionKey = keyof TableOptionValues;\n\n/** The keys of {@link TableOptionValues}, in the order a table prints them. */\nexport const TABLE_OPTION_KEYS: readonly TableOptionKey[] = [\n \"description\", \"defaultPolicies\", \"rlsRequired\", \"tenant\", \"softDelete\", \"history\", \"search\", \"indexes\", \"strictWrites\", \"metadata\"\n];\n\n/**\n * A new table: what its `defineTable(name, { … })` call says. Columns and\n * relations print in the order given.\n *\n * @group Schema\n */\nexport interface NewTable extends Partial<TableOptionValues> {\n /** The name `defineTable` takes; also the file it is written to (`backend/schema/<name>.ts`). */\n name: string;\n /** The slug, when it is not the name. Fixed from here on: renaming a slug moves data. */\n slug?: string;\n /** The SQL table, when it is not the name. */\n table?: string;\n /** The Postgres schema, when it is not `public`. */\n schema?: string;\n columns: Record<string, WireColumnDef>;\n relations?: Record<string, WireRelation>;\n rls: RlsPosture;\n}\n\n/** Create `backend/schema/<name>.ts` holding the table, and export it from the index. @group Schema */\nexport interface CreateTablePatch {\n op: \"createTable\";\n table: NewTable;\n}\n\n/**\n * Adopt a table the database already has and `backend/schema` does not\n * declare (\"Import an existing table\"): write `backend/schema/<name>.ts` from\n * the table's description as introspection reads it — what\n * `GET /api/admin/schema-editor/unmapped-tables/:schema/:table` serves —\n * through the one printer, and export it from the index.\n *\n * The description states the table exactly as the database has it (column\n * types, defaults, keys, foreign keys as `belongsTo`, enums, types Rebase does\n * not create as `col.custom()`), so planning the adopted table changes nothing\n * in the database. Edits the person made on top of it follow as their own\n * operations, naming the adopted table by its slug.\n *\n * @group Schema\n */\nexport interface AdoptTablePatch {\n op: \"adoptTable\";\n table: TableDescriptor;\n}\n\n/**\n * Delete a table's definition (its file, or its statement in a file holding\n * others) and its export from the index. Refused while another table's\n * relation targets it. The SQL table and its rows are not dropped.\n *\n * @group Schema\n */\nexport interface DeleteTablePatch {\n op: \"deleteTable\";\n table: string;\n}\n\n/** Add a column, before the column named by `before`, or last. @group Schema */\nexport interface AddColumnPatch {\n op: \"addColumn\";\n table: string;\n key: string;\n column: WireColumnDef;\n before?: string;\n}\n\n/**\n * Rewrite one column's builder chain. A `.transform()` already written on it\n * is kept as written.\n *\n * @group Schema\n */\nexport interface ChangeColumnPatch {\n op: \"changeColumn\";\n table: string;\n key: string;\n column: WireColumnDef;\n}\n\n/**\n * Rename a column's key, in place, with its new definition. To keep the SQL\n * column, the definition carries `column` with the old SQL name.\n *\n * @group Schema\n */\nexport interface RenameColumnPatch {\n op: \"renameColumn\";\n table: string;\n key: string;\n to: string;\n column: WireColumnDef;\n}\n\n/** Remove a column from `columns`. @group Schema */\nexport interface RemoveColumnPatch {\n op: \"removeColumn\";\n table: string;\n key: string;\n}\n\n/** Move a column before the column named by `before`, or last. @group Schema */\nexport interface MoveColumnPatch {\n op: \"moveColumn\";\n table: string;\n key: string;\n before?: string;\n}\n\n/** Add a relation; the target's import is added to the file. @group Schema */\nexport interface AddRelationPatch {\n op: \"addRelation\";\n table: string;\n name: string;\n relation: WireRelation;\n}\n\n/** Rewrite one relation. @group Schema */\nexport interface ChangeRelationPatch {\n op: \"changeRelation\";\n table: string;\n name: string;\n relation: WireRelation;\n}\n\n/** Remove a relation; an import nothing else uses is removed with it. @group Schema */\nexport interface RemoveRelationPatch {\n op: \"removeRelation\";\n table: string;\n name: string;\n}\n\n/**\n * Replace the whole `rls`: a posture, or a list of rules. Prefer the rule\n * operations for a change to one rule — a policy's name is a hash of its rule\n * as written, and they leave every other rule's text alone.\n *\n * @group Schema\n */\nexport interface SetRlsPatch {\n op: \"setRls\";\n table: string;\n rls: RlsPosture;\n}\n\n/** Insert a rule at `index` (last when omitted) of a table whose `rls` is a list of rules. @group Schema */\nexport interface AddRulePatch {\n op: \"addRule\";\n table: string;\n rule: SecurityRule;\n index?: number;\n}\n\n/** Replace the rule at `index`; every other rule's text stays byte-identical. @group Schema */\nexport interface ReplaceRulePatch {\n op: \"replaceRule\";\n table: string;\n index: number;\n rule: SecurityRule;\n}\n\n/** Remove the rule at `index`. The last rule cannot be removed: set `\"admin-only\"` instead. @group Schema */\nexport interface RemoveRulePatch {\n op: \"removeRule\";\n table: string;\n index: number;\n}\n\n/**\n * Set a table-level key, or remove it with `value: null`.\n *\n * @group Schema\n */\nexport type SetTableOptionPatch = {\n [K in TableOptionKey]: { op: \"setOption\"; table: string; option: K; value: TableOptionValues[K] | null }\n}[TableOptionKey];\n\n/**\n * What is wrong with one operation of a {@link TablePatch} list, reported the\n * way a schema problem is: the table, the key when there is one, and what to\n * send instead.\n *\n * @group Schema\n */\nexport interface TablePatchProblem {\n /** The index of the operation in the list sent. */\n index: number;\n /** The table it names, as sent (\"\" when none was). */\n table: string;\n /** The column, relation or option key, when the problem is about one. */\n key?: string;\n /** What is wrong and what to send instead. */\n message: string;\n}\n\n/**\n * A list of table edits that cannot be applied, with every problem found.\n *\n * @group Schema\n */\nexport class TablePatchError extends Error {\n\n readonly code = \"TABLE_PATCH_INVALID\";\n\n constructor(\n /** Every problem found, in operation order. */\n readonly problems: readonly TablePatchProblem[]\n ) {\n super(TablePatchError.describe(problems));\n this.name = \"TablePatchError\";\n }\n\n private static describe(problems: readonly TablePatchProblem[]): string {\n const lines = problems.map(problem => {\n const table = problem.table || \"(no table)\";\n const where = problem.key ? `${table}.${problem.key}` : table;\n return ` - edit ${problem.index} (${where}): ${problem.message}`;\n });\n const count = problems.length === 1 ? \"1 problem\" : `${problems.length} problems`;\n return `The schema edit cannot be applied (${count}):\\n${lines.join(\"\\n\")}`;\n }\n}\n\n/**\n * A name that reaches SQL as an identifier, or becomes a file name: letters,\n * digits, underscores and dollar signs, not starting with a digit. The same\n * alphabet the DDL builders accept, so a name accepted here is one they take.\n */\nconst SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n/** A key on the JSON row: any non-empty string without control characters. */\nconst isRowKey = (key: string): boolean => key.length > 0 && [...key].every(char => char.charCodeAt(0) >= 32);\n\nconst COLUMN_KINDS = new Set([\n \"text\", \"varchar\", \"char\", \"uuid\", \"enum\", \"smallint\", \"integer\", \"bigint\", \"smallserial\", \"serial\", \"bigserial\",\n \"real\", \"doublePrecision\", \"numeric\", \"boolean\", \"timestamptz\", \"date\", \"time\", \"json\", \"jsonb\", \"vector\", \"bytea\",\n \"array\", \"other\"\n]);\n\nconst RELATION_OPTION_KEYS: Readonly<Record<WireRelation[\"kind\"], readonly string[]>> = {\n belongsTo: [\"localKey\", \"notNull\", \"unique\", \"onDelete\", \"onUpdate\", \"index\", \"constraint\", \"access\", \"private\"],\n hasOne: [\"foreignKey\", \"sourceKey\", \"access\", \"private\"],\n hasMany: [\"foreignKey\", \"sourceKey\", \"orderBy\", \"access\", \"private\"],\n manyToMany: [\"through\", \"sourceKey\", \"targetKey\", \"pivot\", \"onDelete\", \"access\", \"private\"],\n via: [\"steps\", \"cardinality\", \"access\", \"private\"]\n};\n\n/** The relation options that name a SQL column or table. */\nconst RELATION_IDENTIFIER_KEYS = [\"localKey\", \"foreignKey\", \"sourceKey\", \"targetKey\", \"through\"] as const;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst MIGRATION_KEYS: Readonly<Record<string, string>> = {\n slug: \"The slug is the table's address in the API, the SDK, scopes and foreign-key names; renaming it moves data, which is a migration, not an edit. Create a new table and migrate the rows, or rename it in code with a migration.\",\n table: \"Renaming the SQL table moves its rows, which is a migration, not an edit. Write the rename in code together with a migration.\",\n schema: \"Moving the table to another Postgres schema moves its rows, which is a migration, not an edit. Write it in code together with a migration.\",\n name: \"The table's name is its file and its default SQL name; renaming it moves data, which is a migration, not an edit. Write the rename in code together with a migration.\",\n database: \"Moving the table to another database moves its rows, which is a migration, not an edit.\"\n};\n\n/** Problems with a column definition sent on the wire. */\nfunction columnProblems(value: unknown, where: string): string[] {\n if (!isRecord(value)) return [`${where} must be a column definition object.`];\n const problems: string[] = [];\n const type = value.type;\n if (!isRecord(type) || typeof type.kind !== \"string\" || !COLUMN_KINDS.has(type.kind)) {\n problems.push(`${where}.type must be a column type, \\`{ kind: \"text\" }\\`, \\`{ kind: \"varchar\", length: 160 }\\` …`);\n } else if (type.kind === \"array\") {\n if (!isRecord(type.of)) problems.push(`${where}.type.of must be the type of each item.`);\n } else if ((type.kind === \"varchar\" || type.kind === \"char\") && typeof type.length !== \"number\") {\n problems.push(`${where}.type.length must be a number.`);\n } else if (type.kind === \"enum\" && (!Array.isArray(type.values) || type.values.length === 0 || !type.values.every(v => typeof v === \"string\"))) {\n problems.push(`${where}.type.values must be a non-empty list of strings.`);\n } else if (type.kind === \"vector\" && typeof type.dimensions !== \"number\") {\n problems.push(`${where}.type.dimensions must be a number.`);\n } else if (type.kind === \"other\" && typeof type.sqlType !== \"string\") {\n problems.push(`${where}.type.sqlType must be a string.`);\n }\n for (const flag of [\"notNull\", \"primaryKey\", \"unique\", \"readOnly\", \"private\"]) {\n if (value[flag] !== undefined && typeof value[flag] !== \"boolean\") problems.push(`${where}.${flag} must be a boolean.`);\n }\n if (value.column !== undefined && (typeof value.column !== \"string\" || !SQL_IDENTIFIER.test(value.column))) {\n problems.push(`${where}.column must be a SQL identifier (letters, digits, underscores; not starting with a digit).`);\n }\n if (value.transform !== undefined) {\n problems.push(`${where}.transform is code: write it in the table's file. A transform already on the column is kept.`);\n }\n if (value.element !== undefined) problems.push(...columnProblems(value.element, `${where}.element`));\n if (value.json !== undefined && !isRecord(value.json)) problems.push(`${where}.json must be a JSON shape.`);\n return problems;\n}\n\n/** Problems with a table description sent to be adopted. */\nfunction adoptedTableProblems(spec: Record<string, unknown>): { key?: string; message: string }[] {\n const out: { key?: string; message: string }[] = [];\n for (const key of [\"name\", \"slug\", \"table\", \"schema\"] as const) {\n const named = spec[key];\n if (typeof named !== \"string\" || !SQL_IDENTIFIER.test(named)) out.push({ key, message: `\\`${key}\\` must be a SQL identifier.` });\n }\n if (spec.kind !== \"table\") out.push({ key: \"kind\", message: \"only a table can be adopted (`kind: \\\"table\\\"`).\" });\n if (!Array.isArray(spec.columns) || spec.columns.length === 0) {\n out.push({ key: \"columns\", message: \"`columns` must list the table's columns, as introspection described them.\" });\n } else {\n for (const [index, column] of spec.columns.entries()) {\n const key = isRecord(column) && typeof column.key === \"string\" ? column.key : `columns[${index}]`;\n if (!isRecord(column) || typeof column.key !== \"string\" || !isRowKey(column.key)) out.push({ key, message: \"a column must have a `key`.\" });\n else if (typeof column.nullable !== \"boolean\") out.push({ key, message: \"`nullable` must be a boolean.\" });\n for (const message of columnProblems(column, `columns.${key}`)) out.push({ key, message });\n }\n }\n if (!Array.isArray(spec.primaryKey) || spec.primaryKey.length === 0 || !spec.primaryKey.every(key => typeof key === \"string\")) {\n out.push({ key: \"primaryKey\", message: \"`primaryKey` must name the key column (or columns): a table without one cannot be declared.\" });\n }\n if (!Array.isArray(spec.relations) || !spec.relations.every(isRecord)) out.push({ key: \"relations\", message: \"`relations` must be a list of relations.\" });\n const rls = spec.rls;\n if (!isRecord(rls) || (rls.posture !== \"admin-only\" && rls.posture !== \"rules\") || !Array.isArray(rls.rules) || !rls.rules.every(isRecord)) {\n out.push({ key: \"rls\", message: \"`rls` must be `{ posture, rules }`, as introspection described it.\" });\n }\n if (spec.hooks !== undefined) out.push({ key: \"hooks\", message: \"hooks are code: write them in the table's file once it is adopted.\" });\n if (spec.auth !== undefined || spec.view !== undefined) out.push({ message: \"an auth table or a view is not adopted here: declare it in code.\" });\n return out;\n}\n\n/** Problems with a relation sent on the wire. */\nfunction relationProblems(value: unknown, where: string): string[] {\n if (!isRecord(value)) return [`${where} must be a relation object.`];\n const kind = value.kind;\n if (kind !== \"belongsTo\" && kind !== \"hasOne\" && kind !== \"hasMany\" && kind !== \"manyToMany\" && kind !== \"via\") {\n return [`${where}.kind must be one of belongsTo, hasOne, hasMany, manyToMany, via.`];\n }\n const problems: string[] = [];\n if (typeof value.target !== \"string\" || value.target.trim() === \"\") {\n problems.push(`${where}.target must be the slug of the table it points at.`);\n }\n const known = RELATION_OPTION_KEYS[kind];\n for (const key of Object.keys(value)) {\n if (key === \"kind\" || key === \"target\") continue;\n if (!known.includes(key)) problems.push(`${where}.${key} is not an option of \\`rel.${kind}\\`.`);\n }\n for (const key of RELATION_IDENTIFIER_KEYS) {\n const named = value[key];\n if (named !== undefined && (typeof named !== \"string\" || !SQL_IDENTIFIER.test(named))) {\n problems.push(`${where}.${key} must be a SQL identifier.`);\n }\n }\n if (kind === \"via\" && (!Array.isArray(value.steps) || value.steps.length === 0)) {\n problems.push(`${where}.steps must list at least one join step.`);\n }\n if (kind === \"manyToMany\" && value.pivot !== undefined) {\n if (!isRecord(value.pivot)) problems.push(`${where}.pivot must map column keys to column definitions.`);\n else for (const [key, column] of Object.entries(value.pivot)) problems.push(...columnProblems(column, `${where}.pivot.${key}`));\n }\n return problems;\n}\n\n/** Problems with an `rls` value sent on the wire. */\nfunction rlsProblems(value: unknown, where: string): string[] {\n if (value === \"admin-only\" || value === \"inherit\") return [];\n if (!Array.isArray(value)) return [`${where} must be \"admin-only\", \"inherit\" or a list of rules.`];\n if (value.length === 0) return [`${where} is an empty list of rules, which leaves nobody a policy. Send \"admin-only\" instead.`];\n return value.flatMap((rule, index) => (isRecord(rule) ? [] : [`${where}[${index}] must be a rule object.`]));\n}\n\n/** Problems with a table-level option's value. */\nfunction optionProblems(option: TableOptionKey, value: unknown, where: string): string[] {\n if (value === null) return [];\n switch (option) {\n case \"description\":\n return typeof value === \"string\" ? [] : [`${where} must be a string.`];\n case \"history\":\n return typeof value === \"boolean\" ? [] : [`${where} must be a boolean.`];\n case \"defaultPolicies\":\n case \"rlsRequired\":\n return typeof value === \"boolean\" ? [] : [`${where} must be a boolean (or \\`null\\` to remove it).`];\n case \"strictWrites\":\n return value === false ? [] : [`${where} can only be \\`false\\` (or \\`null\\` to remove it).`];\n case \"softDelete\":\n return typeof value === \"boolean\" || isRecord(value) ? [] : [`${where} must be a boolean or \\`{ field }\\`.`];\n case \"tenant\":\n return isRecord(value) && typeof value.field === \"string\" && isRecord(value.from) ? [] : [`${where} must be \\`{ field, from }\\`.`];\n case \"search\":\n case \"metadata\":\n return isRecord(value) ? [] : [`${where} must be an object.`];\n case \"indexes\":\n return Array.isArray(value) && value.every(isRecord) ? [] : [`${where} must be a list of indexes.`];\n }\n}\n\nconst isOptionKey = (value: unknown): value is TableOptionKey =>\n typeof value === \"string\" && (TABLE_OPTION_KEYS as readonly string[]).includes(value);\n\nconst isIndex = (value: unknown): boolean => typeof value === \"number\" && Number.isInteger(value) && value >= 0;\n\n/** The problems of one operation. */\nfunction operationProblems(value: unknown, index: number): TablePatchProblem[] {\n if (!isRecord(value)) return [{ index, table: \"\", message: \"an edit must be an object with an `op`.\" }];\n const table = typeof value.table === \"string\" ? value.table : \"\";\n const problem = (message: string, key?: string): TablePatchProblem => ({ index, table, ...(key !== undefined ? { key } : {}), message });\n const op = value.op;\n\n if (op === \"createTable\") {\n const spec = value.table;\n if (!isRecord(spec)) return [{ index, table: \"\", message: \"`table` must describe the new table: `{ name, columns, rls }`.\" }];\n const name = typeof spec.name === \"string\" ? spec.name : \"\";\n const out: TablePatchProblem[] = [];\n const at = (message: string, key?: string): void => {\n out.push({ index, table: name, ...(key !== undefined ? { key } : {}), message });\n };\n if (!SQL_IDENTIFIER.test(name)) at(\"`name` must be a SQL identifier: it names the table and its file.\");\n for (const key of [\"slug\", \"table\", \"schema\"] as const) {\n const named = spec[key];\n if (named !== undefined && (typeof named !== \"string\" || !SQL_IDENTIFIER.test(named))) at(`\\`${key}\\` must be a SQL identifier.`, key);\n }\n if (!isRecord(spec.columns) || Object.keys(spec.columns).length === 0) {\n at(\"`columns` must declare at least one column (one of them `primaryKey`).\");\n } else {\n for (const [key, column] of Object.entries(spec.columns)) {\n if (!isRowKey(key)) at(\"a column key must be a non-empty string.\", key);\n for (const message of columnProblems(column, `columns.${key}`)) at(message, key);\n }\n }\n if (spec.relations !== undefined) {\n if (!isRecord(spec.relations)) at(\"`relations` must map relation names to relations.\");\n else for (const [key, relation] of Object.entries(spec.relations)) {\n for (const message of relationProblems(relation, `relations.${key}`)) at(message, key);\n }\n }\n for (const message of rlsProblems(spec.rls, \"rls\")) at(message, \"rls\");\n for (const option of TABLE_OPTION_KEYS) {\n if (spec[option] === undefined) continue;\n for (const message of optionProblems(option, spec[option], option)) at(message, option);\n }\n const known = new Set<string>([\"name\", \"slug\", \"table\", \"schema\", \"columns\", \"relations\", \"rls\", ...TABLE_OPTION_KEYS]);\n for (const key of Object.keys(spec)) {\n if (!known.has(key)) at(`\\`${key}\\` is not something the schema editor writes${key === \"hooks\" ? \": hooks are code, write them in the file\" : \"\"}.`, key);\n }\n return out;\n }\n\n if (op === \"adoptTable\") {\n const spec = value.table;\n if (!isRecord(spec)) return [{ index, table: \"\", message: \"`table` must be the description of the table to adopt, as `GET …/unmapped-tables/:schema/:table` serves it.\" }];\n const name = typeof spec.slug === \"string\" ? spec.slug : \"\";\n return adoptedTableProblems(spec).map(found => ({ index, table: name, ...(found.key !== undefined ? { key: found.key } : {}), message: found.message }));\n }\n\n if (table === \"\") return [problem(\"`table` must be the slug of the table to edit.\")];\n\n switch (op) {\n case \"deleteTable\":\n return [];\n case \"addColumn\":\n case \"changeColumn\": {\n const out: TablePatchProblem[] = [];\n const key = typeof value.key === \"string\" ? value.key : undefined;\n if (key === undefined || !isRowKey(key)) out.push(problem(\"`key` must name the column.\"));\n for (const message of columnProblems(value.column, \"column\")) out.push(problem(message, key));\n if (op === \"addColumn\" && value.before !== undefined && typeof value.before !== \"string\") out.push(problem(\"`before` must name a column.\", key));\n return out;\n }\n case \"renameColumn\": {\n const out: TablePatchProblem[] = [];\n const key = typeof value.key === \"string\" ? value.key : undefined;\n if (key === undefined) out.push(problem(\"`key` must name the column.\"));\n if (typeof value.to !== \"string\" || !isRowKey(value.to)) out.push(problem(\"`to` must be the column's new key.\", key));\n for (const message of columnProblems(value.column, \"column\")) out.push(problem(message, key));\n return out;\n }\n case \"removeColumn\":\n return typeof value.key === \"string\" ? [] : [problem(\"`key` must name the column.\")];\n case \"moveColumn\": {\n if (typeof value.key !== \"string\") return [problem(\"`key` must name the column.\")];\n return value.before === undefined || typeof value.before === \"string\" ? [] : [problem(\"`before` must name a column.\", value.key)];\n }\n case \"addRelation\":\n case \"changeRelation\": {\n const name = typeof value.name === \"string\" ? value.name : undefined;\n const out = name === undefined || !isRowKey(name) ? [problem(\"`name` must name the relation.\")] : [];\n return [...out, ...relationProblems(value.relation, \"relation\").map(message => problem(message, name))];\n }\n case \"removeRelation\":\n return typeof value.name === \"string\" ? [] : [problem(\"`name` must name the relation.\")];\n case \"setRls\":\n return rlsProblems(value.rls, \"rls\").map(message => problem(message, \"rls\"));\n case \"addRule\":\n return [\n ...(isRecord(value.rule) ? [] : [problem(\"`rule` must be a rule object.\", \"rls\")]),\n ...(value.index === undefined || isIndex(value.index) ? [] : [problem(\"`index` must be a position in the rules.\", \"rls\")])\n ];\n case \"replaceRule\":\n return [\n ...(isRecord(value.rule) ? [] : [problem(\"`rule` must be a rule object.\", \"rls\")]),\n ...(isIndex(value.index) ? [] : [problem(\"`index` must be a position in the rules.\", \"rls\")])\n ];\n case \"removeRule\":\n return isIndex(value.index) ? [] : [problem(\"`index` must be a position in the rules.\", \"rls\")];\n case \"setOption\": {\n const option = value.option;\n if (typeof option === \"string\" && option in MIGRATION_KEYS) return [problem(MIGRATION_KEYS[option], option)];\n if (option === \"hooks\") return [problem(\"hooks are code: write them in the table's file.\", option)];\n if (!isOptionKey(option)) {\n return [problem(`\\`option\\` must be one of ${TABLE_OPTION_KEYS.join(\", \")}.`, typeof option === \"string\" ? option : undefined)];\n }\n if (!(\"value\" in value)) return [problem(\"`value` is required: the new value, or `null` to remove the key.\", option)];\n return optionProblems(option, value.value, \"value\").map(message => problem(message, option));\n }\n default:\n return [problem(`\\`op\\` ${JSON.stringify(op)} is not a schema edit. Send one of createTable, adoptTable, deleteTable, addColumn, changeColumn, renameColumn, removeColumn, moveColumn, addRelation, changeRelation, removeRelation, setRls, addRule, replaceRule, removeRule, setOption.`)];\n }\n}\n\n/**\n * Every problem with a list of table edits as it arrived, in operation order.\n * Empty when the list is well formed — which says nothing about whether the\n * result compiles: the server compiles it before writing anything.\n *\n * @group Schema\n */\nexport function tablePatchProblems(value: unknown): TablePatchProblem[] {\n if (!Array.isArray(value)) return [{ index: 0, table: \"\", message: \"`patches` must be a list of schema edits.\" }];\n if (value.length === 0) return [{ index: 0, table: \"\", message: \"`patches` is empty: there is nothing to edit.\" }];\n return value.flatMap((operation, index) => operationProblems(operation, index));\n}\n\n/**\n * Whether a value is a well-formed list of {@link TablePatch} operations.\n *\n * @group Schema\n */\nexport function isTablePatchList(value: unknown): value is TablePatch[] {\n return tablePatchProblems(value).length === 0;\n}\n\n/**\n * A list of edits as it arrived, checked: the list, or a\n * {@link TablePatchError} naming every problem.\n *\n * @group Schema\n */\nexport function parseTablePatches(value: unknown): TablePatch[] {\n if (isTablePatchList(value)) return value;\n throw new TablePatchError(tablePatchProblems(value));\n}\n\n/**\n * The column definition a {@link WireColumnDef} stands for, the flags it left\n * out `false`.\n *\n * @group Schema\n */\nexport function columnDefFromWire(column: WireColumnDef): ColumnDef {\n const { element, json, notNull, primaryKey, unique, readOnly, private: isPrivate, ...rest } = column;\n const def: ColumnDef = {\n ...rest,\n notNull: notNull === true,\n primaryKey: primaryKey === true,\n unique: unique === true,\n readOnly: readOnly === true,\n private: isPrivate === true\n };\n if (element !== undefined) def.element = columnDefFromWire(element);\n if (json !== undefined) def.json = json;\n return def;\n}\n\n/** Deep equality of JSON-like values: what a rule read from the wire is compared by. */\nfunction sameValue(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (Array.isArray(a) || Array.isArray(b)) {\n return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));\n }\n if (!isRecord(a) || !isRecord(b)) return false;\n const keys = Object.keys(a).filter(key => a[key] !== undefined);\n const otherKeys = Object.keys(b).filter(key => b[key] !== undefined);\n return keys.length === otherKeys.length && keys.every(key => sameValue(a[key], b[key]));\n}\n\n/**\n * The rule operations that turn one list of rules into another, touching only\n * the rules that changed.\n *\n * A policy's name is a hash of its rule as written, so an editor that sends\n * the whole list back (one `setRls`) would rewrite every rule's text and risk\n * renaming policies it never changed. This pairs the lists by position: an\n * equal rule is left alone, a different one is replaced, a longer list adds\n * rules and a shorter one removes from the end. Positions are those of the\n * list as it is when each operation runs.\n *\n * @group Schema\n */\nexport function rulePatches(table: string, before: readonly SecurityRule[], after: readonly SecurityRule[]): TablePatch[] {\n const out: TablePatch[] = [];\n const shared = Math.min(before.length, after.length);\n for (let index = 0; index < shared; index++) {\n if (!sameValue(before[index], after[index])) out.push({ op: \"replaceRule\", table, index, rule: after[index] });\n }\n for (let index = shared; index < after.length; index++) out.push({ op: \"addRule\", table, rule: after[index], index });\n for (let index = before.length - 1; index >= after.length; index--) out.push({ op: \"removeRule\", table, index });\n return out;\n}\n","export * from \"./errors\";\nexport * from \"./call_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