@rebasepro/server 0.25.1 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{GCSStorageController-CRd9bFrc.js → GCSStorageController-BUClIfp0.js} +40 -3
- package/dist/GCSStorageController-BUClIfp0.js.map +1 -0
- package/dist/{S3StorageController-D00EFa5P.js → S3StorageController-CixCQEky.js} +58 -10
- package/dist/S3StorageController-CixCQEky.js.map +1 -0
- package/dist/access-BFAUvsSs.js +1897 -0
- package/dist/access-BFAUvsSs.js.map +1 -0
- package/dist/api/branch-routes.d.ts +25 -0
- package/dist/api/live-schema-routes.d.ts +10 -0
- package/dist/api/rest/api-generator.d.ts +9 -1
- package/dist/api/rest/idempotency.d.ts +15 -1
- package/dist/api/root-error-handler.d.ts +6 -5
- package/dist/api/types.d.ts +12 -0
- package/dist/{ast-schema-editor-mCeSC03x.js → ast-schema-editor-madTa9Hh.js} +2 -2
- package/dist/{ast-schema-editor-mCeSC03x.js.map → ast-schema-editor-madTa9Hh.js.map} +1 -1
- package/dist/auth/access.d.ts +10 -0
- package/dist/auth/adapter-middleware.d.ts +2 -1
- package/dist/auth/adapter-service-key.d.ts +24 -0
- package/dist/auth/admin-users-route.d.ts +3 -0
- package/dist/auth/api-keys/api-key-middleware.d.ts +21 -1
- package/dist/auth/api-keys/api-key-store.d.ts +8 -1
- package/dist/auth/api-keys/key-grant.d.ts +18 -1
- package/dist/auth/apple-oauth.d.ts +39 -10
- package/dist/auth/capabilities.d.ts +2 -0
- package/dist/auth/expired-token-sweep.d.ts +5 -0
- package/dist/auth/impersonation.d.ts +3 -1
- package/dist/auth/interfaces.d.ts +55 -0
- package/dist/auth/jwt.d.ts +8 -2
- package/dist/auth/oauth-signin-policy.d.ts +21 -35
- package/dist/auth/rls-scope.d.ts +17 -7
- package/dist/auth/rls-simulator-routes.d.ts +51 -0
- package/dist/auth/simulation-read-only.d.ts +28 -0
- package/dist/auth/simulation.d.ts +141 -0
- package/dist/auth/sql-rate-limit-store.d.ts +15 -1
- package/dist/{auth-Dkvo2tTJ.js → auth-DDXPw0mn.js} +527 -1883
- package/dist/auth-DDXPw0mn.js.map +1 -0
- package/dist/auth_adapter-B7RUMk6e.js +89 -0
- package/dist/auth_adapter-B7RUMk6e.js.map +1 -0
- package/dist/backend/create-backend.d.ts +6 -0
- package/dist/backend/options.d.ts +38 -5
- package/dist/{backend-DTAOsLQc.js → backend-CaG_Jyso.js} +9 -2
- package/dist/backend-CaG_Jyso.js.map +1 -0
- package/dist/{backup-B9m3cb3X.js → backup-B6brPSeB.js} +6 -6
- package/dist/{backup-B9m3cb3X.js.map → backup-B6brPSeB.js.map} +1 -1
- package/dist/boot/boot.d.ts +2 -15
- package/dist/boot/ddl-bootstrap.d.ts +34 -0
- package/dist/boot/env.d.ts +12 -0
- package/dist/boot/fetch-bundle.d.ts +5 -1
- package/dist/boot/provision-only.d.ts +23 -0
- package/dist/boot/provision.d.ts +53 -2
- package/dist/boot/role.d.ts +2 -0
- package/dist/boot/schema-change-recorder.d.ts +45 -0
- package/dist/boot/security-headers.d.ts +22 -0
- package/dist/branch-routes-B2vvEx53.js +84 -0
- package/dist/branch-routes-B2vvEx53.js.map +1 -0
- package/dist/{contract-routes-CsFXW7j4.js → contract-routes-CU2A3JnF.js} +2 -2
- package/dist/{contract-routes-CsFXW7j4.js.map → contract-routes-CU2A3JnF.js.map} +1 -1
- package/dist/cron/cron-loader.d.ts +4 -0
- package/dist/cron/cron-store.d.ts +8 -1
- package/dist/{cron-loader-Dj6lA4HQ.js → cron-loader-CC1Jy_KN.js} +14 -6
- package/dist/cron-loader-CC1Jy_KN.js.map +1 -0
- package/dist/{cron-routes-CwbLZguO.js → cron-routes-BK60Rn1r.js} +3 -3
- package/dist/{cron-routes-CwbLZguO.js.map → cron-routes-BK60Rn1r.js.map} +1 -1
- package/dist/{cron-scheduler-B04ACoUE.js → cron-scheduler-DyCjPlQR.js} +40 -27
- package/dist/cron-scheduler-DyCjPlQR.js.map +1 -0
- package/dist/{cron-store-DkyfuLOH.js → cron-store-DLn11M8H.js} +10 -9
- package/dist/cron-store-DLn11M8H.js.map +1 -0
- package/dist/{strings.es-BeZWAodn.js → data_driver-D0mg1Y_x.js} +2 -90
- package/dist/data_driver-D0mg1Y_x.js.map +1 -0
- package/dist/{ddl-bootstrap-Ck20GSIX.js → ddl-bootstrap-CjRrn12l.js} +91 -2
- package/dist/ddl-bootstrap-CjRrn12l.js.map +1 -0
- package/dist/deploy/pod-contract.d.ts +1 -1
- package/dist/{load-failure-L5hvfDoG.js → dynamic-import-Bi3XK5y-.js} +30 -18
- package/dist/dynamic-import-Bi3XK5y-.js.map +1 -0
- package/dist/email/dev-sink.d.ts +6 -0
- package/dist/email/index.d.ts +1 -1
- package/dist/{soft-delete-params-BmlVwecC.js → field-access-DYsvjI_P.js} +27 -57
- package/dist/field-access-DYsvjI_P.js.map +1 -0
- package/dist/{filter-dialect-O1HK6Nvr.js → filter-dialect-TrKFWLqT.js} +3 -3
- package/dist/{filter-dialect-O1HK6Nvr.js.map → filter-dialect-TrKFWLqT.js.map} +1 -1
- package/dist/{function-loader-KKDqTcIr.js → function-loader-eFigStYX.js} +34 -18
- package/dist/function-loader-eFigStYX.js.map +1 -0
- package/dist/functions/function-loader.d.ts +5 -0
- package/dist/functions/hono-like.d.ts +12 -0
- package/dist/functions/index.js +19 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/request-timeout.d.ts +3 -3
- package/dist/history/history-routes.d.ts +6 -0
- package/dist/history/retention-sweep.d.ts +5 -0
- package/dist/{history-recorder-B2rkuhuy.js → history-recorder-Bsau7h4X.js} +6 -6
- package/dist/history-recorder-Bsau7h4X.js.map +1 -0
- package/dist/{history-store-DPofGVDp.js → history-store-BQz5YCkW.js} +26 -2
- package/dist/history-store-BQz5YCkW.js.map +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.es.js +3026 -611
- package/dist/index.es.js.map +1 -1
- package/dist/init/docs.d.ts +1 -1
- package/dist/init/health.d.ts +13 -0
- package/dist/init/process-safety.d.ts +4 -3
- package/dist/init/shutdown.d.ts +8 -0
- package/dist/init.d.ts +6 -1
- package/dist/jobs/job-store.d.ts +8 -1
- package/dist/{jobs-h1WRq3cp.js → jobs-Co6Ni5HP.js} +6 -6
- package/dist/jobs-Co6Ni5HP.js.map +1 -0
- package/dist/{jwt-D3oFauZI.js → jwt-rDS0884_.js} +4 -3
- package/dist/{jwt-D3oFauZI.js.map → jwt-rDS0884_.js.map} +1 -1
- package/dist/{keys-COzQ2aE8.js → keys-BXcdRNhJ.js} +2 -2
- package/dist/{keys-COzQ2aE8.js.map → keys-BXcdRNhJ.js.map} +1 -1
- package/dist/mcp/consent-page.d.ts +38 -1
- package/dist/mcp/mcp-routes.d.ts +9 -0
- package/dist/mcp/mcp-tools.d.ts +7 -1
- package/dist/mcp/oauth-store.d.ts +12 -5
- package/dist/metrics/history-recorder.d.ts +4 -1
- package/dist/metrics/history-store.d.ts +8 -0
- package/dist/metrics/index.d.ts +8 -0
- package/dist/metrics/realtime.d.ts +25 -0
- package/dist/{offline-BrqCRgih-BtDB1ecy.js → offline-AvuEcg7u-DFHL98OT.js} +127 -40
- package/dist/offline-AvuEcg7u-DFHL98OT.js.map +1 -0
- package/dist/{offline-store-BhYXViha-BW5j1We_.js → offline-store-BhYXViha-YTmjBpo2.js} +5 -5
- package/dist/{offline-store-BhYXViha-BW5j1We_.js.map → offline-store-BhYXViha-YTmjBpo2.js.map} +1 -1
- package/dist/{openapi-generator-BjHr6upl.js → openapi-generator-CyxEtYEX.js} +61 -22
- package/dist/openapi-generator-CyxEtYEX.js.map +1 -0
- package/dist/{proxy-CH8Jsovg.js → proxy-BYir8tWK.js} +4 -6
- package/dist/proxy-BYir8tWK.js.map +1 -0
- package/dist/{query-parser-otFZqJsC.js → query-parser-CDXWf2hH.js} +6 -5
- package/dist/{query-parser-otFZqJsC.js.map → query-parser-CDXWf2hH.js.map} +1 -1
- package/dist/{request-timeout-59crS-9u.js → request-timeout-DVjo-c_8.js} +4 -4
- package/dist/request-timeout-DVjo-c_8.js.map +1 -0
- package/dist/rls-simulator-routes-bEY7-5-u.js +190 -0
- package/dist/rls-simulator-routes-bEY7-5-u.js.map +1 -0
- package/dist/schema-edit/deployed-schema-guard.d.ts +47 -0
- package/dist/{schema-editor-routes-Bsut0bCC.js → schema-editor-routes-Dc3DU_jm.js} +3 -3
- package/dist/{schema-editor-routes-Bsut0bCC.js.map → schema-editor-routes-Dc3DU_jm.js.map} +1 -1
- package/dist/services/routed-realtime-service.d.ts +1 -1
- package/dist/soft-delete-params-BRONCOA2.js +59 -0
- package/dist/soft-delete-params-BRONCOA2.js.map +1 -0
- package/dist/{sql-export-routes-DmB_uZ4l.js → sql-export-routes-QycX8W8S.js} +38 -4
- package/dist/sql-export-routes-QycX8W8S.js.map +1 -0
- package/dist/{src-D5Y3N-S4.js → src-Bh9LRPb9.js} +21 -2
- package/dist/{src-D5Y3N-S4.js.map → src-Bh9LRPb9.js.map} +1 -1
- package/dist/storage/GCSStorageController.d.ts +11 -1
- package/dist/storage/LocalStorageController.d.ts +16 -4
- package/dist/storage/S3StorageController.d.ts +6 -2
- package/dist/storage/index.d.ts +1 -0
- package/dist/storage/maintenance-keys.d.ts +17 -0
- package/dist/storage/maintenance-routes.d.ts +28 -5
- package/dist/storage/maintenance.d.ts +136 -4
- package/dist/storage/orphan-scans.d.ts +120 -0
- package/dist/storage/policies.d.ts +1 -1
- package/dist/storage/streams.d.ts +17 -0
- package/dist/storage/types.d.ts +26 -33
- package/dist/strings.es-B7QLnHh2.js +96 -0
- package/dist/strings.es-B7QLnHh2.js.map +1 -0
- package/dist/{upload-validation-Bgo626uY.js → upload-validation-CkkQGs-j.js} +40 -2
- package/dist/upload-validation-CkkQGs-j.js.map +1 -0
- package/dist/utils/load-failure.d.ts +9 -0
- package/package.json +5 -5
- package/dist/GCSStorageController-CRd9bFrc.js.map +0 -1
- package/dist/S3StorageController-D00EFa5P.js.map +0 -1
- package/dist/auth-Dkvo2tTJ.js.map +0 -1
- package/dist/auth_adapter-CIItCTc8.js +0 -21
- package/dist/auth_adapter-CIItCTc8.js.map +0 -1
- package/dist/backend-DTAOsLQc.js.map +0 -1
- package/dist/cron-loader-Dj6lA4HQ.js.map +0 -1
- package/dist/cron-scheduler-B04ACoUE.js.map +0 -1
- package/dist/cron-store-DkyfuLOH.js.map +0 -1
- package/dist/ddl-bootstrap-Ck20GSIX.js.map +0 -1
- package/dist/function-loader-KKDqTcIr.js.map +0 -1
- package/dist/history-recorder-B2rkuhuy.js.map +0 -1
- package/dist/history-store-DPofGVDp.js.map +0 -1
- package/dist/jobs-h1WRq3cp.js.map +0 -1
- package/dist/load-failure-L5hvfDoG.js.map +0 -1
- package/dist/offline-BrqCRgih-BtDB1ecy.js.map +0 -1
- package/dist/openapi-generator-BjHr6upl.js.map +0 -1
- package/dist/proxy-CH8Jsovg.js.map +0 -1
- package/dist/request-timeout-59crS-9u.js.map +0 -1
- package/dist/soft-delete-params-BmlVwecC.js.map +0 -1
- package/dist/sql-export-routes-DmB_uZ4l.js.map +0 -1
- package/dist/strings.es-BeZWAodn.js.map +0 -1
- package/dist/upload-validation-Bgo626uY.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data_driver-D0mg1Y_x.js","names":[],"sources":["../../types/src/errors.ts","../../types/src/controllers/data_driver.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 `SDKCollectionClient`, 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 `as unknown as` 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","import { RebaseApiError } from \"../errors\";\nimport type { CollectionRegistryController } from \"./collection_registry\";\nimport type { EntityStatus, EntityValues } from \"../types/entities\";\nimport type { CollectionConfig, FilterValues } from \"../types/collections\";\nimport type { OrderByTuple } from \"../types/filter-operators\";\nimport type { RebaseCallContext } from \"../call_context\";\nimport type { 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 collection?: CollectionConfig<M>\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\n/**\n * What a row listener subscribes to: the row, and the relations each frame\n * loads into it.\n *\n * @internal\n */\nexport type ListenOneTarget<M extends Record<string, unknown> = Record<string, unknown>> =\n FetchOneProps<M>\n & {\n /**\n * Relations to load into every frame, as {@link FetchCollectionProps.include}\n * loads them into each row of a list. Without it a to-many relation\n * is absent from each frame, and the admin's record form, opened by\n * URL, showed it empty — so a save from it unlinked every related row.\n */\n include?: IncludeSpec;\n }\n\n/**\n * @internal\n */\nexport type ListenOneProps<M extends Record<string, unknown> = Record<string, unknown>> =\n ListenOneTarget<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 collection?: CollectionConfig<M>;\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 collections that do not declare {@link\n * PostgresCollectionConfig.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<EntityValues<M>>;\n id?: string | number; // can be empty for new entities\n previousValues?: Partial<EntityValues<M>>;\n collection?: CollectionConfig<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<EntityValues<M>>[];\n collection?: CollectionConfig<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\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<EntityValues<M>> }[];\n collection?: CollectionConfig<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 collection?: CollectionConfig<M>;\n /**\n * Issue a real `DELETE` on a collection that declares\n * {@link PostgresCollectionConfig.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 collection?: CollectionConfig<M>;\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<EntityValues<M>>;\n collection?: CollectionConfig<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 collection: CollectionConfig;\n filterValues: FilterValues<string>;\n sortBy?: [string, \"asc\" | \"desc\"];\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>`. Rebase wraps drivers via `buildRebaseData` and\n * routes collections to them by their `dataSource` key.\n *\n * For *consuming* data in application code, use `RebaseData` /\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 * 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 * 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: Postgres threw, Mongo 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 rather than a filter, deliberately — see\n * {@link SDKCollectionClient.deleteMany}. 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 * @param collection\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 collection?: CollectionConfig\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 * 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 collection: CollectionConfig;\n /** Rows per page. */\n pageSize?: number;\n }): AsyncIterable<Record<string, unknown>[]>;\n\n /**\n * Check if the given filter combination is valid\n * @param props\n */\n isFilterCombinationValid?(props: Omit<FilterCombinationValidProps, \"collection\"> & {\n databaseId?: string\n }): 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 initTextSearch?: (props: {\n context: RebaseCallContext,\n path: string,\n databaseId?: string,\n collection: CollectionConfig,\n parentCollectionSlugs?: string[];\n parentEntityIds?: string[];\n }) => Promise<boolean>;\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, DocumentAdmin, SchemaAdmin) 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 DocumentAdmin\n * @see SchemaAdmin\n */\n admin?: import(\"../types/backend\").DatabaseAdmin;\n\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 * `count`/`sum`/`avg`/`min`/`max` over the rows a filter selects,\n * optionally grouped.\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 aggregate?(\n collectionPath: string,\n options: {\n aggregates: { fn: \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\"; field?: string; alias: string }[];\n groupBy?: string[];\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8HA,IAAa,iBAAb,cAAoC,MAAM;;CAEtC;;CAEA;;CAEA;;CAEA;;CAEA;CAEA,YAAY,SAAiB,OAAwB,CAAC,GAAG;EACrD,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS,KAAK;EACnB,KAAK,OAAO,KAAK;EACjB,KAAK,UAAU,KAAK;EACpB,KAAK,YAAY,KAAK;EACtB,KAAK,oBAAoB,KAAK;EAC9B,IAAI,KAAK,UAAU,KAAA,GAEf,KAA8B,QAAQ,KAAK;CAEnD;AACJ;;;;;;;;;;AAWA,IAAa,oBAAb,cAAuC,eAAe;;;;;;;;;;;;;;CAclD,YAAY,SAAiB,OAAwB,CAAC,GAAG;EACrD,MAAM,SAAS,IAAI;EACnB,KAAK,OAAO;CAChB;AACJ;;;;;;;;AASA,IAAM,qBAAqB,OAAO,IAAI,0BAA0B;AA8BhE,SAAgB,kBAAqB,SAAoB;CACrD,MAAM,aAAoB;EAItB,MAAM,IAAI,kBAAkB,SAAS,EAAE,MAAM,oBAAoB,CAAC;CACtE;CACA,KAA4B,sBAAsB;CAClD,OAAO;AACX;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,cAAc,QAA0B;CACpD,IAAI,OAAO,WAAW,YAAY,OAAO;CACzC,OAAQ,OAA6B,wBAAwB;AACjE;;ACxJA,IAAa,iBAAiB;;;;;;;;AAmB9B,IAAa,iBAAb,MAAa,uBAAuB,eAAe;;CAE/C;CAEA,YAAY,SAAiB,UAAkB;EAC3C,MAAM,SAAS;GAAE,QAAQ;GAAK,MAAM;EAAgB,CAAC;EACrD,KAAK,OAAO;EACZ,KAAK,WAAW;EAGhB,OAAO,eAAe,MAAM,eAAe,SAAS;CACxD;AACJ;;;;;;;;;;;;;;;;;AAkBA,SAAgB,uBACZ,UACA,OAAqD,CAAC,GAChD;CACN,MAAM,WAAW,KAAK,YAAA;CACtB,IAAI,YAAY,QAAQ,OAAO,QAAQ,CAAC,CAAC,KAAK,MAAM,IAAI;EAGpD,MAAM,SAAS,OAAO,aAAa,WAAW,WAAW,OAAO,OAAO,QAAQ,CAAC,CAAC,KAAK,CAAC;EACvF,IAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,GACtC,MAAM,IAAI,eACN,sBAAsB,OAAO,QAAQ,EAAE,0CAA0C,SAAS,IAC1F,QACJ;EAEJ,IAAI,SAAS,UACT,MAAM,IAAI,eACN,aAAa,OAAO,2BAA2B,SAAS,oBAAoB,SAAS,qJAGrF,QACJ;EAEJ,OAAO;CACX;CACA,OAAO,KAAK,eACL,KAAK,sBAAA,KACL,KAAK,gBAAA;AAChB"}
|
|
@@ -5,6 +5,91 @@ __rebaseCreateRequire(import.meta.url);
|
|
|
5
5
|
import { a as logger } from "./logger-CW8pmTS6.js";
|
|
6
6
|
//#region src/boot/ddl-bootstrap.ts
|
|
7
7
|
/**
|
|
8
|
+
* The first keyword of every statement that changes what the database *is* —
|
|
9
|
+
* its tables, columns, indexes, types, functions, triggers, policies, roles and
|
|
10
|
+
* privileges — as opposed to the rows in it.
|
|
11
|
+
*
|
|
12
|
+
* `DO` is here because every anonymous block Rebase runs exists to make a
|
|
13
|
+
* guarded `GRANT`, `REVOKE` or `CREATE`; there is no row write anywhere in the
|
|
14
|
+
* framework that needs one. `TRUNCATE`, `VACUUM` and `ANALYZE` are not: they
|
|
15
|
+
* act on data and statistics, and none of them is something a change process
|
|
16
|
+
* reviews.
|
|
17
|
+
*/
|
|
18
|
+
var SCHEMA_CHANGE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
19
|
+
"CREATE",
|
|
20
|
+
"ALTER",
|
|
21
|
+
"DROP",
|
|
22
|
+
"GRANT",
|
|
23
|
+
"REVOKE",
|
|
24
|
+
"COMMENT",
|
|
25
|
+
"DO",
|
|
26
|
+
"REINDEX",
|
|
27
|
+
"CLUSTER",
|
|
28
|
+
"SECURITY",
|
|
29
|
+
"IMPORT",
|
|
30
|
+
"REASSIGN"
|
|
31
|
+
]);
|
|
32
|
+
/** A statement with any leading whitespace and comments removed. */
|
|
33
|
+
function withoutLeadingComments(sqlText) {
|
|
34
|
+
let rest = sqlText;
|
|
35
|
+
for (;;) {
|
|
36
|
+
rest = rest.trimStart();
|
|
37
|
+
if (rest.startsWith("--")) {
|
|
38
|
+
const end = rest.indexOf("\n");
|
|
39
|
+
rest = end === -1 ? "" : rest.slice(end + 1);
|
|
40
|
+
} else if (rest.startsWith("/*")) {
|
|
41
|
+
const end = rest.indexOf("*/");
|
|
42
|
+
rest = end === -1 ? "" : rest.slice(end + 2);
|
|
43
|
+
} else return rest;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/** The statement's first keyword, past any leading comments, upper-cased. */
|
|
47
|
+
function leadingKeyword(sqlText) {
|
|
48
|
+
return (withoutLeadingComments(sqlText).match(/^[A-Za-z]+/)?.[0] ?? "").toUpperCase();
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Whether a statement changes the database's structure or its privileges.
|
|
52
|
+
*
|
|
53
|
+
* Decided on the leading keyword, which is exact for every statement the
|
|
54
|
+
* framework writes: none of them hides DDL behind a `WITH` or a function call.
|
|
55
|
+
*/
|
|
56
|
+
function isSchemaChange(sqlText) {
|
|
57
|
+
return SCHEMA_CHANGE_KEYWORDS.has(leadingKeyword(sqlText));
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Raised in place of a schema change on a backend that provisions nothing.
|
|
61
|
+
*
|
|
62
|
+
* Its own class so a bootstrap step can tell "this was not run on purpose" from
|
|
63
|
+
* "this failed", and say the first at `debug` rather than as an error per
|
|
64
|
+
* statement on every boot.
|
|
65
|
+
*/
|
|
66
|
+
var SchemaChangeRefusedError = class extends Error {
|
|
67
|
+
statement;
|
|
68
|
+
code = "REBASE_PROVISIONING_OFF";
|
|
69
|
+
constructor(statement) {
|
|
70
|
+
super(`Not run: this backend changes nothing in its database (provisioning is off). Statement: ${statement.trim().split("\n")[0]}`);
|
|
71
|
+
this.statement = statement;
|
|
72
|
+
this.name = "SchemaChangeRefusedError";
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* `exec`, with every schema change refused and every other statement passed
|
|
77
|
+
* through.
|
|
78
|
+
*
|
|
79
|
+
* What a store is built on when its backend provisions nothing. The store's own
|
|
80
|
+
* bootstrap still runs, so it reads what is there exactly as it always has and
|
|
81
|
+
* reports what is missing in its own words; only the statements that would
|
|
82
|
+
* have changed the database stop here. A guard rather than a branch per store,
|
|
83
|
+
* because a branch is a thing the next store can forget.
|
|
84
|
+
*/
|
|
85
|
+
function refuseSchemaChanges(exec) {
|
|
86
|
+
return (sqlText, options) => isSchemaChange(sqlText) ? Promise.reject(new SchemaChangeRefusedError(sqlText)) : exec(sqlText, options);
|
|
87
|
+
}
|
|
88
|
+
/** {@link refuseSchemaChanges} when `provision` is `false`; `exec` itself otherwise. */
|
|
89
|
+
function provisioningExec(exec, provision) {
|
|
90
|
+
return provision === false ? refuseSchemaChanges(exec) : exec;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
8
93
|
* SQLSTATEs a *simultaneous boot* can raise from statements that are otherwise
|
|
9
94
|
* idempotent. Retrying is always the right answer for these: the second attempt
|
|
10
95
|
* finds the object present and does nothing.
|
|
@@ -114,6 +199,10 @@ function createDdlBootstrapper(exec, scope) {
|
|
|
114
199
|
try {
|
|
115
200
|
await run();
|
|
116
201
|
} catch (err) {
|
|
202
|
+
if (hasInCauseChain(err, (e) => e.code === "REBASE_PROVISIONING_OFF")) {
|
|
203
|
+
logger.debug(`[${scope}] ${label}: not run — this backend changes nothing in its database`);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
117
206
|
logger.error(`[${scope}] ${label} failed`, { error: err });
|
|
118
207
|
}
|
|
119
208
|
};
|
|
@@ -142,6 +231,6 @@ function createDdlBootstrapper(exec, scope) {
|
|
|
142
231
|
};
|
|
143
232
|
}
|
|
144
233
|
//#endregion
|
|
145
|
-
export {
|
|
234
|
+
export { isConcurrentDdlRace as a, provisioningExec as c, hasInCauseChain as i, withoutLeadingComments as l, SchemaChangeRefusedError as n, isDuplicateObjectRace as o, createDdlBootstrapper as r, isSchemaChange as s, CONCURRENT_DDL_SQLSTATES as t };
|
|
146
235
|
|
|
147
|
-
//# sourceMappingURL=ddl-bootstrap-
|
|
236
|
+
//# sourceMappingURL=ddl-bootstrap-CjRrn12l.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ddl-bootstrap-CjRrn12l.js","names":[],"sources":["../src/boot/ddl-bootstrap.ts"],"sourcesContent":["import { logger } from \"../utils/logger.js\";\n\n/**\n * Helpers for the \"create my internal table if it isn't there yet\" bootstrap\n * that several stores run at boot.\n *\n * These all look trivially safe — every statement is `IF NOT EXISTS` — and they\n * are not, for two reasons that only show up with more than one app instance:\n *\n * 1. `CREATE … IF NOT EXISTS` reads the catalog and then writes to it, and\n * those two steps are not one atomic operation. Instances starting together\n * — a rolling deploy, a replica count going from 1 to N, a crash loop\n * restarting the fleet — can both see \"absent\" and both try to create. The\n * loser gets a duplicate key on a *catalog* index instead of the silent\n * no-op the syntax appears to promise. Measured against Postgres 18: with\n * five instances booting at once, 8 of 10 `ensureTable` calls hit it.\n *\n * 2. A bootstrap written as one long `try` block therefore abandons everything\n * after the losing statement — including, in every store that has one, the\n * `REVOKE` that takes the table back off the end-user role. That revoke is\n * a security control and must not be collateral damage from a race.\n *\n * So: retry the race, contain each statement separately, and decide what to do\n * next from what actually exists rather than from who won.\n */\n\n/** A driver's `executeSql`, narrowed to what a bootstrap needs. */\nexport type SqlExec = (sqlText: string, options?: { params?: unknown[] }) => Promise<Record<string, unknown>[]>;\n\n/**\n * The first keyword of every statement that changes what the database *is* —\n * its tables, columns, indexes, types, functions, triggers, policies, roles and\n * privileges — as opposed to the rows in it.\n *\n * `DO` is here because every anonymous block Rebase runs exists to make a\n * guarded `GRANT`, `REVOKE` or `CREATE`; there is no row write anywhere in the\n * framework that needs one. `TRUNCATE`, `VACUUM` and `ANALYZE` are not: they\n * act on data and statistics, and none of them is something a change process\n * reviews.\n */\nconst SCHEMA_CHANGE_KEYWORDS = new Set([\n \"CREATE\", \"ALTER\", \"DROP\", \"GRANT\", \"REVOKE\", \"COMMENT\", \"DO\",\n \"REINDEX\", \"CLUSTER\", \"SECURITY\", \"IMPORT\", \"REASSIGN\"\n]);\n\n/** A statement with any leading whitespace and comments removed. */\nexport function withoutLeadingComments(sqlText: string): string {\n let rest = sqlText;\n for (;;) {\n rest = rest.trimStart();\n if (rest.startsWith(\"--\")) {\n const end = rest.indexOf(\"\\n\");\n rest = end === -1 ? \"\" : rest.slice(end + 1);\n } else if (rest.startsWith(\"/*\")) {\n const end = rest.indexOf(\"*/\");\n rest = end === -1 ? \"\" : rest.slice(end + 2);\n } else {\n return rest;\n }\n }\n}\n\n/** The statement's first keyword, past any leading comments, upper-cased. */\nfunction leadingKeyword(sqlText: string): string {\n return (withoutLeadingComments(sqlText).match(/^[A-Za-z]+/)?.[0] ?? \"\").toUpperCase();\n}\n\n/**\n * Whether a statement changes the database's structure or its privileges.\n *\n * Decided on the leading keyword, which is exact for every statement the\n * framework writes: none of them hides DDL behind a `WITH` or a function call.\n */\nexport function isSchemaChange(sqlText: string): boolean {\n return SCHEMA_CHANGE_KEYWORDS.has(leadingKeyword(sqlText));\n}\n\n/**\n * Raised in place of a schema change on a backend that provisions nothing.\n *\n * Its own class so a bootstrap step can tell \"this was not run on purpose\" from\n * \"this failed\", and say the first at `debug` rather than as an error per\n * statement on every boot.\n */\nexport class SchemaChangeRefusedError extends Error {\n readonly code = \"REBASE_PROVISIONING_OFF\";\n\n constructor(readonly statement: string) {\n super(\n \"Not run: this backend changes nothing in its database (provisioning is off). \" +\n `Statement: ${statement.trim().split(\"\\n\")[0]}`\n );\n this.name = \"SchemaChangeRefusedError\";\n }\n}\n\n/**\n * `exec`, with every schema change refused and every other statement passed\n * through.\n *\n * What a store is built on when its backend provisions nothing. The store's own\n * bootstrap still runs, so it reads what is there exactly as it always has and\n * reports what is missing in its own words; only the statements that would\n * have changed the database stop here. A guard rather than a branch per store,\n * because a branch is a thing the next store can forget.\n */\nexport function refuseSchemaChanges(exec: SqlExec): SqlExec {\n return (sqlText, options) => isSchemaChange(sqlText)\n ? Promise.reject(new SchemaChangeRefusedError(sqlText))\n : exec(sqlText, options);\n}\n\n/** {@link refuseSchemaChanges} when `provision` is `false`; `exec` itself otherwise. */\nexport function provisioningExec(exec: SqlExec, provision: boolean | undefined): SqlExec {\n return provision === false ? refuseSchemaChanges(exec) : exec;\n}\n\n\n/**\n * SQLSTATEs a *simultaneous boot* can raise from statements that are otherwise\n * idempotent. Retrying is always the right answer for these: the second attempt\n * finds the object present and does nothing.\n */\nexport const CONCURRENT_DDL_SQLSTATES = new Set([\n \"23505\", // unique_violation on pg_type / pg_class / pg_namespace\n \"42P06\", // duplicate_schema\n \"42P07\", // duplicate_table\n \"42710\", // duplicate_object — an index or a constraint\n \"40P01\" // deadlock_detected — two boots taking catalog locks in step\n]);\n\n/** Attempts per idempotent DDL statement, including the first. */\nexport const DDL_ATTEMPTS = 4;\nconst DDL_RETRY_BASE_MS = 40;\n\n/**\n * Walk an error's `cause` chain, stopping at the first link `visit` accepts.\n * Drizzle wraps the driver error, so nothing useful is ever on the top level.\n */\nexport function hasInCauseChain(err: unknown, visit: (e: Record<string, unknown>) => boolean): boolean {\n let current: unknown = err;\n for (let depth = 0; depth < 10 && current; depth++) {\n if (typeof current !== \"object\") break;\n const e = current as Record<string, unknown>;\n if (visit(e)) return true;\n current = e.cause;\n }\n return false;\n}\n\n/**\n * Is this the loser of a race to create something that already exists?\n *\n * Deliberately narrow. A permission failure, an unreachable database or a typo\n * in the DDL must surface on the first attempt rather than being retried four\n * times and then reported as a race that never was.\n */\nexport function isConcurrentDdlRace(err: unknown): boolean {\n return hasInCauseChain(err, (e) =>\n (typeof e.code === \"string\" && CONCURRENT_DDL_SQLSTATES.has(e.code)) ||\n // SQLite and MySQL say it in words rather than in a shared SQLSTATE.\n (typeof e.message === \"string\" && /already exists/i.test(e.message))\n );\n}\n\n/**\n * SQLSTATEs that mean, unambiguously, *the object is already there*.\n *\n * A subset of {@link CONCURRENT_DDL_SQLSTATES} and a stricter question. The\n * broad set answers \"should this be retried\"; this one answers \"is it safe to\n * carry on as though the statement had succeeded\", which is a claim about the\n * end state rather than about the attempt. Deadlock is not in it — a deadlocked\n * statement did nothing and must be retried, not skipped.\n */\nconst DUPLICATE_OBJECT_SQLSTATES = new Set([\n \"42P06\", // duplicate_schema\n \"42P07\", // duplicate_table\n \"42710\" // duplicate_object — a type, an index, a constraint\n]);\n\n/**\n * Did this statement fail *because a peer already created the same object*?\n *\n * The narrow companion to {@link isConcurrentDdlRace}, for the one caller that\n * needs to tell \"someone beat me to it\" from \"this genuinely failed\": a loop\n * applying a schema plan, where treating every `23505` as a harmless race would\n * silently swallow the one that matters — a unique constraint that cannot be\n * added because the customer's existing rows violate it.\n *\n * `23505` is therefore only accepted when it names a `pg_catalog` index. That is\n * what a lost `CREATE TYPE`/`CREATE TABLE` race raises (`pg_type_typname_nsp_index`\n * is the one seen in practice); a unique violation on user data names the user's\n * own constraint and is left to the caller.\n *\n * With one exception, in {@link NOT_A_RACE_PG_INDEXES}.\n */\nexport function isDuplicateObjectRace(err: unknown): boolean {\n return hasInCauseChain(err, (e) => {\n if (typeof e.code !== \"string\") return false;\n if (DUPLICATE_OBJECT_SQLSTATES.has(e.code)) return true;\n if (e.code !== \"23505\") return false;\n // node-postgres puts the violated index in `constraint`; some paths only\n // carry it in the detail text, so check both rather than miss the race.\n const constraint = typeof e.constraint === \"string\" ? e.constraint : \"\";\n const detail = typeof e.detail === \"string\" ? e.detail : \"\";\n for (const index of NOT_A_RACE_PG_INDEXES) {\n if (constraint === index || detail.includes(index)) return false;\n }\n return constraint.startsWith(\"pg_\") || /\\bpg_[a-z_]+_index\\b/.test(detail);\n });\n}\n\n/**\n * `pg_catalog` indexes whose `23505` is never a race.\n *\n * `pg_enum_typid_label_index` is unique on (type, label), and one statement\n * violates it on its own: `CREATE TYPE t AS ENUM ('draft', 'draft')` — which is\n * what a collection with two enum entries carrying the same `id` generates.\n * Under the `pg_` prefix rule that read as \"a peer created it first\", so the\n * type was never created, boot carried on, and the column fell back to `TEXT`\n * with no enum behind it. Verified against PGlite: the duplicate `CREATE TYPE`\n * raises exactly this.\n *\n * The concurrent-boot case this rule exists for does not come through here at\n * all. Two pods adding the same label race on `ALTER TYPE … ADD VALUE`, which\n * raises `42710` (already in {@link DUPLICATE_OBJECT_SQLSTATES}) — and the\n * generator writes `ADD VALUE IF NOT EXISTS`, so it usually raises nothing.\n *\n * The duplicate `id` is rejected earlier now, by `validate-config`, which names\n * the property. This is the second line: a config that reaches the database with\n * one fails loudly instead of degrading.\n */\nconst NOT_A_RACE_PG_INDEXES = [\"pg_enum_typid_label_index\"];\n\nexport interface DdlBootstrapper {\n /**\n * Run one idempotent statement — `CREATE … IF NOT EXISTS`, `ALTER TABLE …\n * ADD COLUMN IF NOT EXISTS` — retrying the catalog race a simultaneous boot\n * produces. Never throws: a statement that cannot be made to work is logged\n * and the caller carries on to the next one.\n */\n ensureObject(label: string, sqlText: string): Promise<void>;\n\n /** Contain one step's failure so that the steps after it still run. */\n step(label: string, run: () => Promise<unknown>): Promise<void>;\n\n /**\n * Is this table there and readable? Asked with a query any SQL dialect\n * answers, rather than `to_regclass`, so a future non-Postgres SQL driver\n * gets a real answer instead of a syntax error read as \"missing\".\n */\n isReadable(table: string): Promise<boolean>;\n}\n\n/**\n * @param exec the driver's SQL escape hatch\n * @param scope log prefix identifying the caller, e.g. `\"cron-store\"`\n */\nexport function createDdlBootstrapper(exec: SqlExec, scope: string): DdlBootstrapper {\n /** Jittered, so peers that collided once do not collide again in lockstep. */\n const backoff = (attempt: number) =>\n new Promise(resolve => setTimeout(resolve, DDL_RETRY_BASE_MS * attempt * (1 + Math.random())));\n\n const step: DdlBootstrapper[\"step\"] = async (label, run) => {\n try {\n await run();\n } catch (err) {\n if (hasInCauseChain(err, e => e.code === \"REBASE_PROVISIONING_OFF\")) {\n logger.debug(`[${scope}] ${label}: not run — this backend changes nothing in its database`);\n return;\n }\n logger.error(`[${scope}] ${label} failed`, { error: err });\n }\n };\n\n return {\n step,\n\n ensureObject(label, sqlText) {\n return step(label, async () => {\n for (let attempt = 1; ; attempt++) {\n try {\n await exec(sqlText);\n return;\n } catch (err) {\n if (!isConcurrentDdlRace(err) || attempt >= DDL_ATTEMPTS) throw err;\n logger.debug(\n `[${scope}] Lost a create race for ${label} with another instance ` +\n `(attempt ${attempt}/${DDL_ATTEMPTS}) — retrying`\n );\n await backoff(attempt);\n }\n }\n });\n },\n\n async isReadable(table) {\n try {\n await exec(`SELECT 1 FROM ${table} WHERE false`);\n return true;\n } catch {\n return false;\n }\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,IAAM,yCAAyB,IAAI,IAAI;CACnC;CAAU;CAAS;CAAQ;CAAS;CAAU;CAAW;CACzD;CAAW;CAAW;CAAY;CAAU;AAChD,CAAC;;AAGD,SAAgB,uBAAuB,SAAyB;CAC5D,IAAI,OAAO;CACX,SAAS;EACL,OAAO,KAAK,UAAU;EACtB,IAAI,KAAK,WAAW,IAAI,GAAG;GACvB,MAAM,MAAM,KAAK,QAAQ,IAAI;GAC7B,OAAO,QAAQ,KAAK,KAAK,KAAK,MAAM,MAAM,CAAC;EAC/C,OAAO,IAAI,KAAK,WAAW,IAAI,GAAG;GAC9B,MAAM,MAAM,KAAK,QAAQ,IAAI;GAC7B,OAAO,QAAQ,KAAK,KAAK,KAAK,MAAM,MAAM,CAAC;EAC/C,OACI,OAAO;CAEf;AACJ;;AAGA,SAAS,eAAe,SAAyB;CAC7C,QAAQ,uBAAuB,OAAO,CAAC,CAAC,MAAM,YAAY,CAAC,GAAG,MAAM,GAAA,CAAI,YAAY;AACxF;;;;;;;AAQA,SAAgB,eAAe,SAA0B;CACrD,OAAO,uBAAuB,IAAI,eAAe,OAAO,CAAC;AAC7D;;;;;;;;AASA,IAAa,2BAAb,cAA8C,MAAM;CAG3B;CAFrB,OAAgB;CAEhB,YAAY,WAA4B;EACpC,MACI,2FACc,UAAU,KAAK,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,IAC/C;EAJiB,KAAA,YAAA;EAKjB,KAAK,OAAO;CAChB;AACJ;;;;;;;;;;;AAYA,SAAgB,oBAAoB,MAAwB;CACxD,QAAQ,SAAS,YAAY,eAAe,OAAO,IAC7C,QAAQ,OAAO,IAAI,yBAAyB,OAAO,CAAC,IACpD,KAAK,SAAS,OAAO;AAC/B;;AAGA,SAAgB,iBAAiB,MAAe,WAAyC;CACrF,OAAO,cAAc,QAAQ,oBAAoB,IAAI,IAAI;AAC7D;;;;;;AAQA,IAAa,2CAA2B,IAAI,IAAI;CAC5C;CACA;CACA;CACA;CACA;AACJ,CAAC;AAID,IAAM,oBAAoB;;;;;AAM1B,SAAgB,gBAAgB,KAAc,OAAyD;CACnG,IAAI,UAAmB;CACvB,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,SAAS,SAAS;EAChD,IAAI,OAAO,YAAY,UAAU;EACjC,MAAM,IAAI;EACV,IAAI,MAAM,CAAC,GAAG,OAAO;EACrB,UAAU,EAAE;CAChB;CACA,OAAO;AACX;;;;;;;;AASA,SAAgB,oBAAoB,KAAuB;CACvD,OAAO,gBAAgB,MAAM,MACxB,OAAO,EAAE,SAAS,YAAY,yBAAyB,IAAI,EAAE,IAAI,KAEjE,OAAO,EAAE,YAAY,YAAY,kBAAkB,KAAK,EAAE,OAAO,CACtE;AACJ;;;;;;;;;;AAWA,IAAM,6CAA6B,IAAI,IAAI;CACvC;CACA;CACA;AACJ,CAAC;;;;;;;;;;;;;;;;;AAkBD,SAAgB,sBAAsB,KAAuB;CACzD,OAAO,gBAAgB,MAAM,MAAM;EAC/B,IAAI,OAAO,EAAE,SAAS,UAAU,OAAO;EACvC,IAAI,2BAA2B,IAAI,EAAE,IAAI,GAAG,OAAO;EACnD,IAAI,EAAE,SAAS,SAAS,OAAO;EAG/B,MAAM,aAAa,OAAO,EAAE,eAAe,WAAW,EAAE,aAAa;EACrE,MAAM,SAAS,OAAO,EAAE,WAAW,WAAW,EAAE,SAAS;EACzD,KAAK,MAAM,SAAS,uBAChB,IAAI,eAAe,SAAS,OAAO,SAAS,KAAK,GAAG,OAAO;EAE/D,OAAO,WAAW,WAAW,KAAK,KAAK,uBAAuB,KAAK,MAAM;CAC7E,CAAC;AACL;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAM,wBAAwB,CAAC,2BAA2B;;;;;AA0B1D,SAAgB,sBAAsB,MAAe,OAAgC;;CAEjF,MAAM,WAAW,YACb,IAAI,SAAQ,YAAW,WAAW,SAAS,oBAAoB,WAAW,IAAI,KAAK,OAAO,EAAE,CAAC;CAEjG,MAAM,OAAgC,OAAO,OAAO,QAAQ;EACxD,IAAI;GACA,MAAM,IAAI;EACd,SAAS,KAAK;GACV,IAAI,gBAAgB,MAAK,MAAK,EAAE,SAAS,yBAAyB,GAAG;IACjE,OAAO,MAAM,IAAI,MAAM,IAAI,MAAM,yDAAyD;IAC1F;GACJ;GACA,OAAO,MAAM,IAAI,MAAM,IAAI,MAAM,UAAU,EAAE,OAAO,IAAI,CAAC;EAC7D;CACJ;CAEA,OAAO;EACH;EAEA,aAAa,OAAO,SAAS;GACzB,OAAO,KAAK,OAAO,YAAY;IAC3B,KAAK,IAAI,UAAU,IAAK,WACpB,IAAI;KACA,MAAM,KAAK,OAAO;KAClB;IACJ,SAAS,KAAK;KACV,IAAI,CAAC,oBAAoB,GAAG,KAAK,WAAA,GAAyB,MAAM;KAChE,OAAO,MACH,IAAI,MAAM,2BAA2B,MAAM,kCAC/B,QAAQ,eACxB;KACA,MAAM,QAAQ,OAAO;IACzB;GAER,CAAC;EACL;EAEA,MAAM,WAAW,OAAO;GACpB,IAAI;IACA,MAAM,KAAK,iBAAiB,MAAM,aAAa;IAC/C,OAAO;GACX,QAAQ;IACJ,OAAO;GACX;EACJ;CACJ;AACJ"}
|
|
@@ -83,7 +83,7 @@ export declare const RUNTIME_PROBE_PATHS: {
|
|
|
83
83
|
* rather than to a value: the entry exists to take the decision away from the
|
|
84
84
|
* project, not to make it here.
|
|
85
85
|
*/
|
|
86
|
-
export declare const TOPOLOGY_ENV_VARS: readonly ["REBASE_ROLE", "REBASE_FUNCTIONS_ONLY", "REBASE_FUNCTIONS_EXCLUDE", "REBASE_FUNCTIONS_UPSTREAM", "REBASE_CRON_SCHEDULER", "REBASE_JOB_WORKERS", "REBASE_RLS_AUDIT", "REBASE_MCP_ENABLED", "REBASE_MIGRATE_ON_BOOT", "TRUSTED_PROXY_HOPS", "REBASE_RATE_LIMIT_STORE", "REBASE_REQUIRE_SCHEMA_MATCH"];
|
|
86
|
+
export declare const TOPOLOGY_ENV_VARS: readonly ["REBASE_ROLE", "REBASE_FUNCTIONS_ONLY", "REBASE_FUNCTIONS_EXCLUDE", "REBASE_FUNCTIONS_UPSTREAM", "REBASE_CRON_SCHEDULER", "REBASE_JOB_WORKERS", "REBASE_RLS_AUDIT", "REBASE_MCP_ENABLED", "REBASE_MIGRATE_ON_BOOT", "REBASE_PROVISION", "REBASE_PROVISION_ONLY", "TRUSTED_PROXY_HOPS", "REBASE_RATE_LIMIT_STORE", "REBASE_REQUIRE_SCHEMA_MATCH"];
|
|
87
87
|
export type TopologyEnvVar = (typeof TOPOLOGY_ENV_VARS)[number];
|
|
88
88
|
/** Whether a variable name is one the deployer owns rather than the project. */
|
|
89
89
|
export declare function isTopologyEnvVar(name: string): name is TopologyEnvVar;
|
|
@@ -35,22 +35,6 @@ function warnDeprecated(key, message) {
|
|
|
35
35
|
console.warn(`[Rebase] Deprecated: ${message}`);
|
|
36
36
|
}
|
|
37
37
|
//#endregion
|
|
38
|
-
//#region src/utils/dynamic-import.ts
|
|
39
|
-
/**
|
|
40
|
-
* Native ESM dynamic import.
|
|
41
|
-
*
|
|
42
|
-
* Wrapped in `new Function` so TypeScript / bundlers don't down-compile the
|
|
43
|
-
* `import()` to `require()` — the loaders must import user-authored `.ts`/`.js`
|
|
44
|
-
* files at runtime using the host's real ESM loader. This is the production
|
|
45
|
-
* default for {@link loadFunctionsFromDirectory} / {@link loadCronJobsFromDirectory}.
|
|
46
|
-
*
|
|
47
|
-
* @internal
|
|
48
|
-
*/
|
|
49
|
-
var nativeDynamicImport = (() => {
|
|
50
|
-
const doImport = new Function("url", "return import(url)");
|
|
51
|
-
return (url) => doImport(url);
|
|
52
|
-
})();
|
|
53
|
-
//#endregion
|
|
54
38
|
//#region src/utils/load-failure.ts
|
|
55
39
|
/**
|
|
56
40
|
* How a function or cron file that failed to import is listed in the boot
|
|
@@ -72,9 +56,37 @@ function describeLoadFailure(file, err) {
|
|
|
72
56
|
}
|
|
73
57
|
return `${file} (threw: ${message})`;
|
|
74
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* The boot stopped because a file did not load, under `requireFilesLoaded`.
|
|
61
|
+
*
|
|
62
|
+
* One line, with the files first, because a deployer reads this out of a pod's
|
|
63
|
+
* log and quotes it as the reason a deploy failed.
|
|
64
|
+
*/
|
|
65
|
+
var FilesFailedToLoadError = class extends Error {
|
|
66
|
+
constructor(failures) {
|
|
67
|
+
super(`Failed to load ${failures.join("; ")}. requireFilesLoaded (REBASE_REQUIRE_FILES_LOADED) stops the boot rather than serve without them.`);
|
|
68
|
+
this.name = "FilesFailedToLoadError";
|
|
69
|
+
}
|
|
70
|
+
};
|
|
75
71
|
/** The advice for {@link describeLoadFailure}'s syntax-error entries. */
|
|
76
72
|
var SYNTAX_ERROR_ADVICE = " A file with a syntax error never ran: fix the syntax at the line shown (`tsc --noEmit` or your editor will point at it too).";
|
|
77
73
|
//#endregion
|
|
78
|
-
|
|
74
|
+
//#region src/utils/dynamic-import.ts
|
|
75
|
+
/**
|
|
76
|
+
* Native ESM dynamic import.
|
|
77
|
+
*
|
|
78
|
+
* Wrapped in `new Function` so TypeScript / bundlers don't down-compile the
|
|
79
|
+
* `import()` to `require()` — the loaders must import user-authored `.ts`/`.js`
|
|
80
|
+
* files at runtime using the host's real ESM loader. This is the production
|
|
81
|
+
* default for {@link loadFunctionsFromDirectory} / {@link loadCronJobsFromDirectory}.
|
|
82
|
+
*
|
|
83
|
+
* @internal
|
|
84
|
+
*/
|
|
85
|
+
var nativeDynamicImport = (() => {
|
|
86
|
+
const doImport = new Function("url", "return import(url)");
|
|
87
|
+
return (url) => doImport(url);
|
|
88
|
+
})();
|
|
89
|
+
//#endregion
|
|
90
|
+
export { warnDeprecated as a, describeLoadFailure as i, FilesFailedToLoadError as n, SYNTAX_ERROR_ADVICE as r, nativeDynamicImport as t };
|
|
79
91
|
|
|
80
|
-
//# sourceMappingURL=
|
|
92
|
+
//# sourceMappingURL=dynamic-import-Bi3XK5y-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dynamic-import-Bi3XK5y-.js","names":[],"sources":["../../common/src/util/deprecation.ts","../src/utils/load-failure.ts","../src/utils/dynamic-import.ts"],"sourcesContent":["/**\n * Keys already warned about in this process. A deprecated name is usually\n * reached on a hot path — every request, every render — and one line naming\n * the replacement is enough; repeating it buries everything else in the log.\n */\nconst warnedKeys = new Set<string>();\n\n/**\n * Say once, per process, that a deprecated public name was used.\n *\n * `key` identifies the deprecated name (`\"client.ws.setAuthTokenGetter\"`):\n * the first call with a key prints `message` with `console.warn`, every later\n * call with the same key prints nothing. `message` should name the\n * replacement, so the warning is the whole migration instruction.\n *\n * Node-free and browser-safe: it touches nothing but `console`.\n *\n * @example\n * ```ts\n * // Declared with `@deprecated Use \\`newName\\` instead.` in its JSDoc.\n * export function oldName(...args: Parameters<typeof newName>) {\n * warnDeprecated(\"oldName\", \"`oldName` is deprecated; use `newName` instead.\");\n * return newName(...args);\n * }\n * ```\n */\nexport function warnDeprecated(key: string, message: string): void {\n if (warnedKeys.has(key)) return;\n warnedKeys.add(key);\n console.warn(`[Rebase] Deprecated: ${message}`);\n}\n\n/**\n * Forget which keys have been warned about, so a test can assert that a\n * deprecated name warns — once — regardless of what ran before it.\n *\n * @internal For tests only.\n */\nexport function resetDeprecationWarningsForTests(): void {\n warnedKeys.clear();\n}\n","import * as path from \"path\";\n\n/**\n * How a function or cron file that failed to import is listed in the boot\n * log: `\"<file> (syntax error at <file>:<line>: <message>)\"` for a syntax\n * error, `\"<file> (threw: <message>)\"` for anything else.\n *\n * The two need different remedies. A file that *threw* usually read an\n * undefined env var at module scope; a file with a *syntax error* needs its\n * syntax fixed, and the loaders' advice is keyed on which one this is. Node\n * puts a syntax error's location only in the first line of its stack, so that\n * is where the line number comes from.\n */\nexport function describeLoadFailure(file: string, err: unknown): string {\n const message = err instanceof Error ? err.message : String(err);\n // By name, not `instanceof`: the error comes from whatever realm did the\n // import, and its SyntaxError is not this one's.\n if (err instanceof Error && err.name === \"SyntaxError\") {\n const firstLine = err.stack?.split(\"\\n\", 1)[0] ?? \"\";\n const at = /:(\\d+)(?::\\d+)?$/.exec(firstLine);\n const where = at ? ` at ${path.basename(file)}:${at[1]}` : \"\";\n return `${file} (syntax error${where}: ${message})`;\n }\n return `${file} (threw: ${message})`;\n}\n\n/**\n * The boot stopped because a file did not load, under `requireFilesLoaded`.\n *\n * One line, with the files first, because a deployer reads this out of a pod's\n * log and quotes it as the reason a deploy failed.\n */\nexport class FilesFailedToLoadError extends Error {\n constructor(failures: string[]) {\n super(\n `Failed to load ${failures.join(\"; \")}. ` +\n \"requireFilesLoaded (REBASE_REQUIRE_FILES_LOADED) stops the boot rather than serve without them.\"\n );\n this.name = \"FilesFailedToLoadError\";\n }\n}\n\n/** The advice for {@link describeLoadFailure}'s syntax-error entries. */\nexport const SYNTAX_ERROR_ADVICE =\n \" A file with a syntax error never ran: fix the syntax at the line shown \" +\n \"(`tsc --noEmit` or your editor will point at it too).\";\n","/**\n * Shape returned by a dynamic module import: an object whose `default`\n * property holds the module's default export (CJS `module.exports` is exposed\n * as `default` by Node's ESM interop).\n */\nexport interface ImportedModule {\n default?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * Imports a module by file URL. Injected into the directory loaders so tests\n * can supply a deterministic importer.\n */\nexport type ModuleImporter = (url: string) => Promise<ImportedModule>;\n\n/**\n * Native ESM dynamic import.\n *\n * Wrapped in `new Function` so TypeScript / bundlers don't down-compile the\n * `import()` to `require()` — the loaders must import user-authored `.ts`/`.js`\n * files at runtime using the host's real ESM loader. This is the production\n * default for {@link loadFunctionsFromDirectory} / {@link loadCronJobsFromDirectory}.\n *\n * @internal\n */\nexport const nativeDynamicImport: ModuleImporter = (() => {\n const doImport = new Function(\"url\", \"return import(url)\") as (url: string) => Promise<ImportedModule>;\n return (url: string) => doImport(url);\n})();\n"],"mappings":";;;;;;;;;;;AAKA,IAAM,6BAAa,IAAI,IAAY;;;;;;;;;;;;;;;;;;;;AAqBnC,SAAgB,eAAe,KAAa,SAAuB;CAC/D,IAAI,WAAW,IAAI,GAAG,GAAG;CACzB,WAAW,IAAI,GAAG;CAClB,QAAQ,KAAK,wBAAwB,SAAS;AAClD;;;;;;;;;;;;;;ACjBA,SAAgB,oBAAoB,MAAc,KAAsB;CACpE,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CAG/D,IAAI,eAAe,SAAS,IAAI,SAAS,eAAe;EACpD,MAAM,YAAY,IAAI,OAAO,MAAM,MAAM,CAAC,CAAC,CAAC,MAAM;EAClD,MAAM,KAAK,mBAAmB,KAAK,SAAS;EAE5C,OAAO,GAAG,KAAK,gBADD,KAAK,OAAO,OAAK,SAAS,IAAI,EAAE,GAAG,GAAG,OAAO,GACtB,IAAI,QAAQ;CACrD;CACA,OAAO,GAAG,KAAK,WAAW,QAAQ;AACtC;;;;;;;AAQA,IAAa,yBAAb,cAA4C,MAAM;CAC9C,YAAY,UAAoB;EAC5B,MACI,kBAAkB,SAAS,KAAK,IAAI,EAAE,kGAE1C;EACA,KAAK,OAAO;CAChB;AACJ;;AAGA,IAAa,sBACT;;;;;;;;;;;;;AClBJ,IAAa,6BAA6C;CACtD,MAAM,WAAW,IAAI,SAAS,OAAO,oBAAoB;CACzD,QAAQ,QAAgB,SAAS,GAAG;AACxC,EAAA,CAAG"}
|
package/dist/email/dev-sink.d.ts
CHANGED
|
@@ -82,6 +82,12 @@ export declare function createDevEmailSink(options?: {
|
|
|
82
82
|
* back and mail is still captured, it simply is not readable over HTTP.
|
|
83
83
|
*/
|
|
84
84
|
export declare function registerDevEmailSink(sink: DevEmailSink): DevEmailSink;
|
|
85
|
+
/**
|
|
86
|
+
* The registered mailbox whose `sendEmail` this is — the sink a backend's
|
|
87
|
+
* `auth.email.sendEmail` came from — or `undefined` when it is some other
|
|
88
|
+
* sender, or the process is production.
|
|
89
|
+
*/
|
|
90
|
+
export declare function devEmailSinkFor(sendEmail: object | undefined): DevEmailSink | undefined;
|
|
85
91
|
/** The registered mailbox, if there is one. */
|
|
86
92
|
export declare function activeDevEmailSink(): DevEmailSink | undefined;
|
|
87
93
|
/** Forget the registered mailbox. For tests, and for a server shutting down. */
|
package/dist/email/index.d.ts
CHANGED
|
@@ -5,7 +5,7 @@ export type { EmailService, EmailSendOptions, EmailSendResult, SMTPConfig, Email
|
|
|
5
5
|
export { SMTPEmailService, createEmailService } from "./smtp-email-service.js";
|
|
6
6
|
export { createUnconfiguredEmailService } from "./unconfigured.js";
|
|
7
7
|
export { html, raw, escapeHtml, RawHtml } from "./html.js";
|
|
8
|
-
export { createDevEmailSink, extractLinks, registerDevEmailSink, activeDevEmailSink, clearActiveDevEmailSink } from "./dev-sink.js";
|
|
8
|
+
export { createDevEmailSink, extractLinks, registerDevEmailSink, activeDevEmailSink, devEmailSinkFor, clearActiveDevEmailSink } from "./dev-sink.js";
|
|
9
9
|
export type { DevEmailSink, CapturedEmail } from "./dev-sink.js";
|
|
10
10
|
export { resolveEmailLinkBase, assertEmailLinkBases } from "./link-base.js";
|
|
11
11
|
export type { EmailLinkKind } from "./link-base.js";
|
|
@@ -2,9 +2,8 @@ import { createRequire as __rebaseCreateRequire } from "module";
|
|
|
2
2
|
import __rebaseProcess from "process";
|
|
3
3
|
globalThis.process ??= __rebaseProcess;
|
|
4
4
|
__rebaseCreateRequire(import.meta.url);
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { t as ApiError } from "./errors-OMWkKSH-.js";
|
|
5
|
+
import { G as isRelationalCollectionConfig } from "./src-Bh9LRPb9.js";
|
|
6
|
+
import { r as toSnakeCase } from "./strings.es-B7QLnHh2.js";
|
|
8
7
|
//#region ../utils/dist/plurals.es.js
|
|
9
8
|
/**
|
|
10
9
|
* Returns the singular of an English word.
|
|
@@ -257,13 +256,35 @@ function resolveRelation(relation, sourceCollection, propertyKey) {
|
|
|
257
256
|
...shared,
|
|
258
257
|
kind: "via",
|
|
259
258
|
cardinality: relation.cardinality,
|
|
260
|
-
writable:
|
|
259
|
+
writable: isSingleHopVia(relation.cardinality, relation.joinPath),
|
|
261
260
|
shared: true,
|
|
262
261
|
joinPath: relation.joinPath
|
|
263
262
|
};
|
|
264
263
|
default: throw new Error(`Unknown relation kind: ${JSON.stringify(relation)}`);
|
|
265
264
|
}
|
|
266
265
|
}
|
|
266
|
+
/**
|
|
267
|
+
* Whether a `via` chain has a single link for a write to set — the chains
|
|
268
|
+
* Rebase writes through a create or update:
|
|
269
|
+
*
|
|
270
|
+
* - **to-one, one step** (`{ table: target, on: { from, to } }`): the target
|
|
271
|
+
* row holds the key, and the write points it at this row, as a `hasOne`
|
|
272
|
+
* write does;
|
|
273
|
+
* - **to-many, two steps through one table between the ends**: that table
|
|
274
|
+
* holds the links, and the write sets them as junction rows, as a
|
|
275
|
+
* `manyToMany` write does.
|
|
276
|
+
*
|
|
277
|
+
* Both shipped writable (0.24.0 fixed the one-to-one writer). A longer chain
|
|
278
|
+
* has no single link to maintain: a to-many one found no junction connecting
|
|
279
|
+
* both ends and failed as a 500, and a to-one one re-pointed the target at
|
|
280
|
+
* whatever column the first step read. So those are read-only, and every door
|
|
281
|
+
* reads this answer through `writable` rather than re-deriving it.
|
|
282
|
+
*/
|
|
283
|
+
function isSingleHopVia(cardinality, joinPath) {
|
|
284
|
+
if (!Array.isArray(joinPath)) return false;
|
|
285
|
+
if (cardinality === "one") return joinPath.length === 1;
|
|
286
|
+
return joinPath.length === 2 && joinPath[0].table !== joinPath[1].table;
|
|
287
|
+
}
|
|
267
288
|
/** How this relation is addressed in an error message, before it has a resolved name. */
|
|
268
289
|
function describe(relation, sourceCollection, propertyKey) {
|
|
269
290
|
const name = relation.relationName ?? propertyKey;
|
|
@@ -612,57 +633,6 @@ function namesWhere(collection, restricted) {
|
|
|
612
633
|
};
|
|
613
634
|
}
|
|
614
635
|
//#endregion
|
|
615
|
-
|
|
616
|
-
/**
|
|
617
|
-
* The two query parameters soft delete adds to the REST surface.
|
|
618
|
-
*
|
|
619
|
-
* Kept in their own module so the call sites in `query-parser.ts` and the
|
|
620
|
-
* delete routes are a single line each: the parsing rules belong to soft
|
|
621
|
-
* delete, not to the parser, and a rule spread across the two files that read
|
|
622
|
-
* it is a rule that drifts.
|
|
623
|
-
*/
|
|
624
|
-
/** `?deleted=` — what to do about rows a soft delete has stamped. */
|
|
625
|
-
var DELETED_QUERY_PARAM = "deleted";
|
|
626
|
-
/** `?hard=` — ask for a real `DELETE` on a soft-delete collection. */
|
|
627
|
-
var HARD_DELETE_QUERY_PARAM = "hard";
|
|
628
|
-
/**
|
|
629
|
-
* `?deleted=include|only` → the driver's `withDeleted`.
|
|
630
|
-
*
|
|
631
|
-
* Spelled `deleted` on the wire and `withDeleted` in the driver, deliberately:
|
|
632
|
-
* the URL reads as a question about the rows (`?deleted=only` — "only the
|
|
633
|
-
* deleted ones"), and the driver option reads as an instruction about the query.
|
|
634
|
-
*
|
|
635
|
-
* A value neither word is a 400 rather than a silent fallback to the default.
|
|
636
|
-
* `?deleted=true` quietly hiding every deleted row is the worst of both: it
|
|
637
|
-
* looks like it worked and answers the opposite question. Absent is the
|
|
638
|
-
* default, which is "hide them".
|
|
639
|
-
*/
|
|
640
|
-
function parseWithDeleted(raw) {
|
|
641
|
-
if (raw === void 0 || raw === null || raw === "") return void 0;
|
|
642
|
-
const value = String(raw).trim().toLowerCase();
|
|
643
|
-
if (value === "include") return true;
|
|
644
|
-
if (value === "only") return "only";
|
|
645
|
-
throw ApiError.badRequest(`Invalid \`?${DELETED_QUERY_PARAM}=${String(raw)}\`. It takes 'include' (live rows and deleted ones) or 'only' (deleted rows alone). Omit it to see only the live rows.`, "INVALID_DELETED_PARAM");
|
|
646
|
-
}
|
|
647
|
-
/**
|
|
648
|
-
* `?hard=true` → a real `DELETE` on a collection that soft-deletes.
|
|
649
|
-
*
|
|
650
|
-
* Needs no permission beyond the delete it replaces: it is the same verb, and a
|
|
651
|
-
* second access-control surface for one operation is a second thing to get
|
|
652
|
-
* wrong. What it changes is whether the row can be restored.
|
|
653
|
-
*
|
|
654
|
-
* Only the exact words `true` and `1` mean yes. Anything else is a 400, not a
|
|
655
|
-
* "no" — a typo that silently soft-deletes when the caller asked to purge is a
|
|
656
|
-
* caller who believes the data is gone.
|
|
657
|
-
*/
|
|
658
|
-
function parseHardDelete(raw) {
|
|
659
|
-
if (raw === void 0 || raw === null || raw === "") return false;
|
|
660
|
-
const value = String(raw).trim().toLowerCase();
|
|
661
|
-
if (value === "true" || value === "1") return true;
|
|
662
|
-
if (value === "false" || value === "0") return false;
|
|
663
|
-
throw ApiError.badRequest(`Invalid \`?${HARD_DELETE_QUERY_PARAM}=${String(raw)}\`. It takes 'true' or 'false'.`, "INVALID_HARD_PARAM");
|
|
664
|
-
}
|
|
665
|
-
//#endregion
|
|
666
|
-
export { apiHiddenFieldNames as a, fieldKeyForColumn as c, isJunctionBackedRelation as d, isRelationRequired as f, toWireKey as g, resolveRelation as h, parseWithDeleted as i, findRelation as l, resolveCollectionRelations as m, HARD_DELETE_QUERY_PARAM as n, effectiveAccess as o, relationDeclaringProperty as p, parseHardDelete as r, restrictedFieldNames as s, DELETED_QUERY_PARAM as t, getTableName as u };
|
|
636
|
+
export { findRelation as a, isRelationRequired as c, resolveRelation as d, toWireKey as f, fieldKeyForColumn as i, relationDeclaringProperty as l, effectiveAccess as n, getTableName as o, restrictedFieldNames as r, isJunctionBackedRelation as s, apiHiddenFieldNames as t, resolveCollectionRelations as u };
|
|
667
637
|
|
|
668
|
-
//# sourceMappingURL=
|
|
638
|
+
//# sourceMappingURL=field-access-DYsvjI_P.js.map
|