@rebasepro/server 0.19.2-canary.gef769df → 0.20.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-DqZ9YiGA.js","names":[],"sources":["../../types/src/errors.ts","../../types/src/types/entities.ts","../../types/src/types/policy.ts","../../types/src/types/tenancy.ts","../../types/src/controllers/data.ts","../../types/src/controllers/data_driver.ts","../../../node_modules/.pnpm/object-hash@3.0.0/node_modules/object-hash/dist/object_hash.js","../../utils/dist/index.es.js","../../common/src/util/entities.ts","../../common/src/util/identity.ts","../../common/src/util/enums.ts","../../common/src/util/resolve-relation.ts","../../common/src/util/relations.ts","../../common/src/util/resolutions.ts","../../common/src/util/policy/sqlToPolicy.ts","../../common/src/util/policy/securityRuleToConditions.ts","../../common/src/util/builders.ts","../../common/src/util/tenant.ts","../../common/src/util/auth-default-policies.ts","../../common/src/util/junction-policies.ts","../../../node_modules/.pnpm/json-logic-js@2.0.5/node_modules/json-logic-js/logic.js","../../common/src/util/conditions.ts","../../../node_modules/.pnpm/fast-equals@6.0.2/node_modules/fast-equals/dist/es/index.mjs","../../common/src/data/resolveDataSource.ts","../../common/src/collections/CollectionRegistry.ts","../../common/src/collections/default-collections.ts","../../common/src/collections/field-access.ts","../../common/src/data/cursor.ts","../../common/src/data/sort-dialect.ts","../../common/src/data/include-spec.ts","../../common/src/data/query_builder.ts","../../common/src/data/paginate.ts","../../common/src/data/filter-dialect.ts","../../common/src/data/buildRebaseData.ts","../../common/src/data/buildRoutedRebaseData.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 // `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 */\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 unknown as Record<symbol, boolean>)[UNSUPPORTED_METHOD] = true;\n return stub as unknown 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 unknown as Record<symbol, boolean>)[UNSUPPORTED_METHOD] === true;\n}\n","import type { SearchMatch } from \"./search\";\n/**\n * New or existing status\n * @group Models\n */\nexport type EntityStatus = \"new\" | \"existing\" | \"copy\";\n\n/**\n * Representation of a entity fetched from the driver\n * @group Models\n */\nexport interface Entity<M extends Record<string, unknown> = Record<string, unknown>> {\n\n /**\n * ID of the entity\n */\n id: string | number;\n\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n path: string;\n\n /**\n * Current values\n */\n values: EntityValues<M>;\n\n /**\n * Why this entity is in a search result: which declared fields matched, and\n * the text around each hit.\n *\n * Present only on rows returned by a search that asked for it. A sibling of\n * `values` rather than a key inside it, because it describes the *query*,\n * not the record — nothing in the collection declares it, no form edits it,\n * and a record fetched by id never has one.\n */\n searchMatches?: SearchMatch[];\n\n /**\n * Which driver this entity belongs to (e.g., 'postgres', 'firestore').\n * If not specified, the default driver is assumed.\n */\n driver?: string;\n\n /**\n * Which database within the driver (e.g., for Firestore multi-database).\n * If not specified, the default database of the driver is used.\n */\n databaseId?: string;\n}\n\n/**\n * This type represents a record of key value pairs as described in an\n * entity collection.\n * @group Models\n */\nexport type EntityValues<M extends Record<string, unknown>> = M;\n\n/**\n * Props for creating a EntityReference\n */\nexport interface EntityReferenceProps {\n /** ID of the entity */\n id: string;\n /** Path of the collection (relative to the root of the database) */\n path: string;\n /** Which driver (e.g., 'postgres', 'firestore'). Defaults to \"(default)\" */\n driver?: string;\n /** Which database within the driver. Defaults to \"(default)\" */\n databaseId?: string;\n}\n\n/**\n * Class used to create a reference to a entity in a different path.\n *\n * @example\n * // Simple reference (most common case - single driver, single db)\n * new EntityReference({ id: \"123\", path: \"users\" })\n *\n * // Reference to a different driver (e.g., Firestore)\n * new EntityReference({ id: \"123\", path: \"analytics\", driver: \"firestore\" })\n *\n * // Reference to a specific database within a driver\n * new EntityReference({ id: \"123\", path: \"orders\", driver: \"postgres\", databaseId: \"orders_db\" })\n */\nexport class EntityReference {\n\n readonly __type = \"reference\";\n /**\n * ID of the entity\n */\n readonly id: string;\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n readonly path: string;\n\n /**\n * Which driver (e.g., 'postgres', 'firestore').\n * Defaults to \"(default)\" if not specified.\n */\n readonly driver?: string;\n\n /**\n * Which database within the driver.\n * Defaults to \"(default)\" if not specified.\n */\n readonly databaseId?: string;\n\n /**\n * Create a reference to a entity.\n *\n * @example\n * // Simple reference (most common case)\n * new EntityReference({ id: \"123\", path: \"users\" })\n *\n * // With driver\n * new EntityReference({ id: \"123\", path: \"analytics\", driver: \"firestore\" })\n */\n constructor(props: EntityReferenceProps) {\n this.id = props.id;\n this.path = props.path;\n this.driver = props.driver;\n this.databaseId = props.databaseId;\n }\n\n get pathWithId() {\n return `${this.path}/${this.id}`;\n }\n\n /**\n * Get the full path including driver and database prefixes if specified.\n * For the common case (single driver, single db), this just returns pathWithId.\n */\n get fullPath() {\n const parts: string[] = [];\n\n // Add driver prefix if not default\n if (this.driver && this.driver !== \"(default)\") {\n parts.push(this.driver);\n }\n\n // Add database prefix if specified\n if (this.databaseId && this.databaseId !== \"(default)\") {\n parts.push(this.databaseId);\n }\n\n if (parts.length > 0) {\n return `${parts.join(\":\")}:::${this.path}/${this.id}`;\n }\n return this.pathWithId;\n }\n\n isEntityReference() {\n return true;\n }\n}\n\n/**\n * Class used to create a reference to a entity in a different path\n */\nexport class EntityRelation {\n\n readonly __type = \"relation\";\n /**\n * ID of the entity\n */\n readonly id: string | number;\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */\n readonly path: string;\n\n /**\n * Pre-fetched data payload to eliminate N+1 queries.\n * When present, clients can use this directly instead of fetching.\n */\n readonly data?: Record<string, unknown>;\n\n constructor(id: string | number, path: string, data?: Record<string, unknown>) {\n this.id = id;\n this.path = path;\n this.data = data;\n }\n\n get pathWithId() {\n return `${this.path}/${this.id}`;\n }\n\n isEntityReference() {\n return false;\n }\n\n isEntityRelation() {\n return true;\n }\n}\n\nexport class GeoPoint {\n\n /**\n * The latitude of this GeoPoint instance.\n */\n readonly latitude: number;\n /**\n * The longitude of this GeoPoint instance.\n */\n readonly longitude: number;\n\n constructor(latitude: number, longitude: number) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n}\n\nexport class Vector {\n readonly value: number[];\n\n constructor(value: number[]) {\n this.value = value;\n }\n}\n","/**\n * Structured, engine-agnostic policy expressions.\n *\n * A {@link PolicyExpression} is the single source of truth for a row-level\n * security condition. It is compiled to Postgres `USING`/`WITH CHECK` SQL\n * (authoritative enforcement) and independently evaluated in JavaScript (to\n * drive the admin UI, and — in future — to enforce on engines without native\n * RLS such as MongoDB). Because both the SQL and the JS decision derive from\n * the *same* expression, the UI matches database enforcement by construction —\n * no drift between two hand-written implementations.\n *\n * The only escape hatch that cannot be evaluated client-side is the\n * {@link RawPolicyExpression} node (`{ kind: \"raw\" }`): it preserves full\n * PostgreSQL power but, being arbitrary SQL, is treated as *unknown* by the\n * JavaScript evaluator (never silently allowed) and reflected exactly in the UI\n * via server-computed capability flags.\n *\n * @group Models\n */\nexport type PolicyExpression =\n | TruePolicyExpression\n | FalsePolicyExpression\n | AndPolicyExpression\n | OrPolicyExpression\n | NotPolicyExpression\n | ComparePolicyExpression\n | RolesOverlapPolicyExpression\n | RolesContainPolicyExpression\n | AuthenticatedPolicyExpression\n | RegisteredPolicyExpression\n | ServerContextPolicyExpression\n | ExistsInPolicyExpression\n | RawPolicyExpression;\n\n/**\n * The id a request without a logged-in user reports as `rebase.uid()`.\n *\n * A user-context request always sets `app.uid`: blank would read back as\n * `NULL`, and `NULL` is how the trusted server context is recognised, so an\n * anonymous visitor would be promoted to server privileges. The driver\n * therefore substitutes this sentinel at the single chokepoint where the GUC\n * is set.\n *\n * The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a\n * tautology on the user path** — it is true for anonymous visitors too. Use\n * {@link policy.authenticated} to mean \"signed in\", and\n * {@link policy.serverContext} to mean \"the trusted server context\". Do not\n * hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one\n * literal is not enough.\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_ID = \"anonymous\";\n\n/**\n * Every uid that has ever meant \"nobody is signed in\" — newest first.\n *\n * There are two because there were two. The types, the policy compiler, the\n * JavaScript evaluator and the linter were all built on\n * {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated\n * callers as `'anon'` — so `policy.authenticated()`, which compiled to\n * `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The\n * sanctioned way to write \"signed in\" granted to everyone, and the linter\n * flagged the spelling that actually worked as a foreign convention.\n *\n * The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here\n * because policies outlive the server that generated them: a database still\n * holding policies from before the fix, or a project whose server has not been\n * upgraded yet, must not become a grant in either direction. Compile against\n * this list, not against a single literal.\n *\n * No real user id is ever one of these, so a match is always \"not signed in\".\n *\n * @group Models\n */\nexport const ANONYMOUS_USER_IDS: readonly string[] = [ANONYMOUS_USER_ID, \"anon\"];\n\n/**\n * Whether a uid stands for \"no one is signed in\", in any spelling rebase has\n * used. `null`/`undefined` is the trusted server context, not an anonymous\n * caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.\n *\n * @group Models\n */\nexport function isAnonymousUid(uid: string | null | undefined): boolean {\n return typeof uid === \"string\" && ANONYMOUS_USER_IDS.includes(uid);\n}\n\n/** Always allows. Compiles to `true`. @group Models */\nexport interface TruePolicyExpression {\n kind: \"true\";\n}\n\n/** Always denies. Compiles to `false`. @group Models */\nexport interface FalsePolicyExpression {\n kind: \"false\";\n}\n\n/** Logical AND — every operand must pass. @group Models */\nexport interface AndPolicyExpression {\n kind: \"and\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical OR — at least one operand must pass. @group Models */\nexport interface OrPolicyExpression {\n kind: \"or\";\n operands: readonly PolicyExpression[];\n}\n\n/** Logical negation. @group Models */\nexport interface NotPolicyExpression {\n kind: \"not\";\n operand: PolicyExpression;\n}\n\n/** Comparison operators available to {@link ComparePolicyExpression}. @group Models */\nexport type PolicyCompareOperator = \"eq\" | \"neq\" | \"lt\" | \"lte\" | \"gt\" | \"gte\";\n\n/**\n * Compares two operands, e.g. `owner_id = rebase.uid()`.\n * @group Models\n */\nexport interface ComparePolicyExpression {\n kind: \"compare\";\n op: PolicyCompareOperator;\n left: PolicyOperand;\n right: PolicyOperand;\n}\n\n/**\n * True when the user holds *at least one* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') && ARRAY[...]`.\n * @group Models\n */\nexport interface RolesOverlapPolicyExpression {\n kind: \"rolesOverlap\";\n roles: readonly string[];\n}\n\n/**\n * True when the user holds *all* of the given application roles.\n * Compiles to `string_to_array(rebase.roles(), ',') @> ARRAY[...]`.\n * @group Models\n */\nexport interface RolesContainPolicyExpression {\n kind: \"rolesContain\";\n roles: readonly string[];\n}\n\n/**\n * True when a signed-in user is making the request. Compiles to\n * `rebase.uid() IS NOT NULL AND rebase.uid() <> 'anonymous'`.\n *\n * Both halves are load-bearing. `IS NOT NULL` excludes the server context;\n * the {@link ANONYMOUS_USER_ID} comparison excludes anonymous visitors, who\n * *do* carry a non-null `rebase.uid()`. Checking only `IS NOT NULL` grants to\n * everyone — see {@link ANONYMOUS_USER_ID}.\n *\n * `policy.not(policy.authenticated())` therefore means \"anonymous visitor or\n * the server context\". To single out the server context, use\n * {@link ServerContextPolicyExpression}.\n * @group Models\n */\nexport interface AuthenticatedPolicyExpression {\n kind: \"authenticated\";\n}\n\n/**\n * True for a signed-in caller who has an ACCOUNT — not a guest.\n *\n * The distinction {@link AuthenticatedPolicyExpression} cannot make. Anonymous\n * SIGN-IN (`POST /auth/anonymous`) mints a real user row with a real uid and a\n * real session, so such a caller is \"authenticated\" by every test that looks at\n * `rebase.uid()`: same shape, same default role, indistinguishable inside a\n * policy. On a deployment with anonymous sign-in enabled, every rule meaning\n * \"a signed-in person\" therefore also meant \"anybody at all\", since pressing\n * Continue as guest needs no email, no password and no agreement to anything.\n *\n * Note the two senses of \"anonymous\", which is the reason this was easy to\n * miss. {@link ANONYMOUS_USER_ID} is the sentinel for a request carrying NO\n * session, and `authenticated()` already excludes it. A guest is the other\n * thing: a session with nobody behind it. This node excludes both.\n *\n * Compiles to `authenticated() AND NOT rebase.is_anonymous()`.\n *\n * Use it wherever a rule is about a person who could be held responsible for\n * something — writing a review, joining an organization, spending money. Use\n * `authenticated()` where a guest is genuinely welcome, which is what\n * anonymous sign-in is for: a cart before checkout, a draft before signup.\n * @group Models\n */\nexport interface RegisteredPolicyExpression {\n kind: \"registered\";\n}\n\n/**\n * True only in the trusted **server context** — the built-in flows that run\n * without a user (signup, migrations, `dataAsAdmin`) set no user GUC, so\n * `rebase.uid()` is `NULL` for them and only for them. Compiles to\n * `rebase.uid() IS NULL`.\n *\n * This is what lets the owner connection satisfy a policy even under FORCE RLS.\n * It is deliberately a primitive rather than `not(authenticated())`: the two\n * meant the same thing while `authenticated` ignored {@link ANONYMOUS_USER_ID},\n * and conflating them is what turns a server-only grant into an anonymous one.\n *\n * The JavaScript evaluator always returns `false` for this node — a client is\n * never the server context.\n * @group Models\n */\nexport interface ServerContextPolicyExpression {\n kind: \"serverContext\";\n}\n\n/**\n * Membership / relational access: true when at least one row exists in another\n * collection (a join/membership table) matching `where`. This is what lets you\n * scope reads to \"rows whose team the caller belongs to\" without an N+1\n * per-row lookup — it compiles to a single correlated `EXISTS` subquery.\n *\n * Inside `where`, {@link FieldPolicyOperand} (`policy.field`) references a column\n * of the joined collection, while {@link OuterFieldPolicyOperand}\n * (`policy.outerField`) references a column of the row being checked (the outer\n * table under RLS). Combine with {@link AuthUidPolicyOperand} to correlate to\n * the caller.\n *\n * @example\n * ```ts\n * // documents visible only to members of the document's team:\n * policy.existsIn({\n * collection: \"team_members\",\n * where: policy.and(\n * policy.compare(policy.field(\"team_id\"), \"eq\", policy.outerField(\"team_id\")),\n * policy.compare(policy.field(\"user_id\"), \"eq\", policy.authUid()),\n * ),\n * })\n * // → EXISTS (SELECT 1 FROM team_members _ex0\n * // WHERE _ex0.team_id = documents.team_id AND _ex0.user_id = rebase.uid())\n * ```\n *\n * Postgres-authoritative: like {@link RawPolicyExpression}, the JavaScript\n * evaluator treats it as *unknown* (it cannot run a subquery client-side), so\n * enforcement is always the database's.\n * @group Models\n */\nexport interface ExistsInPolicyExpression {\n kind: \"existsIn\";\n /** Slug of the collection to search (the join / membership table). */\n collection: string;\n /** Condition evaluated against the joined collection's rows. */\n where: PolicyExpression;\n}\n\n/**\n * A raw PostgreSQL boolean expression — the full-power escape hatch.\n *\n * Columns can be referenced as `{column_name}`. This is Postgres-only and\n * **server-authoritative**: the JavaScript evaluator cannot evaluate arbitrary\n * SQL, so it treats this node as *unknown* rather than guessing.\n * @group Models\n */\nexport interface RawPolicyExpression {\n kind: \"raw\";\n sql: string;\n}\n\n/**\n * An operand referenced by a {@link ComparePolicyExpression}.\n * @group Models\n */\nexport type PolicyOperand =\n | FieldPolicyOperand\n | OuterFieldPolicyOperand\n | LiteralPolicyOperand\n | AuthUidPolicyOperand\n | AuthRolesPolicyOperand\n | AuthClaimPolicyOperand;\n\n/** A column value on the row being evaluated. @group Models */\nexport interface FieldPolicyOperand {\n kind: \"field\";\n /** The property/column name (resolved to its DB column when compiled). */\n name: string;\n}\n\n/**\n * A column value on the *outer* row when used inside {@link ExistsInPolicyExpression}\n * — i.e. the row the RLS policy is being evaluated for, referenced from within the\n * subquery. Outside an `existsIn` it is equivalent to {@link FieldPolicyOperand}.\n * @group Models\n */\nexport interface OuterFieldPolicyOperand {\n kind: \"outerField\";\n /** The property/column name on the outer collection. */\n name: string;\n}\n\n/** A constant value. @group Models */\nexport interface LiteralPolicyOperand {\n kind: \"literal\";\n value: string | number | boolean | null;\n}\n\n/** The current user's id — compiles to `rebase.uid()`. @group Models */\nexport interface AuthUidPolicyOperand {\n kind: \"authUid\";\n}\n\n/**\n * The current user's roles as an array — compiles to\n * `string_to_array(rebase.roles(), ',')`.\n * @group Models\n */\nexport interface AuthRolesPolicyOperand {\n kind: \"authRoles\";\n}\n\n/**\n * A named claim on the caller's session token — compiles to\n * `NULLIF(rebase.jwt() ->> '<name>', '')`.\n *\n * The operand multi-tenancy is built on, and the reason it is an operand rather\n * than a {@link RawPolicyExpression}: a claim arrives as **text**, and the\n * column it is compared against usually is not. `org_id = rebase.jwt() ->>\n * 'org_id'` on a `uuid` column is not a policy that denies — it is\n * `CREATE POLICY` failing with \"operator does not exist: uuid = text\", and a\n * table left with RLS enabled and no policy denies every row. Casting the\n * *column* to text instead compiles, but takes the index off the one predicate\n * that is ANDed into every read of the table.\n *\n * As an operand the compiler can see both sides: it casts the claim to the\n * column's type, guarded so a malformed claim denies rather than raising\n * `invalid input syntax` on every query, and the column keeps its index.\n *\n * An absent claim, and a claim set to the empty string, are both NULL — and a\n * comparison against NULL is never true, so a caller carrying no claim sees no\n * rows rather than all of them.\n *\n * Only *custom* claims are reachable. `uid`, `roles`, `aal` and `isAnonymous`\n * are identity claims written after the custom ones when a token is minted,\n * precisely so a claims hook cannot assert them; they have their own operands\n * ({@link AuthUidPolicyOperand}, {@link AuthRolesPolicyOperand}) and naming one\n * here is refused.\n *\n * Postgres-authoritative: the JavaScript evaluator reports *unknown* rather\n * than reproducing Postgres's cast semantics (uuid case folding, numeric\n * widening) a second time and getting them subtly wrong.\n * @group Models\n */\nexport interface AuthClaimPolicyOperand {\n kind: \"authClaim\";\n /** The claim's name on the token, e.g. `\"org_id\"`. */\n name: string;\n}\n\n// ── Constructor helpers ──────────────────────────────────────────────\n// Small, dependency-free builders so callers (and the desugaring in\n// `@rebasepro/common`) can assemble expressions without object-literal noise.\n\n/** @group Models */\nexport const policy = {\n true: (): TruePolicyExpression => ({ kind: \"true\" }),\n false: (): FalsePolicyExpression => ({ kind: \"false\" }),\n and: (...operands: readonly PolicyExpression[]): AndPolicyExpression => ({ kind: \"and\",\noperands: operands as PolicyExpression[] }),\n or: (...operands: readonly PolicyExpression[]): OrPolicyExpression => ({ kind: \"or\",\noperands: operands as PolicyExpression[] }),\n not: (operand: PolicyExpression): NotPolicyExpression => ({ kind: \"not\",\noperand }),\n compare: (left: PolicyOperand, op: PolicyCompareOperator, right: PolicyOperand): ComparePolicyExpression =>\n ({ kind: \"compare\",\nop,\nleft,\nright }),\n rolesOverlap: (roles: readonly string[]): RolesOverlapPolicyExpression => ({ kind: \"rolesOverlap\",\nroles: roles as string[] }),\n rolesContain: (roles: readonly string[]): RolesContainPolicyExpression => ({ kind: \"rolesContain\",\nroles: roles as string[] }),\n authenticated: (): AuthenticatedPolicyExpression => ({ kind: \"authenticated\" }),\n registered: (): RegisteredPolicyExpression => ({ kind: \"registered\" }),\n serverContext: (): ServerContextPolicyExpression => ({ kind: \"serverContext\" }),\n existsIn: (args: { collection: string; where: PolicyExpression }): ExistsInPolicyExpression =>\n ({ kind: \"existsIn\",\ncollection: args.collection,\nwhere: args.where }),\n raw: (sql: string): RawPolicyExpression => ({ kind: \"raw\",\nsql }),\n field: (name: string): FieldPolicyOperand => ({ kind: \"field\",\nname }),\n outerField: (name: string): OuterFieldPolicyOperand => ({ kind: \"outerField\",\nname }),\n literal: (value: string | number | boolean | null): LiteralPolicyOperand => ({ kind: \"literal\",\nvalue }),\n authUid: (): AuthUidPolicyOperand => ({ kind: \"authUid\" }),\n authRoles: (): AuthRolesPolicyOperand => ({ kind: \"authRoles\" }),\n authClaim: (name: string): AuthClaimPolicyOperand => ({ kind: \"authClaim\",\nname })\n};\n","/**\n * First-class multi-tenancy: one declaration, every layer.\n *\n * A tenant-scoped collection was expert work. It took four separate,\n * hand-written pieces that nothing checked against each other — a column, an\n * `existsIn` or raw RLS rule, a value stamped on every insert by a callback,\n * and an index somebody had to remember. Miss the index and the table scans;\n * miss the stamp and the row is invisible the moment it is written; miss the\n * rule and every tenant reads every other tenant's rows, which is the failure\n * nothing surfaces until it is a disclosure.\n *\n * {@link CollectionTenantConfig} is the one place that says \"this collection\n * belongs to a tenant\", and the four pieces are derived from it:\n *\n * - the column is `NOT NULL` and gets a btree index (`planSchema`);\n * - a **restrictive** RLS policy is injected for every operation, so it\n * composes with (rather than replaces) whatever `securityRules` the\n * collection declares — tenancy narrows, it never grants;\n * - the write path stamps the caller's tenant on create, refuses a write that\n * names another tenant, and refuses an update that moves a row between\n * tenants;\n * - the OpenAPI document marks the field so a generated client can see it.\n *\n * @see CollectionTenantConfig\n * @group Models\n */\n\n/**\n * The caller's tenant comes from a claim on their session token.\n *\n * The single-tenant-per-user shape: an identity provider (or Rebase's own\n * custom-claims hook) puts the organization on the token, and every request\n * carries it. Compiles to a comparison against `rebase.jwt() ->> '<claim>'`,\n * which is the same value a hand-written rule would read — so the generated\n * policy and anything an author writes beside it agree by construction.\n *\n * @group Models\n */\nexport interface TenantClaimSource {\n /**\n * The claim's name on the access token, e.g. `\"org_id\"`.\n *\n * Custom claims survive verification and reach RLS as `rebase.jwt()`; the\n * identity claims (`uid`, `roles`, `aal`, `isAnonymous`) are written after\n * them when a token is minted and cannot be shadowed, so naming one of\n * those here is refused rather than quietly reading the identity.\n */\n claim: string;\n}\n\n/**\n * The caller's tenants come from rows of a membership collection.\n *\n * The many-tenants-per-user shape — a `memberships` table with a user column\n * and a tenant column, which is how a person belongs to three organizations at\n * once. Compiles to a correlated `EXISTS` over that table (`policy.existsIn`),\n * so the database answers \"is the caller a member of this row's tenant?\" in the\n * same query rather than in an N+1 of lookups.\n *\n * Nothing is put on the token, so nothing has to be re-minted when somebody\n * joins or leaves a tenant — the next statement already sees the new row.\n *\n * @group Models\n */\nexport interface TenantMembershipSource {\n membership: {\n /** Slug of the collection holding the memberships. */\n collection: string;\n /** The property on it that holds the user id (compared to `rebase.uid()`). */\n userField: string;\n /** The property on it that holds the tenant id. */\n tenantField: string;\n };\n}\n\n/** Where the caller's tenant comes from. @group Models */\nexport type TenantSource = TenantClaimSource | TenantMembershipSource;\n\n/** Narrow a {@link TenantSource} to its claim form. @group Models */\nexport function isTenantClaimSource(source: TenantSource): source is TenantClaimSource {\n return typeof (source as TenantClaimSource).claim === \"string\";\n}\n\n/** Narrow a {@link TenantSource} to its membership form. @group Models */\nexport function isTenantMembershipSource(source: TenantSource): source is TenantMembershipSource {\n return typeof (source as TenantMembershipSource).membership === \"object\"\n && (source as TenantMembershipSource).membership !== null;\n}\n\n/**\n * The roles tenancy does not apply to, when the collection names none.\n *\n * `admin`, mirroring the security baseline every collection already carries\n * (`<table>_default_admin_read` / `_write`): the Studio, `dataAsAdmin` and a\n * support operator all run with it, and a tenancy rule that locked them out\n * would make the admin panel show an empty table on a collection full of rows.\n *\n * @group Models\n */\nexport const DEFAULT_TENANT_BYPASS_ROLES: readonly string[] = [\"admin\"];\n\n/**\n * Declare a collection tenant-scoped.\n *\n * ```ts\n * export const posts = buildCollection({\n * slug: \"posts\",\n * properties: {\n * orgId: { type: \"string\", validation: { required: true } },\n * title: { type: \"string\" }\n * },\n * tenant: { field: \"orgId\", from: { claim: \"org_id\" } }\n * });\n * ```\n *\n * The property has to exist — this says what a column *means*, it does not\n * conjure one into existence, exactly like `softDelete`. A config naming a\n * property the collection does not declare is refused at boot rather than at\n * the first read.\n *\n * ## What it composes with\n *\n * The injected policy is **restrictive**, so it is ANDed with every permissive\n * policy on the table: `securityRules`, `ownerField`, the injected admin\n * baseline. That is the only composition that is safe by construction — a\n * permissive tenancy policy would OR with the author's rules and a single\n * `access: \"public\"` rule would take the whole tenancy boundary off.\n *\n * Postgres-only. RLS is what enforces it, and an engine without row-level\n * security cannot be given this guarantee by an application-layer filter that\n * a raw query goes around.\n *\n * @group Models\n */\nexport interface CollectionTenantConfig<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * The property holding the tenant id.\n *\n * A `string` or `number` property, or a `reference` / `belongsTo` relation\n * to the tenants collection — in which case the foreign key the relation\n * already declares is the column, and no second one is created.\n *\n * The column is made `NOT NULL` and indexed: a nullable tenant column is a\n * row that belongs to nobody and is therefore invisible to everybody, and\n * an unindexed one turns every RLS-filtered read into a sequential scan.\n */\n field: Extract<keyof M, string> | string;\n\n /** Where the caller's tenant comes from. */\n from: TenantSource;\n\n /**\n * Roles that see and write across every tenant.\n *\n * Defaults to {@link DEFAULT_TENANT_BYPASS_ROLES}. An empty array means\n * \"nobody bypasses\" — the trusted server context still does, because it is\n * what runs migrations and the auth flows, and a policy that excluded it\n * would break the boot rather than protect a tenant.\n */\n bypassRoles?: readonly string[];\n}\n","import type { VectorSearchParams } from \"./data_driver\";\nimport type { ComputedSortField, SearchMatch } from \"../types/search\";\nimport { Entity, EntityValues } from \"../types/entities\";\nimport { WhereFilterOp, FieldPath, NonColumnFieldPath, FilterValues, NullsPlacement, OrderBySpec, RelationAggregateSort } from \"../types/filter-operators\";\n\n/**\n * The element type of an array column, and the column's own type otherwise.\n *\n * A generated SDK emits an `array` property as `Array<X>` and a to-many\n * relation as `Array<TargetRow>`, so this is what `array-contains` compares\n * against on either.\n */\nexport type ElementOf<T> = T extends readonly (infer E)[] ? E : T;\n\n/**\n * The `id` of a row-shaped element, and `never` for anything else.\n *\n * A to-many relation is emitted as `Array<TargetRow>`, but the filter compilers\n * compare a relation by **id** — `buildRelationFilterPredicate` in\n * `@rebasepro/server-postgres` unwraps a relation value down to its id — so\n * `where(\"tags\", \"array-contains\", tagId)` is the call that works, and the\n * element type alone would refuse it.\n */\nexport type IdOf<E> = E extends { id: infer I } ? I : never;\n\n/**\n * One member of an array column: its element, or — when the element is a row —\n * that row's id, which is what a relation filter is actually compared against.\n */\nexport type WhereElementOf<T> = ElementOf<T> | IdOf<ElementOf<T>>;\n\n/**\n * The value a given operator takes on a column of type `T`.\n *\n * `WhereValue<T>` was one value type for all sixteen operators, which made\n * `array-contains` uncallable from a generated SDK — it is the one operator\n * whose value is an *element* of the column rather than the column's own type,\n * so on `tags: string[]` it wanted a `string[]` and the documented\n * `.where(\"tags\", \"array-contains\", \"featured\")` was a compile error. The\n * spelling that did compile, `[\"featured\"]`, builds `@> ARRAY[$1]` with the\n * whole array bound as the single element and matches nothing: the correct\n * query rejected, the accepted query silently wrong.\n *\n * The branches mirror `buildSingleFilterCondition` in `@rebasepro/server-postgres`:\n *\n * - `array-contains` → one element of the column (or a related row's id).\n * - `in` / `not-in` / `array-contains-any` → a list of elements; a bare element\n * is read as the one-element list, and `null` is a null check.\n * - `like` / `ilike` / `not-like` / `not-ilike` → a SQL pattern. Always a\n * string, including on numeric and date columns, which the driver casts.\n * - `is-null` / `is-not-null` → nothing; the value is ignored everywhere.\n * - everything else → the column's own type, or `null` for a null comparison.\n *\n * Distributes over `Op`, so a caller holding an unnarrowed `WhereFilterOp`\n * (a dynamic filter UI, say) gets the union of every branch and stays as\n * permissive as it was.\n */\nexport type WhereValueFor<Op extends WhereFilterOp, T> =\n Op extends \"array-contains\"\n ? WhereElementOf<T>\n : Op extends \"in\" | \"not-in\" | \"array-contains-any\"\n ? readonly WhereElementOf<T>[] | WhereElementOf<T> | null\n : Op extends \"like\" | \"ilike\" | \"not-like\" | \"not-ilike\"\n ? string\n : Op extends \"is-null\" | \"is-not-null\"\n ? null | undefined\n : T | null;\n\n/**\n * A group of conditions combined with `and`, `or`, or negated with `not`.\n *\n * ## `not`\n *\n * `not` negates the **conjunction** of its `conditions`: `not(a)` is `NOT a`,\n * and `not(a, b)` is `NOT (a AND b)`. One rule, stated here and applied\n * identically by the wire codec (`or(...)`/`and(...)`/`not(...)` in\n * `@rebasepro/common`), the REST `?not=` parameter and every driver compiler,\n * so a negation means the same thing whichever end writes it.\n *\n * Negation is not expressible by inverting the operators inside the group: SQL\n * three-valued logic makes `NOT (a AND b)` and `(NOT a) OR (NOT b)` differ the\n * moment a NULL is involved, and only one of them is what the caller wrote. It\n * compiles to a real `NOT (...)`.\n */\nexport interface LogicalCondition {\n type: \"and\" | \"or\" | \"not\";\n conditions: (FilterCondition | LogicalCondition)[];\n}\n\nexport interface FilterCondition {\n column: string;\n operator: WhereFilterOp;\n value: unknown;\n}\n\n/**\n * How one relation is loaded by {@link FindParams.include}.\n *\n * `true` loads the relation whole. The object form narrows it — the same four\n * knobs a top-level query has, applied to the rows *inside* one relation — and\n * `include` nests, so a query can ask for \"each post's five newest published\n * comments, each with its author\" in one request.\n *\n * ```ts\n * include: {\n * comments: {\n * limit: 5,\n * where: { published: [\"==\", true] },\n * orderBy: [\"created_at\", \"desc\"],\n * include: { author: true }\n * }\n * }\n * ```\n *\n * Nesting is bounded at {@link MAX_INCLUDE_DEPTH} hops. Each hop is another\n * batched query, and the bound is what stops one request from walking a\n * self-referencing relation forever.\n *\n * @group Data\n */\nexport interface IncludeOptions {\n /** Rows to load per parent row. Applied per parent, not across the page. */\n limit?: number;\n /** Filter the related rows, in the same dialect as {@link FindParams.where}. */\n where?: FilterValues<string>;\n /** An `and`/`or`/`not` group over the related rows. */\n logical?: LogicalCondition;\n /**\n * Sort the related rows — the tuple form, or the `field:direction[:nulls]`\n * shorthand the REST `?orderBy=` parameter uses.\n *\n * The string is accepted because this whole object travels over a query\n * string, where a tuple is three characters of JSON heavier for no gain.\n */\n orderBy?: OrderBySpec<string> | string;\n /** Columns of the *related* row to return. `id` is always included. */\n fields?: string[];\n /** Relations of the related row to load in turn. */\n include?: IncludeSpec;\n}\n\n/**\n * The relations a read loads, as a list of (possibly dotted) names or as a\n * tree.\n *\n * - `[\"author\", \"comments.author\"]` — a dotted path is the same thing as the\n * nested object form, spelled flat. It is what the REST `?include=` parameter\n * carries, and the two forms compile to the same request.\n * - `[\"*\"]` — every relation, one hop deep. The admin panel's shape.\n * - `{ comments: { limit: 5, include: { author: true } } }` — the parametrised\n * form.\n *\n * A name that is not a relation of the collection is a **400\n * `UNKNOWN_RELATION`**, not a silent omission: a read that quietly drops an\n * `include` answers 200 with the field missing, which is indistinguishable from\n * a row that genuinely has no related row.\n *\n * @group Data\n */\nexport type IncludeSpec = string[] | Record<string, true | IncludeOptions>;\n\n/**\n * Hops an {@link IncludeSpec} may nest. `comments.author` is two.\n *\n * @group Data\n */\nexport const MAX_INCLUDE_DEPTH = 3;\n\n/**\n * Parameters for querying a collection.\n *\n * ## How the filter parameters combine\n *\n * `where`, `logical`, and `searchString` are **independent** and, when more\n * than one is present, are combined with **AND** — every clause must match.\n * Concretely the backend builds:\n *\n * ```text\n * (where filters, AND-ed together)\n * AND (logical group)\n * AND (searchString matches, OR-ed across searchable columns)\n * ```\n *\n * So `where` does **not** conflict with or override `logical` — they stack.\n * If you need `where` fields OR-ed with each other, move them into `logical`\n * instead. There is no way to OR `where` against `logical`; express anything\n * that isn't a plain AND of the three groups inside a single `logical` tree.\n *\n * ## Pagination precedence\n *\n * `limit`/`offset` and `page` describe the same window two ways. If **both\n * `offset` and `page` are provided, `page` wins** — the backend computes\n * `offset = (page - 1) * (limit ?? DEFAULT_LIST_LIMIT)` and ignores the\n * explicit `offset`. Pick one style per query.\n *\n * @group Data\n */\nexport interface FindParams<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Maximum number of items to return.\n *\n * Omit it and the backend applies {@link DEFAULT_LIST_LIMIT}, so a read is\n * never unbounded. Provide it and it must be a whole number between 1 and\n * {@link MAX_LIST_LIMIT}: the backend **rejects** anything else with a 400\n * rather than trimming it to fit, because a page quietly smaller than the\n * one you asked for is indistinguishable from having reached the end of the\n * collection. To read past the ceiling, page with `offset` — or let\n * {@link SDKCollectionClient.iterate} / {@link SDKCollectionClient.findAll}\n * do it for you.\n */\n limit?: number;\n /**\n * Number of items to skip. Ignored when {@link FindParams.page} is also\n * set — `page` takes precedence.\n */\n offset?: number;\n /**\n * Page number (1-indexed), alternative to {@link FindParams.offset}.\n * When set, overrides `offset` as `(page - 1) * (limit ?? DEFAULT_LIST_LIMIT)`.\n */\n page?: number;\n /**\n * Filter conditions keyed by field name.\n * Each value is a `[WhereFilterOp, value]` tuple or an array of tuples\n * for multiple conditions on the same field. Multiple fields, and multiple\n * tuples on one field, are **AND-ed**; also AND-ed with `logical` and\n * `searchString` when present (see the interface docs).\n *\n * @example\n * { status: [\"==\", \"active\"] }\n * { age: [\">=\", 18] }\n * { role: [\"in\", [\"admin\", \"editor\"]] }\n * { age: [[\">=\", 18], [\"<\", 65]] }\n */\n where?: FilterValues<FieldPath<M>>;\n /**\n * Logical grouping conditions (AND/OR). Use this for anything `where`\n * can't express — notably OR-ing conditions. AND-ed with `where` and\n * `searchString` when present (see the interface docs).\n */\n logical?: LogicalCondition;\n /**\n * Sort order as a `[field, direction]` tuple, or a list of them applied in\n * order of significance — the second key breaks ties on the first, and so on.\n *\n * @example orderBy: [\"created_at\", \"desc\"]\n * @example orderBy: [[\"roles\", \"asc\"], [\"created_at\", \"desc\"]]\n */\n orderBy?: OrderBySpec<FieldPath<M> | ComputedSortField>;\n /**\n * Relations to load into the response — see {@link IncludeSpec}.\n *\n * Not checked against `M` here: a relation name comes from the collection's\n * `relations`, not from its columns, so nothing in a *hand-written* row type\n * can validate one. A **generated** `Database` narrows this to the\n * collection's actual relation keys, recursively — see `rebase codegen`.\n *\n * An unknown name is a 400 `UNKNOWN_RELATION`. It used to be ignored.\n */\n include?: IncludeSpec;\n\n /**\n * Columns to return, instead of all of them.\n *\n * A real column projection: only these columns are read from the database,\n * so a query that needs two fields of a wide row does not pay for the rest.\n * `excludeFromApi` still applies — naming such a column here does not\n * un-hide it — and the primary key is always returned, because a row that\n * cannot be addressed cannot be updated, deleted or paged past.\n *\n * A relation named in {@link FindParams.include} is loaded regardless of\n * whether it appears here; use {@link IncludeOptions.fields} to narrow the\n * columns *within* an included relation.\n */\n fields?: string[];\n\n /**\n * Collapse rows that are identical over the columns being returned.\n *\n * `SELECT DISTINCT` over the projection — so it is only meaningful\n * alongside {@link FindParams.fields}, and with the primary key in the\n * projection (which it always is) every row is already distinct. Pair it\n * with `fields` naming the columns you actually want the distinct values of.\n *\n * `meta.total` counts distinct rows too, so a distinct listing's `hasMore`\n * describes the set it is paging.\n */\n distinct?: boolean;\n\n /**\n * Continue from where a previous page ended — keyset (\"seek\") pagination.\n *\n * The value is the opaque `meta.nextCursor` of the previous response. It\n * encodes the sort keys the query was ordered by and the last row's values\n * for them, so a page picks up strictly after the last row served rather\n * than at a row *count* that concurrent writes have already moved.\n *\n * It has to describe the same query: `after` alongside a different\n * `orderBy` is a 400 `CURSOR_ORDER_MISMATCH` rather than a page of rows\n * seeked in an order nobody asked for. Mutually exclusive with `offset` and\n * `page` for the same reason.\n *\n * Multi-key sorts and nullable keys both work — the comparison is built\n * over every key, in order, with the NULL placement the sort declared.\n */\n after?: string;\n /**\n * Text search string, AND-ed with `where`/`logical`. This is the value\n * behind the query builder's `.search()` method.\n *\n * What it compiles to depends on the collection. By default — matching\n * every collection that has not said otherwise — it is a case-insensitive\n * substring match OR-ed across the collection's top-level `string`\n * properties: it does not reach inside `map` or `array` properties, it does\n * not stem or rank, and it cannot use an index.\n *\n * A Postgres collection that declares a `search` block instead gets a\n * ranked full-text match over exactly the fields it named, and rows come\n * back with a {@link FindParams.orderBy}-able `_score`.\n */\n searchString?: string;\n\n /**\n * Nearest-neighbour search over a `vector` property.\n *\n * Postgres only, and only for a collection that declares a property of\n * type `vector`. Rows come back ordered by distance, closest first, each\n * carrying a `_distance`. Combines with `where` and `logical`, which are\n * applied as filters before the ordering — so this is \"the nearest rows\n * that also match\", not \"the nearest rows, then filtered\".\n *\n * Supplying the query vector is the caller's job: rebase stores and\n * searches embeddings, it does not compute them.\n */\n vectorSearch?: VectorSearchParams;\n\n /**\n * Ask each returned row to explain itself: which declared search fields\n * matched, with a highlighted snippet from each. Populates `_matches`.\n *\n * Off by default because it is not free — one `ts_headline` per declared\n * field per returned row, and `ts_headline` re-parses the document rather\n * than reading the index. Fine for a page of results, not for an export.\n *\n * Ignored unless the collection declares a `search` block and the query\n * carries a `searchString`; there is nothing to explain otherwise.\n */\n searchExplain?: boolean;\n}\n\n/**\n * Paginated response from a collection query.\n * @group Data\n */\nexport interface FindResponse<M extends Record<string, unknown> = Record<string, unknown>> {\n /** Array of entities matching the query */\n data: Entity<M>[];\n /** Pagination metadata */\n meta: {\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n };\n}\n\n\n\n/**\n * Fluent query builder for the **admin panel** — resolves to `FindResponse<M>`\n * (Snapshot-wrapped rows).\n *\n * @internal App developers should use {@link SDKQueryBuilderInterface}\n * (flat rows, returned by `client.data.*` / `context.data.*`). This\n * Snapshot-flavored variant backs the admin panel internals only.\n *\n * @group Data\n */\nexport interface QueryBuilderInterface<M extends Record<string, unknown> = Record<string, unknown>> {\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): this;\n where(logicalCondition: LogicalCondition): this;\n orderBy(column: (keyof M & string) | ComputedSortField, direction?: \"asc\" | \"desc\"): this;\n limit(count: number): this;\n offset(count: number): this;\n search(searchString: string, options?: { explain?: boolean }): this;\n\n /**\n * Order rows by nearest-neighbour distance to `vector`, closest first.\n *\n * Postgres only, over a property declared as `type: \"vector\"`. Each row\n * comes back with a `_distance`. Any `where` on the same query filters\n * before the ordering; distance decides the order.\n *\n * The query embedding is the caller's to produce.\n */\n vectorSearch(\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): this;\n include(...relations: string[]): this;\n find(): Promise<FindResponse<M>>;\n listen(onUpdate: (data: FindResponse<M>) => void, onError?: (error: Error) => void): () => void;\n}\n\n/**\n * A single collection's CRUD accessor for the **admin panel** — every method\n * resolves to `Snapshot`-wrapped rows (`FindResponse<M>` / `Snapshot<M>`).\n *\n * @internal App developers do **not** use this. The public, symmetric surface\n * is {@link SDKCollectionClient} (flat rows), exposed as `client.data.products`\n * in the SDK and `context.data.products` in framework callbacks. This\n * Snapshot-flavored accessor backs the admin panel view-model only.\n *\n * @group Data\n */\nexport interface CollectionAccessor<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Find multiple records with optional filtering, pagination, and sorting.\n */\n find(params?: FindParams<M>): Promise<FindResponse<M>>;\n\n /**\n * Find a single record by its ID.\n */\n findById(id: string | number): Promise<Entity<M> | undefined>;\n\n /**\n * Create a new record.\n * @param data The entity data to create.\n * @param id Optional specific ID to use for the new record.\n * @returns The created entity\n */\n create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>>;\n\n /**\n * Create many records in a single transaction.\n *\n * See {@link SDKCollectionClient.createMany}. Optional: not every driver can\n * write in bulk, and callers should fall back to `create` per record.\n */\n createMany?(\n data: Partial<EntityValues<M>>[],\n options?: { upsert?: boolean; onConflict?: readonly string[] }\n ): Promise<Entity<M>[]>;\n\n /**\n * Update an existing record by ID.\n * @returns The updated entity\n */\n update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>>;\n\n /**\n * Update many records in a single transaction.\n *\n * See {@link SDKCollectionClient.updateMany}. Optional, as `createMany` is.\n */\n updateMany?(updates: { id: string | number; data: Partial<EntityValues<M>> }[]): Promise<Entity<M>[]>;\n\n /**\n * Delete many records in a single transaction.\n *\n * See {@link SDKCollectionClient.deleteMany}. Optional, as `createMany` is.\n */\n deleteMany?(ids: (string | number)[]): Promise<void>;\n\n /**\n * Delete a record by ID.\n */\n delete(id: string | number): Promise<void>;\n\n /**\n * Subscribe to a collection for real-time updates.\n * Optional method, may not be supported by all implementations (like stateless HTTP clients).\n */\n listen?(params: FindParams<M> | undefined, onUpdate: (response: FindResponse<M>) => void, onError?: (error: Error) => void): () => void;\n\n /**\n * Subscribe to a single record for real-time updates.\n * Optional method.\n */\n listenById?(id: string | number, onUpdate: (entity: Entity<M> | undefined) => void, onError?: (error: Error) => void): () => void;\n\n /**\n * Count the number of records matching the given filter.\n *\n * Optional on this contract because a data source need not support it, and\n * required on `CollectionClient` — the HTTP implementation always has it.\n * So `client.data.posts.count()` compiles in the browser while the same\n * call through a `context.data` accessor needs `count?.()`, which is the\n * one place the two halves of this API are not interchangeable.\n */\n count?(params?: FindParams<M>): Promise<number>;\n\n /**\n * {@link SDKCollectionClient.aggregate}. Optional here for the same reason\n * `count` is: not every data source can compute one, and the SDK wraps an\n * absent implementation in a stub that says so rather than returning a\n * number nothing counted.\n */\n aggregate?(params: AggregateParams<M>): Promise<AggregateRow[]>;\n\n // Fluent Query Builder\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): QueryBuilderInterface<M>;\n where(logicalCondition: LogicalCondition): QueryBuilderInterface<M>;\n orderBy(column: (keyof M & string) | ComputedSortField, direction?: \"asc\" | \"desc\"): QueryBuilderInterface<M>;\n limit(count: number): QueryBuilderInterface<M>;\n offset(count: number): QueryBuilderInterface<M>;\n search(searchString: string, options?: { explain?: boolean }): QueryBuilderInterface<M>;\n\n /**\n * Order rows by nearest-neighbour distance to `vector`, closest first.\n *\n * Postgres only, over a property declared as `type: \"vector\"`. Each row\n * comes back with a `_distance`. Any `where` on the same query filters\n * before the ordering; distance decides the order.\n *\n * The query embedding is the caller's to produce.\n */\n vectorSearch(\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): QueryBuilderInterface<M>;\n include(...relations: string[]): QueryBuilderInterface<M>;\n}\n\n// =============================================================================\n// SDK-facing types — flat rows, no Entity wrapper\n// =============================================================================\n\n/**\n * Pagination metadata returned with collection queries.\n * @group Data\n */\nexport interface PaginationMeta {\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n /**\n * The opaque cursor that continues this listing — pass it back as\n * {@link FindParams.after}.\n *\n * Present whenever there is a next page to describe (`hasMore` is true and\n * the page returned at least one row). Absent on the last page, and absent\n * on a query no cursor can describe (relevance ordering, whose scores are\n * computed per query and are not comparable between two of them).\n *\n * Opaque on purpose: it encodes the sort keys *and* the last row's values\n * for them, and a client that parsed it would be depending on an encoding\n * that exists to be changed.\n */\n nextCursor?: string;\n}\n\n/**\n * Paginated response from a collection query (SDK-facing).\n * Returns flat rows instead of Entity-wrapped objects.\n *\n * @example\n * const { data, meta } = await rebase.data.posts.find();\n * console.log(data[0].title); // direct access — no .values\n * console.log(meta.total);\n *\n * @group Data\n */\nexport interface FindResult<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Flat rows matching the query, each carrying whatever the query computed\n * for it — see {@link QueryComputedFields}.\n */\n data: (M & QueryComputedFields)[];\n /** Pagination metadata */\n meta: PaginationMeta;\n}\n\n/**\n * Values a query attaches to a row that are not columns of it.\n *\n * Both are absent unless the query asked for the thing that produces them, so\n * both are optional — and reading one on a query that did not ask returns\n * `undefined` rather than a wrong number.\n *\n * They live here rather than on the row type because a generated row type\n * describes a *table*, and neither of these is in one. Without this, a caller\n * who sorted by relevance could not then read the relevance.\n *\n * A `type` alias, deliberately, not an `interface`. TypeScript grants an\n * implicit index signature to a type alias and withholds it from an interface,\n * so `Row & QueryComputedFields` stops being assignable to\n * `Record<string, unknown>` the moment this becomes an interface. Seven casts\n * in one downstream app broke on exactly that.\n *\n * @group Data\n */\nexport type QueryComputedFields = {\n /**\n * Relevance, when the collection declares a {@link SearchConfig} and the\n * query carried a search string. Higher is better; the scale is not\n * comparable between two different search strings.\n */\n _score?: number;\n /**\n * Which declared fields matched, and the text around each hit. Present only\n * when the query asked for it — `.search(term, { explain: true })` — because\n * it costs a `ts_headline` per field per row.\n */\n _matches?: SearchMatch[];\n /**\n * Distance to the query vector, when the query used\n * {@link FindParams.vectorSearch}. Lower is closer, and the rows are\n * already ordered by it.\n */\n _distance?: number;\n};\n\n/**\n * One aggregate a query asks for.\n *\n * `count` alone counts rows; every other function names a column, and `count`\n * with a column counts its non-NULL values.\n *\n * The result key is derived rather than chosen: `sum(total)` comes back as\n * `sum_total` and a bare `count()` as `count`. Letting a caller name it would\n * mean checking their name is not also a `groupBy` field — a rule nobody would\n * guess, and a silently overwritten value if it went unchecked.\n *\n * @group Data\n */\nexport type AggregateSelect<M extends Record<string, unknown> = Record<string, unknown>> =\n | { fn: \"count\"; field?: Extract<keyof M, string> }\n | { fn: \"sum\" | \"avg\" | \"min\" | \"max\"; field: Extract<keyof M, string> };\n\n/**\n * One row of an aggregate result: the `groupBy` columns, plus one key per\n * {@link AggregateSelect} under its derived alias.\n *\n * `count`, `sum` and `avg` arrive as numbers — Postgres returns bigint and\n * numeric as strings, and they are parsed once at the driver rather than by\n * every caller. `min`/`max` keep the column's own type.\n *\n * @group Data\n */\nexport type AggregateRow = Record<string, unknown>;\n\n/**\n * What {@link SDKCollectionClient.aggregate} takes: the same narrowing a\n * `find()` takes, minus the parts of it that describe a *page* of rows.\n *\n * `limit` survives and means what it means on the REST route — a bound on the\n * number of **groups**, because grouping by a high-cardinality column is a whole\n * table's worth of rows in one response. It is ignored when there is no\n * `groupBy`, since an ungrouped aggregate is one row.\n *\n * `orderBy`, `include`, `after` and the rest are absent on purpose: an\n * aggregate has no rows to sort, no relations to load and no page to continue.\n * They were silently ignored on the REST route; here they do not typecheck.\n *\n * @group Data\n */\nexport interface AggregateParams<M extends Record<string, unknown> = Record<string, unknown>> {\n /** The aggregates to compute. At least one. */\n select: AggregateSelect<M>[];\n /** Columns to group by. Omit for a single row over everything that matches. */\n groupBy?: Extract<keyof M, string>[];\n /** Filter conditions, as {@link FindParams.where}. */\n where?: FilterValues<FieldPath<M>>;\n /** An `and`/`or`/`not` group, AND-ed with `where`. */\n logical?: LogicalCondition;\n /** Text search, AND-ed with the filters. */\n searchString?: string;\n /** Most groups to return. Ignored without `groupBy`. */\n limit?: number;\n}\n\n/**\n * Which column an iteration seeks on, for keyset (\"seek\") pagination.\n *\n * Either the column name on its own — sorted ascending — or the column plus an\n * explicit direction. The column must be **unique** and must be the column the\n * query is ordered by; see {@link PageWalkOptions.cursor}.\n *\n * @group Data\n */\nexport type CursorSpec<M extends Record<string, unknown> = Record<string, unknown>> =\n | (Extract<keyof M, string>)\n | { field: Extract<keyof M, string>; direction?: \"asc\" | \"desc\" };\n\n/**\n * How {@link SDKCollectionClient.iterate} / {@link SDKCollectionClient.findAll}\n * walk a collection, layered on top of the normal `find()` parameters.\n *\n * @group Data\n */\nexport interface PageWalkOptions<M extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Rows fetched per request. Defaults to 200; values below 1 are clamped up.\n * This is the request size, not a result cap — the iteration keeps going\n * until the server says there is nothing left.\n */\n pageSize?: number;\n /**\n * Paginate by **seeking on a column** instead of by offset.\n *\n * Offset paging — the default — re-counts rows on every request, so a row\n * inserted or deleted *while the iteration runs* shifts the window and the\n * walk silently skips or repeats rows. Seeking is immune to that: each page\n * asks for rows strictly after the last one seen, so concurrent writes\n * before the cursor cannot move it.\n *\n * Prefer this whenever the collection has a unique, sortable column\n * (typically its primary key). The column must be unique — a repeated value\n * at a page boundary either skips rows or stalls, and the iterator throws\n * rather than looping — and the query is ordered by it, so a `cursor` and a\n * conflicting `orderBy` is an error, not a silent override.\n *\n * Implemented with the parameters `find()` already takes (an `orderBy` plus\n * a `>` / `<` filter on the cursor column), so it works on every transport\n * and needs nothing new from the server.\n *\n * @example\n * for await (const job of client.data.jobs.iterate({ cursor: \"id\" })) { … }\n */\n cursor?: CursorSpec<M>;\n /**\n * Hard ceiling on the number of requests one walk may make, so a server\n * that never stops saying `hasMore` cannot spin forever. Defaults to\n * 10 000 pages; hitting it throws.\n */\n maxPages?: number;\n}\n\n/**\n * Parameters accepted by {@link SDKCollectionClient.iterate} — everything\n * `find()` takes except the window itself (`limit`, `offset`, `page`), which\n * the iterator owns, plus the walk options.\n *\n * @group Data\n */\nexport type IterateParams<M extends Record<string, unknown> = Record<string, unknown>> =\n Omit<FindParams<M>, \"limit\" | \"offset\" | \"page\"> & PageWalkOptions<M>;\n\n/**\n * Parameters accepted by {@link SDKCollectionClient.findAll}: the iteration\n * parameters plus the ceiling that keeps a whole collection from being pulled\n * into memory unnoticed.\n *\n * @group Data\n */\nexport type FindAllParams<M extends Record<string, unknown> = Record<string, unknown>> =\n IterateParams<M> & {\n /**\n * Most rows to materialise. Defaults to 10 000. Exceeding it **throws**\n * — a truncated array returned as if it were the whole answer is the\n * kind of quiet wrong that shows up months later in a report. Pass\n * `Infinity` to opt out deliberately, or use `iterate()` to stream.\n */\n maxRows?: number;\n };\n\n/**\n * Fluent Query Builder Interface for the SDK client.\n * Returns `FindResult<M>` (flat rows) instead of `FindResponse<M>` (Entity-wrapped).\n *\n * @group Data\n */\nexport interface SDKQueryBuilderInterface<M extends Record<string, unknown> = Record<string, unknown>> {\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): this;\n /**\n * Filter on a relation path (`author.name`) or a JSON path\n * (`metadata->>tier`).\n *\n * A separate overload because the value cannot be typed: neither addresses\n * a column of `M`, so there is nothing in a generated row type to check\n * against — the driver resolves the path and refuses what it cannot. The\n * key is still constrained to a *path*, so a mistyped column name does not\n * fall through to here and lose its check.\n *\n * `find({ where })` has accepted both all along ({@link FieldPath}); the\n * builder did not, so the documented relation-path filters were compile\n * errors on a typed client.\n */\n where(column: NonColumnFieldPath, operator: WhereFilterOp, value: unknown): this;\n where(logicalCondition: LogicalCondition): this;\n /**\n * Sort by a column, a relation or JSON path, `_score`, or an aggregate over\n * a to-many relation — the same key set {@link FindParams.orderBy} takes.\n */\n orderBy(\n column: FieldPath<M> | ComputedSortField | RelationAggregateSort,\n direction?: \"asc\" | \"desc\",\n nulls?: NullsPlacement\n ): this;\n limit(count: number): this;\n offset(count: number): this;\n search(searchString: string, options?: { explain?: boolean }): this;\n\n /**\n * Order rows by nearest-neighbour distance to `vector`, closest first.\n *\n * Postgres only, over a property declared as `type: \"vector\"`. Each row\n * comes back with a `_distance`. Any `where` on the same query filters\n * before the ordering; distance decides the order.\n *\n * The query embedding is the caller's to produce.\n */\n vectorSearch(\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): this;\n /**\n * Load relations — names, dotted paths (`\"comments.author\"`), or the\n * parametrised tree. Repeated calls merge rather than replace.\n */\n include(...relations: (string | IncludeSpec)[]): this;\n /**\n * Return only these columns. A real projection: the columns are what is\n * read from the database, not what survives a trim of the response.\n */\n fields(...columns: (FieldPath<M> | string)[]): this;\n /** `SELECT DISTINCT` over the projection — see {@link FindParams.distinct}. */\n distinct(enabled?: boolean): this;\n /** Continue after a previous page's `meta.nextCursor`. */\n after(cursor: string): this;\n find(): Promise<FindResult<M>>;\n /**\n * Aggregate the rows this query matches instead of returning them.\n *\n * The builder's `where`/`logical`/`search` narrow which rows are\n * aggregated; its `orderBy`, `include` and window do not apply and are\n * ignored, exactly as they are on the REST route.\n */\n aggregate(params: Omit<AggregateParams<M>, \"where\" | \"logical\" | \"searchString\">): Promise<AggregateRow[]>;\n\n /**\n * Page through everything this query matches, one row at a time.\n *\n * The same walker {@link SDKCollectionClient.iterate} uses, so the ceiling\n * on `limit` is not a ceiling on what a query can read. `.limit()` set on\n * the builder becomes the **page size** here, not a total.\n */\n iterate(options?: PageWalkOptions<M>): AsyncIterableIterator<M>;\n\n /**\n * Collect everything this query matches into one array.\n *\n * {@link SDKCollectionClient.findAll}'s `maxRows` guard applies: an\n * unbounded collect is a memory hazard, so it stops and says so rather than\n * growing until the process dies.\n */\n findAll(options?: PageWalkOptions<M> & { maxRows?: number }): Promise<M[]>;\n\n count(): Promise<number>;\n listen(onUpdate: (data: FindResult<M>) => void, onError?: (error: Error) => void): () => void;\n}\n\n/**\n * SDK collection client — returns flat rows, no Entity wrapper.\n *\n * This is the public API surface for app developers using\n * `createRebaseClient()`. admin internals use `CollectionAccessor` instead.\n *\n * Type parameters:\n * - `M` — the **Row** shape returned by reads (`find`, `findById`, `listen`).\n * - `I` — the **Insert** shape accepted by {@link create}. Defaults to\n * `Partial<M>`; the generated SDK supplies a dedicated `Insert` type where\n * required columns are required and auto-generated / read-only columns are\n * omitted, so `create({})` on a table with required fields is a compile error.\n * - `U` — the **Update** shape accepted by {@link update}. Defaults to\n * `Partial<M>`; the generated SDK supplies a dedicated `Update` type.\n *\n * @example\n * const { data: posts } = await rebase.data.posts.find();\n * console.log(posts[0].title); // flat access\n * console.log(posts[0].id); // id at top level\n *\n * const post = await rebase.data.posts.findById(1);\n * console.log(post?.title); // no .values needed\n *\n * @group Data\n */\n/**\n * A change expressed as an operation on the column's current value, rather than\n * as the value to store.\n *\n * `{ views: 5 }` says what the number becomes; `{ views: { $inc: 1 } }` says\n * what happens to it. The difference is the read the caller no longer has to\n * make — and the race that read opens. Two requests that each read `4`, add one\n * and write `5` lose an increment between them; `SET views = views + 1` cannot,\n * because the arithmetic happens inside the statement holding the row lock.\n *\n * Exactly one operator per field. `{ views: { $inc: 1, $push: \"x\" } }` is\n * refused rather than applied in an order the caller cannot see.\n *\n * @group Data\n */\n/**\n * The operator names, as a value.\n *\n * A runtime list beside the type because three layers have to *recognise* an\n * operation, not just accept one: the REST validator, the driver that compiles\n * it, and the offline queue that must refuse to apply one locally. Three copies\n * of four strings is three chances for one of them to miss an operator added to\n * the other two, and the failure is silent in the worst direction — an\n * unrecognised marker is written to the column as a JSON document.\n *\n * @group Data\n */\nexport const FIELD_OPERATORS = [\"$inc\", \"$push\", \"$pull\", \"$merge\"] as const;\n\n/**\n * The key of a {@link BatchRef}. Declared here, beside the field operators,\n * because the two share one namespace: a `$`-prefixed key in a write payload is\n * a marker, and every reader of that namespace has to know all of it.\n *\n * @group Data\n */\nexport const BATCH_REF_KEY = \"$ref\";\n\n/**\n * Whether a value is *trying* to be a field operation — including a misspelled\n * one, which is the case worth catching.\n *\n * Any `$`-prefixed key counts, because `{ $increment: 1 }` written to a number\n * column as a JSON document is the failure this exists to prevent. No collection\n * can declare a column whose value legitimately has a key beginning with `$`: a\n * `map` property's sub-keys are declared, and `$` is not valid in the\n * identifiers the DDL generators emit.\n *\n * The one exception is `{ $ref: … }`, the batch's backward reference. It stands\n * where a *value* goes and is resolved to one before the row is written, so it\n * is not an operation on a column — reading it as a misspelled operator refused\n * every `$ref` in a batch with \"unknown field operator '$ref'\".\n *\n * @group Data\n */\nexport function isFieldOperation(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null || Array.isArray(value) || value instanceof Date) {\n return false;\n }\n const keys = Object.keys(value);\n if (keys.length === 1 && keys[0] === BATCH_REF_KEY) return false;\n return keys.some((key) => key.startsWith(\"$\"));\n}\n\n/** True when any value in a write payload is (or is attempting to be) one. @group Data */\nexport function hasFieldOperation(values: Record<string, unknown> | undefined): boolean {\n return !!values && Object.values(values).some(isFieldOperation);\n}\n\nexport type FieldOperation =\n /** Add to a `number` column; negative to subtract. `SET col = col + n`. */\n | { $inc: number }\n /** Append one value, or each of an array of values, to an `array` column. */\n | { $push: unknown }\n /** Remove every occurrence of a value from an `array` column. */\n | { $pull: unknown }\n /** Shallow-merge an object into a `map` column. `SET col = col || …::jsonb`. */\n | { $merge: Record<string, unknown> };\n\n/**\n * The payload {@link SDKCollectionClient.update} accepts: plain values, field\n * operations, or both in one body.\n *\n * @group Data\n */\nexport type UpdateValues<U> = { [K in keyof U]?: U[K] | FieldOperation };\n\n/**\n * Where an upsert looks for the row it might be replacing.\n *\n * The columns must carry a uniqueness guarantee the database can use as an\n * `ON CONFLICT` target — the primary key, a property with\n * `validation.unique`, or the columns of a declared `unique` index. Anything\n * else is refused with a 400 rather than sent to Postgres, which would answer\n * `there is no unique or exclusion constraint matching the ON CONFLICT\n * specification` from inside a transaction that has already done work.\n *\n * @group Data\n */\nexport interface UpsertOptions extends WriteOptions {\n /** Column names forming the conflict target. Defaults to the primary key. */\n onConflict?: readonly string[];\n}\n\n/**\n * A placeholder standing for a value only the server will know: the id of a row\n * an earlier operation in the same batch creates.\n *\n * `{ \"$ref\": \"order.id\" }` reads the field `id` off the result of the operation\n * that named itself `ref: \"order\"`. Without it a batch cannot express the one\n * thing a cross-collection batch exists for — writing a parent and its children\n * together — because the child's foreign key is not knowable until the parent\n * has been inserted, and splitting the two into separate requests is exactly\n * the non-atomic sequence the batch replaces.\n *\n * Only backward references resolve. `ref` names must be unique within a batch,\n * and an operation may not reference itself or anything after it.\n *\n * @group Data\n */\nexport interface BatchRef {\n /** `<ref name>.<field>`, e.g. `order.id`. */\n $ref: string;\n}\n\n/** One entry of a batch request. @group Data */\nexport type BatchOperation<DB = Record<string, unknown>> = {\n [K in Extract<keyof DB, string>]:\n | {\n op: \"create\";\n collection: K;\n values: { [F in keyof InsertOf<DB[K]>]?: InsertOf<DB[K]>[F] | BatchRef } & Record<string, unknown>;\n /** Name this row so a later operation can reference its columns. */\n ref?: string;\n }\n | {\n op: \"upsert\";\n collection: K;\n values: { [F in keyof InsertOf<DB[K]>]?: InsertOf<DB[K]>[F] | BatchRef } & Record<string, unknown>;\n /** See {@link UpsertOptions.onConflict}. Defaults to the primary key. */\n onConflict?: readonly string[];\n ref?: string;\n }\n | {\n op: \"update\";\n collection: K;\n id: string | number | BatchRef;\n values: { [F in keyof UpdateOf<DB[K]>]?: UpdateOf<DB[K]>[F] | FieldOperation | BatchRef } & Record<string, unknown>;\n ref?: string;\n }\n | {\n op: \"delete\";\n collection: K;\n id: string | number | BatchRef;\n ref?: string;\n };\n}[Extract<keyof DB, string>];\n\n/**\n * What `POST /api/data/_batch` answers with.\n *\n * `data` is aligned to `operations`: the written row for a create, upsert or\n * update, and `null` for a delete — so an index into one is an index into the\n * other, whatever the batch mixed.\n *\n * @group Data\n */\nexport interface BatchResult<R = Record<string, unknown>> {\n data: (R | null)[];\n meta: { operations: number };\n}\n\n/**\n * Per-request options for a write.\n * @group Data\n */\nexport interface WriteOptions {\n /**\n * Names this write, so re-sending it is recognised instead of repeated.\n *\n * A client that does not see a response cannot know whether the write\n * committed. Retrying is therefore the only option, and without a key the\n * server has no way to tell a retry from a second, genuinely new write — so\n * it performs it again. On a table with a server-assigned id that is a\n * duplicate row, because the id the client chose was never used.\n *\n * A key names **one** request, not a job. It records the method, the path\n * and the body it was claimed for, so re-sending that exact request replays\n * its answer, while the same key on a different one is refused with\n * `IDEMPOTENCY_KEY_REUSED` (422) rather than silently answered with the\n * first request's result. Pass a fresh key — a uuid — per call; a reusable\n * business id shared by the create and the delete of one import means the\n * second of them never runs.\n *\n * Set by the offline queue on every replay. Honoured for 24 hours and scoped\n * to the authenticated user — an unauthenticated caller has no principal to\n * scope it to, so the key is ignored there. A retry sent while the first\n * attempt is still being answered gets `IDEMPOTENCY_KEY_IN_PROGRESS` (409)\n * and should be sent again. A server that cannot store keys ignores the\n * header rather than refusing the write.\n */\n idempotencyKey?: string;\n\n /**\n * Whether the server should send the written row back.\n *\n * `false` sends `Prefer: return=minimal`, and the write answers `204 No\n * Content` — `200` carrying the ids only, for a batch. The row is the\n * default because it carries what the server decided: a serial id, an\n * `autoValue` timestamp, whatever `beforeSave` rewrote. A caller that\n * needs none of that is paying for a full row serialisation and, on\n * Postgres, a read-back per written row.\n *\n * Reach for it on imports and fire-and-forget writes. The method resolves\n * to `undefined` (or `[]`) when it is set, so a caller cannot accidentally\n * use a row the server never sent.\n */\n returning?: boolean;\n\n /**\n * The version of the row this write was made against, so it is refused if\n * the row has moved on.\n *\n * The `ETag` from the read that produced the row — `etagOf(row)` on a row\n * from `findById`, or the `ETag` response header. A mismatch answers `412`\n * rather than writing, which is the difference between \"update the row I\n * read\" and \"overwrite whatever is there now\". Without it a read, an edit\n * and a write is last-writer-wins over everything the write did not send,\n * and the loser is told nothing.\n *\n * `\"*\"` asserts only that the row exists.\n *\n * Honoured on `update` and `delete`.\n */\n ifMatch?: string;\n}\n\nexport interface SDKCollectionClient<\n M extends Record<string, unknown> = Record<string, unknown>,\n I = Partial<M>,\n U = Partial<M>\n> {\n /**\n * Find multiple records with optional filtering, pagination, and sorting.\n *\n * ## What a list method returns\n *\n * Two shapes, and one rule that tells them apart: **a window is wrapped, a\n * whole answer is not.**\n *\n * - `find()` and `listen()` return {@link FindResult} — `{ data, meta }` —\n * because they hand back *one page*. `meta.total` and `meta.hasMore` are\n * the caller's only way to know there is more, so a bare array would lose\n * the answer to the question the call raises.\n * - `findAll()`, `createMany()` and `updateMany()` return a plain `M[]`,\n * because there is nothing left over to report: the walk finished, or the\n * batch is exactly the rows that were written. A `meta` there would be\n * `{ total: rows.length, hasMore: false }`, which says nothing.\n * - `iterate()` yields rows one at a time and never materialises a list at\n * all.\n *\n * So `data` is not a wrapper the SDK sometimes adds and sometimes forgets —\n * it is where the pagination metadata lives, and it is present exactly when\n * there is some.\n */\n find(params?: FindParams<M>): Promise<FindResult<M>>;\n\n /**\n * Walk every record matching a query, one row at a time, fetching pages as\n * the consumer consumes them.\n *\n * This is the pagination primitive: `find()` returns one window, `iterate()`\n * returns all of them without the caller hand-rolling the\n * `limit` / `offset += ` / \"am I done yet\" loop. Nothing is buffered — rows\n * are yielded as each page arrives, so a million-row walk costs one page of\n * memory. `break` stops the walk and no further requests are made.\n *\n * Termination is driven by the server's `meta.hasMore`, never by comparing\n * a page's length against the requested limit — a final page that happens\n * to be exactly full is indistinguishable that way, and a walk that stops\n * there drops rows. An empty page also ends the walk, and\n * {@link PageWalkOptions.maxPages} bounds a server that never stops saying\n * there is more.\n *\n * ## Consistency\n *\n * By default this pages by **offset**, which is only as stable as the table\n * is still: a row inserted or deleted ahead of the cursor between two\n * requests shifts every later window, so the walk can skip a row or hand\n * back the same one twice. That is inherent to offset paging, not a bug\n * here. On a collection with a unique sortable column, pass\n * {@link PageWalkOptions.cursor} to seek on it instead — the walk then\n * asks for rows strictly after the last one it saw, which concurrent writes\n * cannot perturb.\n *\n * @example\n * for await (const job of client.data.jobs.iterate({\n * where: { status: [\"==\", \"queued\"] },\n * cursor: \"id\",\n * pageSize: 500\n * })) {\n * await handle(job);\n * }\n */\n iterate(params?: IterateParams<M>): AsyncIterableIterator<M>;\n\n /**\n * {@link iterate}, collected into an array.\n *\n * Convenient when the result is known to be small and awkward to stream.\n * Because \"known to be small\" is an assumption and not a fact, the result is\n * capped — 10 000 rows by default — and going over the cap **throws**\n * rather than returning a short array that reads like a complete one. Raise\n * {@link FindAllParams.maxRows} when the data really is bigger, or switch to\n * `iterate()` and stream it.\n *\n * The offset-drift caveat on {@link iterate} applies here too.\n *\n * @throws When more rows match than `maxRows` allows.\n *\n * @example\n * const overdue = await client.data.invoices.findAll({\n * where: { due_at: [\"<\", today] },\n * cursor: \"id\"\n * });\n */\n findAll(params?: FindAllParams<M>): Promise<M[]>;\n\n /**\n * Find a single record by its ID.\n */\n findById(id: string | number): Promise<M | undefined>;\n\n /**\n * Read one record by its ID, or throw if it is not there.\n *\n * The counterpart to {@link findById}, and the one most reads want. A row\n * fetched by an id that came from a link, a route parameter or another row\n * is expected to exist; when it does not, that is the error case, not a\n * value to thread through the rest of the function.\n *\n * `findById` returns `M | undefined`, so every caller had to prove the row\n * existed before touching a field:\n *\n * ```ts\n * const post = await rebase.data.posts.findById(id);\n * post.title; // TS18048: 'post' is possibly 'undefined'\n * const ok = (await rebase.data.posts.findById(id))!.title; // the `!` everyone reaches for\n * ```\n *\n * With `get`, the absent case is an exception with a code you can branch on,\n * and the happy path is typed as present:\n *\n * ```ts\n * const post = await rebase.data.posts.get(id); // M, not M | undefined\n * ```\n *\n * Same split as Prisma's `findUnique` / `findUniqueOrThrow`: two contracts,\n * both wanted, named so the choice is visible at the call site.\n *\n * @throws {RebaseApiError} `NOT_FOUND` (status 404) when no such row exists,\n * or is visible to the caller — row-level security makes a row the caller\n * may not read indistinguishable from one that is not there, deliberately.\n */\n get(id: string | number): Promise<M>;\n\n /**\n * Create a new record.\n * @param data The record data to create (the collection's `Insert` shape).\n * @param id Optional specific id, sent as an `id` column. This is for tables\n * whose key *is* `id`: the value goes in as that column. For a table keyed\n * on anything else (a `sku`, a composite key), there is no `id` column to\n * receive it — put the key in `data` instead, where it belongs among the\n * columns.\n * @returns The created row\n */\n create(data: I, id?: string | number, options?: WriteOptions): Promise<M>;\n\n /**\n * Write many records in a single request and a single transaction.\n *\n * Built for imports and ETL, where one call per row means one HTTP round\n * trip and one transaction per row. Every record still runs the normal\n * pipeline — callbacks, relations, row-level security — and the batch is\n * all-or-nothing: if any record is rejected, none of them land and the\n * error names the offending index.\n *\n * A record carrying its primary key updates that row; one without inserts.\n * With `{ upsert: true }` each record is written as INSERT ... ON CONFLICT\n * DO UPDATE on the primary key instead, which is what makes a re-runnable\n * import idempotent.\n *\n * Batches are capped server-side (1000 rows by default) because one batch\n * holds its locks for the whole transaction — chunk larger jobs.\n *\n * Pass {@link WriteOptions.idempotencyKey} on anything that may be retried.\n * A client that never sees the response cannot know whether the batch\n * committed, and without a key the server cannot tell the retry from a\n * second genuine import — so it performs it again, duplicating every row in\n * the batch rather than just one.\n *\n * @returns The written rows, in the order given.\n *\n * @example\n * ```ts\n * for (const chunk of chunks(rows, 1000)) {\n * await client.data.products.createMany(chunk, { upsert: true });\n * }\n * ```\n */\n createMany(data: I[], options?: { upsert?: boolean; onConflict?: readonly string[] } & WriteOptions): Promise<M[]>;\n\n /**\n * Update an existing record by ID.\n * @param data The fields to update (the collection's `Update` shape).\n * @param options Per-request write options — notably `idempotencyKey`.\n * @returns The updated row.\n * @throws {RebaseApiError} with status 404 when the record does not exist.\n *\n * `create`, `createMany`, `updateMany`, `delete` and `deleteMany` all took\n * {@link WriteOptions}; this one did not, so the single-row update was the\n * one write on the surface that could not be made idempotent. A client that\n * never sees the response retries, and without a key the server cannot tell\n * that retry from a second deliberate edit — which on a `PATCH` that\n * increments or appends is a second edit applied.\n */\n update(id: string | number, data: U | UpdateValues<U>, options?: WriteOptions): Promise<M>;\n\n /**\n * Insert the row, or replace the one already occupying its key.\n *\n * `INSERT ... ON CONFLICT DO UPDATE`, in one statement — so unlike a\n * `findById` followed by `create`-or-`update` it cannot lose the race\n * between the two, and unlike `create` it does not fail when the row is\n * already there. That is what makes a re-runnable import idempotent\n * without a key.\n *\n * The conflict target defaults to the primary key. Pass `onConflict` to\n * upsert on a natural key instead — `[\"email\"]`, `[\"tenant_id\", \"slug\"]` —\n * and the columns must carry a uniqueness guarantee the database can use:\n * a property with `validation.unique`, or the columns of a declared\n * `unique` index. Anything else is a 400 rather than a Postgres error\n * raised half-way through a transaction.\n *\n * The `on_create` timestamp of a row that already existed is left alone: a\n * conflict means the row's creation is a fact about the past, and a nightly\n * re-import that reset `createdAt` on everything it touched would take\n * every \"new this week\" query with it.\n *\n * @example\n * ```ts\n * await client.data.users.upsert(\n * { email: \"a@b.c\", name: \"Ada\" },\n * { onConflict: [\"email\"] }\n * );\n * ```\n */\n upsert(data: I, options?: UpsertOptions): Promise<M>;\n\n /**\n * Update many records in a single request and a single transaction.\n *\n * The counterpart to {@link createMany}, and the reason it exists is the\n * same: one call per row means one HTTP round trip and one transaction per\n * row. Every record still runs the normal pipeline — callbacks, relations,\n * row-level security — and the batch is all-or-nothing, so a rejected\n * record leaves none of them written and the error names the offending\n * index.\n *\n * Each entry is `{ id, data }` rather than a flat row carrying its own key.\n * That is deliberate: on a table keyed on something other than `id` — a\n * `sku`, a composite key — a flat row cannot say whether a column is the\n * address or a value to write. Naming the address separately mirrors\n * single-row `update(id, data)` exactly and leaves nothing to infer.\n *\n * An id that matches no row fails the batch with a 404 rather than being\n * skipped, for the same reason `update()` does: silently updating four of\n * five rows is worse than updating none.\n *\n * Batches share `createMany`'s server-side cap (1000 rows by default),\n * because one batch holds its locks for the whole transaction.\n *\n * Pass {@link WriteOptions.idempotencyKey} on anything that may be retried.\n * An update replayed in full is naturally idempotent, but one interleaved\n * with another writer's is not — the key is what stops a lost ACK from\n * re-applying a stale batch over newer data.\n *\n * @returns The updated rows, in the order given.\n *\n * @example\n * ```ts\n * await client.data.orders.updateMany([\n * { id: \"o-1\", data: { status: \"shipped\" } },\n * { id: \"o-2\", data: { status: \"shipped\" } }\n * ]);\n * ```\n */\n updateMany(updates: { id: string | number; data: U | UpdateValues<U> }[], options?: WriteOptions): Promise<M[]>;\n\n /**\n * Delete a record by ID.\n * @throws {RebaseApiError} with status 404 when the record does not exist.\n *\n * Takes {@link WriteOptions} like every other write. It did not, so the one\n * mutation that cannot be made safe by repeating it — a delete replayed\n * after the row is gone answers 404, which an offline queue reads as a\n * permanent failure — was also the one that could not carry an\n * `idempotencyKey`.\n */\n delete(id: string | number, options?: WriteOptions): Promise<void>;\n\n /**\n * Delete many records in a single request and a single transaction.\n *\n * Takes ids, not a filter. A filter-shaped bulk delete is a different and\n * far more dangerous operation — the failure mode is an omitted or\n * mistyped condition emptying a table, and it cannot be reviewed at the\n * call site the way an explicit list can. Read first, then pass the ids you\n * meant.\n *\n * `beforeDelete` and `afterDelete` fire per row, exactly as they do for\n * single deletes, and returning `false` from `beforeDelete` fails the batch\n * rather than quietly dropping one row from it. All-or-nothing, so an id\n * that matches no row 404s the whole call.\n *\n * Shares `createMany`'s row cap.\n *\n * @example\n * ```ts\n * const stale = await client.data.sessions.findAll({\n * where: { expires_at: [\"<\", cutoff] }\n * });\n * await client.data.sessions.deleteMany(stale.map(s => s.id as string));\n * ```\n */\n deleteMany(ids: (string | number)[], options?: WriteOptions): Promise<void>;\n\n /**\n * The low-level realtime subscription: raw server pushes, nothing else.\n *\n * **Prefer `observe()`** on a client from `@rebasepro/client`, which wraps\n * this one and is what a UI actually wants — it emits from the local\n * database first when offline is enabled, re-emits on local writes and\n * rollbacks, and de-duplicates emissions so a refresh that changes nothing\n * does not call back. `listen` does none of that; it forwards what the\n * socket sends.\n *\n * Always present. A client that cannot subscribe — one built with\n * `realtime: false`, or on a driver with no `listenCollection` — installs a\n * stub that throws a `RebaseClientError` naming the configuration that\n * would make it work. It used to be optional, which made every call site\n * either write `listen!(…)` or a null check the type system could not tell\n * apart from a real capability question; the answer to *that* question is\n * {@link isUnsupported}, and the answer for ordinary code is to just call\n * it.\n *\n * `observe()` degrades to a single fetch instead of throwing, which is the\n * other reason to reach for it instead.\n */\n listen(params: FindParams<M> | undefined, onUpdate: (response: FindResult<M>) => void, onError?: (error: Error) => void): () => void;\n\n /** {@link listen} for a single row. Prefer `observeById()`. */\n listenById(id: string | number, onUpdate: (row: M | undefined) => void, onError?: (error: Error) => void): () => void;\n\n /**\n * Count the number of records matching the given filter.\n *\n * Always present; see {@link listen} for what a transport that cannot serve\n * it does instead.\n */\n count(params?: FindParams<M>): Promise<number>;\n\n /**\n * `count`/`sum`/`avg`/`min`/`max` over the matching rows, optionally\n * grouped — the SDK half of `GET /<collection>/aggregate`.\n *\n * The whole point is not to fetch rows in order to reduce them: \"revenue by\n * status\" over a million orders is one query and one row per status here,\n * and a `findAll()` plus a loop everywhere else — which is wrong under a\n * `limit` and unaffordable without one. It runs through the same\n * request-scoped handle as every other read, so RLS applies to the rows\n * being aggregated.\n *\n * ```ts\n * const rows = await rebase.data.orders.aggregate({\n * select: [{ fn: \"sum\", field: \"total\" }, { fn: \"count\" }],\n * groupBy: [\"status\"],\n * where: { created_at: [\">=\", startOfMonth] }\n * });\n * // [{ status: \"paid\", sum_total: 41822.5, count: 317 }, …]\n * ```\n *\n * Always present; a backend whose driver cannot aggregate answers 501\n * naming the capability rather than an empty result set, which would read\n * as \"nothing matched\".\n */\n aggregate(params: AggregateParams<M>): Promise<AggregateRow[]>;\n\n // Fluent Query Builder\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): SDKQueryBuilderInterface<M>;\n /** A relation path (`author.name`) or a JSON path (`metadata->>tier`). */\n where(column: NonColumnFieldPath, operator: WhereFilterOp, value: unknown): SDKQueryBuilderInterface<M>;\n where(logicalCondition: LogicalCondition): SDKQueryBuilderInterface<M>;\n orderBy(\n column: FieldPath<M> | ComputedSortField | RelationAggregateSort,\n direction?: \"asc\" | \"desc\",\n nulls?: NullsPlacement\n ): SDKQueryBuilderInterface<M>;\n limit(count: number): SDKQueryBuilderInterface<M>;\n offset(count: number): SDKQueryBuilderInterface<M>;\n search(searchString: string, options?: { explain?: boolean }): SDKQueryBuilderInterface<M>;\n /**\n * Order rows by nearest-neighbour distance to `vector`, closest first.\n * Postgres only, over a `type: \"vector\"` property. See\n * {@link SDKQueryBuilderInterface.vectorSearch}.\n */\n vectorSearch(\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): SDKQueryBuilderInterface<M>;\n include(...relations: (string | IncludeSpec)[]): SDKQueryBuilderInterface<M>;\n /** {@link SDKQueryBuilderInterface.fields} */\n fields(...columns: (FieldPath<M> | string)[]): SDKQueryBuilderInterface<M>;\n /** {@link SDKQueryBuilderInterface.distinct} */\n distinct(enabled?: boolean): SDKQueryBuilderInterface<M>;\n /** {@link SDKQueryBuilderInterface.after} */\n after(cursor: string): SDKQueryBuilderInterface<M>;\n}\n\n/**\n * The unified data access object for the **admin panel** (Entity-shaped).\n *\n * Access collections as dynamic properties: `data.products.find(...)`. Each\n * accessor returns `Entity`-wrapped records (`{ id, path, values }`) — the\n * view-model the admin renders. This is what `useData()` / the admin\n * `RebaseContext.data` are backed by.\n *\n * @internal App developers do **not** use this — they use\n * {@link RebaseSdkData} (flat rows), which is what the SDK client and backend\n * `context.data` expose. This Entity-shaped map backs the admin panel only.\n *\n * @group Data\n */\nexport type RebaseData<DB = unknown> = {\n /**\n * Get a collection accessor by slug.\n * Alternative to dynamic property access for cases where\n * the collection name is a variable.\n *\n * @example\n * const accessor = data.collection(\"products\");\n * await accessor.find({ limit: 10 });\n */\n collection<M extends Record<string, unknown> = Record<string, unknown>>(slug: string): CollectionAccessor<M>;\n} & (\n DB extends Record<string, unknown>\n ? { [K in keyof DB]: CollectionAccessor<DB[K] extends { Row: infer R extends Record<string, unknown> } ? R : Record<string, unknown>> }\n : {\n /**\n * Dynamic collection accessor.\n * Access any collection by its slug as a property.\n *\n * The index signature is `CollectionAccessor` alone, for the reason\n * spelled out on {@link RebaseSdkData}: unioning in the `collection`\n * method's own signature is unnecessary across an intersection, and it\n * costs `data.products.find()` — the access this `@example` documents.\n *\n * @example\n * data.products.find({ where: { status: [\"==\", \"published\"] } })\n */\n [collectionSlug: string]: CollectionAccessor;\n }\n);\n\n/**\n * The unified data access object for the **SDK** — flat rows, no Entity wrapper.\n *\n * This is the symmetric developer-facing data API, identical in shape on both\n * sides of the stack:\n * - The frontend SDK client (`client.data.products.find()`)\n * - Backend framework callbacks & scripts (`context.data.products.find()`)\n *\n * Every accessor returns flat rows (the table's columns) via\n * {@link SDKCollectionClient} — access fields directly (`row.title`), never\n * `row.values.title`. The admin uses {@link RebaseData} (Entity) instead.\n *\n * @example\n * // Frontend SDK\n * const { data: posts } = await client.data.posts.find();\n * console.log(posts[0].title); // flat — no .values\n *\n * // Backend callback — identical shape\n * callbacks: {\n * beforeSave: async ({ context }) => {\n * const product = await context.data.products.findById(id);\n * console.log(product?.price); // flat — no .values\n * }\n * }\n *\n * @group Data\n */\n/**\n * Extract the `Row` shape from a generated `Database[slug]` entry, falling\n * back to an open record when the entry is untyped.\n * @group Data\n */\nexport type RowOf<T> = T extends { Row: infer R extends Record<string, unknown> } ? R : Record<string, unknown>;\n\n/**\n * Extract the `Insert` shape from a generated `Database[slug]` entry (the\n * input accepted by `create`), falling back to `Partial<Row>`.\n * @group Data\n */\nexport type InsertOf<T> = T extends { Insert: infer I extends Record<string, unknown> } ? I : Partial<RowOf<T>>;\n\n/**\n * Extract the `Update` shape from a generated `Database[slug]` entry (the\n * input accepted by `update`), falling back to `Partial<Row>`.\n * @group Data\n */\nexport type UpdateOf<T> = T extends { Update: infer U extends Record<string, unknown> } ? U : Partial<RowOf<T>>;\n\n/**\n * Note on the untyped branch below: its index signature is\n * `SDKCollectionClient`, NOT `SDKCollectionClient | ((slug: string) => …)`.\n *\n * The union looks like it is needed so `collection` — a method on this same\n * object — satisfies the index signature. It is not, because `collection` is\n * declared in a *separate* member of the intersection, and TypeScript only\n * requires named properties to be assignable to an index signature declared\n * alongside them. Including the function arm cost the documented accessor:\n *\n * rebase.dataAsAdmin.projects.find()\n * // ^ Property 'find' does not exist on type\n * // 'SDKCollectionClient | ((slug: string) => …)'\n *\n * Every project without a generated `Database` type lands on this branch, so\n * property-style access — the form used by the `@example` below, by the\n * scaffolded function template, and by the 0.13 migration note — did not\n * compile for any of them. Do not restore the arm; use `collection(slug)` if a\n * caller genuinely needs the by-slug function.\n */\nexport type RebaseSdkData<DB = unknown> = {\n /**\n * Get a flat collection accessor by slug.\n *\n * @example\n * const accessor = data.collection(\"products\");\n * await accessor.find({ limit: 10 });\n */\n collection<M extends Record<string, unknown> = Record<string, unknown>>(slug: string): SDKCollectionClient<M>;\n} & (\n DB extends Record<string, unknown>\n ? { [K in keyof DB]: SDKCollectionClient<RowOf<DB[K]>, InsertOf<DB[K]>, UpdateOf<DB[K]>> }\n : {\n /**\n * Dynamic flat collection accessor.\n * Access any collection by its slug as a property.\n *\n * @example\n * data.products.find({ where: { status: [\"==\", \"published\"] } })\n */\n [collectionSlug: string]: SDKCollectionClient;\n }\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 * @internal\n */\nexport type ListenOneProps<M extends Record<string, unknown> = Record<string, unknown>> =\n FetchOneProps<M>\n & {\n onUpdate: (row: Record<string, unknown> | null) => void,\n onError?: (error: Error) => void,\n }\n\n/**\n * Configuration for vector similarity search queries.\n * Vector search applies an ORDER BY distance expression and optionally\n * filters results by a distance threshold.\n */\nexport interface VectorSearchParams {\n /** Property name containing the vector column */\n property: string;\n /** Query vector to compare against */\n vector: number[];\n /** Distance function (default: \"cosine\") */\n distance?: \"cosine\" | \"l2\" | \"inner_product\";\n /** Only return results within this distance threshold */\n threshold?: number;\n}\n\n// ── List pagination bounds ────────────────────────────────────────────────\n//\n// Client-driven list reads (REST `GET /<collection>` and the WebSocket\n// `subscribe_collection` message) accept a client-supplied `limit`. Without\n// bounds, an ABSENT limit streams the entire table into memory — a trivial\n// OOM/DoS — and `limit=100000000` (or `limit=0`, historically an unlimited\n// bypass) is honoured verbatim. `resolveClientListLimit` is the single shared\n// enforcement point so every untrusted ingress behaves identically. Trusted\n// server-side callers build fetch options directly and are intentionally NOT\n// bounded here (migrations, admin exports, and CDC refetches may need the full\n// set).\n//\n// A limit the platform will not serve is REFUSED, not quietly shrunk. Clamping\n// answers a request for 100 000 rows with 1 000 of them, and a short page is\n// indistinguishable from \"that is all the data there is\" — which is how a CSV\n// export shipped 50 rows of a 100 000-row collection under a filename that read\n// like the whole thing. `meta.total`/`meta.hasMore` make truncation *detectable*\n// on the REST list response, but only for a caller who thinks to compare what it\n// asked for against what it got, and the WebSocket `collection_update` frame\n// carries neither — so signalling cannot be the answer on every surface and\n// rejecting is. An ABSENT limit still defaults: naming no window is not the same\n// as asking for one that cannot be served.\n\n/** Rows returned for a plain / text-search list read when the client sends no `limit`. */\nexport const DEFAULT_LIST_LIMIT = 50;\n/** Rows returned for a vector-search list read when the client sends no `limit`. */\nexport const DEFAULT_VECTOR_LIST_LIMIT = 10;\n/** Largest `limit` a client may ask for on any surface. Above it, the read is refused. */\nexport const MAX_LIST_LIMIT = 1000;\n\n/** Overridable bounds for {@link resolveClientListLimit}. */\nexport interface ListLimitBounds {\n /** Default page size for plain and text-search reads. */\n defaultLimit?: number;\n /** Default page size for vector-search reads. */\n vectorDefaultLimit?: number;\n /** Largest limit a client may ask for. A larger one is rejected, not clamped. */\n maxLimit?: number;\n}\n\n/**\n * Thrown by {@link resolveClientListLimit} for a `limit` the platform will not\n * serve. Carries an HTTP status so an ingress that speaks HTTP can forward it\n * verbatim, and `maxLimit` so one can be built without re-deriving the ceiling.\n *\n * @group Errors\n */\nexport class ListLimitError extends RebaseApiError {\n /** The ceiling that was exceeded — what the caller should page by instead. */\n readonly maxLimit: number;\n\n constructor(message: string, maxLimit: number) {\n super(message, { status: 400, code: \"INVALID_LIMIT\" });\n this.name = \"ListLimitError\";\n this.maxLimit = maxLimit;\n // Keeps `instanceof` working when this is compiled down for an older\n // target, where extending a builtin otherwise loses the prototype.\n Object.setPrototypeOf(this, ListLimitError.prototype);\n }\n}\n\n/**\n * Resolve a client-supplied list `limit` into a safe, always-defined value.\n *\n * - An absent / blank limit falls back to the mode default:\n * `vectorDefaultLimit` for a vector search, otherwise `defaultLimit`.\n * - A limit that is present must be an integer in `[1, maxLimit]`. Anything\n * else — `0`, a negative, `1.5`, `abc`, `100000000` — throws\n * {@link ListLimitError} rather than being coerced into range, because every\n * coercion answers a question the caller did not ask with a page it cannot\n * tell apart from the whole collection.\n *\n * The return is never `undefined` — no ingress that routes its client limit\n * through this can produce an unbounded read.\n *\n * @throws {ListLimitError} when a present `limit` is not an integer in range.\n */\nexport function resolveClientListLimit(\n rawLimit: number | string | null | undefined,\n opts: ListLimitBounds & { vectorSearch?: boolean } = {}\n): number {\n const maxLimit = opts.maxLimit ?? MAX_LIST_LIMIT;\n if (rawLimit != null && String(rawLimit).trim() !== \"\") {\n // `Number`, not `parseInt`: `parseInt(\"50rows\")` is 50, which silently\n // reads a typo as a window the caller never wrote.\n const parsed = typeof rawLimit === \"number\" ? rawLimit : Number(String(rawLimit).trim());\n if (!Number.isInteger(parsed) || parsed < 1) {\n throw new ListLimitError(\n `Invalid \\`limit\\`: ${String(rawLimit)}. Expected a whole number between 1 and ${maxLimit}.`,\n maxLimit\n );\n }\n if (parsed > maxLimit) {\n throw new ListLimitError(\n `\\`limit\\` ${parsed} is above the maximum of ${maxLimit}. Ask for at most ${maxLimit} rows ` +\n \"per read and page through the rest with `offset` — answering with a smaller page would be \" +\n \"indistinguishable from there being no more rows.\",\n maxLimit\n );\n }\n return parsed;\n }\n return opts.vectorSearch\n ? (opts.vectorDefaultLimit ?? DEFAULT_VECTOR_LIST_LIMIT)\n : (opts.defaultLimit ?? DEFAULT_LIST_LIMIT);\n}\n\n/**\n * @internal\n */\nexport interface FetchCollectionProps<M extends Record<string, unknown> = Record<string, unknown>> {\n path: string;\n 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 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/**\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 row: { id: string | number; path: string; values?: Partial<EntityValues<M>> };\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/**\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 * 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 * 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 * 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 // ── 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 limit?: number;\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","!function(e){var t;\"object\"==typeof exports?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(\"undefined\"!=typeof window?t=window:\"undefined\"!=typeof global?t=global:\"undefined\"!=typeof self&&(t=self),t.objectHash=e())}(function(){return function r(o,i,u){function s(n,e){if(!i[n]){if(!o[n]){var t=\"function\"==typeof require&&require;if(!e&&t)return t(n,!0);if(a)return a(n,!0);throw new Error(\"Cannot find module '\"+n+\"'\")}e=i[n]={exports:{}};o[n][0].call(e.exports,function(e){var t=o[n][1][e];return s(t||e)},e,e.exports,r,o,i,u)}return i[n].exports}for(var a=\"function\"==typeof require&&require,e=0;e<u.length;e++)s(u[e]);return s}({1:[function(w,b,m){!function(e,n,s,c,d,h,p,g,y){\"use strict\";var r=w(\"crypto\");function t(e,t){t=u(e,t);var n;return void 0===(n=\"passthrough\"!==t.algorithm?r.createHash(t.algorithm):new l).write&&(n.write=n.update,n.end=n.update),f(t,n).dispatch(e),n.update||n.end(\"\"),n.digest?n.digest(\"buffer\"===t.encoding?void 0:t.encoding):(e=n.read(),\"buffer\"!==t.encoding?e.toString(t.encoding):e)}(m=b.exports=t).sha1=function(e){return t(e)},m.keys=function(e){return t(e,{excludeValues:!0,algorithm:\"sha1\",encoding:\"hex\"})},m.MD5=function(e){return t(e,{algorithm:\"md5\",encoding:\"hex\"})},m.keysMD5=function(e){return t(e,{algorithm:\"md5\",encoding:\"hex\",excludeValues:!0})};var o=r.getHashes?r.getHashes().slice():[\"sha1\",\"md5\"],i=(o.push(\"passthrough\"),[\"buffer\",\"hex\",\"binary\",\"base64\"]);function u(e,t){var n={};if(n.algorithm=(t=t||{}).algorithm||\"sha1\",n.encoding=t.encoding||\"hex\",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error(\"Object argument required.\");for(var r=0;r<o.length;++r)o[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=o[r]);if(-1===o.indexOf(n.algorithm))throw new Error('Algorithm \"'+n.algorithm+'\" not supported. supported values: '+o.join(\", \"));if(-1===i.indexOf(n.encoding)&&\"passthrough\"!==n.algorithm)throw new Error('Encoding \"'+n.encoding+'\" not supported. supported values: '+i.join(\", \"));return n}function a(e){if(\"function\"==typeof e)return null!=/^function\\s+\\w*\\s*\\(\\s*\\)\\s*{\\s+\\[native code\\]\\s+}$/i.exec(Function.prototype.toString.call(e))}function f(o,t,i){i=i||[];function u(e){return t.update?t.update(e,\"utf8\"):t.write(e,\"utf8\")}return{dispatch:function(e){return this[\"_\"+(null===(e=o.replacer?o.replacer(e):e)?\"null\":typeof e)](e)},_object:function(t){var n,e=Object.prototype.toString.call(t),r=/\\[object (.*)\\]/i.exec(e);r=(r=r?r[1]:\"unknown:[\"+e+\"]\").toLowerCase();if(0<=(e=i.indexOf(t)))return this.dispatch(\"[CIRCULAR:\"+e+\"]\");if(i.push(t),void 0!==s&&s.isBuffer&&s.isBuffer(t))return u(\"buffer:\"),u(t);if(\"object\"===r||\"function\"===r||\"asyncfunction\"===r)return e=Object.keys(t),o.unorderedObjects&&(e=e.sort()),!1===o.respectType||a(t)||e.splice(0,0,\"prototype\",\"__proto__\",\"constructor\"),o.excludeKeys&&(e=e.filter(function(e){return!o.excludeKeys(e)})),u(\"object:\"+e.length+\":\"),n=this,e.forEach(function(e){n.dispatch(e),u(\":\"),o.excludeValues||n.dispatch(t[e]),u(\",\")});if(!this[\"_\"+r]){if(o.ignoreUnknown)return u(\"[\"+r+\"]\");throw new Error('Unknown object type \"'+r+'\"')}this[\"_\"+r](t)},_array:function(e,t){t=void 0!==t?t:!1!==o.unorderedArrays;var n=this;if(u(\"array:\"+e.length+\":\"),!t||e.length<=1)return e.forEach(function(e){return n.dispatch(e)});var r=[],t=e.map(function(e){var t=new l,n=i.slice();return f(o,t,n).dispatch(e),r=r.concat(n.slice(i.length)),t.read().toString()});return i=i.concat(r),t.sort(),this._array(t,!1)},_date:function(e){return u(\"date:\"+e.toJSON())},_symbol:function(e){return u(\"symbol:\"+e.toString())},_error:function(e){return u(\"error:\"+e.toString())},_boolean:function(e){return u(\"bool:\"+e.toString())},_string:function(e){u(\"string:\"+e.length+\":\"),u(e.toString())},_function:function(e){u(\"fn:\"),a(e)?this.dispatch(\"[native]\"):this.dispatch(e.toString()),!1!==o.respectFunctionNames&&this.dispatch(\"function-name:\"+String(e.name)),o.respectFunctionProperties&&this._object(e)},_number:function(e){return u(\"number:\"+e.toString())},_xml:function(e){return u(\"xml:\"+e.toString())},_null:function(){return u(\"Null\")},_undefined:function(){return u(\"Undefined\")},_regexp:function(e){return u(\"regex:\"+e.toString())},_uint8array:function(e){return u(\"uint8array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return u(\"uint8clampedarray:\"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return u(\"int8array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return u(\"uint16array:\"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return u(\"int16array:\"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return u(\"uint32array:\"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return u(\"int32array:\"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return u(\"float32array:\"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return u(\"float64array:\"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return u(\"arraybuffer:\"),this.dispatch(new Uint8Array(e))},_url:function(e){return u(\"url:\"+e.toString())},_map:function(e){u(\"map:\");e=Array.from(e);return this._array(e,!1!==o.unorderedSets)},_set:function(e){u(\"set:\");e=Array.from(e);return this._array(e,!1!==o.unorderedSets)},_file:function(e){return u(\"file:\"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(o.ignoreUnknown)return u(\"[blob]\");throw Error('Hashing Blob objects is currently not supported\\n(see https://github.com/puleos/object-hash/issues/26)\\nUse \"options.replacer\" or \"options.ignoreUnknown\"\\n')},_domwindow:function(){return u(\"domwindow\")},_bigint:function(e){return u(\"bigint:\"+e.toString())},_process:function(){return u(\"process\")},_timer:function(){return u(\"timer\")},_pipe:function(){return u(\"pipe\")},_tcp:function(){return u(\"tcp\")},_udp:function(){return u(\"udp\")},_tty:function(){return u(\"tty\")},_statwatcher:function(){return u(\"statwatcher\")},_securecontext:function(){return u(\"securecontext\")},_connection:function(){return u(\"connection\")},_zlib:function(){return u(\"zlib\")},_context:function(){return u(\"context\")},_nodescript:function(){return u(\"nodescript\")},_httpparser:function(){return u(\"httpparser\")},_dataview:function(){return u(\"dataview\")},_signal:function(){return u(\"signal\")},_fsevent:function(){return u(\"fsevent\")},_tlswrap:function(){return u(\"tlswrap\")}}}function l(){return{buf:\"\",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}m.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),f(t=u(e,t),n).dispatch(e)}}.call(this,w(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},w(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/fake_9a5aa49d.js\",\"/\")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){!function(e){\"use strict\";var a=\"undefined\"!=typeof Uint8Array?Uint8Array:Array,t=\"+\".charCodeAt(0),n=\"/\".charCodeAt(0),r=\"0\".charCodeAt(0),o=\"a\".charCodeAt(0),i=\"A\".charCodeAt(0),u=\"-\".charCodeAt(0),s=\"_\".charCodeAt(0);function f(e){e=e.charCodeAt(0);return e===t||e===u?62:e===n||e===s?63:e<r?-1:e<r+10?e-r+26+26:e<i+26?e-i:e<o+26?e-o+26:void 0}e.toByteArray=function(e){var t,n;if(0<e.length%4)throw new Error(\"Invalid string. Length must be a multiple of 4\");var r=e.length,r=\"=\"===e.charAt(r-2)?2:\"=\"===e.charAt(r-1)?1:0,o=new a(3*e.length/4-r),i=0<r?e.length-4:e.length,u=0;function s(e){o[u++]=e}for(t=0;t<i;t+=4,0)s((16711680&(n=f(e.charAt(t))<<18|f(e.charAt(t+1))<<12|f(e.charAt(t+2))<<6|f(e.charAt(t+3))))>>16),s((65280&n)>>8),s(255&n);return 2==r?s(255&(n=f(e.charAt(t))<<2|f(e.charAt(t+1))>>4)):1==r&&(s((n=f(e.charAt(t))<<10|f(e.charAt(t+1))<<4|f(e.charAt(t+2))>>2)>>8&255),s(255&n)),o},e.fromByteArray=function(e){var t,n,r,o,i=e.length%3,u=\"\";function s(e){return\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)n=(e[t]<<16)+(e[t+1]<<8)+e[t+2],u+=s((o=n)>>18&63)+s(o>>12&63)+s(o>>6&63)+s(63&o);switch(i){case 1:u=(u+=s((n=e[e.length-1])>>2))+s(n<<4&63)+\"==\";break;case 2:u=(u=(u+=s((n=(e[e.length-2]<<8)+e[e.length-1])>>10))+s(n>>4&63))+s(n<<2&63)+\"=\"}return u}}(void 0===f?this.base64js={}:f)}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js\",\"/node_modules/gulp-browserify/node_modules/base64-js/lib\")},{buffer:3,lYpoI2:11}],3:[function(O,e,H){!function(e,n,f,r,h,p,g,y,w){var a=O(\"base64-js\"),i=O(\"ieee754\");function f(e,t,n){if(!(this instanceof f))return new f(e,t,n);var r,o,i,u,s=typeof e;if(\"base64\"===t&&\"string\"==s)for(e=(u=e).trim?u.trim():u.replace(/^\\s+|\\s+$/g,\"\");e.length%4!=0;)e+=\"=\";if(\"number\"==s)r=j(e);else if(\"string\"==s)r=f.byteLength(e,t);else{if(\"object\"!=s)throw new Error(\"First argument needs to be a number, array or string.\");r=j(e.length)}if(f._useTypedArrays?o=f._augment(new Uint8Array(r)):((o=this).length=r,o._isBuffer=!0),f._useTypedArrays&&\"number\"==typeof e.byteLength)o._set(e);else if(C(u=e)||f.isBuffer(u)||u&&\"object\"==typeof u&&\"number\"==typeof u.length)for(i=0;i<r;i++)f.isBuffer(e)?o[i]=e.readUInt8(i):o[i]=e[i];else if(\"string\"==s)o.write(e,0,t);else if(\"number\"==s&&!f._useTypedArrays&&!n)for(i=0;i<r;i++)o[i]=0;return o}function b(e,t,n,r){return f._charsWritten=c(function(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function m(e,t,n,r){return f._charsWritten=c(function(e){for(var t,n,r=[],o=0;o<e.length;o++)n=e.charCodeAt(o),t=n>>8,n=n%256,r.push(n),r.push(t);return r}(t),e,n,r)}function v(e,t,n){var r=\"\";n=Math.min(e.length,n);for(var o=t;o<n;o++)r+=String.fromCharCode(e[o]);return r}function o(e,t,n,r){r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+1<e.length,\"Trying to read beyond buffer length\"));var o,r=e.length;if(!(r<=t))return n?(o=e[t],t+1<r&&(o|=e[t+1]<<8)):(o=e[t]<<8,t+1<r&&(o|=e[t+1])),o}function u(e,t,n,r){r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+3<e.length,\"Trying to read beyond buffer length\"));var o,r=e.length;if(!(r<=t))return n?(t+2<r&&(o=e[t+2]<<16),t+1<r&&(o|=e[t+1]<<8),o|=e[t],t+3<r&&(o+=e[t+3]<<24>>>0)):(t+1<r&&(o=e[t+1]<<16),t+2<r&&(o|=e[t+2]<<8),t+3<r&&(o|=e[t+3]),o+=e[t]<<24>>>0),o}function _(e,t,n,r){if(r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+1<e.length,\"Trying to read beyond buffer length\")),!(e.length<=t))return r=o(e,t,n,!0),32768&r?-1*(65535-r+1):r}function E(e,t,n,r){if(r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(null!=t,\"missing offset\"),d(t+3<e.length,\"Trying to read beyond buffer length\")),!(e.length<=t))return r=u(e,t,n,!0),2147483648&r?-1*(4294967295-r+1):r}function I(e,t,n,r){return r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(t+3<e.length,\"Trying to read beyond buffer length\")),i.read(e,t,n,23,4)}function A(e,t,n,r){return r||(d(\"boolean\"==typeof n,\"missing or invalid endian\"),d(t+7<e.length,\"Trying to read beyond buffer length\")),i.read(e,t,n,52,8)}function s(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+1<e.length,\"trying to write beyond buffer length\"),Y(t,65535));o=e.length;if(!(o<=n))for(var i=0,u=Math.min(o-n,2);i<u;i++)e[n+i]=(t&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function l(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"trying to write beyond buffer length\"),Y(t,4294967295));o=e.length;if(!(o<=n))for(var i=0,u=Math.min(o-n,4);i<u;i++)e[n+i]=t>>>8*(r?i:3-i)&255}function B(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+1<e.length,\"Trying to write beyond buffer length\"),F(t,32767,-32768)),e.length<=n||s(e,0<=t?t:65535+t+1,n,r,o)}function L(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"Trying to write beyond buffer length\"),F(t,2147483647,-2147483648)),e.length<=n||l(e,0<=t?t:4294967295+t+1,n,r,o)}function U(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+3<e.length,\"Trying to write beyond buffer length\"),D(t,34028234663852886e22,-34028234663852886e22)),e.length<=n||i.write(e,t,n,r,23,4)}function x(e,t,n,r,o){o||(d(null!=t,\"missing value\"),d(\"boolean\"==typeof r,\"missing or invalid endian\"),d(null!=n,\"missing offset\"),d(n+7<e.length,\"Trying to write beyond buffer length\"),D(t,17976931348623157e292,-17976931348623157e292)),e.length<=n||i.write(e,t,n,r,52,8)}H.Buffer=f,H.SlowBuffer=f,H.INSPECT_MAX_BYTES=50,f.poolSize=8192,f._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&\"function\"==typeof t.subarray}catch(e){return!1}}(),f.isEncoding=function(e){switch(String(e).toLowerCase()){case\"hex\":case\"utf8\":case\"utf-8\":case\"ascii\":case\"binary\":case\"base64\":case\"raw\":case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return!0;default:return!1}},f.isBuffer=function(e){return!(null==e||!e._isBuffer)},f.byteLength=function(e,t){var n;switch(e+=\"\",t||\"utf8\"){case\"hex\":n=e.length/2;break;case\"utf8\":case\"utf-8\":n=T(e).length;break;case\"ascii\":case\"binary\":case\"raw\":n=e.length;break;case\"base64\":n=M(e).length;break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":n=2*e.length;break;default:throw new Error(\"Unknown encoding\")}return n},f.concat=function(e,t){if(d(C(e),\"Usage: Buffer.concat(list, [totalLength])\\nlist should be an Array.\"),0===e.length)return new f(0);if(1===e.length)return e[0];if(\"number\"!=typeof t)for(o=t=0;o<e.length;o++)t+=e[o].length;for(var n=new f(t),r=0,o=0;o<e.length;o++){var i=e[o];i.copy(n,r),r+=i.length}return n},f.prototype.write=function(e,t,n,r){isFinite(t)?isFinite(n)||(r=n,n=void 0):(a=r,r=t,t=n,n=a),t=Number(t)||0;var o,i,u,s,a=this.length-t;switch((!n||a<(n=Number(n)))&&(n=a),r=String(r||\"utf8\").toLowerCase()){case\"hex\":o=function(e,t,n,r){n=Number(n)||0;var o=e.length-n;(!r||o<(r=Number(r)))&&(r=o),d((o=t.length)%2==0,\"Invalid hex string\"),o/2<r&&(r=o/2);for(var i=0;i<r;i++){var u=parseInt(t.substr(2*i,2),16);d(!isNaN(u),\"Invalid hex string\"),e[n+i]=u}return f._charsWritten=2*i,i}(this,e,t,n);break;case\"utf8\":case\"utf-8\":i=this,u=t,s=n,o=f._charsWritten=c(T(e),i,u,s);break;case\"ascii\":case\"binary\":o=b(this,e,t,n);break;case\"base64\":i=this,u=t,s=n,o=f._charsWritten=c(M(e),i,u,s);break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":o=m(this,e,t,n);break;default:throw new Error(\"Unknown encoding\")}return o},f.prototype.toString=function(e,t,n){var r,o,i,u,s=this;if(e=String(e||\"utf8\").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):s.length)===t)return\"\";switch(e){case\"hex\":r=function(e,t,n){var r=e.length;(!t||t<0)&&(t=0);(!n||n<0||r<n)&&(n=r);for(var o=\"\",i=t;i<n;i++)o+=k(e[i]);return o}(s,t,n);break;case\"utf8\":case\"utf-8\":r=function(e,t,n){var r=\"\",o=\"\";n=Math.min(e.length,n);for(var i=t;i<n;i++)e[i]<=127?(r+=N(o)+String.fromCharCode(e[i]),o=\"\"):o+=\"%\"+e[i].toString(16);return r+N(o)}(s,t,n);break;case\"ascii\":case\"binary\":r=v(s,t,n);break;case\"base64\":o=s,u=n,r=0===(i=t)&&u===o.length?a.fromByteArray(o):a.fromByteArray(o.slice(i,u));break;case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":r=function(e,t,n){for(var r=e.slice(t,n),o=\"\",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}(s,t,n);break;default:throw new Error(\"Unknown encoding\")}return r},f.prototype.toJSON=function(){return{type:\"Buffer\",data:Array.prototype.slice.call(this._arr||this,0)}},f.prototype.copy=function(e,t,n,r){if(t=t||0,(r=r||0===r?r:this.length)!==(n=n||0)&&0!==e.length&&0!==this.length){d(n<=r,\"sourceEnd < sourceStart\"),d(0<=t&&t<e.length,\"targetStart out of bounds\"),d(0<=n&&n<this.length,\"sourceStart out of bounds\"),d(0<=r&&r<=this.length,\"sourceEnd out of bounds\"),r>this.length&&(r=this.length);var o=(r=e.length-t<r-n?e.length-t+n:r)-n;if(o<100||!f._useTypedArrays)for(var i=0;i<o;i++)e[i+t]=this[i+n];else e._set(this.subarray(n,n+o),t)}},f.prototype.slice=function(e,t){var n=this.length;if(e=S(e,n,0),t=S(t,n,n),f._useTypedArrays)return f._augment(this.subarray(e,t));for(var r=t-e,o=new f(r,void 0,!0),i=0;i<r;i++)o[i]=this[i+e];return o},f.prototype.get=function(e){return console.log(\".get() is deprecated. Access using array indexes instead.\"),this.readUInt8(e)},f.prototype.set=function(e,t){return console.log(\".set() is deprecated. Access using array indexes instead.\"),this.writeUInt8(e,t)},f.prototype.readUInt8=function(e,t){if(t||(d(null!=e,\"missing offset\"),d(e<this.length,\"Trying to read beyond buffer length\")),!(e>=this.length))return this[e]},f.prototype.readUInt16LE=function(e,t){return o(this,e,!0,t)},f.prototype.readUInt16BE=function(e,t){return o(this,e,!1,t)},f.prototype.readUInt32LE=function(e,t){return u(this,e,!0,t)},f.prototype.readUInt32BE=function(e,t){return u(this,e,!1,t)},f.prototype.readInt8=function(e,t){if(t||(d(null!=e,\"missing offset\"),d(e<this.length,\"Trying to read beyond buffer length\")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},f.prototype.readInt16LE=function(e,t){return _(this,e,!0,t)},f.prototype.readInt16BE=function(e,t){return _(this,e,!1,t)},f.prototype.readInt32LE=function(e,t){return E(this,e,!0,t)},f.prototype.readInt32BE=function(e,t){return E(this,e,!1,t)},f.prototype.readFloatLE=function(e,t){return I(this,e,!0,t)},f.prototype.readFloatBE=function(e,t){return I(this,e,!1,t)},f.prototype.readDoubleLE=function(e,t){return A(this,e,!0,t)},f.prototype.readDoubleBE=function(e,t){return A(this,e,!1,t)},f.prototype.writeUInt8=function(e,t,n){n||(d(null!=e,\"missing value\"),d(null!=t,\"missing offset\"),d(t<this.length,\"trying to write beyond buffer length\"),Y(e,255)),t>=this.length||(this[t]=e)},f.prototype.writeUInt16LE=function(e,t,n){s(this,e,t,!0,n)},f.prototype.writeUInt16BE=function(e,t,n){s(this,e,t,!1,n)},f.prototype.writeUInt32LE=function(e,t,n){l(this,e,t,!0,n)},f.prototype.writeUInt32BE=function(e,t,n){l(this,e,t,!1,n)},f.prototype.writeInt8=function(e,t,n){n||(d(null!=e,\"missing value\"),d(null!=t,\"missing offset\"),d(t<this.length,\"Trying to write beyond buffer length\"),F(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},f.prototype.writeInt16LE=function(e,t,n){B(this,e,t,!0,n)},f.prototype.writeInt16BE=function(e,t,n){B(this,e,t,!1,n)},f.prototype.writeInt32LE=function(e,t,n){L(this,e,t,!0,n)},f.prototype.writeInt32BE=function(e,t,n){L(this,e,t,!1,n)},f.prototype.writeFloatLE=function(e,t,n){U(this,e,t,!0,n)},f.prototype.writeFloatBE=function(e,t,n){U(this,e,t,!1,n)},f.prototype.writeDoubleLE=function(e,t,n){x(this,e,t,!0,n)},f.prototype.writeDoubleBE=function(e,t,n){x(this,e,t,!1,n)},f.prototype.fill=function(e,t,n){if(t=t||0,n=n||this.length,d(\"number\"==typeof(e=\"string\"==typeof(e=e||0)?e.charCodeAt(0):e)&&!isNaN(e),\"value is not a number\"),d(t<=n,\"end < start\"),n!==t&&0!==this.length){d(0<=t&&t<this.length,\"start out of bounds\"),d(0<=n&&n<=this.length,\"end out of bounds\");for(var r=t;r<n;r++)this[r]=e}},f.prototype.inspect=function(){for(var e=[],t=this.length,n=0;n<t;n++)if(e[n]=k(this[n]),n===H.INSPECT_MAX_BYTES){e[n+1]=\"...\";break}return\"<Buffer \"+e.join(\" \")+\">\"},f.prototype.toArrayBuffer=function(){if(\"undefined\"==typeof Uint8Array)throw new Error(\"Buffer.toArrayBuffer not supported in this browser\");if(f._useTypedArrays)return new f(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t<n;t+=1)e[t]=this[t];return e.buffer};var t=f.prototype;function S(e,t,n){return\"number\"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function j(e){return(e=~~Math.ceil(+e))<0?0:e}function C(e){return(Array.isArray||function(e){return\"[object Array]\"===Object.prototype.toString.call(e)})(e)}function k(e){return e<16?\"0\"+e.toString(16):e.toString(16)}function T(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(e.charCodeAt(n));else for(var o=n,i=(55296<=r&&r<=57343&&n++,encodeURIComponent(e.slice(o,n+1)).substr(1).split(\"%\")),u=0;u<i.length;u++)t.push(parseInt(i[u],16))}return t}function M(e){return a.toByteArray(e)}function c(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);o++)t[o+n]=e[o];return o}function N(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function Y(e,t){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(0<=e,\"specified a negative value for writing an unsigned value\"),d(e<=t,\"value is larger than maximum value for type\"),d(Math.floor(e)===e,\"value has a fractional component\")}function F(e,t,n){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(e<=t,\"value larger than maximum allowed value\"),d(n<=e,\"value smaller than minimum allowed value\"),d(Math.floor(e)===e,\"value has a fractional component\")}function D(e,t,n){d(\"number\"==typeof e,\"cannot write a non-number as a number\"),d(e<=t,\"value larger than maximum allowed value\"),d(n<=e,\"value smaller than minimum allowed value\")}function d(e,t){if(!e)throw new Error(t||\"Failed assertion\")}f._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=t.get,e.set=t.set,e.write=t.write,e.toString=t.toString,e.toLocaleString=t.toString,e.toJSON=t.toJSON,e.copy=t.copy,e.slice=t.slice,e.readUInt8=t.readUInt8,e.readUInt16LE=t.readUInt16LE,e.readUInt16BE=t.readUInt16BE,e.readUInt32LE=t.readUInt32LE,e.readUInt32BE=t.readUInt32BE,e.readInt8=t.readInt8,e.readInt16LE=t.readInt16LE,e.readInt16BE=t.readInt16BE,e.readInt32LE=t.readInt32LE,e.readInt32BE=t.readInt32BE,e.readFloatLE=t.readFloatLE,e.readFloatBE=t.readFloatBE,e.readDoubleLE=t.readDoubleLE,e.readDoubleBE=t.readDoubleBE,e.writeUInt8=t.writeUInt8,e.writeUInt16LE=t.writeUInt16LE,e.writeUInt16BE=t.writeUInt16BE,e.writeUInt32LE=t.writeUInt32LE,e.writeUInt32BE=t.writeUInt32BE,e.writeInt8=t.writeInt8,e.writeInt16LE=t.writeInt16LE,e.writeInt16BE=t.writeInt16BE,e.writeInt32LE=t.writeInt32LE,e.writeInt32BE=t.writeInt32BE,e.writeFloatLE=t.writeFloatLE,e.writeFloatBE=t.writeFloatBE,e.writeDoubleLE=t.writeDoubleLE,e.writeDoubleBE=t.writeDoubleBE,e.fill=t.fill,e.inspect=t.inspect,e.toArrayBuffer=t.toArrayBuffer,e}}.call(this,O(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},O(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/buffer/index.js\",\"/node_modules/gulp-browserify/node_modules/buffer\")},{\"base64-js\":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(c,d,e){!function(e,t,a,n,r,o,i,u,s){var a=c(\"buffer\").Buffer,f=4,l=new a(f);l.fill(0);d.exports={hash:function(e,t,n,r){for(var o=t(function(e,t){e.length%f!=0&&(n=e.length+(f-e.length%f),e=a.concat([e,l],n));for(var n,r=[],o=t?e.readInt32BE:e.readInt32LE,i=0;i<e.length;i+=f)r.push(o.call(e,i));return r}(e=a.isBuffer(e)?e:new a(e),r),8*e.length),t=r,i=new a(n),u=t?i.writeInt32BE:i.writeInt32LE,s=0;s<o.length;s++)u.call(i,o[s],4*s,!0);return i}}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{buffer:3,lYpoI2:11}],5:[function(v,e,_){!function(l,c,u,d,h,p,g,y,w){var u=v(\"buffer\").Buffer,e=v(\"./sha\"),t=v(\"./sha256\"),n=v(\"./rng\"),b={sha1:e,sha256:t,md5:v(\"./md5\")},s=64,a=new u(s);function r(e,n){var r=b[e=e||\"sha1\"],o=[];return r||i(\"algorithm:\",e,\"is not yet supported\"),{update:function(e){return u.isBuffer(e)||(e=new u(e)),o.push(e),e.length,this},digest:function(e){var t=u.concat(o),t=n?function(e,t,n){u.isBuffer(t)||(t=new u(t)),u.isBuffer(n)||(n=new u(n)),t.length>s?t=e(t):t.length<s&&(t=u.concat([t,a],s));for(var r=new u(s),o=new u(s),i=0;i<s;i++)r[i]=54^t[i],o[i]=92^t[i];return n=e(u.concat([r,n])),e(u.concat([o,n]))}(r,n,t):r(t);return o=null,e?t.toString(e):t}}}function i(){var e=[].slice.call(arguments).join(\" \");throw new Error([e,\"we accept pull requests\",\"http://github.com/dominictarr/crypto-browserify\"].join(\"\\n\"))}a.fill(0),_.createHash=function(e){return r(e)},_.createHmac=r,_.randomBytes=function(e,t){if(!t||!t.call)return new u(n(e));try{t.call(this,void 0,new u(n(e)))}catch(e){t(e)}};var o,f=[\"createCredentials\",\"createCipher\",\"createCipheriv\",\"createDecipher\",\"createDecipheriv\",\"createSign\",\"createVerify\",\"createDiffieHellman\",\"pbkdf2\"],m=function(e){_[e]=function(){i(\"sorry,\",e,\"is not implemented yet\")}};for(o in f)m(f[o],o)}.call(this,v(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},v(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./md5\":6,\"./rng\":7,\"./sha\":8,\"./sha256\":9,buffer:3,lYpoI2:11}],6:[function(w,b,e){!function(e,r,o,i,u,a,f,l,y){var t=w(\"./helpers\");function n(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var n=1732584193,r=-271733879,o=-1732584194,i=271733878,u=0;u<e.length;u+=16){var s=n,a=r,f=o,l=i,n=c(n,r,o,i,e[u+0],7,-680876936),i=c(i,n,r,o,e[u+1],12,-389564586),o=c(o,i,n,r,e[u+2],17,606105819),r=c(r,o,i,n,e[u+3],22,-1044525330);n=c(n,r,o,i,e[u+4],7,-176418897),i=c(i,n,r,o,e[u+5],12,1200080426),o=c(o,i,n,r,e[u+6],17,-1473231341),r=c(r,o,i,n,e[u+7],22,-45705983),n=c(n,r,o,i,e[u+8],7,1770035416),i=c(i,n,r,o,e[u+9],12,-1958414417),o=c(o,i,n,r,e[u+10],17,-42063),r=c(r,o,i,n,e[u+11],22,-1990404162),n=c(n,r,o,i,e[u+12],7,1804603682),i=c(i,n,r,o,e[u+13],12,-40341101),o=c(o,i,n,r,e[u+14],17,-1502002290),n=d(n,r=c(r,o,i,n,e[u+15],22,1236535329),o,i,e[u+1],5,-165796510),i=d(i,n,r,o,e[u+6],9,-1069501632),o=d(o,i,n,r,e[u+11],14,643717713),r=d(r,o,i,n,e[u+0],20,-373897302),n=d(n,r,o,i,e[u+5],5,-701558691),i=d(i,n,r,o,e[u+10],9,38016083),o=d(o,i,n,r,e[u+15],14,-660478335),r=d(r,o,i,n,e[u+4],20,-405537848),n=d(n,r,o,i,e[u+9],5,568446438),i=d(i,n,r,o,e[u+14],9,-1019803690),o=d(o,i,n,r,e[u+3],14,-187363961),r=d(r,o,i,n,e[u+8],20,1163531501),n=d(n,r,o,i,e[u+13],5,-1444681467),i=d(i,n,r,o,e[u+2],9,-51403784),o=d(o,i,n,r,e[u+7],14,1735328473),n=h(n,r=d(r,o,i,n,e[u+12],20,-1926607734),o,i,e[u+5],4,-378558),i=h(i,n,r,o,e[u+8],11,-2022574463),o=h(o,i,n,r,e[u+11],16,1839030562),r=h(r,o,i,n,e[u+14],23,-35309556),n=h(n,r,o,i,e[u+1],4,-1530992060),i=h(i,n,r,o,e[u+4],11,1272893353),o=h(o,i,n,r,e[u+7],16,-155497632),r=h(r,o,i,n,e[u+10],23,-1094730640),n=h(n,r,o,i,e[u+13],4,681279174),i=h(i,n,r,o,e[u+0],11,-358537222),o=h(o,i,n,r,e[u+3],16,-722521979),r=h(r,o,i,n,e[u+6],23,76029189),n=h(n,r,o,i,e[u+9],4,-640364487),i=h(i,n,r,o,e[u+12],11,-421815835),o=h(o,i,n,r,e[u+15],16,530742520),n=p(n,r=h(r,o,i,n,e[u+2],23,-995338651),o,i,e[u+0],6,-198630844),i=p(i,n,r,o,e[u+7],10,1126891415),o=p(o,i,n,r,e[u+14],15,-1416354905),r=p(r,o,i,n,e[u+5],21,-57434055),n=p(n,r,o,i,e[u+12],6,1700485571),i=p(i,n,r,o,e[u+3],10,-1894986606),o=p(o,i,n,r,e[u+10],15,-1051523),r=p(r,o,i,n,e[u+1],21,-2054922799),n=p(n,r,o,i,e[u+8],6,1873313359),i=p(i,n,r,o,e[u+15],10,-30611744),o=p(o,i,n,r,e[u+6],15,-1560198380),r=p(r,o,i,n,e[u+13],21,1309151649),n=p(n,r,o,i,e[u+4],6,-145523070),i=p(i,n,r,o,e[u+11],10,-1120210379),o=p(o,i,n,r,e[u+2],15,718787259),r=p(r,o,i,n,e[u+9],21,-343485551),n=g(n,s),r=g(r,a),o=g(o,f),i=g(i,l)}return Array(n,r,o,i)}function s(e,t,n,r,o,i){return g((t=g(g(t,e),g(r,i)))<<o|t>>>32-o,n)}function c(e,t,n,r,o,i,u){return s(t&n|~t&r,e,t,o,i,u)}function d(e,t,n,r,o,i,u){return s(t&r|n&~r,e,t,o,i,u)}function h(e,t,n,r,o,i,u){return s(t^n^r,e,t,o,i,u)}function p(e,t,n,r,o,i,u){return s(n^(t|~r),e,t,o,i,u)}function g(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}b.exports=function(e){return t.hash(e,n,16)}}.call(this,w(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},w(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],7:[function(e,l,t){!function(e,t,n,r,o,i,u,s,f){var a;l.exports=a||function(e){for(var t,n=new Array(e),r=0;r<e;r++)0==(3&r)&&(t=4294967296*Math.random()),n[r]=t>>>((3&r)<<3)&255;return n}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{buffer:3,lYpoI2:11}],8:[function(c,d,e){!function(e,t,n,r,o,s,a,f,l){var i=c(\"./helpers\");function u(l,c){l[c>>5]|=128<<24-c%32,l[15+(c+64>>9<<4)]=c;for(var e,t,n,r=Array(80),o=1732584193,i=-271733879,u=-1732584194,s=271733878,d=-1009589776,h=0;h<l.length;h+=16){for(var p=o,g=i,y=u,w=s,b=d,a=0;a<80;a++){r[a]=a<16?l[h+a]:v(r[a-3]^r[a-8]^r[a-14]^r[a-16],1);var f=m(m(v(o,5),(f=i,t=u,n=s,(e=a)<20?f&t|~f&n:!(e<40)&&e<60?f&t|f&n|t&n:f^t^n)),m(m(d,r[a]),(e=a)<20?1518500249:e<40?1859775393:e<60?-1894007588:-899497514)),d=s,s=u,u=v(i,30),i=o,o=f}o=m(o,p),i=m(i,g),u=m(u,y),s=m(s,w),d=m(d,b)}return Array(o,i,u,s,d)}function m(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function v(e,t){return e<<t|e>>>32-t}d.exports=function(e){return i.hash(e,u,20,!0)}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],9:[function(c,d,e){!function(e,t,n,r,u,s,a,f,l){function b(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function o(e,l){var c,d=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),t=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),n=new Array(64);e[l>>5]|=128<<24-l%32,e[15+(l+64>>9<<4)]=l;for(var r,o,h=0;h<e.length;h+=16){for(var i=t[0],u=t[1],s=t[2],p=t[3],a=t[4],g=t[5],y=t[6],w=t[7],f=0;f<64;f++)n[f]=f<16?e[f+h]:b(b(b((o=n[f-2],m(o,17)^m(o,19)^v(o,10)),n[f-7]),(o=n[f-15],m(o,7)^m(o,18)^v(o,3))),n[f-16]),c=b(b(b(b(w,m(o=a,6)^m(o,11)^m(o,25)),a&g^~a&y),d[f]),n[f]),r=b(m(r=i,2)^m(r,13)^m(r,22),i&u^i&s^u&s),w=y,y=g,g=a,a=b(p,c),p=s,s=u,u=i,i=b(c,r);t[0]=b(i,t[0]),t[1]=b(u,t[1]),t[2]=b(s,t[2]),t[3]=b(p,t[3]),t[4]=b(a,t[4]),t[5]=b(g,t[5]),t[6]=b(y,t[6]),t[7]=b(w,t[7])}return t}var i=c(\"./helpers\"),m=function(e,t){return e>>>t|e<<32-t},v=function(e,t){return e>>>t};d.exports=function(e){return i.hash(e,o,32,!0)}}.call(this,c(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},c(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js\",\"/node_modules/gulp-browserify/node_modules/crypto-browserify\")},{\"./helpers\":4,buffer:3,lYpoI2:11}],10:[function(e,t,f){!function(e,t,n,r,o,i,u,s,a){f.read=function(e,t,n,r,o){var i,u,l=8*o-r-1,c=(1<<l)-1,d=c>>1,s=-7,a=n?o-1:0,f=n?-1:1,o=e[t+a];for(a+=f,i=o&(1<<-s)-1,o>>=-s,s+=l;0<s;i=256*i+e[t+a],a+=f,s-=8);for(u=i&(1<<-s)-1,i>>=-s,s+=r;0<s;u=256*u+e[t+a],a+=f,s-=8);if(0===i)i=1-d;else{if(i===c)return u?NaN:1/0*(o?-1:1);u+=Math.pow(2,r),i-=d}return(o?-1:1)*u*Math.pow(2,i-r)},f.write=function(e,t,l,n,r,c){var o,i,u=8*c-r-1,s=(1<<u)-1,a=s>>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:c-1,h=n?1:-1,c=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(i=isNaN(t)?1:0,o=s):(o=Math.floor(Math.log(t)/Math.LN2),t*(n=Math.pow(2,-o))<1&&(o--,n*=2),2<=(t+=1<=o+a?d/n:d*Math.pow(2,1-a))*n&&(o++,n/=2),s<=o+a?(i=0,o=s):1<=o+a?(i=(t*n-1)*Math.pow(2,r),o+=a):(i=t*Math.pow(2,a-1)*Math.pow(2,r),o=0));8<=r;e[l+f]=255&i,f+=h,i/=256,r-=8);for(o=o<<r|i,u+=r;0<u;e[l+f]=255&o,f+=h,o/=256,u-=8);e[l+f-h]|=128*c}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/ieee754/index.js\",\"/node_modules/gulp-browserify/node_modules/ieee754\")},{buffer:3,lYpoI2:11}],11:[function(e,h,t){!function(e,t,n,r,o,f,l,c,d){var i,u,s;function a(){}(e=h.exports={}).nextTick=(u=\"undefined\"!=typeof window&&window.setImmediate,s=\"undefined\"!=typeof window&&window.postMessage&&window.addEventListener,u?function(e){return window.setImmediate(e)}:s?(i=[],window.addEventListener(\"message\",function(e){var t=e.source;t!==window&&null!==t||\"process-tick\"!==e.data||(e.stopPropagation(),0<i.length&&i.shift()())},!0),function(e){i.push(e),window.postMessage(\"process-tick\",\"*\")}):function(e){setTimeout(e,0)}),e.title=\"browser\",e.browser=!0,e.env={},e.argv=[],e.on=a,e.addListener=a,e.once=a,e.off=a,e.removeListener=a,e.removeAllListeners=a,e.emit=a,e.binding=function(e){throw new Error(\"process.binding is not supported\")},e.cwd=function(){return\"/\"},e.chdir=function(e){throw new Error(\"process.chdir is not supported\")}}.call(this,e(\"lYpoI2\"),\"undefined\"!=typeof self?self:\"undefined\"!=typeof window?window:{},e(\"buffer\").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],\"/node_modules/gulp-browserify/node_modules/process/browser.js\",\"/node_modules/gulp-browserify/node_modules/process\")},{buffer:3,lYpoI2:11}]},{},[1])(1)});","import hash from \"object-hash\";\nimport { GeoPoint } from \"@rebasepro/types\";\n//#region src/strings.ts\nvar tokenizeRegex = /[A-Z]{2,}(?=[A-Z][a-z]|\\b)|[A-Z]?[a-z]+|[0-9]+(?:[a-z](?![a-z]))?|[A-Z]/g;\nvar toKebabCase = (str) => {\n\tif (!str || typeof str !== \"string\") return \"\";\n\tconst regExpMatchArray = str.match(tokenizeRegex);\n\tif (!regExpMatchArray) return \"\";\n\treturn regExpMatchArray.map((x) => x.toLowerCase()).join(\"-\");\n};\nvar snakeCaseRegex = tokenizeRegex;\nvar toSnakeCase = (str) => {\n\tif (!str || typeof str !== \"string\") return \"\";\n\tconst regExpMatchArray = str.match(snakeCaseRegex);\n\tif (!regExpMatchArray) return \"\";\n\treturn regExpMatchArray.map((x) => x.toLowerCase()).join(\"_\");\n};\nfunction camelCase(str) {\n\tif (!str) return \"\";\n\tif (str.length === 1) return str.toLowerCase();\n\tconst parts = str.split(/[-_ ]+/).filter(Boolean);\n\tif (parts.length === 0) return \"\";\n\treturn parts[0].toLowerCase() + parts.slice(1).map((part) => part.charAt(0).toUpperCase() + part.substring(1).toLowerCase()).join(\"\");\n}\n/**\n* A random base-36 string of exactly `strLength` characters.\n*\n* Not `Math.random().toString(36).slice(2, 2 + strLength)`: that has no\n* guaranteed length. Base-36 of a double drops trailing zeros, so the source\n* string is short about once in 36 calls and the slice quietly returns fewer\n* characters than asked for — `randomString(10)` returning 9. These values\n* prefix uploaded filenames to keep them apart, so a short one is a likelier\n* collision, and it fails at the rate that makes a test look flaky.\n*/\nfunction randomString(strLength = 5) {\n\tconst alphabet = \"0123456789abcdefghijklmnopqrstuvwxyz\";\n\tlet result = \"\";\n\tfor (let i = 0; i < strLength; i++) result += alphabet.charAt(Math.floor(Math.random() * 36));\n\treturn result;\n}\nfunction randomColor() {\n\treturn Math.floor(Math.random() * 16777215).toString(16);\n}\nfunction slugify(text, separator = \"_\", lowercase = true) {\n\tif (!text) return \"\";\n\tconst from = \"ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;-\";\n\tconst to = `aaaaaeeeeeiiiiooooouuuunc${separator}${separator}${separator}${separator}${separator}${separator}${separator}`;\n\tfor (let i = 0, l = 32; i < l; i++) text = text.replace(new RegExp(from.charAt(i), \"g\"), to.charAt(i));\n\ttext = text.toString().trim().replace(/^\\s+|\\s+$/g, \"\").replace(/\\s+/g, separator).replace(/&/g, separator).replace(/[^\\w\\\\-]+/g, \"\").replace(new RegExp(\"\\\\\" + separator + \"\\\\\" + separator + \"+\", \"g\"), separator);\n\treturn lowercase ? text.toLowerCase() : text;\n}\nfunction unslugify(slug) {\n\tif (!slug) return \"\";\n\tif (slug.includes(\"-\") || slug.includes(\"_\") || !slug.includes(\" \")) return slug.replace(/[-_]/g, \" \").replace(/\\w\\S*/g, function(txt) {\n\t\treturn txt.charAt(0).toUpperCase() + txt.substring(1);\n\t}).trim();\n\telse return slug.trim();\n}\n/**\n* Are these two identifiers one edit apart, ignoring case?\n*\n* Tight on purpose. A suggester that fires on two edits offers `columnWidth`\n* for `colWith` and `readOnly` for `required`, and a \"did you mean\" that is\n* usually wrong teaches people to stop reading them. One edit covers what\n* actually happens — a dropped letter (`multilne`), a doubled one, a transposed\n* pair (`validaton`), a wrong case — and nothing else.\n*\n* Lives here rather than beside either caller because both the CLI's manifest\n* reader and the server's collection validator answer the same question about\n* an unknown key, and two copies of a similarity rule is two rules the moment\n* one of them is tuned.\n*/\nfunction isNearMiss(a, b) {\n\tconst x = a.toLowerCase();\n\tconst y = b.toLowerCase();\n\tif (x === y) return true;\n\tif (Math.abs(x.length - y.length) > 1) return false;\n\tconst [shorter, longer] = x.length <= y.length ? [x, y] : [y, x];\n\tlet i = 0;\n\tlet j = 0;\n\tlet edits = 0;\n\twhile (i < shorter.length && j < longer.length) {\n\t\tif (shorter[i] === longer[j]) {\n\t\t\ti++;\n\t\t\tj++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (++edits > 1) return false;\n\t\tif (shorter.length === longer.length) i++;\n\t\tj++;\n\t}\n\treturn edits + (longer.length - j) + (shorter.length - i) <= 1;\n}\n/**\n* The key in `known` that `key` was probably meant to be, if any.\n*\n* `undefined` when nothing is close — which is the common case for a key that\n* is simply from a newer version, and the reason the caller must be able to say\n* \"unknown\" without saying \"wrong\".\n*/\nfunction suggestNearMiss(known, key) {\n\treturn known.find((candidate) => isNearMiss(candidate, key));\n}\nfunction prettifyIdentifier(input) {\n\tif (!input) return \"\";\n\tlet text = input;\n\ttext = text.replace(/([a-z])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3 $2$4\");\n\ttext = text.replace(/[_-]+/g, \" \");\n\treturn text.trim().replace(/\\b\\w/g, (char) => char.toUpperCase());\n}\n//#endregion\n//#region src/objects.ts\n/** @private is the value an empty array? */\nvar isEmptyArray = (value) => Array.isArray(value) && value.length === 0;\n/** @private is the given object a Function? */\nvar isFunction = (obj) => typeof obj === \"function\";\n/** @private is the given object an integer? */\nvar isInteger = (obj) => String(Math.floor(Number(obj))) === String(obj);\n/** @private is the given object a NaN? */\nvar isNaN = (obj) => obj !== obj;\n/**\n* Segments that reach the prototype chain rather than a property of the object.\n*\n* The twin of this function in `@rebasepro/forms` could be made to write onto\n* `Object.prototype` through a path of `__proto__.x`. This copy survives the\n* write by accident — its `clone` always spreads into a fresh object, while the\n* form engine's has a \"preserve class instances\" branch that hands back\n* `Object.prototype` itself — but `getIn` still *reads* through the chain, and\n* handing back `Object.prototype` is how a polluted value is read out again.\n*\n* Closed on both sides here, so the two implementations agree.\n*/\nvar UNSAFE_PATH_SEGMENTS = /* @__PURE__ */ new Set([\n\t\"__proto__\",\n\t\"constructor\",\n\t\"prototype\"\n]);\n/** Whether any segment of this path would traverse the prototype chain. */\nfunction pathTraversesPrototype(path) {\n\treturn toPath(path).some((segment) => UNSAFE_PATH_SEGMENTS.has(segment));\n}\n/**\n* Whether writing this single key with `obj[key] = …` would reach the prototype\n* chain instead of creating a property.\n*\n* The single-key counterpart of {@link pathTraversesPrototype}, for the many\n* places that copy an object one key at a time. `JSON.parse` creates\n* `__proto__` as an *own* property, so it survives `hasOwnProperty` — and then\n* `target[key] = value` invokes the setter and replaces the target's prototype.\n*/\nfunction isPrototypePollutingKey(key) {\n\treturn UNSAFE_PATH_SEGMENTS.has(key);\n}\n/**\n* Deeply get a value from an object via its path.\n*/\nfunction getIn(obj, key, def, p = 0) {\n\tif (pathTraversesPrototype(key)) return def;\n\tconst path = toPath(key);\n\twhile (obj && p < path.length) obj = obj[path[p++]];\n\tif (p !== path.length && !obj) return def;\n\treturn obj === void 0 ? def : obj;\n}\nfunction setIn(obj, path, value) {\n\tif (pathTraversesPrototype(path)) return obj;\n\tconst res = clone(obj);\n\tlet resVal = res;\n\tlet i = 0;\n\tconst pathArray = toPath(path);\n\tfor (; i < pathArray.length - 1; i++) {\n\t\tconst currentPath = pathArray[i];\n\t\tconst currentObj = getIn(obj, pathArray.slice(0, i + 1));\n\t\tif (currentObj && (isObject(currentObj) || Array.isArray(currentObj))) resVal = resVal[currentPath] = clone(currentObj);\n\t\telse {\n\t\t\tconst nextPath = pathArray[i + 1];\n\t\t\tresVal = resVal[currentPath] = isInteger(nextPath) && Number(nextPath) >= 0 ? [] : {};\n\t\t}\n\t}\n\tif ((i === 0 ? obj : resVal)[pathArray[i]] === value) return obj;\n\tif (value === void 0) delete resVal[pathArray[i]];\n\telse resVal[pathArray[i]] = value;\n\tif (i === 0 && value === void 0) delete res[pathArray[i]];\n\treturn res;\n}\nfunction clone(value) {\n\tif (Array.isArray(value)) return [...value];\n\telse if (typeof value === \"object\" && value !== null) return { ...value };\n\telse return value;\n}\n/**\n* Deep clone a value, preserving function references and class instances.\n* Unlike structuredClone, this handles objects that contain functions\n* (e.g. CollectionConfig with target(), childCollections(), callbacks).\n*/\nfunction deepClone(value) {\n\tif (value === null || value === void 0) return value;\n\tif (typeof value === \"function\") return value;\n\tif (typeof value !== \"object\") return value;\n\tif (Array.isArray(value)) return value.map((item) => deepClone(item));\n\tif (Object.getPrototypeOf(value) !== Object.prototype) return value;\n\tconst result = {};\n\tfor (const key of Object.keys(value)) result[key] = deepClone(value[key]);\n\treturn result;\n}\nfunction toPath(value) {\n\tif (Array.isArray(value)) return value;\n\treturn value.replace(/\\[(\\d+)]/g, \".$1\").replace(/^\\./, \"\").replace(/\\.$/, \"\").split(\".\");\n}\nvar pick = (obj, ...args) => ({ ...args.reduce((res, key) => ({\n\t...res,\n\t[key]: obj[key]\n}), {}) });\nfunction isObject(item) {\n\treturn !!item && typeof item === \"object\" && !Array.isArray(item);\n}\nfunction isPlainObject(obj) {\n\tif (typeof obj !== \"object\" || obj === null || Array.isArray(obj)) return false;\n\treturn Object.getPrototypeOf(obj) === Object.prototype;\n}\nfunction mergeDeep(target, source, ignoreUndefined = false) {\n\tif (!isObject(target)) return target;\n\tconst output = { ...target };\n\tif (!isObject(source)) return output;\n\tfor (const key in source) {\n\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n\t\tif (Object.prototype.hasOwnProperty.call(source, key)) {\n\t\t\tconst sourceValue = source[key];\n\t\t\tconst outputValue = output[key];\n\t\t\tif (ignoreUndefined && sourceValue === void 0) continue;\n\t\t\tif (sourceValue instanceof Date) output[key] = new Date(sourceValue.getTime());\n\t\t\telse if (Array.isArray(sourceValue)) if (Array.isArray(outputValue)) if (!(sourceValue.some(isPlainObject) || outputValue.some(isPlainObject))) output[key] = [...sourceValue];\n\t\t\telse {\n\t\t\t\tconst newArray = [];\n\t\t\t\tconst maxLength = Math.max(outputValue.length, sourceValue.length);\n\t\t\t\tfor (let i = 0; i < maxLength; i++) {\n\t\t\t\t\tconst sourceItem = sourceValue[i];\n\t\t\t\t\tconst targetItem = outputValue[i];\n\t\t\t\t\tif (i >= sourceValue.length) newArray[i] = targetItem;\n\t\t\t\t\telse if (i >= outputValue.length) newArray[i] = sourceItem;\n\t\t\t\t\telse if (sourceItem === null) newArray[i] = targetItem;\n\t\t\t\t\telse if (isPlainObject(sourceItem) && isPlainObject(targetItem)) newArray[i] = mergeDeep(targetItem, sourceItem, ignoreUndefined);\n\t\t\t\t\telse newArray[i] = sourceItem;\n\t\t\t\t}\n\t\t\t\toutput[key] = newArray;\n\t\t\t}\n\t\t\telse output[key] = [...sourceValue];\n\t\t\telse if (isPlainObject(sourceValue)) if (isPlainObject(outputValue)) output[key] = mergeDeep(outputValue, sourceValue, ignoreUndefined);\n\t\t\telse output[key] = sourceValue;\n\t\t\telse if (isObject(sourceValue)) output[key] = sourceValue;\n\t\t\telse output[key] = sourceValue;\n\t\t}\n\t}\n\treturn output;\n}\nfunction getValueInPath(o, path) {\n\tif (!o) return void 0;\n\tif (typeof o === \"object\") {\n\t\tif (path in o) return o[path];\n\t\tif (path.includes(\".\") || path.includes(\"[\")) {\n\t\t\tlet pathSegments = path.split(/[.[]/);\n\t\t\tif (path.includes(\"[\")) pathSegments = pathSegments.map((segment) => segment.replace(\"]\", \"\"));\n\t\t\tconst firstSegment = pathSegments[0];\n\t\t\tconst isArrayAndIndexExists = Array.isArray(o[firstSegment]) && !isNaN(parseInt(pathSegments[1]));\n\t\t\tconst nextObject = isArrayAndIndexExists ? o[firstSegment][parseInt(pathSegments[1])] : o[firstSegment];\n\t\t\tconst nextPath = pathSegments.slice(isArrayAndIndexExists ? 2 : 1).join(\".\");\n\t\t\tif (nextPath === \"\") return nextObject;\n\t\t\treturn getValueInPath(nextObject, nextPath);\n\t\t}\n\t}\n}\nfunction removeInPath(o, path) {\n\tconst res = clone(o);\n\tlet current = res;\n\tconst parts = path.split(\".\");\n\tconst last = parts.pop();\n\tfor (const part of parts) if (part in current && current[part] !== null && typeof current[part] === \"object\") {\n\t\tcurrent[part] = clone(current[part]);\n\t\tcurrent = current[part];\n\t} else return res;\n\tif (last && current && typeof current === \"object\") delete current[last];\n\treturn res;\n}\nfunction removeFunctions(o) {\n\tif (o === void 0) return void 0;\n\tif (o === null) return null;\n\tif (typeof o === \"object\") {\n\t\tif (Array.isArray(o)) return o.filter((v) => typeof v !== \"function\").map((v) => removeFunctions(v));\n\t\tif (!isPlainObject(o)) return o;\n\t\treturn Object.entries(o).filter(([_, value]) => typeof value !== \"function\").reduce((acc, [key, value]) => {\n\t\t\tacc[key] = removeFunctions(value);\n\t\t\treturn acc;\n\t\t}, {});\n\t}\n\treturn o;\n}\nfunction getHashValue(v) {\n\tif (!v) return null;\n\tif (typeof v === \"object\" && v !== null) {\n\t\tif (\"id\" in v) return String(v.id);\n\t\telse if (v instanceof Date) return v.toLocaleString();\n\t\telse if (v instanceof GeoPoint) return hash(v);\n\t}\n\treturn hash(v, { ignoreUnknown: true });\n}\nfunction removeUndefined(value, removeEmptyStrings) {\n\tif (typeof value === \"function\") return value;\n\tif (Array.isArray(value)) return value.map((v) => removeUndefined(v, removeEmptyStrings));\n\tif (typeof value === \"object\") {\n\t\tif (value === null) return value;\n\t\tif (!isPlainObject(value)) return value;\n\t\tconst res = {};\n\t\tObject.keys(value).forEach((key) => {\n\t\t\tif (!isEmptyObject(value)) {\n\t\t\t\tconst childRes = removeUndefined(value[key], removeEmptyStrings);\n\t\t\t\tconst isString = typeof childRes === \"string\";\n\t\t\t\tconst shouldKeepIfString = !removeEmptyStrings || removeEmptyStrings && !isString || removeEmptyStrings && isString && childRes !== \"\";\n\t\t\t\tif (childRes !== void 0 && !isEmptyObject(childRes) && shouldKeepIfString) res[key] = childRes;\n\t\t\t}\n\t\t});\n\t\treturn res;\n\t}\n\treturn value;\n}\nfunction removeNulls(value) {\n\tif (typeof value === \"function\") return value;\n\tif (Array.isArray(value)) return value.map((v) => removeNulls(v));\n\tif (typeof value === \"object\") {\n\t\tif (value === null) return value;\n\t\tif (!isPlainObject(value)) return value;\n\t\tconst res = {};\n\t\tconst obj = value;\n\t\tObject.keys(obj).forEach((key) => {\n\t\t\tif (obj[key] !== null) res[key] = removeNulls(obj[key]);\n\t\t});\n\t\treturn res;\n\t}\n\treturn value;\n}\nfunction isEmptyObject(obj) {\n\treturn obj && Object.getPrototypeOf(obj) === Object.prototype && Object.keys(obj).length === 0;\n}\nfunction removePropsIfExisting(source, comparison) {\n\tconst isObject = (val) => typeof val === \"object\" && val !== null;\n\tconst isArray = (val) => Array.isArray(val);\n\tif (!isObject(source) || !isObject(comparison)) return source;\n\tconst res = isArray(source) ? [...source] : { ...source };\n\tif (isArray(res)) {\n\t\tfor (let i = res.length - 1; i >= 0; i--) if (res[i] === comparison[i]) res.splice(i, 1);\n\t\telse if (isObject(res[i]) && isObject(comparison[i])) res[i] = removePropsIfExisting(res[i], comparison[i]);\n\t} else Object.keys(comparison).forEach((key) => {\n\t\tif (key in res) {\n\t\t\tif (isObject(res[key]) && isObject(comparison[key])) res[key] = removePropsIfExisting(res[key], comparison[key]);\n\t\t\telse if (res[key] === comparison[key]) delete res[key];\n\t\t}\n\t});\n\treturn res;\n}\n//#endregion\n//#region src/arrays.ts\n/**\n* Normalise a value that may be a single item or a list into a list.\n*\n* Only `null`/`undefined` mean \"nothing\". A truthiness check here silently\n* swallowed legitimate values — `toArray(0)`, `toArray(false)` and `toArray(\"\")`\n* all came back empty, so a caller normalising a single falsy item lost it.\n*/\nfunction toArray(input) {\n\tif (Array.isArray(input)) return input;\n\tif (input === void 0 || input === null) return [];\n\treturn [input];\n}\n//#endregion\n//#region src/dates.ts\nvar defaultDateFormat = \"MMMM dd, yyyy, HH:mm:ss\";\n/** Seven days, the distance past which a relative phrase stops being useful. */\nvar DEFAULT_MAX_MS = 10080 * 60 * 1e3;\nfunction toTime(value) {\n\tif (value === null || value === void 0 || value === \"\") return null;\n\tconst time = value instanceof Date ? value.getTime() : new Date(value).getTime();\n\treturn Number.isNaN(time) ? null : time;\n}\n/**\n* Describes an instant relative to another one — \"5m ago\", \"in 3h\".\n*\n* The direction is part of the answer. Every hand-rolled version of this in the\n* codebase computed `now - then` and then tested only the positive side, so a\n* timestamp in the future fell through to whichever branch happened to be\n* first: a date scheduled for next month read \"Just now\", and one a couple of\n* hours out read \"-1d ago\". Both are dates a CMS holds all the time — a publish\n* date, a due date, an expiry — and neither shape can occur here, because the\n* distance is measured with {@link Math.abs} and the tense is chosen from the\n* sign rather than assumed.\n*\n* Returns `null` when the value is unreadable, or when it is further than\n* {@link FormatRelativeTimeOptions.maxMs} away in either direction. `null` is\n* \"say it another way\", not an error: the caller owns the absolute format, and\n* the locale and precision that go with it.\n*/\nfunction formatRelativeTime(value, options = {}) {\n\tconst then = toTime(value);\n\tif (then === null) return null;\n\tconst now = options.now instanceof Date ? options.now.getTime() : options.now ?? Date.now();\n\tconst maxMs = options.maxMs ?? DEFAULT_MAX_MS;\n\tconst delta = now - then;\n\tconst distance = Math.abs(delta);\n\tif (distance > maxMs) return null;\n\tconst future = delta < 0;\n\tconst minutes = Math.floor(distance / 6e4);\n\tif (minutes < 1) return future ? \"in a moment\" : \"just now\";\n\tif (minutes < 60) return future ? `in ${minutes}m` : `${minutes}m ago`;\n\tconst hours = Math.floor(distance / 36e5);\n\tif (hours < 24) return future ? `in ${hours}h` : `${hours}h ago`;\n\tconst days = Math.floor(distance / 864e5);\n\treturn future ? `in ${days}d` : `${days}d ago`;\n}\n//#endregion\n//#region src/storage.ts\n/**\n* The ambient `localStorage`, or `null` where there is not one. Access itself\n* is what throws when storage is disabled, so even reaching for it is guarded.\n*/\nfunction getWebStorage() {\n\ttry {\n\t\treturn globalThis.localStorage ?? null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n/**\n* Reads and parses a JSON value a previous session stored, falling back rather\n* than throwing. See the module comment for what it is falling back from.\n*\n* A rejected value is deliberately left in place rather than cleared: this\n* version not understanding it is not evidence that nothing does.\n*/\nfunction readStoredJson(key, options) {\n\tconst storage = options.storage === void 0 ? getWebStorage() : options.storage;\n\tif (!storage) return options.fallback;\n\tlet raw;\n\ttry {\n\t\traw = storage.getItem(key);\n\t} catch {\n\t\treturn options.fallback;\n\t}\n\tif (raw === null || raw === \"\") return options.fallback;\n\tlet parsed;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn options.fallback;\n\t}\n\tif (options.accept && !options.accept(parsed)) return options.fallback;\n\treturn parsed;\n}\n/**\n* Persists a value as JSON. Returns whether it was stored, so a caller that\n* cares can say so — most do not, and for them the point is simply that a full\n* quota does not throw out of the effect doing the writing.\n*/\nfunction writeStoredJson(key, value, options = {}) {\n\tconst storage = options.storage === void 0 ? getWebStorage() : options.storage;\n\tif (!storage) return false;\n\ttry {\n\t\tstorage.setItem(key, JSON.stringify(value));\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/**\n* Persists an already-serialised string, for the values kept as plain text\n* rather than JSON — a selected id, a pane size.\n*/\nfunction writeStoredString(key, value, options = {}) {\n\tconst storage = options.storage === void 0 ? getWebStorage() : options.storage;\n\tif (!storage) return false;\n\ttry {\n\t\tstorage.setItem(key, value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n/** Reads a plain string, absent rather than throwing where there is no storage. */\nfunction readStoredString(key, options = {}) {\n\tconst storage = options.storage === void 0 ? getWebStorage() : options.storage;\n\tif (!storage) return null;\n\ttry {\n\t\treturn storage.getItem(key);\n\t} catch {\n\t\treturn null;\n\t}\n}\n/** `accept` for a caller whose fallback is an array. */\nvar isArrayValue = (value) => Array.isArray(value);\n/** `accept` for a caller whose fallback is a keyed object — and not an array. */\nvar isRecordValue = (value) => typeof value === \"object\" && value !== null && !Array.isArray(value);\n//#endregion\n//#region src/hash.ts\nfunction hashString(str) {\n\tif (!str) return 0;\n\tlet hash = 0;\n\tlet i;\n\tlet chr;\n\tfor (i = 0; i < str.length; i++) {\n\t\tchr = str.charCodeAt(i);\n\t\thash = (hash << 5) - hash + chr;\n\t\thash |= 0;\n\t}\n\treturn Math.abs(hash);\n}\n//#endregion\n//#region src/sha1.ts\n/**\n* Minimal SHA-1 implementation that runs in both Node and the browser.\n*\n* This exists because generated Postgres policy names embed a SHA-1 digest of\n* the security rule. The DDL generator runs on the server (where `node:crypto`\n* is available) but the Studio has to derive the same names in the browser to\n* tell a policy it generated apart from one it did not. `node:crypto` cannot be\n* bundled for the browser, so the shared derivation needs a portable digest.\n*\n* SHA-1 is used purely to name things deterministically — never for security.\n* The output is byte-identical to `createHash(\"sha1\").update(str).digest(\"hex\")`,\n* which `sha1.test.ts` pins against `node:crypto` directly.\n*/\n/** Rotate a 32-bit word left by `n` bits. */\nfunction rotl(value, n) {\n\treturn value << n | value >>> 32 - n;\n}\n/**\n* SHA-1 digest of a string, hex-encoded.\n*\n* The input is encoded as UTF-8, matching Node's default handling of strings\n* passed to `hash.update(str)`.\n*/\nfunction sha1Hex(input) {\n\tconst bytes = Array.from(new TextEncoder().encode(input));\n\tconst bitLength = bytes.length * 8;\n\tbytes.push(128);\n\twhile (bytes.length % 64 !== 56) bytes.push(0);\n\tconst hi = Math.floor(bitLength / 4294967296);\n\tconst lo = bitLength >>> 0;\n\tbytes.push(hi >>> 24 & 255, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255);\n\tbytes.push(lo >>> 24 & 255, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255);\n\tlet h0 = 1732584193;\n\tlet h1 = 4023233417;\n\tlet h2 = 2562383102;\n\tlet h3 = 271733878;\n\tlet h4 = 3285377520;\n\tconst w = new Array(80);\n\tfor (let offset = 0; offset < bytes.length; offset += 64) {\n\t\tfor (let i = 0; i < 16; i++) {\n\t\t\tconst j = offset + i * 4;\n\t\t\tw[i] = bytes[j] << 24 | bytes[j + 1] << 16 | bytes[j + 2] << 8 | bytes[j + 3] | 0;\n\t\t}\n\t\tfor (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);\n\t\tlet a = h0;\n\t\tlet b = h1;\n\t\tlet c = h2;\n\t\tlet d = h3;\n\t\tlet e = h4;\n\t\tfor (let i = 0; i < 80; i++) {\n\t\t\tlet f;\n\t\t\tlet k;\n\t\t\tif (i < 20) {\n\t\t\t\tf = b & c | ~b & d;\n\t\t\t\tk = 1518500249;\n\t\t\t} else if (i < 40) {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 1859775393;\n\t\t\t} else if (i < 60) {\n\t\t\t\tf = b & c | b & d | c & d;\n\t\t\t\tk = 2400959708;\n\t\t\t} else {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 3395469782;\n\t\t\t}\n\t\t\tconst temp = rotl(a, 5) + f + e + k + w[i] | 0;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rotl(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\t\th0 = h0 + a | 0;\n\t\th1 = h1 + b | 0;\n\t\th2 = h2 + c | 0;\n\t\th3 = h3 + d | 0;\n\t\th4 = h4 + e | 0;\n\t}\n\treturn [\n\t\th0,\n\t\th1,\n\t\th2,\n\t\th3,\n\t\th4\n\t].map((word) => (word >>> 0).toString(16).padStart(8, \"0\")).join(\"\");\n}\n//#endregion\n//#region src/policy-names.ts\n/**\n* Naming of the Postgres policies generated from a collection's security rules.\n*\n* A rule without an explicit `name` is compiled to `<table>_<op>_<hash>`, where\n* the hash covers the rule's semantics. The Studio needs the same names to tell\n* \"this policy came from your code\" apart from \"someone wrote this in SQL\" —\n* without them it treats generated policies as foreign and offers to import\n* them back into the codebase they came from.\n*\n* This is the single definition of that naming. The DDL and Drizzle generators\n* both derive names from here, so a change cannot silently rename every policy\n* in every deployed database while the UI keeps matching the old ones.\n*/\n/** Stable digest of the parts of a rule that determine what the policy does. */\nfunction getPolicyNameHash(rule) {\n\treturn sha1Hex(JSON.stringify({\n\t\ta: rule.access,\n\t\tm: rule.mode,\n\t\top: rule.operation,\n\t\tops: rule.operations?.slice().sort(),\n\t\town: rule.ownerField,\n\t\trol: rule.roles?.slice().sort(),\n\t\tpg: rule.pgRoles?.slice().sort(),\n\t\tu: rule.using,\n\t\tw: rule.withCheck,\n\t\tc: rule.condition,\n\t\tch: rule.check\n\t})).substring(0, 7);\n}\n/** The operations a rule expands to — `operations` wins over `operation`. */\nfunction getPolicyOperations(rule) {\n\treturn rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? \"all\"];\n}\n/**\n* Every Postgres policy name a single rule compiles to — one per operation.\n*\n* @param rule The security rule as written in the collection config.\n* @param tableName The rule's table (see `getTableName` in `@rebasepro/common`).\n*/\nfunction getPolicyNamesForRule(rule, tableName) {\n\tconst ops = getPolicyOperations(rule);\n\tconst ruleHash = getPolicyNameHash(rule);\n\treturn ops.map((op, opIdx) => rule.name ? ops.length > 1 ? `${rule.name}_${op}` : rule.name : `${tableName}_${op}_${ruleHash}${ops.length > 1 ? `_${opIdx}` : \"\"}`);\n}\n/** Every policy name a set of rules compiles to, for membership checks. */\nfunction getPolicyNamesForRules(rules, tableName) {\n\tconst names = /* @__PURE__ */ new Set();\n\tfor (const rule of rules) for (const name of getPolicyNamesForRule(rule, tableName)) names.add(name);\n\treturn names;\n}\n//#endregion\n//#region src/regexp.ts\nfunction serializeRegExp(input) {\n\tif (!input) return \"\";\n\treturn input.toString();\n}\n/**\n* Get a RegExp out of a serialized string\n* @param input\n*/\nfunction hydrateRegExp(input) {\n\tif (!input) return void 0;\n\tconst fragments = input.match(/\\/(.*?)\\/([a-z]*)?$/i);\n\tif (fragments) return new RegExp(fragments[1], fragments[2] || \"\");\n\telse return new RegExp(input, \"\");\n}\n/**\n* Is `input` something {@link hydrateRegExp} can turn into a working RegExp?\n*\n* This used to pattern-match the *shape* of a regex literal and, failing that,\n* fall back to \"does it contain any regex-ish character\" — which said yes to\n* malformed input like `/[a-z/g`. The only answer that matters to a caller is\n* whether hydration succeeds, so ask the engine instead of approximating it.\n*/\nfunction isValidRegExp(input) {\n\tif (!input) return false;\n\ttry {\n\t\treturn hydrateRegExp(input) !== void 0;\n\t} catch {\n\t\treturn false;\n\t}\n}\n//#endregion\n//#region src/flatten_object.ts\nfunction flattenObject(obj, parentKey = \"\") {\n\tif (!obj) return obj;\n\treturn Object.keys(obj).reduce((flatObj, key) => {\n\t\tconst newKey = parentKey ? `${parentKey}.${key}` : key;\n\t\tif (typeof obj[key] === \"object\" && obj[key] !== null) if (Array.isArray(obj[key])) obj[key].forEach((item, index) => {\n\t\t\tif (typeof item === \"object\" && item !== null) Object.assign(flatObj, flattenObject(item, `${newKey}[${index}]`));\n\t\t\telse flatObj[`${newKey}[${index}]`] = item;\n\t\t});\n\t\telse Object.assign(flatObj, flattenObject(obj[key], newKey));\n\t\telse flatObj[newKey] = obj[key];\n\t\treturn flatObj;\n\t}, {});\n}\nfunction getArrayValuesCount(array) {\n\treturn array.reduce((acc, obj) => {\n\t\tObject.entries(obj).forEach(([key, value]) => {\n\t\t\tif (Array.isArray(value)) acc[key] = Math.max(acc[key] || 0, value.length);\n\t\t\tif (typeof value === \"object\" && value !== null) {\n\t\t\t\tconst nested = getArrayValuesCount([value]);\n\t\t\t\tObject.entries(nested).forEach(([nestedKey, nestedCount]) => {\n\t\t\t\t\tconst compoundKey = `${key}.${nestedKey}`;\n\t\t\t\t\tacc[compoundKey] = Math.max(acc[compoundKey] || 0, nestedCount);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t\treturn acc;\n\t}, {});\n}\n//#endregion\n//#region src/plurals.ts\n/**\n* Returns the plural of an English word.\n*\n* @param {string} word\n* @param {number} [amount]\n* @returns {string}\n*/\nfunction plural(word, amount) {\n\tif (amount !== void 0 && amount === 1) return word;\n\tconst plurals = {\n\t\t\"(quiz)$\": \"$1zes\",\n\t\t\"^(ox)$\": \"$1en\",\n\t\t\"([m|l])ouse$\": \"$1ice\",\n\t\t\"(matr|vert|ind)ix|ex$\": \"$1ices\",\n\t\t\"(x|ch|ss|sh)$\": \"$1es\",\n\t\t\"([^aeiouy]|qu)y$\": \"$1ies\",\n\t\t\"(hive)$\": \"$1s\",\n\t\t\"(?:([^f])fe|([lr])f)$\": \"$1$2ves\",\n\t\t\"(shea|lea|loa|thie)f$\": \"$1ves\",\n\t\tsis$: \"ses\",\n\t\t\"([ti])um$\": \"$1a\",\n\t\t\"(tomat|potat|ech|her|vet)o$\": \"$1oes\",\n\t\t\"(bu)s$\": \"$1ses\",\n\t\t\"(alias)$\": \"$1es\",\n\t\t\"(octop)us$\": \"$1i\",\n\t\t\"(ax|test)is$\": \"$1es\",\n\t\t\"(us)$\": \"$1es\",\n\t\t\"([^s]+)$\": \"$1s\"\n\t};\n\tconst irregular = {\n\t\tmove: \"moves\",\n\t\tfoot: \"feet\",\n\t\tgoose: \"geese\",\n\t\tsex: \"sexes\",\n\t\tchild: \"children\",\n\t\tman: \"men\",\n\t\ttooth: \"teeth\",\n\t\tperson: \"people\"\n\t};\n\tif ([\n\t\t\"sheep\",\n\t\t\"fish\",\n\t\t\"deer\",\n\t\t\"moose\",\n\t\t\"series\",\n\t\t\"species\",\n\t\t\"money\",\n\t\t\"rice\",\n\t\t\"information\",\n\t\t\"equipment\",\n\t\t\"bison\",\n\t\t\"cod\",\n\t\t\"offspring\",\n\t\t\"pike\",\n\t\t\"salmon\",\n\t\t\"shrimp\",\n\t\t\"swine\",\n\t\t\"trout\",\n\t\t\"aircraft\",\n\t\t\"hovercraft\",\n\t\t\"spacecraft\",\n\t\t\"sugar\",\n\t\t\"tuna\",\n\t\t\"you\",\n\t\t\"wood\"\n\t].indexOf(word.toLowerCase()) >= 0) return word;\n\tfor (const w in irregular) {\n\t\tconst pattern = new RegExp(`${w}$`, \"i\");\n\t\tconst replace = irregular[w];\n\t\tif (pattern.test(word)) return word.replace(pattern, replace);\n\t}\n\tfor (const reg in plurals) {\n\t\tconst pattern = new RegExp(reg, \"i\");\n\t\tif (pattern.test(word)) return word.replace(pattern, plurals[reg]);\n\t}\n\treturn word;\n}\n/**\n* Returns the singular of an English word.\n*\n* @param {string} word\n* @param {number} [amount]\n* @returns {string}\n*/\nfunction singular(word, amount) {\n\tif (amount !== void 0 && amount !== 1) return word;\n\tconst singulars = {\n\t\t\"(quiz)zes$\": \"$1\",\n\t\t\"(matr)ices$\": \"$1ix\",\n\t\t\"(vert|ind)ices$\": \"$1ex\",\n\t\t\"^(ox)en$\": \"$1\",\n\t\t\"(alias)es$\": \"$1\",\n\t\t\"(octop|vir)i$\": \"$1us\",\n\t\t\"(cris|ax|test)es$\": \"$1is\",\n\t\t\"(shoe)s$\": \"$1\",\n\t\t\"(o)es$\": \"$1\",\n\t\t\"(bus)es$\": \"$1\",\n\t\t\"([m|l])ice$\": \"$1ouse\",\n\t\t\"(x|ch|ss|sh)es$\": \"$1\",\n\t\t\"(m)ovies$\": \"$1ovie\",\n\t\t\"(s)eries$\": \"$1eries\",\n\t\t\"([^aeiouy]|qu)ies$\": \"$1y\",\n\t\t\"([lr])ves$\": \"$1f\",\n\t\t\"(tive)s$\": \"$1\",\n\t\t\"(hive)s$\": \"$1\",\n\t\t\"(li|wi|kni)ves$\": \"$1fe\",\n\t\t\"(shea|loa|lea|thie)ves$\": \"$1f\",\n\t\t\"(^analy)ses$\": \"$1sis\",\n\t\t\"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$\": \"$1$2sis\",\n\t\t\"([ti])a$\": \"$1um\",\n\t\t\"(n)ews$\": \"$1ews\",\n\t\t\"(h|bl)ouses$\": \"$1ouse\",\n\t\t\"(corpse)s$\": \"$1\",\n\t\t\"(us)es$\": \"$1\",\n\t\ts$: \"\"\n\t};\n\tconst irregular = {\n\t\tmove: \"moves\",\n\t\tfoot: \"feet\",\n\t\tgoose: \"geese\",\n\t\tsex: \"sexes\",\n\t\tchild: \"children\",\n\t\tman: \"men\",\n\t\ttooth: \"teeth\",\n\t\tperson: \"people\"\n\t};\n\tif ([\n\t\t\"sheep\",\n\t\t\"fish\",\n\t\t\"deer\",\n\t\t\"moose\",\n\t\t\"series\",\n\t\t\"species\",\n\t\t\"money\",\n\t\t\"rice\",\n\t\t\"information\",\n\t\t\"equipment\",\n\t\t\"bison\",\n\t\t\"cod\",\n\t\t\"offspring\",\n\t\t\"pike\",\n\t\t\"salmon\",\n\t\t\"shrimp\",\n\t\t\"swine\",\n\t\t\"trout\",\n\t\t\"aircraft\",\n\t\t\"hovercraft\",\n\t\t\"spacecraft\",\n\t\t\"sugar\",\n\t\t\"tuna\",\n\t\t\"you\",\n\t\t\"wood\"\n\t].indexOf(word.toLowerCase()) >= 0) return word;\n\tfor (const w in irregular) {\n\t\tconst pattern = new RegExp(`${irregular[w]}$`, \"i\");\n\t\tif (pattern.test(word)) return word.replace(pattern, w);\n\t}\n\tfor (const reg in singulars) {\n\t\tconst pattern = new RegExp(reg, \"i\");\n\t\tif (pattern.test(word)) return word.replace(pattern, singulars[reg]);\n\t}\n\treturn word;\n}\n//#endregion\n//#region src/names.ts\n/**\n* Generates a foreign key column name from a given string, typically a collection slug or name.\n* It singularizes the name, converts it to snake_case and appends '_id'.\n*\n* Singularization runs *before* snake-casing so that acronyms survive: `toSnakeCase`\n* splits on every capital, which turned \"URLs\" into \"ur_ls\" and then \"ur_l_id\".\n*\n* @param name The base name to convert to a foreign key.\n* @returns A foreign key name in the format 'singular_name_id'.\n*\n* @example\n* // returns \"user_id\"\n* generateForeignKeyName(\"users\")\n*\n* @example\n* // returns \"category_id\"\n* generateForeignKeyName(\"categories\")\n*\n* @example\n* // returns \"product_id\"\n* generateForeignKeyName(\"Product\")\n*\n*/\nfunction generateForeignKeyName(name) {\n\treturn `${toSnakeCase(singularizeForKey(name))}_id`;\n}\n/**\n* `singular()` handles real English plurals, but its final catch-all rule strips\n* any trailing \"s\", which mangles words that only look plural. Guard the two\n* cases that produce a column name nobody would recognise:\n*\n* - a double \"s\" ending is never a plural marker (\"address\", \"class\", \"process\"),\n* so stripping it yields \"addres\";\n* - a name that singularizes to nothing (the literal \"s\") would yield \"_id\".\n*/\nfunction singularizeForKey(name) {\n\tif (/ss$/i.test(name)) return name;\n\tconst result = singular(name);\n\treturn result.length > 0 ? result : name;\n}\n/**\n* What `generateForeignKeyName` returned before it learned to singularize:\n* snake-case the name, then chop one trailing \"s\".\n*\n* This is here to be *detected*, never to be generated. A database provisioned\n* under the old rule carries `categorie_id`, `addresse_id`, `children_id` or\n* `ur_l_id` where the current rule expects `category_id`, `address_id`,\n* `child_id` and `url_id` — and the boot-time schema ensure is additive, so it\n* would create the new column empty beside the populated old one and leave the\n* relation reading nothing. No error, no missing table: the failure is silent,\n* which is the only reason this function still exists.\n*\n* `ensureCollectionSchema` calls it to recognise that shape and say so.\n* Returns the same string as `generateForeignKeyName` for every regular plural,\n* so a caller can compare the two and act only when they differ.\n*/\nfunction legacyForeignKeyName(name) {\n\tconst snake = toSnakeCase(name);\n\treturn `${snake.endsWith(\"s\") ? snake.slice(0, -1) : snake}_id`;\n}\n/**\n* Truncate an identifier to what Postgres will actually store.\n*\n* Postgres silently truncates identifiers at NAMEDATALEN-1 = 63 **bytes**, so a\n* name generated longer than that is not the name the database ends up holding.\n* Anything that later looks the object up by the name it generated then misses.\n*\n* Byte length, not string length: NAMEDATALEN is a byte bound, and a multi-byte\n* character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.\n*\n* `TextEncoder` rather than `Buffer`, which is not a matter of taste: `Buffer`\n* is a Node global, and this package is imported by browser-facing ones. It\n* typechecked only where `@types/node` happened to be in scope, so\n* `packages/codegen` — whose tsconfig is `lib: [\"ESNext\", \"dom\"]` — could not\n* compile the file at all, and both of its suites failed to run. `TextEncoder`\n* and `TextDecoder` are standard in both runtimes and need no ambient types.\n*/\nfunction toPostgresIdentifier(name) {\n\treturn truncateToBytes(name, 63);\n}\n/**\n* {@link toPostgresIdentifier} with the bound lifted to a parameter.\n*\n* Exists for names that end in something load-bearing. Truncating at 63 keeps\n* the *head* of a name and discards the tail, which is right for a descriptive\n* identifier and wrong for a hashed one: the hash is the part that makes it\n* unique, and it is at the end. A caller that appends a fingerprint truncates\n* the readable head to `63 - <tail>` itself and then appends, so the bound is\n* still 63 and the hash always survives.\n*\n* `contracts/derived-names.txt` records what the alternative costs — a foreign\n* key frozen as `..._corres`, its `_fkey` suffix truncated away, so a second\n* foreign key on that table would derive a byte-identical name.\n*\n* One truncation rule, in one function, so the two cannot drift.\n*/\nfunction truncateToBytes(name, maxBytes) {\n\tconst bytes = new TextEncoder().encode(name);\n\tif (bytes.byteLength <= maxBytes) return name;\n\treturn new TextDecoder(\"utf-8\").decode(bytes.subarray(0, maxBytes)).replace(/�+$/, \"\");\n}\n/**\n* The API name a database column is served under.\n*\n* The wire name of a field is its property key, and Rebase's property keys are\n* camelCase — `displayName`, `createdAt`, `photoURL`. Columns are snake_case,\n* because an unquoted Postgres identifier folds to lower case and a camelCase\n* column is therefore reachable only as `\"authorId\"` forever: in hand-written\n* SQL, in psql, in an RLS policy body, in a dump, and in every third-party tool\n* that ever touches the database. So the two conventions are both right, and\n* this is the function that crosses between them.\n*\n* It exists because two sources of field names never crossed: a foreign key\n* derived from a relation (`author_id`) and a column read back by introspection\n* (`user_id`) both landed on the wire under their column name, while every\n* hand-authored collection next to them used camelCase. One API, two\n* conventions, and no rule a caller could infer from outside — those names are\n* also the `where` and `orderBy` keys, so it was not a matter of taste.\n*\n* Rules, in the order they matter:\n*\n* - **A name with no separator is returned unchanged.** `photoURL` stays\n* `photoURL` and `id` stays `id`. Lower-casing a single token is what makes\n* a \"camelCase\" helper destructive — `camelCase(\"photoURL\")` is `photourl` —\n* and this function is applied to names that are *already* keys.\n* - **Each following segment keeps its own casing** apart from an upper-cased\n* first letter, so `photo_URL` → `photoURL` rather than `photoUrl`.\n* - **The result may still not be a JavaScript identifier.** `2fa_enabled`\n* becomes `2faEnabled`, which is a perfectly good object key and still needs\n* quoting where one is written into generated source.\n*\n* Not the inverse of {@link toSnakeCase}: `toSnakeCase` tokenises on case\n* boundaries and would turn `photoURL` into `photo_url`. Round-tripping is not\n* a property either function promises, which is why a column name that a\n* property maps explicitly is always read off `columnName` rather than derived.\n*/\nfunction toWireKey(columnName) {\n\tif (!columnName) return columnName;\n\tconst segments = columnName.split(/[-_ ]+/).filter(Boolean);\n\tif (segments.length <= 1) return columnName;\n\treturn segments.map((segment, index) => index === 0 ? segment.charAt(0).toLowerCase() + segment.slice(1) : segment.charAt(0).toUpperCase() + segment.slice(1)).join(\"\");\n}\n/**\n* The first candidate key not already used, or a numbered fallback.\n*\n* Introspection turns a set of column names into a set of object keys, and the\n* mapping is not injective: `user_id` and `userId` are two columns and one\n* {@link toWireKey}, and two foreign keys can strip to the same relation name.\n* A duplicate key in a generated object literal is a TypeScript error, so the\n* whole collection stops compiling — and a duplicate key in a `Record` built at\n* runtime is worse, because it silently drops a column instead.\n*\n* The numbered tail is what makes this total: a function that returns a key it\n* cannot guarantee is free has only moved the duplicate one line down.\n*\n* Structurally typed on `has` so a `Map` of emitted blocks and a `Set` of taken\n* names both satisfy it. Lives here, in the package both introspection\n* producers and the admin's table import can reach, because they must resolve a\n* collision the same way or one database describes itself three ways.\n*/\nfunction firstFreeKey(candidates, taken) {\n\tfor (const candidate of candidates) if (!taken.has(candidate)) return candidate;\n\tconst base = candidates[candidates.length - 1];\n\tfor (let suffix = 2;; suffix++) {\n\t\tconst candidate = `${base}_${suffix}`;\n\t\tif (!taken.has(candidate)) return candidate;\n\t}\n}\n//#endregion\n//#region src/fields.ts\nfunction isDefaultFieldConfigId(id) {\n\treturn [\n\t\t\"text_field\",\n\t\t\"multiline\",\n\t\t\"markdown\",\n\t\t\"url\",\n\t\t\"email\",\n\t\t\"switch\",\n\t\t\"select\",\n\t\t\"multi_select\",\n\t\t\"number_input\",\n\t\t\"number_select\",\n\t\t\"multi_number_select\",\n\t\t\"file_upload\",\n\t\t\"multi_file_upload\",\n\t\t\"reference\",\n\t\t\"multi_references\",\n\t\t\"relation\",\n\t\t\"date_time\",\n\t\t\"group\",\n\t\t\"key_value\",\n\t\t\"repeat\",\n\t\t\"custom_array\",\n\t\t\"block\"\n\t].includes(id);\n}\n//#endregion\nexport { camelCase, clone, deepClone, defaultDateFormat, firstFreeKey, flattenObject, formatRelativeTime, generateForeignKeyName, getArrayValuesCount, getHashValue, getIn, getPolicyNameHash, getPolicyNamesForRule, getPolicyNamesForRules, getPolicyOperations, getValueInPath, getWebStorage, hashString, hydrateRegExp, isArrayValue, isDefaultFieldConfigId, isEmptyArray, isEmptyObject, isFunction, isInteger, isNaN, isNearMiss, isObject, isPlainObject, isPrototypePollutingKey, isRecordValue, isValidRegExp, legacyForeignKeyName, mergeDeep, pathTraversesPrototype, pick, plural, prettifyIdentifier, randomColor, randomString, readStoredJson, readStoredString, removeFunctions, removeInPath, removeNulls, removePropsIfExisting, removeUndefined, serializeRegExp, setIn, sha1Hex, singular, slugify, suggestNearMiss, toArray, toKebabCase, toPostgresIdentifier, toSnakeCase, toWireKey, truncateToBytes, unslugify, writeStoredJson, writeStoredString };\n\n//# sourceMappingURL=index.es.js.map","import {\n DataType,\n Entity,\n EntityReference,\n EntityRelation,\n EntityStatus,\n EntityValues,\n Properties,\n Property\n} from \"@rebasepro/types\";\nimport { DEFAULT_ONE_OF_TYPE, DEFAULT_ONE_OF_VALUE } from \"./common\";\nimport { mergeDeep } from \"@rebasepro/utils\";\n\nexport function isPropertyBuilder(property?: Property) {\n return typeof property?.dynamicProps === \"function\";\n}\n\n/**\n * What a form opens with: a value for every property it can write.\n *\n * `excludeFromApi` columns are left out, and that is the whole of the rule —\n * they are not part of the API surface in either direction, so there is nothing\n * for a form to open showing and nothing it may send back. Including them was\n * not cosmetic: the baseline is what gets submitted, so a new record carried\n * `passwordHash: null` and `emailVerificationToken: null` into the create, and\n * the server refused the whole write with \"these columns are the server's to\n * set\" — the users collection could not be added to from the panel at all. The\n * fields were invisible on screen (`admin.disabled.hidden`), which is what made\n * the error read as being about the roles the operator *had* just edited.\n *\n * Server-side defaulting does not come through here: `applyDefaultValuesOnCreate`\n * asks each property for its own default, so an excluded column with a declared\n * `defaultValue` is still filled in on an in-process write.\n */\nexport function getDefaultValuesFor<M extends Record<string, unknown>>(properties: Properties): Partial<EntityValues<M>> {\n if (!properties) return {};\n return Object.entries(properties)\n .map(([key, property]) => {\n if (!property) return {};\n if ((property as Property).excludeFromApi) return {};\n const value = getDefaultValueFor(property);\n return value === undefined ? {} : { [key]: value };\n })\n .reduce((a, b) => ({ ...a,\n...b }), {}) as EntityValues<M>;\n}\n\nexport function getDefaultValueFor(property?: Property): unknown {\n if (!property) return undefined;\n if (isPropertyBuilder(property)) return undefined;\n // `defaultValue !== undefined`, not truthiness. The test used to be\n // `property.defaultValue || property.defaultValue === null`, which special-\n // cased exactly one falsy value and dropped the rest: `defaultValue: 0`\n // fell through to the per-type default and became `null`, `defaultValue: \"\"`\n // became `null`, and `defaultValue: false` survived only by coincidence\n // (the per-type default for a boolean is also `false`). A default of zero\n // is the most ordinary default a number column has.\n if (property.defaultValue !== undefined) {\n return property.defaultValue;\n } else if (property.type === \"map\" && property.properties) {\n const defaultValuesFor = getDefaultValuesFor(property.properties as Properties);\n if (Object.keys(defaultValuesFor).length === 0) return undefined;\n return defaultValuesFor;\n } else {\n return getDefaultValueFortype(property.type);\n }\n}\n\nexport function getDefaultValueFortype(type: DataType): unknown {\n if (type === \"string\") {\n return null;\n } else if (type === \"number\") {\n return null;\n } else if (type === \"boolean\") {\n return false;\n } else if (type === \"date\") {\n return null;\n } else if (type === \"array\") {\n return [];\n } else if (type === \"map\") {\n return {};\n } else if (type === \"vector\") {\n return null;\n } else if (type === \"binary\") {\n return null;\n } else {\n return null;\n }\n}\n\n/**\n * Update the automatic values in a entity before save\n * @group Driver\n */\nexport function updateDateAutoValues<M extends Record<string, unknown>>({\n inputValues,\n properties,\n status,\n timestampNowValue\n}:\n {\n inputValues: Partial<EntityValues<M>>,\n properties: Properties,\n status: EntityStatus,\n timestampNowValue: unknown\n }): EntityValues<M> {\n return traverseValuesProperties(\n inputValues,\n properties,\n (inputValue, property) => {\n if (property.type === \"date\") {\n if (status === \"existing\" && property.autoValue === \"on_update\") {\n return timestampNowValue;\n } else if ((status === \"new\" || status === \"copy\") &&\n (property.autoValue === \"on_update\" || property.autoValue === \"on_create\")) {\n return timestampNowValue;\n } else {\n return inputValue;\n }\n } else {\n return inputValue;\n }\n }\n ) ?? {} as M;\n}\n\n/**\n * Stamp the acting user's uid into the `user_on_create` / `user_on_update`\n * columns a collection declares.\n *\n * A deliberate sibling of {@link updateDateAutoValues} rather than another\n * branch inside it. The two share a shape and nothing else: one takes an\n * instant the server generates and the other takes an identity the request\n * carries, so overloading the timestamp function would have meant threading a\n * second, unrelated argument through every one of its callers and letting a\n * `date` property and a `string` property compete for the same `autoValue`\n * union. Called side by side in the driver.\n *\n * The stamped value overwrites whatever arrived in the body. A caller who can\n * set `createdBy` is a caller who can attribute their write to somebody else,\n * which is the one thing an audit column must not allow.\n *\n * `uid` is `undefined` for an anonymous request, a service token or an\n * in-process write; the column is set to an explicit `null` there. Explicit\n * matters on an update: leaving the key absent would keep whatever uid the\n * column already held, so an anonymous edit would be recorded as the previous\n * editor's. Refusing that write outright is `required`'s job, not this\n * function's — see `assertWriteValuesValid`.\n *\n * Top-level properties only, deliberately, unlike {@link updateDateAutoValues}.\n * `traverseValuesProperties` cannot express \"set this key to null\" — a `null`\n * from its operation means \"leave the key out\" — and an audit column nested\n * inside a `map` is not a column at all, so there is nothing down there to\n * stamp.\n *\n * @group Driver\n */\nexport function updateUserAutoValues<M extends Record<string, unknown>>({\n inputValues,\n properties,\n status,\n uid\n}:\n {\n inputValues: Partial<EntityValues<M>>,\n properties: Properties,\n status: EntityStatus,\n uid: string | undefined\n }): EntityValues<M> {\n const result = { ...(inputValues ?? {}) } as Record<string, unknown>;\n for (const [key, property] of Object.entries(properties ?? {})) {\n const prop = property as (Property & { autoValue?: string }) | undefined;\n if (!prop || prop.type !== \"string\") continue;\n const autoValue = prop.autoValue;\n if (autoValue !== \"user_on_create\" && autoValue !== \"user_on_update\") continue;\n // `user_on_create` says nothing about an update: the column holds the\n // creator's uid and this write is not rewriting it.\n if (status === \"existing\" && autoValue === \"user_on_create\") continue;\n // A copy is a new row and gets a new author, exactly as it gets a new\n // `created_on`.\n result[key] = uid ?? null;\n }\n return result as EntityValues<M>;\n}\n\n/**\n * Fill in the `defaultValue`s a create left unset.\n *\n * `defaultValue` was read by exactly one thing: the Studio's form, which uses it\n * to prefill inputs. Every other way into the same collection — the REST create,\n * the SDK, the socket, an import — stored whatever arrived and nothing where the\n * key was absent. So `active: { type: \"boolean\", defaultValue: true }` produced\n * rows with `active` unset through the API and `true` through the panel, from\n * one declaration that reads like a promise about the data.\n *\n * Only genuinely absent keys are filled. An explicit `null` is a caller saying\n * \"no value\", which is a different statement from not mentioning the field, and\n * overwriting it would make the default impossible to opt out of.\n *\n * `getDefaultValuesFor` also invents a per-type default for properties with no\n * `defaultValue` at all (`false` for a boolean, `[]` for an array, `null` for\n * the rest) — right for a form, which must render *something* in every input,\n * and wrong here, where an absent key must stay absent so the column's own\n * DEFAULT applies. Only declared defaults are taken.\n *\n * @param values the caller's payload\n * @param properties the collection's declared properties\n * @group Driver\n */\nexport function applyDefaultValuesOnCreate<M extends Record<string, unknown>>(\n values: Partial<EntityValues<M>> | undefined,\n properties: Properties\n): Partial<EntityValues<M>> {\n if (!properties) return values ?? {};\n const result = { ...(values ?? {}) } as Record<string, unknown>;\n\n for (const [key, property] of Object.entries(properties)) {\n if (!property) continue;\n const declared = declaresDefault(property as Property);\n if (!declared) continue;\n // Asked of the property, not read out of `getDefaultValuesFor`: that\n // one answers for a *form*, and leaves out the columns the API excludes.\n // A server-owned column with a declared default is still defaulted here.\n const defaultValue = getDefaultValueFor(property as Property);\n if (result[key] !== undefined) {\n // A map whose own sub-properties carry defaults is filled in\n // field by field, so `{ notify: false }` keeps `notify` and still\n // gains the siblings it did not mention.\n if ((property as Property).type === \"map\" &&\n (property as Property & { defaultValue?: unknown }).defaultValue === undefined &&\n isPlainObject(result[key])) {\n result[key] = {\n ...(defaultValue as Record<string, unknown> ?? {}),\n ...(result[key] as Record<string, unknown>)\n };\n }\n continue;\n }\n if (defaultValue !== undefined) result[key] = defaultValue;\n }\n return result as Partial<EntityValues<M>>;\n}\n\n/** Does this property, or something nested under it, state a `defaultValue`? */\nfunction declaresDefault(property: Property): boolean {\n if (isPropertyBuilder(property)) return false;\n if (property.defaultValue !== undefined) return true;\n if (property.type === \"map\" && property.properties) {\n return Object.values(property.properties as Properties)\n .some(child => child && declaresDefault(child as Property));\n }\n return false;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Add missing required fields, expected in the collection, to the values of a entity\n * @param values\n * @param properties\n * @group Driver\n */\nexport function sanitizeData<M extends Record<string, unknown>>\n (\n values: EntityValues<M>,\n properties: Properties\n ) {\n const result = values as Record<string, unknown>;\n Object.entries(properties)\n .forEach(([key, property]) => {\n if (values && values[key] !== undefined) result[key] = values[key];\n else if ((property as Property).validation?.required) result[key] = null;\n });\n return result;\n}\n\nexport function getReferenceFrom<M extends Record<string, unknown>>(entity: Entity<M>): EntityReference {\n if (typeof entity.id !== \"string\")\n throw new Error(\"Only string IDs are supported in references\");\n return new EntityReference({\n id: entity.id,\n path: entity.path,\n driver: entity.driver,\n databaseId: entity.databaseId\n });\n}\n\nexport function getRelationFrom<M extends Record<string, unknown>>(entity: Entity<M>): EntityRelation {\n return new EntityRelation(entity.id, entity.path, entity as unknown as Record<string, unknown>);\n}\n\n/**\n * Normalize a value into a proper EntityRelation instance.\n * Handles EntityRelation class instances, and plain objects\n * with `__type === \"relation\"` or an `isEntityRelation()` method.\n *\n * When `propertyType` is `\"relation\"`, also accepts plain objects that\n * have `id` and `path` fields — these are relation-shaped objects from\n * edge cases in the data pipeline (REST fallback, stale cache, custom data source).\n *\n * When `targetPath` is given, also accepts a bare id. A relation column is a\n * foreign key, and the REST layer returns it as the scalar it is; only some\n * fetch paths hydrate it into an object. Which form a caller sees therefore\n * depends on how the row was loaded, and a caller that only accepted objects\n * reported half of its own data as a type error. The declared target is the\n * missing half: with it, an id is a relation that has not been fetched yet.\n *\n * Returns null if the value cannot be coerced.\n */\nexport function normalizeToEntityRelation(value: unknown, propertyType?: string, targetPath?: string): EntityRelation | null {\n if (value instanceof EntityRelation) return value;\n\n if (targetPath && (typeof value === \"string\" || typeof value === \"number\")) {\n // An empty string is an unset foreign key, not row \"\".\n if (value === \"\") return null;\n return new EntityRelation(value, targetPath);\n }\n\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\n const obj = value as Record<string, unknown>;\n const isRelationLike =\n obj.__type === \"relation\" ||\n obj.__type === \"reference\" ||\n (typeof obj.isEntityRelation === \"function\" && (obj.isEntityRelation as () => boolean)()) ||\n (typeof obj.isEntityReference === \"function\" && (obj.isEntityReference as () => boolean)()) ||\n (propertyType === \"relation\" && typeof obj.id !== \"undefined\" && typeof obj.path === \"string\");\n\n if (!isRelationLike) return null;\n\n return new EntityRelation(\n obj.id as string | number,\n obj.path as string,\n obj.data as Record<string, unknown> | undefined\n );\n}\n\nexport function traverseValuesProperties<M extends Record<string, unknown>>(\n inputValues: Partial<EntityValues<M>>,\n properties: Properties,\n operation: (value: unknown, property: Property) => unknown\n): EntityValues<M> | undefined {\n // Handle null/undefined inputValues - use empty object as base for mergeDeep\n const safeInputValues = inputValues ?? {};\n\n const updatedValues = Object.entries(properties)\n .map(([key, property]) => {\n const inputValue = safeInputValues && (safeInputValues)[key];\n const updatedValue = traverseValueProperty(inputValue, property as Property, operation);\n if (updatedValue === null) return null;\n if (updatedValue === undefined) return undefined;\n return ({ [key]: updatedValue });\n })\n .reduce((a, b) => ({ ...a,\n...b }), {}) as EntityValues<M>;\n // Use mergeDeep to preserve class instances like EntityReference, GeoPoint\n const result = mergeDeep(safeInputValues, updatedValues);\n if (!result || Object.keys(result).length === 0) return undefined;\n return result;\n}\n\nexport function traverseValueProperty(inputValue: unknown,\n property: Property,\n operation: (value: unknown, property: Property) => unknown): unknown {\n\n let value;\n if (property.type === \"map\" && property.properties) {\n value = traverseValuesProperties(inputValue as Partial<Record<string, unknown>>, property.properties, operation);\n } else if (property.type === \"array\") {\n const of = property.of;\n if (of && Array.isArray(inputValue) && !Array.isArray(of)) {\n value = inputValue.map((e) => traverseValueProperty(e, of, operation));\n } else if (of && Array.isArray(inputValue) && Array.isArray(of)) {\n value = inputValue.map((e, i) => {\n if (i < of.length)\n return traverseValueProperty(e, of[i], operation);\n return null\n }).filter(Boolean);\n } else if (property.oneOf && Array.isArray(inputValue)) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const valueField = property.oneOf?.valueField ?? DEFAULT_ONE_OF_VALUE;\n value = inputValue.map((e) => {\n if (e === null) return null;\n if (typeof e !== \"object\") return e;\n const rec = e as Record<string, unknown>;\n const type = rec[typeField] as string;\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return e;\n return {\n [typeField]: type,\n [valueField]: traverseValueProperty(rec[valueField], childProperty, operation)\n };\n });\n } else {\n value = inputValue;\n }\n } else {\n value = operation(inputValue, property);\n }\n\n return value;\n}\n\n/**\n * Relation reference types used throughout the server layer.\n * These replace the 50+ manual `{ id, path, __type: \"relation\" }` constructions.\n */\nexport interface RelationRef {\n readonly id: string | number;\n readonly path: string;\n readonly __type: \"relation\";\n}\n\nexport interface RelationRefWithData extends RelationRef {\n readonly data: Entity;\n}\n\n/**\n * Create a lightweight relation stub for admin views.\n * Replaces inline `{ id, path, __type: \"relation\" }` object literals.\n */\nexport function createRelationRef(id: string | number, path: string): RelationRef {\n return { id,\npath,\n__type: \"relation\" };\n}\n\n/**\n * Create a hydrated relation reference that includes the full entity data.\n * Used when entity data has been pre-fetched (e.g., via batch loading or JOINs).\n */\nexport function createRelationRefWithData(id: string | number, path: string, data: Entity): RelationRefWithData {\n return { id,\npath,\n__type: \"relation\",\ndata };\n}\n","/**\n * Row identity: the address of a row, and how to derive it.\n *\n * Postgres has no `id`. A row is identified by its primary key — one or more\n * columns, with any names and any types. `id` is something we synthesize on top\n * of that: a single string token, because the admin needs *one* value it can put\n * in a URL (`/products/1:::2`), use as a cache key, and hang a relation ref off.\n *\n * That token is an address, not data. It is derived from the row's columns and\n * never stored in them — a row is exactly its columns, with their real types.\n * Writing the address back into the row is what used to rename primary keys\n * (`sku` → `id`) and restringify them (`42` → `\"42\"`) on the way out.\n *\n * These live in `common` because both sides need them and must agree exactly:\n * the driver parses an incoming address back into key columns, and the admin\n * derives the address from a row it was served.\n */\n\n/**\n * A primary-key column: its name, the type it round-trips as, and whether it is\n * a UUID (which is a string despite sometimes being described as an id \"number\").\n */\nexport interface PrimaryKeyInfo {\n fieldName: string;\n type: \"string\" | \"number\";\n isUUID?: boolean;\n}\n\n/** Separator between the parts of a composite address. */\nexport const COMPOSITE_ID_SEPARATOR = \":::\";\n\n/** The eight-four-four-four-twelve shape of a UUID, any version. */\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Whether one address part can be a value of the column it addresses. */\nfunction partIsAddressable(part: string | number, pk: PrimaryKeyInfo): boolean {\n if (pk.isUUID) return UUID_PATTERN.test(String(part));\n if (pk.type === \"number\") {\n return typeof part === \"number\"\n ? Number.isFinite(part)\n : !isNaN(parseInt(String(part), 10));\n }\n return true;\n}\n\n/**\n * Whether an address could name a row at all, before asking the database.\n *\n * A `uuid` column cannot hold `\"new\"`, and an `integer` column cannot hold\n * `\"abc\"` — so the answer to \"which row is this\" is \"none\", and that is a 404,\n * not a failure. Postgres cannot say so politely: the comparison never runs, it\n * raises `22P02` and aborts the enclosing transaction, after which every\n * further statement returns the far less helpful `25P02`.\n *\n * `isUUID` must come from the column, not from `isId: \"uuid\"` in a config: the\n * config is a claim about a key, and a `text` column that holds ids of some\n * other shape is a working app this must not start rejecting.\n */\nexport function isAddressableId(idValue: string | number, primaryKeys: PrimaryKeyInfo[]): boolean {\n if (primaryKeys.length === 0) return false;\n if (primaryKeys.length === 1) return partIsAddressable(idValue, primaryKeys[0]);\n\n const parts = String(idValue).split(COMPOSITE_ID_SEPARATOR);\n if (parts.length !== primaryKeys.length) return false;\n return parts.every((part, i) => partIsAddressable(part, primaryKeys[i]));\n}\n\n/**\n * Derive a row's address from its key columns.\n *\n * Single key → the value as a string. Composite → each part joined by\n * {@link COMPOSITE_ID_SEPARATOR}, in primary-key order, which is what\n * {@link parseIdValues} expects to invert.\n */\nexport function buildCompositeId(values: Record<string, unknown>, primaryKeys: PrimaryKeyInfo[]): string {\n if (primaryKeys.length === 0) {\n return \"\";\n }\n if (primaryKeys.length === 1) {\n return String(values[primaryKeys[0].fieldName] ?? \"\");\n }\n return primaryKeys.map(pk => String(values[pk.fieldName] ?? \"\")).join(COMPOSITE_ID_SEPARATOR);\n}\n\n/**\n * Invert {@link buildCompositeId}: turn an address back into key columns, each\n * coerced to the type its column actually round-trips as.\n *\n * This is the boundary where a URL segment becomes a query parameter, so a\n * malformed address must throw rather than silently produce a query that\n * matches the wrong row (or none).\n */\nexport function parseIdValues(idValue: string | number, primaryKeys: PrimaryKeyInfo[]): Record<string, string | number> {\n const result: Record<string, string | number> = {};\n\n if (primaryKeys.length === 0) {\n return result;\n }\n\n if (primaryKeys.length === 1) {\n const pk = primaryKeys[0];\n if (pk.type === \"number\" && !pk.isUUID) {\n const parsed = typeof idValue === \"number\" ? idValue : parseInt(String(idValue), 10);\n if (isNaN(parsed)) {\n throw new Error(`Invalid numeric ID: ${idValue}`);\n }\n result[pk.fieldName] = parsed;\n } else {\n result[pk.fieldName] = String(idValue);\n }\n return result;\n }\n\n // Composite key\n const parts = String(idValue).split(COMPOSITE_ID_SEPARATOR);\n if (parts.length !== primaryKeys.length) {\n throw new Error(`Composite ID parts mismatch. Expected ${primaryKeys.length}, got ${parts.length} for ID: ${idValue}`);\n }\n\n for (let i = 0; i < primaryKeys.length; i++) {\n const pk = primaryKeys[i];\n const val = parts[i];\n if (pk.type === \"number\" && !pk.isUUID) {\n const parsed = parseInt(val, 10);\n if (isNaN(parsed)) {\n throw new Error(`Invalid numeric ID component: ${val}`);\n }\n result[pk.fieldName] = parsed;\n } else {\n result[pk.fieldName] = val;\n }\n }\n\n return result;\n}\n\n/**\n * The primary keys of a collection, as declared by its properties.\n *\n * This is the only tier both sides can read, because it is the only one written\n * in the config: the postgres driver can also infer keys from the Drizzle\n * schema, which the browser never sees and is never sent — the admin compiles\n * the collection files into its own bundle rather than being served them. A key\n * that lives only in the Drizzle schema is therefore invisible here, and the\n * server says so at boot (`warnOnKeysTheAdminCannotResolve`) naming the `isId`\n * to add.\n *\n * Returns an empty array when a collection declares none, which callers must\n * treat as \"not addressable\" rather than defaulting to `id`: guessing a key\n * that is not the real one produces confidently wrong addresses.\n */\nexport function getDeclaredPrimaryKeys(collection: {\n properties?: Record<string, unknown>;\n}): PrimaryKeyInfo[] {\n const properties = collection.properties;\n if (!properties) return [];\n\n const keys: PrimaryKeyInfo[] = [];\n for (const [fieldName, propRaw] of Object.entries(properties)) {\n const prop = propRaw as { type?: string; isId?: unknown } | undefined;\n if (!prop || typeof prop !== \"object\") continue;\n if (!(\"isId\" in prop) || !prop.isId) continue;\n keys.push({\n fieldName,\n type: prop.type === \"number\" ? \"number\" : \"string\",\n isUUID: prop.isId === \"uuid\"\n });\n }\n return keys;\n}\n\n/**\n * The keys to address a collection's rows with, resolved the way the driver\n * resolves them — minus the tier the browser cannot reach.\n *\n * The postgres driver tries, in order: properties marked `isId`; the primary\n * keys of the Drizzle schema; and finally a column literally named `id`. Only\n * the first and last are visible in a `CollectionConfig`, which is what both\n * sides share.\n *\n * So the two agree except on a collection that declares no `isId` and whose key\n * is known only to Drizzle. There, the driver reads the real key, and this\n * either resolves nothing (reported to the console by the caller) or — if the\n * table happens to have an unrelated `id` property — resolves `id`, which is\n * the wrong key and cannot be detected from here: the addresses look right and\n * route wrong. Only the config can settle it, so the server names both cases\n * at boot (`warnOnKeysTheAdminCannotResolve`) with the `isId` to add.\n */\nexport function resolvePrimaryKeys(collection: {\n properties?: Record<string, unknown>;\n}): PrimaryKeyInfo[] {\n const declared = getDeclaredPrimaryKeys(collection);\n if (declared.length > 0) return declared;\n\n const idProp = collection.properties?.id as { type?: string } | undefined;\n if (idProp && typeof idProp === \"object\") {\n return [{ fieldName: \"id\",\ntype: idProp.type === \"number\" ? \"number\" : \"string\" }];\n }\n\n return [];\n}\n","import { EnumValueConfig, EnumValues } from \"@rebasepro/types\";\n\nexport function enumToObjectEntries(enumValues: EnumValues): EnumValueConfig[] {\n if (Array.isArray(enumValues)) {\n return enumValues;\n } else {\n return Object.entries(enumValues).map(([id, value]) => {\n if (typeof value === \"string\") {\n return {\n id,\n label: value\n }\n } else {\n return {\n ...value,\n id\n }\n }\n });\n }\n}\n\nexport function getLabelOrConfigFrom(enumValues: EnumValueConfig[], key?: string | number): EnumValueConfig | undefined {\n if (key === null || key === undefined) return undefined;\n return enumValues.find((entry) => String(entry.id) === String(key));\n}\n","import {\n CollectionConfig,\n Relation,\n ResolvedRelation\n} from \"@rebasepro/types\";\nimport { generateForeignKeyName, toSnakeCase } from \"@rebasepro/utils\";\n\nimport { getTableName } from \"./relations\";\n\n/**\n * Fill in a relation's defaults.\n *\n * This replaces `sanitizeRelation`, which had to work out *which kind of link\n * you meant* from whichever optional fields happened to be set — 194 lines of\n * it, including a pass that inspected the target collection's own relations to\n * decide whether a `many`/`inverse` pair was a one-to-many or the far side of a\n * many-to-many, wrapped in a `try/catch` that fell through to the wrong answer\n * when it could not tell. Two consumers running that logic at different moments\n * could reach different conclusions about the same relation.\n *\n * With the kind declared there is nothing to work out. What remains is\n * defaulting — a table name, a column name — which is deterministic, depends\n * only on the relation and its two endpoints, and cannot fail. That is why this\n * function returns rather than throws, and why it needs no cache to be\n * consistent.\n */\nexport function resolveRelation(\n relation: Relation,\n sourceCollection: CollectionConfig,\n propertyKey?: string\n): ResolvedRelation {\n const target = relation.target;\n if (typeof target !== \"function\") {\n throw new Error(\n `Relation${relation.relationName ? ` '${relation.relationName}'` : \"\"} on ` +\n `'${sourceCollection.slug}' has no \\`target\\`. Give it a thunk: \\`target: () => otherCollection\\`.`\n );\n }\n\n const targetCollection = callTarget(relation, sourceCollection, propertyKey, target);\n\n // The name is the address: the `include` key, the admin tab, and the\n // segment of a nested path. Declared name wins, then the declaring\n // property's key, then the target's slug.\n const relationName = relation.relationName ?? propertyKey ?? toSnakeCase(targetCollection.slug);\n\n const shared: Pick<ResolvedRelation, \"relationName\" | \"target\" | \"targetSlug\" | \"onUpdate\" | \"onDelete\" | \"overrides\"> = {\n relationName,\n // Normalised, not the thunk as written. Resolution reads the target once\n // and every later consumer calls it again — the driver building a join,\n // the DDL and policy generators, the admin's relation fields — so\n // handing back the raw thunk would give all of them the module namespace\n // `callTarget` just looked past, and the fix would hold only for the\n // fields resolution happens to read here. Still lazy: same call at the\n // same moment, one unwrap on the way out.\n target: () => unwrapModuleNamespace(target()) as CollectionConfig,\n targetSlug: targetCollection.slug,\n onUpdate: relation.onUpdate,\n onDelete: relation.onDelete,\n overrides: relation.overrides\n // No `validation`. Whether the link is required is a fact about the\n // *property*, and copying it onto the resolved relation gave the\n // question two answers that were free to disagree. Ask\n // `isRelationRequired(collection, relation)`, which reads the one.\n };\n\n const sourceName = toSnakeCase(sourceCollection.slug ?? sourceCollection.name);\n\n switch (relation.kind) {\n case \"belongsTo\":\n return {\n ...shared,\n kind: \"belongsTo\",\n cardinality: \"one\",\n writable: true,\n shared: false,\n localKey: relation.localKey ?? generateForeignKeyName(relationName)\n };\n\n case \"hasOne\":\n return {\n ...shared,\n kind: \"hasOne\",\n cardinality: \"one\",\n writable: true,\n shared: false,\n foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName),\n sourceKey: relation.sourceKey\n };\n\n case \"hasMany\":\n return {\n ...shared,\n kind: \"hasMany\",\n cardinality: \"many\",\n writable: true,\n shared: false,\n foreignKeyOnTarget: relation.foreignKeyOnTarget ?? generateForeignKeyName(sourceName),\n // Not defaulted: the source's primary key needs the driver's\n // schema to resolve, which resolution does not have. `undefined`\n // means \"the primary key\" — see `ResolvedHasMany.sourceKey`.\n sourceKey: relation.sourceKey\n };\n\n case \"manyToMany\": {\n const sourceTable = getTableName(sourceCollection);\n const targetTable = getTableName(targetCollection);\n return {\n ...shared,\n kind: \"manyToMany\",\n cardinality: \"many\",\n writable: true,\n shared: true,\n through: {\n // Sorted so both sides of the same link derive the same\n // table without having to agree in advance.\n table: relation.through?.table ?? [sourceTable, targetTable].sort().join(\"_\"),\n sourceColumn: relation.through?.sourceColumn ?? generateForeignKeyName(sourceName),\n targetColumn: relation.through?.targetColumn ?? generateForeignKeyName(relationName),\n // `{}` rather than `undefined`, for the reason every other\n // field here is filled in: a consumer reads one shape and\n // does not have to decide what an absent payload means.\n properties: relation.through?.properties ?? {}\n }\n };\n }\n\n case \"via\":\n return {\n ...shared,\n kind: \"via\",\n cardinality: relation.cardinality,\n writable: false,\n // A join chain reaches rows that other parents reach too, and\n // Rebase does not know which hop, if any, is a link it owns.\n shared: true,\n joinPath: relation.joinPath\n };\n\n default: {\n // Exhaustive: a new kind is a compile error here, not a silent\n // fall-through to whatever shape happened to match first.\n const exhaustive: never = relation;\n throw new Error(`Unknown relation kind: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n\n/** How this relation is addressed in an error message, before it has a resolved name. */\nfunction describe(relation: Relation, sourceCollection: CollectionConfig, propertyKey?: string): string {\n const name = relation.relationName ?? propertyKey;\n return `Relation${name ? ` '${name}'` : \"\"} on '${sourceCollection.slug}'`;\n}\n\n/**\n * A module namespace, unwrapped to the collection it exports.\n *\n * A cycle transpiled to CommonJS does not hand the importing module the\n * *default export* — it hands it the module object, `{ __esModule: true,\n * default: … }`, captured before the exporting module finished evaluating. The\n * `default` slot fills in later, so by the time a lazy `target` thunk runs the\n * collection is sitting right there, one level down. Returning the namespace is\n * never a thing a thunk means to do, and there is exactly one reading of it.\n *\n * Only unwrapped when the inner value is itself a collection: a `default` that\n * is not one is a genuinely wrong thunk, and it should reach the error below\n * rather than be quietly swapped in.\n */\nfunction unwrapModuleNamespace(value: unknown): unknown {\n if (!value || typeof value !== \"object\") return value;\n if ((value as { slug?: unknown }).slug) return value;\n const inner = (value as { default?: unknown }).default;\n return inner && typeof inner === \"object\" && (inner as { slug?: unknown }).slug ? inner : value;\n}\n\n/**\n * Call the `target` thunk, and translate the ways an import cycle breaks it into\n * an error that names the cause — or, where the value is recoverable, into the\n * collection the thunk meant.\n *\n * The thunk exists to defer the reference until every module has finished\n * evaluating, and for a cycle that closes at import time it does. Two cycles\n * leave the binding permanently unusable:\n *\n * - **ESM/TDZ.** `const` and `class` bindings in a not-yet-evaluated module are\n * in the temporal dead zone, so reading one throws `ReferenceError: x is not\n * defined`. The stack points at the thunk — a one-line arrow function that is\n * obviously fine — and says nothing about the cycle that made it throw.\n * - **CJS interop, unresolved.** The half-initialised module object has no\n * `default` yet, the import resolves to `undefined`, and the thunk returns it\n * without complaint. That one used to surface here as \"did not resolve to a\n * collection\", which is true and unhelpful.\n *\n * Both mean the same thing, and the fix for both is the same: break the cycle,\n * or move the relation into the collection that does not close it.\n *\n * A third shape is *not* an error, and used to be reported as one. A loader that\n * transpiles ESM to CJS — jiti, which is what `rebase generate-sdk` and\n * `rebase build` load collections with — gives the module entered second in a\n * cycle a namespace object rather than the default export, and never replaces it\n * with a live binding. The thunk then returns `{ __esModule: true, default: … }`\n * holding the fully-initialised collection. Native ESM resolves the same thunk\n * to the collection directly, so this was a loader artefact reported as an\n * authoring mistake, and the advice it gave — make the target a lazy thunk — was\n * already satisfied by the code it was rejecting. Bidirectional relations make\n * these cycles unavoidable, and the lazy thunk is this framework's own answer to\n * them, so {@link unwrapModuleNamespace} takes the collection and moves on.\n */\nfunction callTarget(\n relation: Relation,\n sourceCollection: CollectionConfig,\n propertyKey: string | undefined,\n target: Relation[\"target\"]\n): ReturnType<Relation[\"target\"]> {\n let targetCollection: ReturnType<Relation[\"target\"]> | undefined;\n try {\n targetCollection = unwrapModuleNamespace(target()) as ReturnType<Relation[\"target\"]>;\n } catch (error) {\n // A ReferenceError from inside the thunk is a binding that was never\n // initialised — nothing else in a one-expression arrow can raise one.\n if (error instanceof ReferenceError) {\n throw new Error(\n `${describe(relation, sourceCollection, propertyKey)} targets a collection that is not ` +\n `initialized yet — almost always an import cycle between the two collection files. ` +\n `Break the cycle (move the shared piece into a third module, or import the target ` +\n `lazily) so the target's module finishes evaluating before the registry is built.`,\n { cause: error }\n );\n }\n throw error;\n }\n\n if (!targetCollection?.slug) {\n throw new Error(\n `${describe(relation, sourceCollection, propertyKey)} has a \\`target\\` that resolved to ` +\n `${targetCollection === undefined ? \"`undefined`\" : \"something that is not a collection\"}. ` +\n (targetCollection === undefined\n ? \"Under CommonJS interop an import cycle resolves the default import to `undefined`, \" +\n \"so check whether this collection and its target import each other. Otherwise the thunk \" +\n \"is returning the wrong value — it must return the collection itself, not a promise or a module.\"\n : typeof (targetCollection as { then?: unknown }).then === \"function\"\n ? \"The thunk returned a promise — `target: () => import(\\\"./other\\\")` is asynchronous. \" +\n \"Import the collection at the top of the file and return the binding: \" +\n \"`target: () => otherCollection`.\"\n : \"The thunk must return a collection config with a `slug`.\")\n );\n }\n\n return targetCollection;\n}\n","import { CollectionConfig, isRelationalCollectionConfig, Property, ResolvedRelation, RelationProperty } from \"@rebasepro/types\";\nimport { toSnakeCase, toWireKey } from \"@rebasepro/utils\";\n\nimport { resolveRelation } from \"./resolve-relation\";\n\n/**\n * Whether the target rows are shared with other parents — a many-to-many, or a\n * multi-hop `via` chain.\n *\n * Decides what a write \"through\" the relation may touch: a shared target\n * belongs to every parent that links it, so the parent owns the *link* and not\n * the row. The backend enforces that (an unlink rather than a delete) and the\n * admin renders it (remove-from-parent rather than delete).\n *\n * Now a field on the resolved relation rather than a re-derivation, so both\n * sides read the same answer instead of each computing one.\n */\nexport function isJunctionBackedRelation(relation: ResolvedRelation): boolean {\n return relation.shared;\n}\n\n/** WeakMap cache — same collection instance always yields the same relation map. */\nconst _resolvedRelationsCache = new WeakMap<CollectionConfig, Record<string, ResolvedRelation>>();\n\n/**\n * Every relation a collection declares, keyed by the name it is addressed by.\n *\n * A relation reaches the map from either of two places — the collection's\n * `relations` array, or a `relation` property that declares one inline — and is\n * keyed by its resolved `relationName`, which is what a nested path segment,\n * an `include` key and an admin tab all match against.\n *\n * Resolution no longer swallows failures. It used to wrap each relation in a\n * `try/catch` that dropped anything it could not work out, so a\n * mis-declared relation silently vanished instead of being reported; with the\n * kind declared, the only remaining failure is a `target` that does not resolve,\n * which is worth hearing about.\n */\nexport function resolveCollectionRelations(\n collection: CollectionConfig\n): Record<string, ResolvedRelation> {\n const cached = _resolvedRelationsCache.get(collection);\n if (cached) return cached;\n\n if (!isRelationalCollectionConfig(collection)) return {};\n\n const relations: Record<string, ResolvedRelation> = {};\n\n for (const relation of collection.relations ?? []) {\n const resolved = resolveRelation(relation, collection);\n relations[resolved.relationName] = resolved;\n }\n\n // A property declaring a relation inline is registered under the property\n // key as well: the fetch layer hydrates the result back onto that key, and\n // it is the name the admin addresses the field by.\n for (const [propertyKey, property] of Object.entries(collection.properties ?? {})) {\n if ((property as Property)?.type !== \"relation\") continue;\n const declared = (property as RelationProperty).relation;\n if (!declared || relations[propertyKey]) continue;\n\n relations[propertyKey] = resolveRelation(declared, collection, propertyKey);\n }\n\n _resolvedRelationsCache.set(collection, relations);\n return relations;\n}\n\n/**\n * The `type: \"relation\"` property that declares a link, or `undefined` for one\n * that only exists in the collection's `relations` array.\n *\n * Both declaration sites end up in {@link resolveCollectionRelations}, and only\n * one of them has a property to carry field-level facts — `name`, `admin`, and\n * the one this exists for, `validation.required`.\n */\nexport function relationDeclaringProperty(\n collection: CollectionConfig,\n relation: ResolvedRelation\n): RelationProperty | undefined {\n const resolved = resolveCollectionRelations(collection);\n for (const [key, raw] of Object.entries(collection.properties ?? {})) {\n const prop = raw as Property | undefined;\n if (prop?.type !== \"relation\") continue;\n // A relation declared inline is keyed by the property; one declared in\n // `relations` is keyed by its name, which the property addresses.\n if (resolved[key] === relation) return prop as RelationProperty;\n const addressed = (prop as RelationProperty).relation?.relationName;\n if (addressed && findRelation(resolved, addressed) === relation) return prop as RelationProperty;\n }\n return undefined;\n}\n\n/**\n * Must every row of this collection point at a target through this link?\n *\n * Read from the declaring property's `validation.required` — the same key every\n * other field uses, and the only place it lives.\n *\n * `RelationBase` carried its own `validation.required` until 0.18, which made\n * this two questions rather than one. They were answered by different readers:\n * the Postgres DDL generator asked the property (so the foreign-key column was\n * `NOT NULL`) and the SDK type generator asked the relation (so the generated\n * `Insert` type made the field optional). A `create()` that left the relation\n * out therefore typechecked and then failed at the database with a not-null\n * violation, and the two `required`s had to be written twice, identically, for\n * the pair to agree.\n *\n * A relation with no declaring property — an entry in `relations` nothing\n * points at — is not required. There is no field to fill in.\n */\nexport function isRelationRequired(collection: CollectionConfig, relation: ResolvedRelation): boolean {\n return Boolean(relationDeclaringProperty(collection, relation)?.validation?.required);\n}\n\n/**\n * The path of the collection a relation property points at, derived from the\n * property alone.\n *\n * A preview holds a property and a value and no collection, so it cannot call\n * `resolveRelationProperty`. It does not need to: both forms that carry a\n * target — the stamped `resolvedRelation` and the inline `relation` — name it\n * directly. Only the third form, a relation declared by name in the\n * collection's `relations` array, is out of reach, and that one has no target\n * to read without the collection anyway.\n *\n * This is what lets a preview render a relation column that arrived as a bare\n * foreign key: the id says *which* row, the declared target says *which\n * collection*, and `RelationPreview` fetches the rest. Without it a scalar id\n * is indistinguishable from a value of the wrong type.\n */\nexport function getRelationTargetPath(property: RelationProperty): string | undefined {\n const stamped = property.resolvedRelation?.targetSlug;\n if (stamped) return stamped;\n\n const target = property.relation?.target;\n if (typeof target !== \"function\") return undefined;\n try {\n return target()?.slug;\n } catch (_e) {\n // A thunk reaching into a module that has not finished initialising:\n // there is no target to name yet, and a preview is not worth throwing over.\n return undefined;\n }\n}\n\n/**\n * The table a collection reads and writes.\n *\n * `table` when it is set, otherwise `toSnakeCase(slug)` — which is what made it\n * safe to drop `table` from the required fields on the config type: the runtime\n * had always derived it, and the type was demanding a value it did not need.\n *\n * The `||` chain is load-bearing. `toSnakeCase(undefined)` returns `\"\"`, not\n * `undefined`, so the previous `??` chain short-circuited on the empty string\n * and the name fallback could never run — a safety net that read like one and\n * caught nothing. It was unreachable while `slug` was required; it stops being\n * unreachable the moment anything constructs a config without one.\n */\nexport function getTableName(collection: CollectionConfig): string {\n const declared = isRelationalCollectionConfig(collection) ? collection.table : undefined;\n return declared || toSnakeCase(collection.slug) || toSnakeCase(collection.name);\n}\n\n/**\n * A JavaScript identifier: what a generated `export const <name> =` needs.\n *\n * Deliberately the same shape the two schema generators already define\n * privately — this is the third place that needed it, and the first two guard\n * property keys and member accesses while nothing guarded the variable name\n * itself.\n */\nconst JS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;\n\n/**\n * The variable name a generated table is bound to.\n *\n * Camel-cases underscores, and then guarantees the result is a legal\n * identifier. It did only the first, so a table name that is legal in Postgres\n * and not in JavaScript produced a `schema.generated.ts` that does not parse:\n *\n * `2024_archive` → `export const 2024Archive = pgTable(…)`\n * \"An identifier or keyword cannot immediately follow\n * a numeric literal\"\n * `reporting.events` → `export const reporting.events = pgTable(…)`\n * \"',' expected\"\n *\n * That file is imported by the server, so the failure is not one broken\n * collection — `rebase build` and `db push` fail at tsc for the whole\n * directory. And it is reachable from a documented flow: `rebase init` against\n * a database holding a table called `2024_archive` writes a collection file\n * that parses and a schema file that does not.\n *\n * **A no-op for every name that already worked**, which is what makes changing\n * a derived name safe here: the only inputs whose output changes are the ones\n * that produced a syntax error, and nothing can be running against those.\n * Separators become camel case rather than disappearing, so `reporting.events`\n * and `reporting_events` do not collide into one variable.\n */\nexport function getTableVarName(tableName: string): string {\n const camel = tableName.replace(/_([a-z])/g, (_, char: string) => char.toUpperCase());\n if (JS_IDENTIFIER.test(camel)) return camel;\n\n const sanitised = camel\n // Any other separator gets the same treatment `_` did, so two tables\n // differing only by separator keep differing.\n .replace(/[^A-Za-z0-9_$]+([A-Za-z0-9])?/g, (_, char?: string) =>\n (char ? char.toUpperCase() : \"\"))\n // A leading digit is legal in Postgres and not in JavaScript. Prefixed\n // rather than stripped, so `2024_archive` and `archive` stay distinct.\n .replace(/^([0-9])/, \"t$1\");\n\n return JS_IDENTIFIER.test(sanitised) ? sanitised : `t${sanitised}`;\n}\n\nexport function getEnumVarName(tableName: string, propName: string): string {\n const tableVar = getTableVarName(tableName);\n const propVar = propName.charAt(0).toUpperCase() + propName.slice(1);\n return `${tableVar}${propVar}`;\n}\n\nexport function getColumnName(fullColumn: string): string {\n return fullColumn.includes(\".\") ? fullColumn.split(\".\").pop()! : fullColumn;\n}\n\n/**\n * The field key a database column is served and addressed under.\n *\n * A column has two names and they are not the same name. `author_id` is what\n * Postgres stores; `authorId` is the key on the JSON row, the key in the\n * generated Drizzle table, and the key a caller writes in `where` and\n * `orderBy`. Every place that starts from a column and has to reach a row, a\n * Drizzle table or a payload goes through here, so there is one answer rather\n * than one per call site — the two that disagreed put `displayName` and\n * `author_id` on the same API.\n *\n * A declared property is the authority when there is one, because its key *is*\n * the wire name and `columnName` is the only thing that ever renamed the\n * column:\n *\n * 1. an explicit `columnName` equal to this column;\n * 2. a property whose key is literally the column (an author who wrote\n * `author_id:` meant `author_id` on the wire, and gets it);\n * 3. a property whose key snake-cases to the column, which is the default\n * mapping — `authorId` → `author_id`.\n *\n * With no property in the way — a foreign key derived from a relation, which\n * usually has none — the name is derived: {@link toWireKey}.\n *\n * Note the fallback is *not* the column verbatim. That was the old behaviour\n * and it is precisely the defect: a derived foreign key reached the wire under\n * its column name while every hand-authored field beside it was camelCase.\n */\nexport function fieldKeyForColumn(collection: CollectionConfig | undefined, column: string): string {\n const properties = collection?.properties;\n if (properties) {\n for (const [key, prop] of Object.entries(properties)) {\n const columnName = (prop as { columnName?: unknown } | undefined)?.columnName;\n if (typeof columnName === \"string\" && columnName === column) return key;\n }\n for (const key of Object.keys(properties)) {\n if (key === column) return key;\n if (toSnakeCase(key) === column) return key;\n }\n }\n return toWireKey(column);\n}\n\n/**\n * Look up a relation by key with forgiving normalization.\n *\n * `resolveCollectionRelations` stores each relation under a single canonical\n * key (no aliases). This helper tries the given key as-is, then falls back to\n * slug form (underscores → hyphens) and snake_case form (hyphens → underscores)\n * so that callers that receive a key from external input (URL path segments,\n * user-provided config, etc.) can still find the right entry.\n */\nexport function findRelation(\n resolvedRelations: Record<string, ResolvedRelation>,\n key: string\n): ResolvedRelation | undefined {\n // Exact match first\n if (resolvedRelations[key]) return resolvedRelations[key];\n\n // Try slug form (e.g. \"company_id\" → \"company-id\")\n const slugKey = key.replace(/_/g, \"-\");\n if (slugKey !== key && resolvedRelations[slugKey]) return resolvedRelations[slugKey];\n\n // Try snake_case form (e.g. \"company-id\" → \"company_id\")\n const snakeKey = key.replace(/-/g, \"_\");\n if (snakeKey !== key && resolvedRelations[snakeKey]) return resolvedRelations[snakeKey];\n\n return undefined;\n}\n","import {\n ArrayProperty,\n AuthState,\n CollectionConfig,\n EnumValueConfig,\n EnumValues,\n NumberProperty,\n Properties,\n Property,\n RelationProperty,\n ResolvedRelation,\n StringProperty,\n getDataSourceCapabilities,\n getDeclaredSubcollections,\n type EntityChildView\n} from \"@rebasepro/types\";\n\ntype PropertyConfig = { property: unknown; [key: string]: unknown };\nimport { isPropertyBuilder } from \"./entities\";\nimport { enumToObjectEntries } from \"./enums\";\nimport { DEFAULT_ONE_OF_TYPE } from \"./common\";\nimport { isDefaultFieldConfigId } from \"@rebasepro/utils\";\nimport { getIn, mergeDeep } from \"@rebasepro/utils\";\nimport { isJunctionBackedRelation, resolveCollectionRelations } from \"./relations\";\nimport { resolveRelation } from \"./resolve-relation\";\n\n/**\n * Resolve property builders, enums and arrays.\n */\n\nexport type ResolvePropertyProps<M extends Record<string, unknown> = Record<string, unknown>> = {\n property: Property\n propertyKey?: string,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}\n\nexport function resolveProperty<M extends Record<string, unknown> = Record<string, unknown>>(props: ResolvePropertyProps<M>): Property | null {\n\n const {\n property,\n ignoreMissingFields = false,\n ...rest\n } = props;\n\n let resultProperty: Property;\n\n if (isPropertyBuilder(property)) {\n const path = rest.path;\n if (!path) {\n // When path is not available (e.g. in preview contexts), skip dynamic\n // resolution and use the property as-is without dynamic modifications.\n resultProperty = property as Property;\n } else {\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicProps = property.dynamicProps?.({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n resultProperty = mergeDeep(property, dynamicProps ?? {});\n }\n } else {\n resultProperty = property as Property;\n }\n\n // Apply dynamic properties if they exist\n if (resultProperty?.dynamicProps && rest.path) {\n const path = rest.path;\n const usedPropertyValue = rest.propertyKey ? getIn(rest.values, rest.propertyKey) : undefined;\n const dynamicPropsResult = resultProperty.dynamicProps({\n ...rest,\n path,\n propertyValue: usedPropertyValue,\n values: rest.values ?? {},\n previousValues: rest.previousValues ?? rest.values ?? {}\n });\n\n if (dynamicPropsResult) {\n resultProperty = mergeDeep(resultProperty, dynamicPropsResult);\n }\n }\n\n let resolvedProperty: Property | null;\n\n if (resultProperty?.type === \"map\" && resultProperty.properties) {\n const properties = resolveProperties({\n ignoreMissingFields,\n ...rest,\n properties: resultProperty.properties\n });\n resolvedProperty = {\n ...resultProperty,\n properties\n } as Property;\n } else if (resultProperty?.type === \"array\") {\n resolvedProperty = resultProperty;\n } else if ((resultProperty?.type === \"string\" || resultProperty?.type === \"number\") && resultProperty.enum) {\n resolvedProperty = resolvePropertyEnum(resultProperty);\n } else {\n resolvedProperty = resultProperty;\n }\n\n if (resolvedProperty?.propertyConfig && !isDefaultFieldConfigId(resolvedProperty.propertyConfig)) {\n const cmsFields = rest.propertyConfigs;\n if (!cmsFields && !ignoreMissingFields) {\n throw Error(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property configs were provided. Use the property 'propertyConfigs' in your app config to provide them`);\n }\n const customField: PropertyConfig | undefined = cmsFields?.[resolvedProperty.propertyConfig];\n if (!customField) {\n console.warn(`Trying to resolve a property with key '${resolvedProperty.propertyConfig}' that inherits from a custom property config but no custom property config with that key was found. Check the 'propertyConfigs' in your app config`)\n return resolvedProperty;\n }\n if (customField.property) {\n const restConfigProperty = { ...customField.property } as Record<string, unknown>;\n delete restConfigProperty.propertyConfig;\n const customFieldProperty = resolveProperty({\n property: { name: \"\",\n...restConfigProperty } as Property,\n ignoreMissingFields,\n ...rest\n });\n if (customFieldProperty) {\n resolvedProperty = mergeDeep(customFieldProperty, resolvedProperty);\n }\n }\n\n }\n\n return resolvedProperty;\n}\n\n/**\n * The resolved relation a relation property refers to.\n *\n * Normalization stamps `resolvedRelation` onto the property, so this is usually\n * a field read. It falls back to resolving from the collection for properties\n * that never went through the registry — a preview, or a form rendered straight\n * from an authored config.\n */\nexport function resolveRelationProperty(\n property: RelationProperty,\n collection: CollectionConfig,\n propertyKey?: string\n): ResolvedRelation {\n if (property.resolvedRelation) return property.resolvedRelation;\n\n if (property.relation) {\n return resolveRelation(property.relation, collection, propertyKey);\n }\n\n const name = propertyKey ?? \"\";\n const declared = resolveCollectionRelations(collection)[name];\n if (!declared) {\n throw Error(\n `Relation property '${name || \"(unnamed)\"}' on '${collection.slug}' declares no \\`relation\\`, ` +\n \"and the collection has no relation of that name.\"\n );\n }\n return declared;\n}\n\n/**\n * Resolve enum aliases for a string or number property\n * @param property\n */\nexport function resolvePropertyEnum(property: StringProperty | NumberProperty): StringProperty | NumberProperty {\n if (typeof property.enum === \"object\") {\n return {\n ...property,\n enum: enumToObjectEntries(property.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? []\n };\n }\n return property as StringProperty | NumberProperty;\n}\n\n/**\n * Resolve enums and arrays for properties\n * @param properties\n * @param value\n */\nexport function resolveProperties<M extends Record<string, unknown>>({\n propertyKey,\n properties,\n ignoreMissingFields,\n ...props\n}: {\n propertyKey?: string,\n properties: Properties,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}): Properties {\n return Object.entries<Property>(properties as Record<string, Property>)\n .map(([key, property]) => {\n const childResolvedProperty = resolveProperty({\n propertyKey: propertyKey ? `${propertyKey}.${key}` : undefined,\n property: property,\n ignoreMissingFields,\n ...props\n });\n if (!childResolvedProperty) return {};\n return {\n [key]: childResolvedProperty\n };\n })\n .filter((a) => a !== null)\n .reduce((a, b) => ({ ...a,\n...b }), {}) as Properties;\n}\n\nexport function resolveArrayProperties<M>({\n propertyKey,\n property,\n ignoreMissingFields = false,\n ...props\n}: {\n propertyKey?: string,\n property: ArrayProperty,\n values?: Partial<M>,\n previousValues?: Partial<M>,\n path?: string,\n entityId?: string | number,\n index?: number,\n propertyConfigs?: Record<string, PropertyConfig>;\n ignoreMissingFields?: boolean;\n authController: AuthState;\n}): Property[] {\n const propertyValue = propertyKey ? getIn(props.values, propertyKey) : undefined;\n\n if (property.of) {\n if (Array.isArray(property.of)) {\n return property.of.map((p, index) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: p as Property,\n ignoreMissingFields,\n ...props,\n index\n });\n }) as Property[];\n } else {\n const of = property.of;\n const resolvedProperties = getArrayResolvedProperties({\n propertyValue,\n propertyKey,\n property,\n ignoreMissingFields,\n ...props\n });\n // Destructured to be *excluded* from `...rest`, not to be used —\n // see the comment below. Said explicitly so the discarded-value\n // ratchet does not carry a finding that is working as intended.\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { values, previousValues, ...rest } = props;\n const ofProperty = resolveProperty({ // we don't want to pass the values of the parent entity\n property: of,\n ignoreMissingFields,\n ...rest\n });\n if (!ofProperty && !ignoreMissingFields)\n throw Error(\"When using a property builder as the 'of' prop of an ArrayProperty, you must return a valid child property\")\n return resolvedProperties;\n }\n } else if (property.oneOf) {\n const typeField = property.oneOf?.typeField ?? DEFAULT_ONE_OF_TYPE;\n const resolvedProperties: Property[] = Array.isArray(propertyValue)\n ? propertyValue.map((v, index) => {\n const type = v && v[typeField];\n const childProperty = property.oneOf?.properties[type];\n if (!type || !childProperty) return null;\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: childProperty,\n ignoreMissingFields,\n ...props\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n return resolvedProperties;\n } else if (!property.columnType) {\n // An array with neither `of`/`oneOf` nor a `columnType` describes no element\n // type, so nothing can be generated or rendered from it.\n //\n // The escape hatch used to be `ui.Field` — \"a custom component can render\n // anything\" — which made a *presentation* field decide whether a schema was\n // valid, in code the Postgres generator runs. `columnType` is the same escape\n // hatch stated as data: `columnType: \"text[]\"` says what the column holds,\n // which is what both the generator and the form actually need.\n throw Error(`The array property (${propertyKey}) needs to declare an 'of' or a 'oneOf' property, or a \\`columnType\\` such as \"text[]\"`);\n } else {\n return [];\n }\n\n}\n\nexport function getArrayResolvedProperties({\n propertyKey,\n propertyValue,\n property,\n ...props\n}: {\n propertyValue: unknown,\n propertyKey?: string,\n property: ArrayProperty,\n ignoreMissingFields: boolean,\n values?: object;\n previousValues?: object;\n path?: string;\n entityId?: string | number;\n index?: number;\n propertyConfigs?: Record<string, PropertyConfig>;\n authController: AuthState;\n}) {\n\n const of = property.of;\n if (!of)\n throw Error(\n `Trying to resolve an array property (${propertyKey}) without providing an 'of' property`\n )\n return Array.isArray(propertyValue)\n ? propertyValue.map((v: unknown, index: number) => {\n return resolveProperty({\n propertyKey: `${propertyKey}.${index}`,\n property: Array.isArray(of) ? of[index] : of,\n ...props,\n index\n });\n }).filter(e => Boolean(e)) as Property[]\n : [];\n}\n\nexport function resolveEnumValues(input: EnumValues): EnumValueConfig[] | undefined {\n if (typeof input === \"object\") {\n return Object.entries(input).map(([id, value]) =>\n (typeof value === \"string\"\n ? {\n id,\n label: value\n }\n : value));\n } else if (Array.isArray(input)) {\n return input as EnumValueConfig[];\n } else {\n return undefined;\n }\n}\n\n\n/**\n * The lists rendered inside an entity view of `collection` — its tabs.\n *\n * The single derivation. There used to be two that disagreed: this one, and a\n * copy in `CollectionRegistry.normalizeCollection` that stamped each child with\n * the *target collection's* slug instead of the relation key. Since the\n * registry ran first and cached its answer onto `childCollections`, its version\n * was the one that won, and the frontend addressed child listings by a segment\n * the backend could not resolve.\n *\n * Order of precedence:\n * 1. `childCollections` — the explicit escape hatch for custom drivers.\n * 2. `subcollections` on an engine that has real containment (Firestore).\n * 3. many-relations on an engine that has relations (SQL).\n */\nexport function getEntityChildViews<M extends Record<string, unknown> = Record<string, unknown>>(\n collection: CollectionConfig<M>\n): EntityChildView[] {\n const asSubcollections = (collections: CollectionConfig<Record<string, unknown>>[]): EntityChildView[] =>\n collections.filter(Boolean).map(child => ({\n key: child.slug,\n collection: child,\n source: { kind: \"subcollection\" as const }\n }));\n\n if (collection.childCollections) {\n return asSubcollections(collection.childCollections() ?? []);\n }\n\n const capabilities = getDataSourceCapabilities(collection.engine);\n\n const declaredSubcollections = getDeclaredSubcollections(collection);\n if (capabilities.supportsSubcollections && declaredSubcollections) {\n return asSubcollections(declaredSubcollections() ?? []);\n }\n\n if (!capabilities.supportsRelations) return [];\n\n const resolvedRelations = resolveCollectionRelations(collection);\n const views: EntityChildView[] = [];\n const seen = new Set<string>();\n\n // Keyed by the map key, not by `relationName`: the map key is what\n // `findRelation` matches a path segment against, so it is the only one that\n // addresses the same relation on both sides of the wire. The map registers\n // some relations twice — once canonically, once under the declaring\n // property key — so dedupe on the underlying relation.\n for (const [relationKey, relation] of Object.entries(resolvedRelations)) {\n if (relation.cardinality !== \"many\") continue;\n\n const identity = relation.relationName ?? relationKey;\n if (seen.has(identity)) continue;\n\n let target: CollectionConfig | undefined;\n try {\n target = relation.target();\n } catch {\n continue;\n }\n if (!target) continue;\n seen.add(identity);\n\n // A name given to the declaring property is the author naming the tab.\n const declaringProperty = Object.entries((collection.properties ?? {}) as Record<string, Property>)\n .find(([propKey, p]) => p.type === \"relation\" && ((p as RelationProperty).relation?.relationName ?? propKey) === identity);\n const customName = declaringProperty?.[1]?.name;\n\n const base: CollectionConfig<Record<string, unknown>> = {\n ...target,\n slug: relationKey,\n ...(customName ? { name: customName,\nsingularName: customName } : {})\n } as CollectionConfig<Record<string, unknown>>;\n\n views.push({\n key: relationKey,\n collection: (relation.overrides ? mergeDeep(base, relation.overrides) : base) as CollectionConfig<Record<string, unknown>>,\n source: {\n kind: \"relation\",\n relationKey,\n mode: isJunctionBackedRelation(relation) ? \"linked\" : \"owned\",\n targetSlug: target.slug\n }\n });\n }\n\n return views;\n}\n\n/**\n * Each of `collection`'s tabs paired with the property that declared it, when a\n * property declared it: child view key → property key.\n *\n * A many-relation can only be declared as a property — that is the documented\n * and only mechanism — and {@link getEntityChildViews} promotes it to a tab. So\n * one declaration reaches the panel twice, and neither surface knew about the\n * other. The form rendered a relation picker beside the tab, and the collection\n * table rendered *two* columns under one heading: the relation's own column,\n * showing the child rows, and a jump-to-tab button carrying the same name.\n *\n * The pairing is what lets each surface decide which half is redundant, and it\n * has to be a pairing rather than two sets because the two keys differ whenever\n * a relation is named. The match is on the resolved `relationName` — the\n * identity `getEntityChildViews` itself dedupes on — so a relation declared in\n * `relations` and pointed at by a differently-named property is recognised too.\n *\n * A relation with no property of its own is absent here, which is the point: it\n * has exactly one surface already, and nothing to weigh it against.\n *\n * Only top-level properties: a relation nested inside a `map` gets no tab.\n */\nexport function getChildViewDeclaringProperties<M extends Record<string, unknown> = Record<string, unknown>>(\n collection: CollectionConfig<M>\n): Map<string, string> {\n const pairs = new Map<string, string>();\n\n const relationProperties = Object.entries((collection.properties ?? {}) as Record<string, Property>)\n .filter(([, property]) => property?.type === \"relation\");\n if (relationProperties.length === 0) return pairs;\n\n const relationViews = getEntityChildViews(collection)\n .filter(view => view.source.kind === \"relation\");\n if (relationViews.length === 0) return pairs;\n\n const resolvedRelations = resolveCollectionRelations(collection);\n const identityOf = (relationKey: string): string =>\n resolvedRelations[relationKey]?.relationName ?? relationKey;\n\n const declaringPropertyByIdentity = new Map<string, string>();\n for (const [propertyKey, property] of relationProperties) {\n const relation = (property as RelationProperty).resolvedRelation ?? resolvedRelations[propertyKey];\n // A to-one relation is a foreign key the author edits, never a tab. No\n // view will match it — the views here are many-relations only — but\n // reading the cardinality says so where someone is looking.\n if (relation?.cardinality !== \"many\") continue;\n const identity = relation.relationName ?? propertyKey;\n if (!declaringPropertyByIdentity.has(identity)) declaringPropertyByIdentity.set(identity, propertyKey);\n }\n\n for (const view of relationViews) {\n const propertyKey = declaringPropertyByIdentity.get(\n identityOf((view.source as { relationKey: string }).relationKey));\n if (propertyKey) pairs.set(view.key, propertyKey);\n }\n\n return pairs;\n}\n\n/**\n * The property keys of `collection` whose relation is already one of its tabs.\n *\n * What a form asks: the tab is the treatment for a list of child rows, so the\n * picker beside it is the redundant half. See\n * {@link getChildViewDeclaringProperties}.\n */\nexport function getChildViewRelationPropertyKeys<M extends Record<string, unknown> = Record<string, unknown>>(\n collection: CollectionConfig<M>\n): Set<string> {\n return new Set(getChildViewDeclaringProperties(collection).values());\n}\n\n/**\n * The child views of `collection` as bare collections.\n *\n * The flattened view of {@link getEntityChildViews}, for navigation code that\n * only needs to match a path segment against a slug. Anything that cares *what\n * kind* of list it is showing — chiefly the admin, which must not offer a\n * global delete on a shared row — should read the views instead.\n */\nexport function getSubcollections<M extends Record<string, unknown> = Record<string, unknown>>(collection: CollectionConfig<M>): CollectionConfig<Record<string, unknown>>[] {\n return getEntityChildViews(collection).map(view => view.collection);\n}\n","import { ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, LiteralPolicyOperand, PolicyExpression, policy, rewriteLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * A tiny, regex-based SQL \"parser\" for security rules.\n *\n * This is NOT a full SQL parser. It is designed to handle the subset of SQL\n * commonly used in `USING` and `WITH CHECK` clauses, enough to drive the\n * optimistic client-side UI decision.\n *\n * It handles:\n * - `field = 'literal'`\n * - `field != 'literal'`\n * - `field = current_setting('app.uid')` (or the legacy `app.user_id`)\n * - `A AND B`, `A OR B` — only where the keyword is at the top level\n * - `true`\n * - `IN (...)` (as optimistic true)\n *\n * For anything it doesn't understand, it returns a `raw` expression, which\n * the evaluator treats as \"unknown\" (and usually optimistic true).\n *\n * **This output also round-trips back into DDL** via `policyToPostgres` (the\n * schema/policy generators), so decomposing a clause the parser only partly\n * understands is not a cosmetic mistake — it emits invalid SQL. When in doubt,\n * prefer `raw`: it is reproduced verbatim.\n */\n/** True when `keyword` starts at `i` as a standalone word. */\nfunction isKeywordAt(upper: string, i: number, keyword: string): boolean {\n if (!upper.startsWith(keyword, i)) return false;\n const before = i === 0 ? \" \" : upper[i - 1];\n const after = upper[i + keyword.length] ?? \" \";\n return /[\\s()]/.test(before) && /[\\s()]/.test(after);\n}\n\n/**\n * Split `sql` on a boolean keyword, but only where it sits at paren depth 0 and\n * outside a string literal. Returns null when it never does, so the caller\n * leaves the clause alone.\n *\n * This used to be `sql.split(/ AND /i)`, which tore subqueries in half: the\n * `AND` inside\n * `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id = rebase.uid())`\n * split the expression, and re-emitting the halves produced\n * `(EXISTS (...) AND m.user_id = rebase.uid())`\n * where `m` is no longer in scope — SQL that Postgres rejects outright with\n * \"missing FROM-clause entry for table\". Returning null instead keeps such a\n * clause as a `raw` expression, which round-trips verbatim.\n */\nfunction splitTopLevel(sql: string, keyword: \"AND\" | \"OR\"): string[] | null {\n const upper = sql.toUpperCase();\n const parts: string[] = [];\n let depth = 0;\n let inString = false;\n let start = 0;\n\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n if (inString) {\n if (ch === \"'\") {\n if (sql[i + 1] === \"'\") i++; // '' escapes a quote inside a literal\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") { depth++; continue; }\n if (ch === \")\") { depth--; continue; }\n if (depth === 0 && isKeywordAt(upper, i, keyword)) {\n parts.push(sql.slice(start, i));\n i += keyword.length - 1;\n start = i + 1;\n }\n }\n\n if (parts.length === 0) return null;\n parts.push(sql.slice(start));\n const trimmedParts = parts.map(p => p.trim()).filter(p => p.length > 0);\n return trimmedParts.length > 1 ? trimmedParts : null;\n}\n\n/** Drop redundant wrapping parens (`(a AND b)` → `a AND b`), never `(a) AND (b)`. */\nfunction stripOuterParens(sql: string): string {\n let s = sql.trim();\n for (;;) {\n if (!s.startsWith(\"(\") || !s.endsWith(\")\")) return s;\n let depth = 0;\n let inString = false;\n let wraps = true;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === \"'\") {\n if (s[i + 1] === \"'\") i++;\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n if (depth === 0 && i < s.length - 1) { wraps = false; break; }\n }\n }\n if (!wraps) return s;\n s = s.slice(1, -1).trim();\n }\n}\n\nexport function sqlToPolicy(sql: string): PolicyExpression {\n // Normalised before anything else looks at it, so every pattern below only\n // has to know the current spelling. A database migrated by a pre-1.0 release\n // still holds `auth.uid()` in its policy bodies until the next push or boot\n // recompiles them — and until then the admin UI reads those bodies back\n // through here. Without this they parse as opaque `raw`, and the framework's\n // own policies get badged as hand-written drift.\n //\n // Normalising rather than accepting both spellings throughout is deliberate:\n // it also means a legacy policy that falls through to `raw` is stored in the\n // new spelling, so editing and saving one in the Studio migrates it.\n const trimmed = stripOuterParens(rewriteLegacyRlsFunctions(sql).trim());\n\n if (trimmed.toLowerCase() === \"true\") return policy.true();\n if (trimmed.toLowerCase() === \"false\") return policy.false();\n\n // Handle roles overlap (&&)\n // Matches: string_to_array(rebase.roles(), ',') && ARRAY['admin', 'editor']\n const overlapMatch = trimmed.match(/^string_to_array\\s*\\(\\s*rebase\\.roles\\(\\)\\s*,\\s*','\\s*\\)\\s*&&\\s*ARRAY\\s*\\[(.+)\\]$/i);\n if (overlapMatch) {\n const roles = overlapMatch[1].split(\",\").map(s => s.trim().replace(/^'|'$/g, \"\"));\n return policy.rolesOverlap(roles);\n }\n\n // Handle roles containment (@>)\n // Matches: string_to_array(rebase.roles(), ',') @> ARRAY['admin']\n const containMatch = trimmed.match(/^string_to_array\\s*\\(\\s*rebase\\.roles\\(\\)\\s*,\\s*','\\s*\\)\\s*@>\\s*ARRAY\\s*\\[(.+)\\]$/i);\n if (containMatch) {\n const roles = containMatch[1].split(\",\").map(s => s.trim().replace(/^'|'$/g, \"\"));\n return policy.rolesContain(roles);\n }\n\n // OR binds looser than AND, so it splits first.\n const orParts = splitTopLevel(trimmed, \"OR\");\n if (orParts) return policy.or(...orParts.map(sqlToPolicy));\n\n const andParts = splitTopLevel(trimmed, \"AND\");\n if (andParts) return policy.and(...andParts.map(sqlToPolicy));\n\n // Handle = and !=\n const match = trimmed.match(/^(.+?)\\s*(!?=)\\s*(.+)$/);\n if (match) {\n const [, leftStr, op, rightStr] = match;\n const left = parseOperand(leftStr.trim());\n const right = parseOperand(rightStr.trim());\n if (left && right) {\n return policy.compare(left, op === \"=\" ? \"eq\" : \"neq\", right);\n }\n }\n\n // Fallback to raw — the NORMALISED text, not the input. Storing the input\n // verbatim would mean a legacy policy read out of a database, edited in the\n // Studio and saved, writes `auth.uid()` back into the project's config: a\n // call to a function 1.0 no longer creates.\n return policy.raw(trimmed);\n}\n\n/**\n * Literals from other BaaS platforms that people compare `rebase.uid()` against\n * out of habit. Mirrors the driver's `FOREIGN_CONVENTION_ROLES` guard on\n * `pgRoles`, one surface over: the same muscle memory inside a `using:` string\n * is the more dangerous spelling, because it inverts a rule instead of\n * emptying a table.\n */\n/**\n * A `Map`, not an object literal.\n *\n * As `Record<string, string>` this was indexed with a literal taken straight\n * out of a policy, so every key on `Object.prototype` answered: a rule\n * comparing `rebase.uid()` to `\"valueOf\"`, `\"toString\"`, `\"constructor\"` or\n * `\"hasOwnProperty\"` found a truthy \"platform\" and reported an anonymous-grant\n * risk that does not exist — with the matched function interpolated into the\n * explanation as the platform's name. A security warning that fires on\n * innocent input is worse than none: it is what teaches people to skip the\n * warnings that are real.\n *\n * Same shape as the prototype-pollution class swept out of `setIn`, `getIn`,\n * `mergeDeep` and `unflattenObject` — a data-derived key reaching a plain\n * object. Found by a property test, on the input `\"valueOf\"`.\n */\nconst FOREIGN_CONVENTION_UIDS = new Map<string, string>([\n [\"anon\", \"Supabase\"],\n [\"authenticated\", \"Supabase\"],\n [\"service_role\", \"Supabase\"]\n]);\n\n/**\n * The same foreign literals, as a pattern for SQL that could not be parsed\n * back into structure.\n */\nconst FOREIGN_UID_LITERAL_SQL = new RegExp(\n String.raw`rebase\\.uid\\(\\)\\s*=\\s*'(${[...FOREIGN_CONVENTION_UIDS.keys()].join(\"|\")})'`,\n \"i\"\n);\n\n/** A clause that reads as a lockdown but admits anonymous callers. */\nexport interface AnonymousGrantRisk {\n /** Which spelling was found. */\n pattern: \"foreign-uid-literal\" | \"uid-not-null\";\n /** The offending fragment — the literal, or the SQL that is a tautology. */\n detail: string;\n /** Why it admits anonymous callers, and what to write instead. */\n explanation: string;\n}\n\n/**\n * `rebase.uid() IS NOT NULL` in raw SQL, the clause that is always true.\n *\n * Both schema spellings, because this runs over policy bodies read back from a\n * database, and one migrated by a pre-1.0 release still holds `auth.uid()`.\n * A security check that stops recognising a dangerous clause because the\n * framework renamed a function is a check that silently turns off.\n */\nconst UID_NOT_NULL = /\\b(?:rebase|auth)\\.uid\\(\\)\\s+IS\\s+NOT\\s+NULL/i;\n\n/**\n * Find clauses that read as \"signed-in users only\" but admit anonymous callers.\n *\n * Both spellings come from the same place — Supabase, where its own `auth.uid()`\n * really is NULL for an anonymous request. Rebase substitutes\n * {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which\n * is how the trusted *server* context is recognised), so:\n *\n * - `rebase.uid() IS NOT NULL` is a tautology on the user path, and\n * - `rebase.uid() != 'anon'` excludes one spelling of anonymous and admits the\n * other. This one is not hypothetical and was not only a foreign habit:\n * rebase's own request path reported `'anon'` while everything that compiled\n * or checked a policy used `'anonymous'`, so whichever literal an author\n * picked, half the anonymous callers walked through. See\n * {@link ANONYMOUS_USER_IDS}.\n *\n * Either one turns a lockdown into a full grant, and neither looks wrong. No\n * real user id is ever one of these literals, and a user-context request is\n * never NULL, so a match is always a mistake rather than a deliberate check.\n *\n * Structured expressions are checked too, not just parsed SQL: `policy.compare`\n * can spell the same mistake.\n */\nexport function findAnonymousGrants(expr: PolicyExpression): AnonymousGrantRisk[] {\n const found: AnonymousGrantRisk[] = [];\n\n const visit = (e: PolicyExpression): void => {\n switch (e.kind) {\n case \"and\":\n case \"or\":\n e.operands.forEach(visit);\n return;\n case \"not\":\n visit(e.operand);\n return;\n case \"existsIn\":\n visit(e.where);\n return;\n case \"raw\": {\n if (UID_NOT_NULL.test(e.sql)) {\n found.push({\n pattern: \"uid-not-null\",\n detail: e.sql,\n explanation: \"`rebase.uid() IS NOT NULL` is true for every request that came from a client, \" +\n `including anonymous ones — they carry '${ANONYMOUS_USER_ID}', not NULL. ` +\n \"Use `condition: policy.authenticated()` to mean \\\"signed in\\\".\"\n });\n }\n // The foreign literals have to be looked for here too, not only\n // in `compare`. `sqlToPolicy` falls back to `raw` for anything\n // it cannot structure — an `EXISTS (...)` subquery always does —\n // so a policy read back from the database arrives as one opaque\n // string. Checking only the tautology meant a genuine\n // `rebase.uid() = 'anon'` inside an `existsIn` was structurally\n // undetectable once round-tripped, and the caller read the empty\n // result as \"no risks found\".\n const foreign = FOREIGN_UID_LITERAL_SQL.exec(e.sql);\n if (foreign) {\n const literal = foreign[1];\n found.push({\n pattern: \"foreign-uid-literal\",\n detail: literal,\n explanation: `'${literal}' is a ${FOREIGN_CONVENTION_UIDS.get(literal)} convention. Rebase ` +\n `reports an anonymous request as '${ANONYMOUS_USER_ID}', so comparing against ` +\n `'${literal}' passes for every caller. Use \\`condition: policy.authenticated()\\` to ` +\n \"mean \\\"signed in\\\".\"\n });\n }\n return;\n }\n case \"compare\": {\n const literal = [e.left, e.right].find(o => o.kind === \"literal\") as LiteralPolicyOperand | undefined;\n const comparesUid = e.left.kind === \"authUid\" || e.right.kind === \"authUid\";\n if (!comparesUid || typeof literal?.value !== \"string\") return;\n const platform = FOREIGN_CONVENTION_UIDS.get(literal.value);\n if (!platform) return;\n found.push({\n pattern: \"foreign-uid-literal\",\n detail: literal.value,\n explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous ` +\n `request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for ` +\n \"every caller. Use `condition: policy.authenticated()` to mean \\\"signed in\\\" — it \" +\n `compiles to NOT IN (${ANONYMOUS_USER_IDS.map(v => `'${v}'`).join(\", \")}), covering ` +\n \"every spelling rebase has reported rather than whichever one you remember.\"\n });\n return;\n }\n default:\n return;\n }\n };\n\n visit(expr);\n return found;\n}\n\nfunction parseOperand(str: string) {\n // current_setting('app.uid') or rebase.uid(). `app.user_id` is the\n // pre-rename spelling and stays parseable: policies are data, so a\n // database provisioned before the rename still holds rules written\n // against it, and round-tripping one must not silently drop the operand.\n //\n // ANCHORED, and that is the whole point. These tests used to be\n // unanchored — `.test(str)` rather than `^…$` — so any operand text that\n // merely *contained* a uid call was replaced wholesale by the call itself.\n // Everything else in the expression was discarded with it, including a\n // leading `NOT (`:\n //\n // NOT (rebase.uid() = rebase.uid()) parsed as rebase.uid() = rebase.uid()\n //\n // A deny became an unconditional grant. The realistic spelling is a\n // hand-written defensive rule with a uid call on both sides —\n // COALESCE(rebase.uid(), '') = COALESCE(owner_id, rebase.uid())\n // — which collapsed to the same tautology. This is not confined to the\n // admin UI: `securityRuleToConditions` feeds a rule's raw `using:` string\n // through here, and the Postgres DDL generators compile the result, so the\n // tautology was written into the database as the policy body.\n //\n // An operand this cannot identify exactly must return null, which drops the\n // whole clause to `raw` and reproduces it verbatim. That is the rule the\n // rest of this file already follows: when in doubt, prefer `raw`.\n if (/^current_setting\\s*\\(\\s*'app\\.(uid|user_id)'\\s*\\)$/i.test(str) || /^rebase\\.uid\\(\\)$/i.test(str)) {\n return policy.authUid();\n }\n\n // Literal string: 'value', with `''` decoded back to a single quote.\n //\n // `quoteLiteral` doubles every quote on the way out, and this did not undo\n // it, so a literal containing an apostrophe grew on every trip: O'Brien →\n // O''Brien → O''''Brien, doubling each time a policy was read back and\n // recompiled. Past the first trip the emitted policy compares against a\n // string no row holds.\n const literal = parseSingleQuoted(str);\n if (literal !== null) {\n return policy.literal(literal);\n }\n\n // Unquoted literals, which must be recognised BEFORE the bare-word branch\n // below or they are read as column names.\n //\n // `quoteLiteral` emits booleans, numbers and null unquoted, so `a = false`\n // came back as a comparison against a *field* called `false`, and `a = 42`\n // against a field called `42`. The recompiled SQL is identical either way,\n // which is why this survived a round-trip check on the SQL — but the\n // expression is now wrong, and the expression is what the admin UI\n // evaluates. Against a row with no `a`, Postgres denies (`NULL = false` is\n // not true) while the JS evaluator compared two missing columns, found them\n // equal, and allowed. That is precisely the client/database drift the\n // shared PolicyExpression model exists to make impossible.\n //\n // Unambiguous in both directions: a SQL identifier cannot begin with a\n // digit, and bare `true`/`false`/`null` are always the literals — a column\n // so named would have to be double-quoted to be referenced at all.\n if (/^-?\\d+$/.test(str)) return policy.literal(Number(str));\n if (/^-?\\d*\\.\\d+$/.test(str)) return policy.literal(Number(str));\n if (/^true$/i.test(str)) return policy.literal(true);\n if (/^false$/i.test(str)) return policy.literal(false);\n if (/^null$/i.test(str)) return policy.literal(null);\n\n // Bare field name — but only one that survives the snake-casing the\n // compiler will apply to it. `toSnakeCase(\"_\")` is the empty string, and a\n // field that compiles to an empty column reference emits `= 'x'`, which is\n // a syntax error at CREATE POLICY time. Such a name is left to `raw`, where\n // it round-trips verbatim instead. `toSnakeCase` itself is not touched:\n // column names derived by it are already in shipped databases.\n if (/^\\w+$/.test(str) && toSnakeCase(str) !== \"\") {\n return policy.field(str);\n }\n\n return null;\n}\n\n/**\n * Decode a single-quoted SQL literal, or null when `str` is not exactly one.\n *\n * Rejecting is as important as decoding: `'a' = 'b'` is two literals and an\n * operator, not one literal whose body contains a quote, and a regex anchored\n * on the outer quotes would happily read it as the latter. Every interior quote\n * must therefore be part of a `''` pair.\n */\nfunction parseSingleQuoted(str: string): string | null {\n if (str.length < 2 || !str.startsWith(\"'\") || !str.endsWith(\"'\")) return null;\n const body = str.slice(1, -1);\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n if (body[i] !== \"'\") {\n out += body[i];\n continue;\n }\n if (body[i + 1] === \"'\") {\n out += \"'\";\n i++;\n continue;\n }\n return null; // a bare quote — `str` is not a single literal\n }\n return out;\n}\n","import { PolicyExpression, SecurityRule, policy } from \"@rebasepro/types\";\nimport { sqlToPolicy } from \"./sqlToPolicy\";\n\n/**\n * The normalized `USING` / `WITH CHECK` conditions for a single security rule,\n * expressed in the engine-agnostic {@link PolicyExpression} model.\n *\n * A `null` clause means \"this rule contributes no condition for that clause\";\n * consumers apply the default (Postgres denies with `false`).\n */\nexport interface RuleConditions {\n usingExpr: PolicyExpression | null;\n withCheckExpr: PolicyExpression | null;\n}\n\n/**\n * Desugars a {@link SecurityRule} — its `access`/`ownerField`/`roles` shortcuts,\n * structured `condition`/`check`, and raw `using`/`withCheck` — into a single\n * normalized {@link PolicyExpression} pair.\n *\n * **This is the linchpin against drift:** both the Postgres DDL generators and\n * the client-side evaluator consume this one function, so there is exactly one\n * definition of what a rule means. In particular, application `roles` are folded\n * into the expression here (AND'd with the base condition, matching how Postgres\n * generates the clause) rather than being handled separately by each consumer.\n */\nexport function securityRuleToConditions(rule: SecurityRule): RuleConditions {\n return {\n usingExpr: withRoles(baseUsing(rule), rule),\n withCheckExpr: withRoles(baseWithCheck(rule), rule)\n };\n}\n\nfunction baseUsing(rule: SecurityRule): PolicyExpression | null {\n if (rule.condition) return rule.condition;\n if (rule.using != null) return sqlToPolicy(rule.using);\n if (rule.access === \"public\") return policy.true();\n if (rule.ownerField) return policy.compare(policy.field(rule.ownerField), \"eq\", policy.authUid());\n return null;\n}\n\nfunction baseWithCheck(rule: SecurityRule): PolicyExpression | null {\n if (rule.check) return rule.check;\n if (rule.withCheck != null) return sqlToPolicy(rule.withCheck);\n // No explicit WITH CHECK → fall back to the USING condition, matching\n // PostgreSQL's own default behavior.\n return baseUsing(rule);\n}\n\n/**\n * AND the base condition with an application-role check, or produce a roles-only\n * condition when there is no base. Mirrors the Postgres generator so that a\n * role-scoped restrictive rule denies exactly the same set of users on both\n * sides.\n */\nfunction withRoles(base: PolicyExpression | null, rule: SecurityRule): PolicyExpression | null {\n if (!rule.roles || rule.roles.length === 0) return base;\n const rolesExpr = policy.rolesOverlap(rule.roles);\n if (rule.mode === \"restrictive\") {\n // Restrictive rule: applies ONLY if user has the roles.\n // If user DOES NOT have the roles, they are NOT restricted (passes).\n // If user HAS the roles, they must pass the base condition.\n // Logical equivalent: NOT(roles) OR base\n return base ? policy.or(policy.not(rolesExpr), base) : policy.not(rolesExpr);\n }\n return base ? policy.and(base, rolesExpr) : rolesExpr;\n}\n","import {\n CollectionConfig,\n FirebaseCollectionConfig,\n FirebaseProperties,\n FirebaseProperty,\n InferEntityType,\n MongoDBCollectionConfig,\n MongoProperties,\n MongoProperty,\n PostgresCollectionConfig,\n PostgresProperties,\n PostgresProperty,\n Properties,\n Property,\n StrictProperties,\n User,\n resolveResourceRefs,\n type ResourceRef\n} from \"@rebasepro/types\";\n\n\n// ── defineCollection ─────────────────────────────────────────────────────\n// A smarter builder that uses `const` type-parameter inference (TS 5.0+)\n// to capture literal property types automatically. This gives you\n// autocomplete on `display.title`, `sort`, `propertiesOrder`, `fixedFilter`,\n// callbacks, etc. — without writing `as const` or passing manual generics.\n\n/** The engines a collection can declare. `postgres` when it says nothing. */\ntype CollectionEngine = \"postgres\" | \"firestore\" | \"mongodb\";\n\n/**\n * The concrete collection type an `engine` selects.\n *\n * This builder used to be three overloads — one per engine — and overload\n * resolution is what made its errors unreadable. When no overload matches,\n * TypeScript emits **one** diagnostic at the call site listing each overload's\n * *first* failure, so a misspelled key on a Postgres collection came back as\n * three paragraphs of `No overload matches this call. Overload 1 of 3 … Overload\n * 3 of 3, '(collection: Omit<MongoDBCollectionConfig<…>>)'` — pointing at\n * `defineCollection(` and blaming a database the project does not use.\n *\n * One signature, with the engine as a type parameter, reports the error at the\n * key instead. Same fix as `@rebasepro/cms-types`, and deliberately the same\n * shape: this is the builder a headless (`--headless`) scaffold, `rebase schema\n * introspect` output and the example app's own collections use, so the two must\n * not diverge.\n */\ntype CollectionConfigForEngine<E, P, USER extends User> =\n E extends \"firestore\" ? FirebaseCollectionConfig<EntityShapeOf<P>, USER>\n : E extends \"mongodb\" ? MongoDBCollectionConfig<EntityShapeOf<P>, USER>\n : PostgresCollectionConfig<EntityShapeOf<P>, USER>;\n\n/**\n * `InferEntityType`, tolerant of a property map that has an error in it.\n *\n * The key set has to survive a bad property, or one mistake hides every other\n * check that reads it. See `KEYS` on the signature below.\n */\ntype EntityShapeOf<P> = InferEntityType<{\n [K in keyof P]: P[K] extends Property ? P[K] : Property;\n}>;\n\n/** The property union an engine admits — the engine gate, as a type. */\ntype PropertyForEngine<E> =\n E extends \"firestore\" ? FirebaseProperty\n : E extends \"mongodb\" ? MongoProperty\n : PostgresProperty;\n\n/** {@link PropertyForEngine} as a property map, for the `P` constraint. */\ntype PropertiesForEngine<E> =\n E extends \"firestore\" ? FirebaseProperties\n : E extends \"mongodb\" ? MongoProperties\n : PostgresProperties;\n\n/**\n * Define a collection with full type inference. Postgres unless `engine` says\n * otherwise.\n *\n * The `const P` generic captures literal property types from your\n * `properties` object, so every key that names a property — a security rule's\n * `ownerField`, a relation's `localKey`, an entity callback's `value` — is\n * checked against the collection's own property names rather than `string`.\n *\n * This is the builder for a project with no admin panel. One with an admin\n * panel wants `defineCollection` from `@rebasepro/cms-types`, which is the same\n * function with the `admin` block type-checked.\n *\n * @example\n * ```ts\n * const products = defineCollection({\n * name: \"Products\",\n * slug: \"products\",\n * table: \"products\",\n * properties: {\n * name: { name: \"Name\", type: \"string\", validation: { required: true } },\n * price: { name: \"Price\", type: \"number\" },\n * },\n * securityRules: [{ operation: \"select\", access: \"public\" }]\n * });\n * ```\n *\n * @group Builder\n */\nexport function defineCollection<\n const E extends CollectionEngine = \"postgres\",\n /**\n * The properties, **constrained**. This is what checks them, and what\n * supplies the contextual type inside them: without a constraint the\n * parameter of an inline `callbacks: { beforeSave: ({ value }) => … }` has\n * nothing to be typed from, and TypeScript reports an implicit `any` on a\n * callback the author wrote correctly.\n */\n const P extends PropertiesForEngine<E> & Properties = PropertiesForEngine<E> & Properties,\n /**\n * The properties again, **unconstrained**, and this is why there are two.\n *\n * A constraint TypeScript cannot satisfy is one it silently falls back\n * from: one property with a bad `defaultValue` made `P` become\n * `PostgresProperties`, the entity shape become `Record<string, unknown>`,\n * and every key that is checked against the property names — `display.title`,\n * `propertiesOrder`, `sort` — widen to `string` and stop being checked.\n *\n * `KEYS` has no constraint to fall back from, so `keyof KEYS` survives a bad\n * property and the rest of the collection is still checked against the real\n * key set.\n */\n const KEYS = Properties,\n USER extends User = User\n>(\n collection: Omit<CollectionConfigForEngine<E, KEYS, USER>, \"properties\" | \"engine\" | \"dataSource\">\n & {\n engine?: E;\n properties: StrictProperties<P, PropertyForEngine<E>> & KEYS;\n dataSource?: ResourceRef;\n }\n): CollectionConfigForEngine<E, KEYS, USER> & { properties: KEYS };\n\n/**\n * At runtime this is a plain identity function: a resource handle written where\n * a key belongs — `dataSource: analytics` — becomes its key, so past this point\n * a collection is plain data. The signature above is the rest of the point.\n * @group Builder\n */\nexport function defineCollection(\n collection: Omit<CollectionConfig, \"dataSource\"> & { dataSource?: ResourceRef }\n): CollectionConfig {\n return resolveResourceRefs(collection) as CollectionConfig;\n}\n\n","/**\n * The one reading of `collection.tenant`.\n *\n * Four things have to agree for a tenant-scoped collection to work — the\n * column, the RLS policy, the value stamped on insert and the index — and\n * before this they were four hand-written declarations that nothing compared.\n * The three that are schema become a {@link SecurityRule} and a column effect\n * derived here and in `planSchema`; the fourth, the write path, is\n * {@link resolveTenantWrite}.\n *\n * Everything in this module is pure. The policy it builds is a `SecurityRule`\n * like any other, which is what makes `db push`, the doctor, boot-ensure, the\n * drift detector and the Studio treat the tenancy policy as what it is —\n * generated, named, and recognisable — rather than as somebody's hand-written\n * SQL that a push should offer to drop.\n */\nimport {\n DEFAULT_TENANT_BYPASS_ROLES,\n isTenantClaimSource,\n policy,\n type CollectionConfig,\n type CollectionTenantConfig,\n type EntityStatus,\n type PolicyExpression,\n type SecurityRule\n} from \"@rebasepro/types\";\nimport { getTableName } from \"./relations\";\n\n/**\n * The collection's tenancy declaration, or nothing.\n *\n * Read through this rather than off the object, so the one shape check —\n * `tenant` is an object carrying a `field` and a `from` — is in one place. A\n * config that is *wrong* is refused by `validateCollectionConfig` with a\n * message; this is only asking whether there is one.\n */\nexport function getTenantConfig(collection: CollectionConfig | undefined): CollectionTenantConfig | undefined {\n const tenant = (collection as { tenant?: unknown } | undefined)?.tenant as CollectionTenantConfig | undefined;\n if (!tenant || typeof tenant !== \"object\") return undefined;\n if (typeof tenant.field !== \"string\" || !tenant.field) return undefined;\n if (!tenant.from || typeof tenant.from !== \"object\") return undefined;\n return tenant;\n}\n\n/** The roles tenancy does not apply to, defaulted. */\nexport function tenantBypassRoles(tenant: CollectionTenantConfig): readonly string[] {\n return tenant.bypassRoles ?? DEFAULT_TENANT_BYPASS_ROLES;\n}\n\n/**\n * The name of the policy a tenant declaration compiles to.\n *\n * Explicit — not a `getPolicyNameHash` of the rule — precisely because the\n * rule's *body* is compiled with more information in some callers than in\n * others (`planSchema` can resolve a relation's target collection and so knows\n * the column's type; the Studio, asking only for names, cannot). A hashed name\n * would then differ between the two, and the same policy would read as drift.\n * A frozen identifier: see `contracts/derived-names.txt`.\n */\nexport function tenantPolicyName(tableName: string): string {\n return `${tableName}_tenant_scope`;\n}\n\n/** The `reason` on the index a tenant column gets. Rendered into `schema.sql`. */\nexport const TENANT_INDEX_REASON = \"tenant scope\";\n\n/**\n * The condition a tenant declaration means, as a policy expression.\n *\n * `serverContext()` first, for the same reason every injected baseline rule\n * carries it: the trusted plane runs migrations, the auth flows and the boot,\n * and a restrictive policy that excluded it would not protect a tenant, it\n * would stop the server from starting.\n *\n * Then the bypass roles, then the tenancy test itself — a claim comparison or a\n * correlated `EXISTS` over the membership table, which are the two ways a\n * deployment answers \"which tenant is this caller in\".\n */\nexport function tenantScopeExpression(tenant: CollectionTenantConfig): PolicyExpression {\n const match: PolicyExpression = isTenantClaimSource(tenant.from)\n ? policy.compare(policy.field(tenant.field), \"eq\", policy.authClaim(tenant.from.claim))\n : policy.existsIn({\n collection: tenant.from.membership.collection,\n where: policy.and(\n policy.compare(\n policy.field(tenant.from.membership.tenantField),\n \"eq\",\n policy.outerField(tenant.field)\n ),\n policy.compare(\n policy.field(tenant.from.membership.userField),\n \"eq\",\n policy.authUid()\n )\n )\n });\n\n const bypass = tenantBypassRoles(tenant);\n return bypass.length > 0\n ? policy.or(policy.serverContext(), policy.rolesOverlap(bypass), match)\n : policy.or(policy.serverContext(), match);\n}\n\n/**\n * The rule a tenant declaration compiles to, or nothing when there is none.\n *\n * **Restrictive**, and that is the whole design. A restrictive policy is ANDed\n * with every other policy on the table, so tenancy narrows what the\n * collection's own `securityRules` allow and can never widen it. A permissive\n * one would OR with them, and a single `access: \"public\"` rule elsewhere in the\n * file would take the entire tenancy boundary off without contradicting\n * anything a reader could see.\n *\n * One rule with `operation: \"all\"` rather than four with `operations: [...]`:\n * `FOR ALL` gives Postgres the USING clause for SELECT/UPDATE/DELETE and the\n * WITH CHECK clause for INSERT/UPDATE, which is exactly the coverage wanted,\n * as one policy with one name instead of four.\n */\nexport function buildTenantSecurityRule(collection: CollectionConfig): SecurityRule | undefined {\n const tenant = getTenantConfig(collection);\n if (!tenant) return undefined;\n const expression = tenantScopeExpression(tenant);\n return {\n name: tenantPolicyName(getTableName(collection)),\n mode: \"restrictive\",\n operation: \"all\",\n condition: expression,\n check: expression\n };\n}\n\n// ── The write path ───────────────────────────────────────────────────────────\n\n/** Why a write was refused by tenancy. */\nexport interface TenantWriteRefusal {\n code: \"TENANT_REQUIRED\" | \"TENANT_MISMATCH\" | \"TENANT_IMMUTABLE\";\n /** The property, for a `violations` entry and for the message. */\n field: string;\n message: string;\n}\n\n/** What {@link resolveTenantWrite} decided. */\nexport type TenantWriteDecision =\n /** The values to write, with the tenant stamped if it was missing. */\n | { values: Record<string, unknown>; refusal?: undefined }\n | { refusal: TenantWriteRefusal; values?: undefined };\n\nexport interface TenantWriteInput {\n tenant: CollectionTenantConfig;\n /** The write's values, after defaults and hooks. */\n values: Record<string, unknown>;\n status: EntityStatus;\n /**\n * Every tenant the caller may write into.\n *\n * One entry for a claim, however many memberships they hold for the\n * membership form, and none for a caller carrying neither.\n */\n callerTenants: readonly unknown[];\n /**\n * Whether `callerTenants` is the whole list.\n *\n * A membership lookup is capped — a caller with more memberships than the\n * cap would otherwise make every write of theirs a large read. When the cap\n * is hit this is `false`, and a value that is not in the list is **let\n * through** rather than refused: the list is no longer evidence of absence,\n * and the policy's `WITH CHECK` is what actually decides. The API check is\n * an earlier, clearer refusal of the same writes, never a second authority.\n */\n callerTenantsComplete?: boolean;\n /**\n * True when tenancy does not apply to this caller — a bypass role, or the\n * trusted server context. The same set the policy lets through, so the API\n * and the database refuse the same writes.\n */\n bypass: boolean;\n /** The row's current values, on an update. */\n previousValues?: Record<string, unknown>;\n /** The collection slug, for the message. */\n slug: string;\n}\n\n/**\n * An id, however it arrived.\n *\n * A tenant field may be a `belongsTo` relation or a `reference`, and those\n * arrive over the wire as `{ id }` envelopes as often as bare ids. Comparing\n * the envelope to a bare id would refuse every correct write with\n * `TENANT_MISMATCH`, which is the most confusing possible failure — the caller\n * sent exactly the tenant they belong to.\n */\nfunction tenantIdOf(value: unknown): unknown {\n if (value === null || value === undefined) return value;\n if (typeof value === \"object\") {\n const id = (value as { id?: unknown }).id;\n return id === undefined ? value : id;\n }\n return value;\n}\n\n/**\n * Compare two tenant ids as the database will.\n *\n * Stringified, because JSON has one number type and Postgres has several: a\n * caller sending `\"42\"` for a `bigint` tenant column is writing the same row as\n * one sending `42`, and Postgres agrees after the cast. Refusing one of them\n * would be an API rule the database does not have.\n */\nfunction sameTenant(a: unknown, b: unknown): boolean {\n if (a === null || a === undefined || b === null || b === undefined) return false;\n return String(tenantIdOf(a)) === String(tenantIdOf(b));\n}\n\n/**\n * Stamp, or refuse, the tenant on a write.\n *\n * Three refusals, and each exists because the alternative lands somewhere\n * worse:\n *\n * - **`TENANT_REQUIRED`** — the caller has no tenant, or belongs to several and\n * named none. Stamping a guess would put the row in the wrong tenant; letting\n * it through would write a NULL into a `NOT NULL` column and surface as a\n * 23502 naming a column the caller never wrote.\n * - **`TENANT_MISMATCH`** — the caller named a tenant that is not theirs. The\n * database refuses this too, through the policy's `WITH CHECK`, but as a\n * 42501 \"new row violates row-level security policy\" with no mention of which\n * field or why. Refused here so the answer names the field.\n * - **`TENANT_IMMUTABLE`** — an update that moves a row to another tenant. RLS\n * would allow it whenever the caller belongs to both, and it is almost never\n * what anybody meant: it takes the row out of one tenant's history and drops\n * it into another's, with no trace on either side. A deliberate move is a\n * `bypassRoles` operation.\n *\n * A bypass caller is exempt from all three: they are trusted across tenants by\n * declaration, and stamping their write would silently confine a support\n * operator's row to whichever tenant they happen to carry.\n */\nexport function resolveTenantWrite(input: TenantWriteInput): TenantWriteDecision {\n const { tenant, values, status, callerTenants, bypass, previousValues, slug } = input;\n const field = tenant.field;\n const complete = input.callerTenantsComplete !== false;\n /** Is `value` one the caller may write? Unknown counts as yes — see `callerTenantsComplete`. */\n const callerHas = (value: unknown): boolean =>\n callerTenants.some(t => sameTenant(t, value)) || !complete;\n\n if (bypass) return { values };\n\n const provided = values[field];\n const creating = status !== \"existing\";\n\n if (!creating) {\n // An update that does not mention the field cannot move the row, and\n // the row's own tenant is already what RLS checked to let the update\n // through. Nothing to do.\n if (provided === undefined) return { values };\n\n const previous = previousValues?.[field];\n if (previous !== undefined && !sameTenant(provided, previous)) {\n return {\n refusal: {\n code: \"TENANT_IMMUTABLE\",\n field,\n message:\n `'${field}' is the tenant '${slug}' rows belong to, and a row cannot change tenant. ` +\n `This update would move it from '${String(tenantIdOf(previous))}' to ` +\n `'${String(tenantIdOf(provided))}'. Create the row in the other tenant and delete ` +\n \"this one, or perform the move with a role listed in `tenant.bypassRoles`.\"\n }\n };\n }\n if (previous === undefined && !callerHas(provided)) {\n return { refusal: mismatch(field, slug, provided, callerTenants) };\n }\n return { values };\n }\n\n if (provided === undefined || provided === null || provided === \"\") {\n if (callerTenants.length === 1) {\n return { values: { ...values, [field]: tenantIdOf(callerTenants[0]) } };\n }\n return {\n refusal: {\n code: \"TENANT_REQUIRED\",\n field,\n message: callerTenants.length === 0\n ? `'${slug}' is scoped to a tenant and this request carries none, so there is nothing ` +\n `to write into '${field}'. ` + sourceHint(tenant)\n : `'${slug}' is scoped to a tenant and this caller belongs to ${callerTenants.length} ` +\n `of them, so '${field}' cannot be inferred. Send it on the write — it must be one ` +\n \"the caller belongs to.\"\n }\n };\n }\n\n if (!callerHas(provided)) {\n return { refusal: mismatch(field, slug, provided, callerTenants) };\n }\n\n return { values };\n}\n\nfunction mismatch(\n field: string,\n slug: string,\n provided: unknown,\n callerTenants: readonly unknown[]\n): TenantWriteRefusal {\n return {\n code: \"TENANT_MISMATCH\",\n field,\n message:\n `'${field}' names tenant '${String(tenantIdOf(provided))}', which this caller does not belong ` +\n `to, so the write to '${slug}' would be refused by the database as well. ` +\n (callerTenants.length === 0\n ? \"This request carries no tenant at all.\"\n : `The caller's ${callerTenants.length === 1 ? \"tenant is\" : \"tenants are\"} ` +\n callerTenants.map(t => `'${String(tenantIdOf(t))}'`).join(\", \") + \".\")\n };\n}\n\n/** Where a caller's tenant was supposed to come from, for the 400. */\nfunction sourceHint(tenant: CollectionTenantConfig): string {\n return isTenantClaimSource(tenant.from)\n ? `The tenant comes from the '${tenant.from.claim}' claim on the caller's token; this one has no ` +\n \"such claim. Sign in, or add the claim in the custom-claims hook.\"\n : `The tenant comes from rows of '${tenant.from.membership.collection}' whose ` +\n `'${tenant.from.membership.userField}' is the caller; this caller has none.`;\n}\n","import { CollectionConfig, SecurityRule, SecurityOperation, AuthCollectionConfig, PolicyExpression, isPostgresCollectionConfig, policy } from \"@rebasepro/types\";\nimport { getTableName } from \"./relations\";\nimport { buildTenantSecurityRule } from \"./tenant\";\nimport { getPolicyNamesForRules } from \"@rebasepro/utils\";\n\n/**\n * Default RLS policies injected by the schema generator.\n *\n * Rebase's enforcement model is unified: authenticated (user-context) requests\n * run under the restricted `rebase_user` role, so Postgres RLS binds *every*\n * statement — reads and writes. A collection's `securityRules` are the whole\n * authorization model. The server context (auth flows, migrations, raw\n * `rebase.sql`) runs as the owner and bypasses RLS.\n *\n * `rebase.dataAsAdmin` is **not** in that set, despite the name: it is scoped as\n * `{ uid: \"service\", roles: [\"admin\"] }`, so it runs as `rebase_user` like any\n * other caller and clears the baseline below through the *admin* arm, not the\n * server arm. Which is why `disableDefaultPolicies` plus a lone\n * `policy.serverContext()` rule locks it out too.\n *\n * Because RLS default-denies, every collection is **locked by default**: with\n * no rules, only the server context and admins can touch it. The generator\n * injects that safe baseline:\n *\n * **For every collection**\n * 1. A permissive **server-or-admin SELECT** grant.\n * 2. A permissive **server-or-admin write** grant (insert/update/delete).\n *\n * Author `securityRules` are permissive and OR together, so explicit rules only\n * *broaden* access from this locked baseline (e.g. \"users read/write their own\n * rows\").\n *\n * **For auth collections additionally**\n * 3. A permissive **self SELECT** grant (`id = rebase.uid()`), so users can read\n * their own row (profile, session bootstrap) without every app re-declaring\n * it.\n * 4. A **restrictive** admin write gate. Restrictive policies are AND'd with\n * every other policy, so a write is rejected unless the caller is an admin\n * (or the server context) — even if the author also wrote a permissive rule\n * such as \"a user may edit their own row\". Without this, a permissive owner\n * rule would let a user change their own `roles`.\n *\n * The server context is recognised as `rebase.uid() IS NULL` (`policy.serverContext()`)\n * — the built-in flows that run without a user (signup, migrations) set no user\n * GUC — which also lets the owner connection satisfy these policies even under\n * FORCE RLS. A *user* request never reaches that state: an anonymous one carries\n * `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.\n *\n * **For a collection declaring `tenant`, additionally**\n * 5. A **restrictive** tenancy gate for every operation. Same kind of thing as\n * the admin write gate and injected for the same reason: it is ANDed with\n * every other policy, so it narrows what the author's permissive rules\n * grant and can never widen them. See `./tenant.ts`.\n *\n * Opt out with `disableDefaultPolicies: true` to take full responsibility for\n * the collection's RLS. The *restrictive* rules are not part of that opt-out:\n * dropping a rule that can only remove access could express nothing but \"let\n * more people in\", which is what the flag already does by removing the grants.\n */\n// Expressed structurally (not as raw SQL) so the admin UI can evaluate it\n// exactly — the framework's most security-critical policies must be reflected\n// precisely, not left as un-evaluable raw clauses. Compiles to\n// `rebase.uid() IS NULL OR (string_to_array(rebase.roles(), ',') && ARRAY['admin'])`.\n//\n// `serverContext()`, emphatically not `not(authenticated())`: the server arm of\n// this grant must match the server context and nothing else. Anonymous visitors\n// are not signed in either, so a negated `authenticated()` would hand them the\n// server-or-admin grant on every collection's default policy.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/** Write operations that must be admin-gated by default on auth collections. */\nconst DEFAULT_GUARDED_OPS: SecurityOperation[] = [\"insert\", \"update\", \"delete\"];\n\n/** Whether a collection is flagged as an authentication collection. */\nfunction isAuthCollection(collection: CollectionConfig): boolean {\n const auth = collection.auth;\n return auth === true || (typeof auth === \"object\" && (auth as AuthCollectionConfig)?.enabled === true);\n}\n\n/** The property marked as the row id (falls back to `id`). */\nfunction getIdPropertyName(collection: CollectionConfig): string {\n for (const [name, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && (prop as { isId?: unknown }).isId) {\n return name;\n }\n }\n return \"id\";\n}\n\n/**\n * Returns the security rules that should be applied to a collection: the\n * author's explicit `securityRules` plus the framework defaults described in\n * the module doc (baseline server/admin read for all collections; self-read\n * and the admin write gate for auth collections).\n *\n * Collections that opt out via `disableDefaultPolicies` are returned unchanged.\n */\n/**\n * The restrictive write gate for an auth collection.\n *\n * Restrictive, so it is ANDed with everything else: whatever an author's\n * permissive rules allow, a write to this table still has to satisfy this too.\n * It is the only thing standing between \"users may edit their own row\" and\n * \"users may grant themselves any role\".\n */\nfunction adminWriteGate(tableName: string): SecurityRule {\n return {\n name: `${tableName}_require_admin_write`,\n mode: \"restrictive\",\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n };\n}\n\n/**\n * The restrictive tenancy policy, as a list of zero or one.\n *\n * A list so the two call sites can splice it in without a conditional, and a\n * separate function so it is obvious that it is injected on *both* paths —\n * including the `disableDefaultPolicies` one, where it is the only permissive-\n * looking thing that stays. See `./tenant.ts`.\n */\nfunction tenantRule(collection: CollectionConfig): SecurityRule[] {\n const rule = buildTenantSecurityRule(collection);\n return rule ? [rule] : [];\n}\n\nexport function getEffectiveSecurityRules(collection: CollectionConfig): SecurityRule[] {\n const explicit = [...(collection.securityRules ?? [])];\n\n const tableName = getTableName(collection);\n const injected: SecurityRule[] = [];\n\n if (isPostgresCollectionConfig(collection) && collection.disableDefaultPolicies) {\n // The opt-out drops the *permissive* defaults — the ones that grant.\n // The restrictive admin-write gate on an auth collection is not among\n // them, because it is different in kind: a restrictive policy is ANDed\n // with every other policy and can only ever remove access, so opting\n // out of it cannot express anything except \"let more people write\".\n //\n // Dropping it did exactly that. `{ disableDefaultPolicies: true,\n // securityRules: [{ operation: \"all\", ownerField: \"id\" }] }` — an\n // ordinary \"users may edit their own row\" configuration — let any\n // signed-in user set their own `roles` to `[\"admin\"]`, with no warning\n // from any boot guard, doctor check or validator.\n //\n // An author who needs a different gate can add their own restrictive\n // rule; they cannot end up with none by accident.\n // Tenancy survives the opt-out for exactly the reason the write gate\n // does: it is restrictive, so it can only ever remove access. Dropping\n // it could express nothing except \"let every tenant read every other\n // tenant's rows\", which is not a thing `disableDefaultPolicies` is for\n // — that flag is about taking over the *grants*.\n return [...explicit, ...tenantRule(collection), ...(isAuthCollection(collection)\n ? [adminWriteGate(tableName)]\n : [])];\n }\n\n // Baseline read + write: the server context and admins can always operate.\n // RLS default-denies under the user role, so without these a rule-less\n // collection would be locked to everyone — including the admin studio.\n // Author rules are permissive and broaden access from here.\n injected.push({\n name: `${tableName}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n injected.push({\n name: `${tableName}_default_admin_write`,\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n if (isAuthCollection(collection)) {\n // Self-read: a user can always read their own row.\n injected.push({\n name: `${tableName}_default_self_read`,\n operations: [\"select\"],\n condition: policy.compare(policy.field(getIdPropertyName(collection)), \"eq\", policy.authUid())\n });\n\n // Restrictive gate: AND'd with all other policies, so no permissive rule\n // (e.g. an owner \"edit your own row\" rule) can let a non-admin change\n // privileged columns like `roles`. Survives `disableDefaultPolicies` —\n // see the note above the opt-out.\n injected.push(adminWriteGate(tableName));\n }\n\n // Last, so it reads as what it is: a restriction ANDed over everything\n // above it, author rules included.\n injected.push(...tenantRule(collection));\n\n return [...explicit, ...injected];\n}\n\n/**\n * The framework defaults that {@link getEffectiveSecurityRules} would add to a\n * collection, without the author's own rules.\n *\n * These policies appear in the database under names the author never wrote, and\n * a permissive policy ORs with every other permissive policy — so someone\n * reading their `securityRules` and then the real ACL sees more access than they\n * declared. Dropping them by hand does nothing either: `db push` is declarative,\n * so the next push asserts them again. Callers use this to say, in the generated\n * DDL, which policies are injected and how to take them off.\n */\nexport function getInjectedSecurityRules(collection: CollectionConfig): SecurityRule[] {\n if (isPostgresCollectionConfig(collection) && collection.disableDefaultPolicies) {\n // Not empty for an auth collection, nor for a tenant-scoped one: both\n // restrictive rules are still injected, and the generated DDL has to\n // say so — a policy in the database that the author never wrote and\n // cannot find in this list is exactly the surprise this function exists\n // to prevent.\n return [...tenantRule(collection), ...(isAuthCollection(collection)\n ? [adminWriteGate(getTableName(collection))]\n : [])];\n }\n\n const explicitCount = (collection.securityRules ?? []).length;\n // getEffectiveSecurityRules appends the defaults after the author's rules,\n // so everything past the author's count is injected.\n return getEffectiveSecurityRules(collection).slice(explicitCount);\n}\n\n/**\n * Every policy name `rebase db push` would write for a collection.\n *\n * This is the answer to \"did the codebase produce this live policy?\", and it is\n * more than `securityRules.map(r => r.name)` for two reasons:\n *\n * - a rule without an explicit `name` compiles to `<table>_<op>_<hash>`, one\n * per operation, so comparing `rule.name` to `policyname` never matches it;\n * - the generator also injects the safe-by-default baseline\n * (`<table>_default_admin_*`), which is in no collection's `securityRules`.\n *\n * Every UI that flags drift has to get both right, and each one that derived it\n * by hand got a different subset — which is how four policies *Rebase itself\n * wrote* came to be badged as hand-written drift on every table in a project,\n * with a button offering to import them back into the codebase that produced\n * them. There is one derivation now, and this is it.\n */\nexport function getGeneratedPolicyNames(collection: CollectionConfig): Set<string> {\n return getPolicyNamesForRules(getEffectiveSecurityRules(collection), getTableName(collection));\n}\n","import {\n CollectionConfig,\n JUNCTION_PIVOT_KEY,\n PolicyExpression,\n PolicyOperand,\n Properties,\n Property,\n Relation,\n SecurityRule,\n isPostgresCollectionConfig,\n policy\n} from \"@rebasepro/types\";\nimport { getPolicyOperations } from \"@rebasepro/utils\";\nimport { getTableName } from \"./relations\";\nimport { resolveCollectionRelations } from \"./relations\";\nimport { isManyToMany } from \"@rebasepro/types\";\nimport { securityRuleToConditions } from \"./policy/securityRuleToConditions\";\n\n/**\n * RLS derivation for many-to-many junction tables.\n *\n * A `through` relation makes the generator create a table nobody declared as a\n * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind\n * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,\n * so with the endpoints locked down, any signed-up user could still read or wipe\n * every edge between them. There is also nowhere in the config to write rules\n * for a junction, so the author could not even fix it by hand.\n *\n * The architecture here is that a junction's security is *derived*, never\n * hand-written:\n *\n * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every\n * collection gets, so the invariant holds again: every table the generator\n * creates is default-deny, and rules only broaden.\n *\n * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint\n * rows are visible — two correlated `EXISTS` subqueries. The subqueries run\n * under the caller's role, so each endpoint's own RLS filters them: junction\n * visibility delegates to the endpoints' policies, whatever they become,\n * with nothing duplicated. A public blog keeps rendering its tags; a private\n * CRM's edges are exactly as hidden as its rows.\n *\n * 3. **Writes follow the owning side's update rules.** Linking or unlinking an\n * edge *is* an edit of the owning row — tagging a post is editing the post —\n * so edge writes inherit the declaring collection's explicit permissive\n * `update` rules, each wrapped in an `EXISTS` against the owning row. Where\n * a rule cannot be embedded faithfully (see below) it is dropped, so the\n * failure mode is always *too locked*, never open. Explicit **restrictive**\n * update rules are inherited as restrictive junction rules; if one of them\n * cannot be embedded, the whole derived write grant for that side is\n * suppressed — granting without the author's gate would be looser than the\n * parent itself.\n *\n * **Embeddability.** A parent rule is embedded by moving its condition inside\n * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.\n * In that scope, `field` operands bind to the parent — which is what the author\n * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind\n * to the RLS row, which is now the junction, not the parent the author wrote\n * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`\n * (equivalent to `field` outside a subquery) is rewritten to `field`; an\n * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies\n * the rule.\n *\n * Injected parent defaults are never inherited — the junction's own baseline\n * already covers the server/admin plane, and an auth collection's restrictive\n * `require_admin_write` gate exists to protect privileged parent *columns*,\n * which an edge write cannot touch. Inheriting it would stop users managing\n * e.g. their own interests through a `users_interests` junction for no gain.\n *\n * Everything flows through the shared naming machinery, so the Studio\n * recognises these policies as generated instead of offering to \"import\" them.\n */\n\n/** One side of a junction: the collection and the FK column pointing at it. */\nexport interface JunctionEndpoint {\n collection: CollectionConfig;\n /** Junction column holding this endpoint's key. */\n junctionColumn: string;\n}\n\n/** A collection that declares the `through` relation (owns the edge semantics). */\nexport interface JunctionDeclaringSide extends JunctionEndpoint {\n relation: Relation;\n}\n\nexport interface JunctionSpec {\n /** Bare table name (schema stripped). */\n table: string;\n /** Schema the junction is created in — mirrors the CREATE TABLE path. */\n schema: string;\n /** The two endpoints, in [source, target] order of the first declaring relation. */\n endpoints: [JunctionEndpoint, JunctionEndpoint];\n /** Every collection that declares a relation through this table. */\n declaringSides: JunctionDeclaringSide[];\n /**\n * The junction's own columns beyond the two keys — `through.properties`,\n * merged across every declaring side. `{}` when there are none.\n *\n * See {@link ManyToManyRelation.through} for what they are; every side that\n * names a key has to describe the same column, which is checked when the\n * specs are resolved rather than left for `CREATE TABLE` to discover.\n */\n properties: Properties;\n}\n\n// Mirrors auth-default-policies: the server context or an admin.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/**\n * Walk every collection's resolved relations and aggregate the junction tables\n * they declare. Two collections may declare the same junction from opposite\n * sides (posts→tags and tags→posts through `posts_tags`); both become\n * `declaringSides` of one spec, so derived write grants consider both.\n */\nexport function resolveJunctionSpecs(collections: CollectionConfig[]): Map<string, JunctionSpec> {\n const specs = new Map<string, JunctionSpec>();\n\n for (const collection of collections) {\n const resolved = resolveCollectionRelations(collection);\n for (const relation of Object.values(resolved)) {\n // Narrowed rather than probed: only a many-to-many has a junction,\n // and only after narrowing is `through` guaranteed complete.\n if (!isManyToMany(relation)) continue;\n\n const targetCollection: CollectionConfig | undefined = relation.target();\n if (!targetCollection) continue;\n\n const rawName = relation.through.table;\n // The CREATE TABLE path strips a schema prefix from the name but\n // still creates in \"public\"; the policies must target the same\n // table, so mirror that behaviour exactly.\n const table = rawName.includes(\".\") ? rawName.split(\".\").pop()! : rawName;\n const schema = \"public\";\n\n const source: JunctionDeclaringSide = {\n collection,\n junctionColumn: relation.through.sourceColumn,\n relation\n };\n const target: JunctionEndpoint = {\n collection: targetCollection,\n junctionColumn: relation.through.targetColumn\n };\n\n const existing = specs.get(table);\n if (!existing) {\n specs.set(table, {\n table,\n schema,\n endpoints: [source, target],\n declaringSides: [source],\n properties: mergeJunctionPayload({}, relation.through.properties, table, collection)\n });\n } else {\n // Merged whether or not this side is new: the same collection\n // can reach one junction under two relation names, and the\n // columns each of them asks for all have to exist.\n existing.properties = mergeJunctionPayload(\n existing.properties, relation.through.properties, table, collection);\n if (!existing.declaringSides.some(s => s.collection === collection)) {\n existing.declaringSides.push(source);\n }\n }\n }\n }\n\n return specs;\n}\n\n/**\n * Fold one side's `through.properties` into the junction's, refusing a\n * disagreement rather than picking a winner.\n *\n * Both ends of a link may declare it — `posts.tags` and `tags.posts` are one\n * junction — and each end may name the payload. Only one table gets created, so\n * two descriptions of `role` that are not the same description are a question\n * with no correct answer: whichever won, one of the two collections would be\n * writing through a column it does not think it has. Compared structurally, so\n * two sides that spell the same property twice (the normal case, and the one\n * the docs recommend) are fine.\n */\nfunction mergeJunctionPayload(\n into: Properties,\n incoming: Properties | undefined,\n table: string,\n collection: CollectionConfig\n): Properties {\n if (!incoming || Object.keys(incoming).length === 0) return into;\n const merged: Properties = { ...into };\n for (const [key, property] of Object.entries(incoming)) {\n const already = merged[key as keyof Properties] as Property | undefined;\n if (already && JSON.stringify(already) !== JSON.stringify(property)) {\n throw new Error(\n `The junction table \"${table}\" is declared from more than one side, and they disagree ` +\n `about the payload column \"${key}\": \"${collection.slug ?? collection.name}\" describes it ` +\n \"differently than another declaring collection does. One table is created, so both \" +\n \"`through.properties` blocks have to describe the same column — or only one side should \" +\n \"declare it.\"\n );\n }\n (merged as Record<string, Property>)[key] = property as Property;\n }\n return merged;\n}\n\n/**\n * A synthetic CollectionConfig standing in for the junction during policy\n * compilation and naming. Its two FK columns carry explicit `columnName`s so\n * `outerField` operands resolve to the exact columns the CREATE TABLE emitted,\n * whatever their casing.\n *\n * The payload columns are here too, exactly as authored. That is what lets one\n * reading of a `Property` serve the junction as well as a collection: the\n * schema planner plans these columns with the same function it plans a\n * collection's with, and the write path validates a `_pivot` against them with\n * the same validator a row's values go through. A second description of a\n * payload column anywhere is a second description that can disagree.\n */\nexport function getJunctionCollectionConfig(spec: JunctionSpec): CollectionConfig {\n const properties: Record<string, unknown> = {};\n for (const endpoint of spec.endpoints) {\n properties[endpoint.junctionColumn] = {\n type: \"string\",\n columnName: endpoint.junctionColumn\n };\n }\n // After the keys, so a payload property that collides with a key column\n // cannot quietly replace it — `checkJunctionPayload` refuses that config at\n // boot, and this ordering means the key column survives if one gets past.\n for (const [key, property] of Object.entries(spec.properties)) {\n if (key === JUNCTION_PIVOT_KEY || key in properties) continue;\n properties[key] = property;\n }\n return {\n slug: spec.table,\n name: spec.table,\n table: spec.table,\n schema: spec.schema,\n properties\n } as unknown as CollectionConfig;\n}\n\n/** The property marked as the row id (falls back to `id`). */\nfunction getIdPropertyName(collection: CollectionConfig): string {\n for (const [name, prop] of Object.entries(collection.properties ?? {})) {\n if (prop && typeof prop === \"object\" && \"isId\" in prop && (prop as { isId?: unknown }).isId) {\n return name;\n }\n }\n return \"id\";\n}\n\n/** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */\nfunction existsEndpoint(endpoint: JunctionEndpoint, extra?: PolicyExpression): PolicyExpression {\n const correlation = policy.compare(\n policy.field(getIdPropertyName(endpoint.collection)),\n \"eq\",\n policy.outerField(endpoint.junctionColumn)\n );\n return policy.existsIn({\n collection: endpoint.collection.slug,\n where: extra ? policy.and(correlation, extra) : correlation\n });\n}\n\n/**\n * Whether a parent-rule expression keeps its meaning when moved inside the\n * junction's `EXISTS` subquery — and the re-scoped copy if it does.\n *\n * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL\n * anywhere (its `{column}` placeholders would bind to the junction), or an\n * `outerField` inside a nested `existsIn` (it would bind to the junction while\n * the author meant the parent, and no operand can express \"the middle scope\").\n * Top-level `outerField`s are rewritten to `field`, which is what they meant.\n */\nexport function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {\n switch (expr.kind) {\n case \"raw\":\n return null;\n case \"and\":\n case \"or\": {\n const parts: PolicyExpression[] = [];\n for (const child of expr.operands) {\n const embedded = embedParentExpression(child, depth);\n if (!embedded) return null;\n parts.push(embedded);\n }\n return expr.kind === \"and\" ? policy.and(...parts) : policy.or(...parts);\n }\n case \"not\": {\n const embedded = embedParentExpression(expr.operand, depth);\n return embedded ? policy.not(embedded) : null;\n }\n case \"existsIn\": {\n const where = embedParentExpression(expr.where, depth + 1);\n return where ? policy.existsIn({ collection: expr.collection, where }) : null;\n }\n case \"compare\": {\n const left = embedOperand(expr.left, depth);\n const right = embedOperand(expr.right, depth);\n if (!left || !right) return null;\n return { ...expr, left, right };\n }\n default:\n // Leaf expressions with no field references (true, false,\n // serverContext, authenticated, rolesOverlap, rolesContain) are\n // position-independent.\n return expr;\n }\n}\n\n/** Re-scope an operand, or return `null` if its binding cannot be preserved. */\nfunction embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {\n if (operand.kind === \"outerField\") {\n // Outside a subquery, outerField ≡ field: the author meant their own\n // row, which after embedding is the EXISTS's joined table → field.\n if (depth === 0) return policy.field(operand.name);\n // Inside the author's own existsIn it meant the parent row; after\n // embedding it would bind to the junction. Not expressible.\n return null;\n }\n return operand;\n}\n\n/** Does the rule cover the `update` operation? */\nfunction coversUpdate(rule: SecurityRule): boolean {\n return getPolicyOperations(rule).some(op => op === \"update\" || op === \"all\");\n}\n\n/**\n * The full derived policy set for a junction table: the locked server/admin\n * baseline, the endpoint-visibility read grant, inherited write grants, and\n * inherited restrictive gates. Returns `[]` when every declaring collection set\n * `disableDefaultPolicies` — the junction is then the author's to police, and\n * stays locked (RLS is still enabled) until they write policies for it.\n */\nexport function getJunctionSecurityRules(spec: JunctionSpec): SecurityRule[] {\n if (spec.declaringSides.every(side => isPostgresCollectionConfig(side.collection) && side.collection.disableDefaultPolicies)) {\n return [];\n }\n\n const rules: SecurityRule[] = [];\n\n // 1. Locked baseline — same shape and naming as every collection's.\n rules.push({\n name: `${spec.table}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n rules.push({\n name: `${spec.table}_default_admin_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n // 2. Reads follow the endpoints: the edge is visible iff both rows are.\n // The EXISTS subqueries run under the caller's role, so each endpoint's\n // own RLS applies inside them — visibility is delegated, not copied.\n rules.push({\n name: `${spec.table}_default_edge_read`,\n operations: [\"select\"],\n condition: policy.and(\n existsEndpoint(spec.endpoints[0]),\n existsEndpoint(spec.endpoints[1])\n )\n });\n\n // 3. Writes follow the owning side's explicit update rules.\n const writeGrants: PolicyExpression[] = [];\n for (const side of spec.declaringSides) {\n const explicitRules = (isPostgresCollectionConfig(side.collection)\n ? side.collection.securityRules\n : undefined) ?? [];\n const updateRules = explicitRules.filter(coversUpdate);\n\n const permissive = updateRules.filter(r => r.mode !== \"restrictive\");\n const restrictive = updateRules.filter(r => r.mode === \"restrictive\");\n\n // Embed the restrictive gates first: if any of them cannot be carried\n // over, granting writes from this side would be looser than the parent\n // itself allows — so the whole side's grant is suppressed.\n const embeddedGates: PolicyExpression[] = [];\n let gatesEmbeddable = true;\n for (const gate of restrictive) {\n const using = securityRuleToConditions(gate).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (!embedded) {\n gatesEmbeddable = false;\n break;\n }\n embeddedGates.push(embedded);\n }\n if (!gatesEmbeddable) continue;\n\n const grants: PolicyExpression[] = [];\n for (const rule of permissive) {\n const using = securityRuleToConditions(rule).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (embedded) grants.push(embedded);\n }\n if (grants.length === 0) continue;\n\n // \"May update the owning row\": any permissive grant, AND every gate.\n const condition = embeddedGates.length > 0\n ? policy.and(policy.or(...grants), ...embeddedGates)\n : policy.or(...grants);\n\n writeGrants.push(existsEndpoint(side, condition));\n }\n\n if (writeGrants.length > 0) {\n rules.push({\n name: `${spec.table}_default_edge_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),\n check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)\n });\n }\n\n return rules;\n}\n","/* globals define,module */\n/*\nUsing a Universal Module Loader that should be browser, require, and AMD friendly\nhttp://ricostacruz.com/cheatsheets/umdjs.html\n*/\n;(function(root, factory) {\n if (typeof define === \"function\" && define.amd) {\n define(factory);\n } else if (typeof exports === \"object\") {\n module.exports = factory();\n } else {\n root.jsonLogic = factory();\n }\n}(this, function() {\n \"use strict\";\n /* globals console:false */\n\n if ( ! Array.isArray) {\n Array.isArray = function(arg) {\n return Object.prototype.toString.call(arg) === \"[object Array]\";\n };\n }\n\n /**\n * Return an array that contains no duplicates (original not modified)\n * @param {array} array Original reference array\n * @return {array} New array with no duplicates\n */\n function arrayUnique(array) {\n var a = [];\n for (var i=0, l=array.length; i<l; i++) {\n if (a.indexOf(array[i]) === -1) {\n a.push(array[i]);\n }\n }\n return a;\n }\n\n var jsonLogic = {};\n var operations = {\n \"==\": function(a, b) {\n return a == b;\n },\n \"===\": function(a, b) {\n return a === b;\n },\n \"!=\": function(a, b) {\n return a != b;\n },\n \"!==\": function(a, b) {\n return a !== b;\n },\n \">\": function(a, b) {\n return a > b;\n },\n \">=\": function(a, b) {\n return a >= b;\n },\n \"<\": function(a, b, c) {\n return (c === undefined) ? a < b : (a < b) && (b < c);\n },\n \"<=\": function(a, b, c) {\n return (c === undefined) ? a <= b : (a <= b) && (b <= c);\n },\n \"!!\": function(a) {\n return jsonLogic.truthy(a);\n },\n \"!\": function(a) {\n return !jsonLogic.truthy(a);\n },\n \"%\": function(a, b) {\n return a % b;\n },\n \"log\": function(a) {\n console.log(a); return a;\n },\n \"in\": function(a, b) {\n if (!b || typeof b.indexOf === \"undefined\") return false;\n return (b.indexOf(a) !== -1);\n },\n \"cat\": function() {\n return Array.prototype.join.call(arguments, \"\");\n },\n \"substr\": function(source, start, end) {\n if (end < 0) {\n // JavaScript doesn't support negative end, this emulates PHP behavior\n var temp = String(source).substr(start);\n return temp.substr(0, temp.length + end);\n }\n return String(source).substr(start, end);\n },\n \"+\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) + parseFloat(b, 10);\n }, 0);\n },\n \"*\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return parseFloat(a, 10) * parseFloat(b, 10);\n });\n },\n \"-\": function(a, b) {\n if (b === undefined) {\n return -a;\n } else {\n return a - b;\n }\n },\n \"/\": function(a, b) {\n return a / b;\n },\n \"min\": function() {\n return Math.min.apply(this, arguments);\n },\n \"max\": function() {\n return Math.max.apply(this, arguments);\n },\n \"merge\": function() {\n return Array.prototype.reduce.call(arguments, function(a, b) {\n return a.concat(b);\n }, []);\n },\n \"var\": function(a, b) {\n var not_found = (b === undefined) ? null : b;\n var data = this;\n if (typeof a === \"undefined\" || a===\"\" || a===null) {\n return data;\n }\n var sub_props = String(a).split(\".\");\n for (var i = 0; i < sub_props.length; i++) {\n if (data === null || data === undefined) {\n return not_found;\n }\n // Descending into data\n data = data[sub_props[i]];\n if (data === undefined) {\n return not_found;\n }\n }\n return data;\n },\n \"missing\": function() {\n /*\n Missing can receive many keys as many arguments, like {\"missing:[1,2]}\n Missing can also receive *one* argument that is an array of keys,\n which typically happens if it's actually acting on the output of another command\n (like 'if' or 'merge')\n */\n\n var missing = [];\n var keys = Array.isArray(arguments[0]) ? arguments[0] : arguments;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = jsonLogic.apply({\"var\": key}, this);\n if (value === null || value === \"\") {\n missing.push(key);\n }\n }\n\n return missing;\n },\n \"missing_some\": function(need_count, options) {\n // missing_some takes two arguments, how many (minimum) items must be present, and an array of keys (just like 'missing') to check for presence.\n var are_missing = jsonLogic.apply({\"missing\": options}, this);\n\n if (options.length - are_missing.length >= need_count) {\n return [];\n } else {\n return are_missing;\n }\n },\n };\n\n jsonLogic.is_logic = function(logic) {\n return (\n typeof logic === \"object\" && // An object\n logic !== null && // but not null\n ! Array.isArray(logic) && // and not an array\n Object.keys(logic).length === 1 // with exactly one key\n );\n };\n\n /*\n This helper will defer to the JsonLogic spec as a tie-breaker when different language interpreters define different behavior for the truthiness of primitives. E.g., PHP considers empty arrays to be falsy, but Javascript considers them to be truthy. JsonLogic, as an ecosystem, needs one consistent answer.\n\n Spec and rationale here: http://jsonlogic.com/truthy\n */\n jsonLogic.truthy = function(value) {\n if (Array.isArray(value) && value.length === 0) {\n return false;\n }\n return !! value;\n };\n\n\n jsonLogic.get_operator = function(logic) {\n return Object.keys(logic)[0];\n };\n\n jsonLogic.get_values = function(logic) {\n return logic[jsonLogic.get_operator(logic)];\n };\n\n jsonLogic.apply = function(logic, data) {\n // Does this array contain logic? Only one way to find out.\n if (Array.isArray(logic)) {\n return logic.map(function(l) {\n return jsonLogic.apply(l, data);\n });\n }\n // You've recursed to a primitive, stop!\n if ( ! jsonLogic.is_logic(logic) ) {\n return logic;\n }\n\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n var i;\n var current;\n var scopedLogic;\n var scopedData;\n var initial;\n\n // easy syntax for unary operators, like {\"var\" : \"x\"} instead of strict {\"var\" : [\"x\"]}\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n // 'if', 'and', and 'or' violate the normal rule of depth-first calculating consequents, let each manage recursion as needed.\n if (op === \"if\" || op == \"?:\") {\n /* 'if' should be called with a odd number of parameters, 3 or greater\n This works on the pattern:\n if( 0 ){ 1 }else{ 2 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else{ 4 };\n if( 0 ){ 1 }else if( 2 ){ 3 }else if( 4 ){ 5 }else{ 6 };\n\n The implementation is:\n For pairs of values (0,1 then 2,3 then 4,5 etc)\n If the first evaluates truthy, evaluate and return the second\n If the first evaluates falsy, jump to the next pair (e.g, 0,1 to 2,3)\n given one parameter, evaluate and return it. (it's an Else and all the If/ElseIf were false)\n given 0 parameters, return NULL (not great practice, but there was no Else)\n */\n for (i = 0; i < values.length - 1; i += 2) {\n if ( jsonLogic.truthy( jsonLogic.apply(values[i], data) ) ) {\n return jsonLogic.apply(values[i+1], data);\n }\n }\n if (values.length === i+1) {\n return jsonLogic.apply(values[i], data);\n }\n return null;\n } else if (op === \"and\") { // Return first falsy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( ! jsonLogic.truthy(current)) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"or\") {// Return first truthy, or last\n for (i=0; i < values.length; i+=1) {\n current = jsonLogic.apply(values[i], data);\n if ( jsonLogic.truthy(current) ) {\n return current;\n }\n }\n return current; // Last\n } else if (op === \"filter\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n // Return only the elements from the array in the first argument,\n // that return truthy when passed to the logic in the second argument.\n // For parity with JavaScript, reindex the returned array\n return scopedData.filter(function(datum) {\n return jsonLogic.truthy( jsonLogic.apply(scopedLogic, datum));\n });\n } else if (op === \"map\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData)) {\n return [];\n }\n\n return scopedData.map(function(datum) {\n return jsonLogic.apply(scopedLogic, datum);\n });\n } else if (op === \"reduce\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n initial = typeof values[2] !== \"undefined\" ? jsonLogic.apply(values[2], data) : null;\n\n if ( ! Array.isArray(scopedData)) {\n return initial;\n }\n\n return scopedData.reduce(\n function(accumulator, current) {\n return jsonLogic.apply(\n scopedLogic,\n {current: current, accumulator: accumulator}\n );\n },\n initial\n );\n } else if (op === \"all\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n // All of an empty set is false. Note, some and none have correct fallback after the for loop\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( ! jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First falsy, short circuit\n }\n }\n return true; // All were truthy\n } else if (op === \"none\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return true;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return false; // First truthy, short circuit\n }\n }\n return true; // None were truthy\n } else if (op === \"some\") {\n scopedData = jsonLogic.apply(values[0], data);\n scopedLogic = values[1];\n\n if ( ! Array.isArray(scopedData) || ! scopedData.length) {\n return false;\n }\n for (i=0; i < scopedData.length; i+=1) {\n if ( jsonLogic.truthy( jsonLogic.apply(scopedLogic, scopedData[i]) )) {\n return true; // First truthy, short circuit\n }\n }\n return false; // None were truthy\n }\n\n // Everyone else gets immediate depth-first recursion\n values = values.map(function(val) {\n return jsonLogic.apply(val, data);\n });\n\n\n // The operation is called with \"data\" bound to its \"this\" and \"values\" passed as arguments.\n // Structured commands like % or > can name formal arguments while flexible commands (like missing or merge) can operate on the pseudo-array arguments\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments\n if (operations.hasOwnProperty(op) && typeof operations[op] === \"function\") {\n return operations[op].apply(data, values);\n } else if (op.indexOf(\".\") > 0) { // Contains a dot, and not in the 0th position\n var sub_ops = String(op).split(\".\");\n var operation = operations;\n for (i = 0; i < sub_ops.length; i++) {\n if (!operation.hasOwnProperty(sub_ops[i])) {\n throw new Error(\"Unrecognized operation \" + op +\n \" (failed at \" + sub_ops.slice(0, i+1).join(\".\") + \")\");\n }\n // Descending into operations\n operation = operation[sub_ops[i]];\n }\n\n return operation.apply(data, values);\n }\n\n throw new Error(\"Unrecognized operation \" + op );\n };\n\n jsonLogic.uses_data = function(logic) {\n var collection = [];\n\n if (jsonLogic.is_logic(logic)) {\n var op = jsonLogic.get_operator(logic);\n var values = logic[op];\n\n if ( ! Array.isArray(values)) {\n values = [values];\n }\n\n if (op === \"var\") {\n // This doesn't cover the case where the arg to var is itself a rule.\n collection.push(values[0]);\n } else {\n // Recursion!\n values.forEach(function(val) {\n collection.push.apply(collection, jsonLogic.uses_data(val) );\n });\n }\n }\n\n return arrayUnique(collection);\n };\n\n jsonLogic.add_operation = function(name, code) {\n operations[name] = code;\n };\n\n jsonLogic.rm_operation = function(name) {\n delete operations[name];\n };\n\n jsonLogic.rule_like = function(rule, pattern) {\n // console.log(\"Is \". JSON.stringify(rule) . \" like \" . JSON.stringify(pattern) . \"?\");\n if (pattern === rule) {\n return true;\n } // TODO : Deep object equivalency?\n if (pattern === \"@\") {\n return true;\n } // Wildcard!\n if (pattern === \"number\") {\n return (typeof rule === \"number\");\n }\n if (pattern === \"string\") {\n return (typeof rule === \"string\");\n }\n if (pattern === \"array\") {\n // !logic test might be superfluous in JavaScript\n return Array.isArray(rule) && ! jsonLogic.is_logic(rule);\n }\n\n if (jsonLogic.is_logic(pattern)) {\n if (jsonLogic.is_logic(rule)) {\n var pattern_op = jsonLogic.get_operator(pattern);\n var rule_op = jsonLogic.get_operator(rule);\n\n if (pattern_op === \"@\" || pattern_op === rule_op) {\n // echo \"\\nOperators match, go deeper\\n\";\n return jsonLogic.rule_like(\n jsonLogic.get_values(rule, false),\n jsonLogic.get_values(pattern, false)\n );\n }\n }\n return false; // pattern is logic, rule isn't, can't be eq\n }\n\n if (Array.isArray(pattern)) {\n if (Array.isArray(rule)) {\n if (pattern.length !== rule.length) {\n return false;\n }\n /*\n Note, array order MATTERS, because we're using this array test logic to consider arguments, where order can matter. (e.g., + is commutative, but '-' or 'if' or 'var' are NOT)\n */\n for (var i = 0; i < pattern.length; i += 1) {\n // If any fail, we fail\n if ( ! jsonLogic.rule_like(rule[i], pattern[i])) {\n return false;\n }\n }\n return true; // If they *all* passed, we pass\n } else {\n return false; // Pattern is array, rule isn't\n }\n }\n\n // Not logic, not array, not a === match for rule.\n return false;\n };\n\n return jsonLogic;\n}));\n","import jsonLogic from \"json-logic-js\";\nimport {\n ArrayProperty,\n AuthState,\n ConditionContext,\n ConditionRule,\n EnumValueConfig,\n NumberProperty,\n PropertyConditions,\n Property,\n ReferenceProperty,\n StringProperty\n} from \"@rebasepro/types\";\n\n/**\n * Access a nested property from an object via dot notation.\n */\nfunction getIn(obj: Record<string, unknown> | unknown, path: string): unknown {\n if (!obj || !path) return undefined;\n return path.split(\".\").reduce((acc: unknown, part: string) => acc && (acc as Record<string, unknown>)[part], obj);\n}\n\nlet operationsRegistered = false;\n\n/**\n * Register custom JSON Logic operations for Rebase.\n * Call this once at app initialization.\n */\nexport function registerConditionOperations(): void {\n if (operationsRegistered) return;\n\n // Check if user has a specific role by ID\n jsonLogic.add_operation(\"hasRole\", function (this: ConditionContext, roleId: string) {\n return this?.user?.roles?.includes(roleId) ?? false;\n });\n\n // Check if user has any of the specified roles\n jsonLogic.add_operation(\"hasAnyRole\", function (this: ConditionContext, roleIds: string[]) {\n if (!this?.user?.roles || !Array.isArray(roleIds)) return false;\n return roleIds.some(role => this.user.roles.includes(role));\n });\n\n // Check if a timestamp is today\n jsonLogic.add_operation(\"isToday\", (timestamp: number) => {\n if (!timestamp) return false;\n const date = new Date(timestamp);\n const today = new Date();\n return date.getFullYear() === today.getFullYear() &&\n date.getMonth() === today.getMonth() &&\n date.getDate() === today.getDate();\n });\n\n // Check if a timestamp is in the past\n jsonLogic.add_operation(\"isPast\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp < Date.now();\n });\n\n // Check if a timestamp is in the future\n jsonLogic.add_operation(\"isFuture\", (timestamp: number) => {\n if (!timestamp) return false;\n return timestamp > Date.now();\n });\n\n operationsRegistered = true;\n}\n\n/**\n * Evaluate a condition against the given context.\n *\n * A condition may be stated as a literal instead of a rule — `hidden: true`\n * rather than `hidden: { \"==\": [1, 1] }` — and a literal is already its own\n * answer, so it is returned rather than handed to the evaluator.\n */\nexport function evaluateCondition(rule: ConditionRule, context: ConditionContext): unknown {\n if (typeof rule === \"boolean\") return rule;\n // Ensure operations are registered\n registerConditionOperations();\n return jsonLogic.apply(rule, context);\n}\n\n/**\n * Convert a value to a format suitable for JSON Logic evaluation.\n * Specifically handles Date objects by converting them to Unix timestamps.\n */\nfunction serializeValueForConditions(value: unknown): unknown {\n if (value === null || value === undefined) {\n return value;\n }\n\n // Handle Date objects\n if (value instanceof Date) {\n return value.getTime();\n }\n\n // Handle Firestore Timestamp-like objects (have toDate or toMillis)\n if (typeof (value as { toMillis?: () => number })?.toMillis === \"function\") {\n return (value as { toMillis: () => number }).toMillis();\n }\n if (typeof (value as { toDate?: () => Date })?.toDate === \"function\") {\n return (value as { toDate: () => Date }).toDate().getTime();\n }\n\n // Handle arrays recursively\n if (Array.isArray(value)) {\n return value.map(serializeValueForConditions);\n }\n\n // Handle plain objects recursively\n if (typeof value === \"object\") {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = serializeValueForConditions((value as Record<string, unknown>)[key]);\n }\n return result;\n }\n\n return value;\n}\n\n/**\n * Build a ConditionContext from the current property resolution context.\n */\nexport function buildConditionContext(params: {\n propertyKey?: string;\n values?: Record<string, unknown>;\n previousValues?: Record<string, unknown>;\n path: string;\n entityId?: string;\n index?: number;\n authController: AuthState;\n}): ConditionContext {\n const {\n propertyKey,\n values,\n previousValues,\n path,\n entityId,\n index,\n authController\n } = params;\n\n const user = authController.user;\n const serializedValues = serializeValueForConditions(values ?? {});\n const serializedPreviousValues = serializeValueForConditions(previousValues ?? values ?? {});\n\n return {\n values: serializedValues as Record<string, unknown>,\n previousValues: serializedPreviousValues as Record<string, unknown>,\n propertyValue: propertyKey ? getIn(serializedValues, propertyKey) : undefined,\n path,\n entityId,\n isNew: !entityId,\n index,\n user: {\n uid: user?.uid ?? \"\",\n email: user?.email ?? null,\n displayName: user?.displayName ?? null,\n photoURL: user?.photoURL ?? null,\n roles: (user?.roles ?? []).map((r: unknown) => typeof r === \"string\" ? r : (r as { id: string }).id)\n },\n now: Date.now()\n };\n}\n\n/**\n * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.\n */\n","const { getOwnPropertyNames, getOwnPropertySymbols } = Object;\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst { hasOwnProperty } = Object.prototype;\n/**\n * Combine two comparators into a single comparators.\n */\nfunction combineComparators(comparatorA, comparatorB) {\n return function isEqual(a, b, state) {\n return comparatorA(a, b, state) && comparatorB(a, b, state);\n };\n}\n/**\n * Wrap the provided `areItemsEqual` method to manage the circular state, allowing\n * for circular references to be safely included in the comparison without creating\n * stack overflows.\n */\nfunction createIsCircular(areItemsEqual) {\n return function isCircular(a, b, state) {\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') {\n return areItemsEqual(a, b, state);\n }\n const { cache } = state;\n const cachedA = cache.get(a);\n const cachedB = cache.get(b);\n if (cachedA && cachedB) {\n return cachedA === b && cachedB === a;\n }\n cache.set(a, b);\n cache.set(b, a);\n const result = areItemsEqual(a, b, state);\n cache.delete(a);\n cache.delete(b);\n return result;\n };\n}\n/**\n * Get the properties to strictly examine, which include both own properties that are\n * not enumerable and symbol properties.\n */\nfunction getStrictProperties(object) {\n const symbols = getOwnPropertySymbols(object);\n return symbols.length\n ? getOwnPropertyNames(object).concat(symbols)\n : getOwnPropertyNames(object);\n}\n/**\n * Whether the object contains the property passed as an own property.\n */\nconst hasOwn = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.hasOwn || ((object, property) => hasOwnProperty.call(object, property));\n\nconst PREACT_VNODE = '__v';\nconst PREACT_OWNER = '__o';\nconst REACT_OWNER = '_owner';\nconst { getOwnPropertyDescriptor, keys } = Object;\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevalue) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`) or both are `NaN`.\n *\n * @note\n * When available in the environment, this is just a re-export of the global\n * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) method.\n */\nconst sameValueEqual = \n// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\nObject.is\n || function sameValueEqual(a, b) {\n return a === b ? a !== 0 || 1 / a === 1 / b : a !== a && b !== b;\n };\n/**\n * Whether the values passed are equal based on a [SameValue](https://262.ecma-international.org/7.0/#sec-samevaluezero) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`), both are `NaN`, or both\n * are either positive or negative zero.\n */\nfunction sameValueZeroEqual(a, b) {\n return a === b || (a !== a && b !== b);\n}\n/**\n * Whether the values passed are equal based on a\n * [Strict Equality Comparison](https://262.ecma-international.org/7.0/#sec-strict-equality-comparison) basis.\n * Simplified, this maps to if the two values are referentially equal to one another (`a === b`).\n *\n * @note\n * This is mainly available as a convenience function, such as being a default when a function to determine equality between\n * two objects is used.\n */\nfunction strictEqual(a, b) {\n return a === b;\n}\n/**\n * Whether the array buffers are equal in value.\n */\nfunction areArrayBuffersEqual(a, b) {\n return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b));\n}\n/**\n * Whether the arrays are equal in value.\n */\nfunction areArraysEqual(a, b, state) {\n let index = a.length;\n if (b.length !== index) {\n return false;\n }\n while (index-- > 0) {\n if (!state.equals(a[index], b[index], index, index, a, b, state)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the dataviews are equal in value.\n */\nfunction areDataViewsEqual(a, b) {\n return (a.byteLength === b.byteLength\n && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)));\n}\n/**\n * Whether the dates passed are equal in value.\n */\nfunction areDatesEqual(a, b) {\n return sameValueEqual(a.getTime(), b.getTime());\n}\n/**\n * Whether the errors passed are equal in value.\n */\nfunction areErrorsEqual(a, b) {\n return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack;\n}\n/**\n * Whether the `Map`s are equal in value.\n */\nfunction areMapsEqual(a, b, state) {\n const size = a.size;\n if (size !== b.size) {\n return false;\n }\n if (!size) {\n return true;\n }\n const matchedIndices = new Uint8Array(size);\n const aIterable = a.entries();\n let aResult;\n let bResult;\n let index = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n const bIterable = b.entries();\n let hasMatch = 0;\n let matchIndex = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n if (matchedIndices[matchIndex]) {\n matchIndex++;\n continue;\n }\n const aEntry = aResult.value;\n const bEntry = bResult.value;\n if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state)\n && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) {\n hasMatch = matchedIndices[matchIndex] = 1;\n break;\n }\n matchIndex++;\n }\n if (!hasMatch) {\n return false;\n }\n index++;\n }\n return true;\n}\n/**\n * Whether the objects are equal in value.\n */\nfunction areObjectsEqual(a, b, state) {\n const properties = keys(a);\n let index = properties.length;\n if (keys(b).length !== index) {\n return false;\n }\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n if (!isPropertyEqual(a, b, state, properties[index])) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the objects are equal in value with strict property checking.\n */\nfunction areObjectsEqualStrict(a, b, state) {\n const properties = getStrictProperties(a);\n let index = properties.length;\n if (getStrictProperties(b).length !== index) {\n return false;\n }\n let property;\n let descriptorA;\n let descriptorB;\n // Decrementing `while` showed faster results than either incrementing or\n // decrementing `for` loop and than an incrementing `while` loop. Declarative\n // methods like `some` / `every` were not used to avoid incurring the garbage\n // cost of anonymous callbacks.\n while (index-- > 0) {\n property = properties[index];\n if (!isPropertyEqual(a, b, state, property)) {\n return false;\n }\n descriptorA = getOwnPropertyDescriptor(a, property);\n descriptorB = getOwnPropertyDescriptor(b, property);\n if ((descriptorA || descriptorB)\n && (!descriptorA\n || !descriptorB\n || descriptorA.configurable !== descriptorB.configurable\n || descriptorA.enumerable !== descriptorB.enumerable\n || descriptorA.writable !== descriptorB.writable)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the primitive wrappers passed are equal in value.\n */\nfunction arePrimitiveWrappersEqual(a, b) {\n return sameValueEqual(a.valueOf(), b.valueOf());\n}\n/**\n * Whether the regexps passed are equal in value.\n */\nfunction areRegExpsEqual(a, b) {\n return a.source === b.source && a.flags === b.flags;\n}\n/**\n * Whether the `Set`s are equal in value.\n */\nfunction areSetsEqual(a, b, state) {\n const size = a.size;\n if (size !== b.size) {\n return false;\n }\n if (!size) {\n return true;\n }\n const matchedIndices = new Uint8Array(size);\n const aIterable = a.values();\n let aResult;\n let bResult;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((aResult = aIterable.next())) {\n if (aResult.done) {\n break;\n }\n const bIterable = b.values();\n let hasMatch = 0;\n let matchIndex = 0;\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n while ((bResult = bIterable.next())) {\n if (bResult.done) {\n break;\n }\n if (!matchedIndices[matchIndex]\n && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) {\n hasMatch = matchedIndices[matchIndex] = 1;\n break;\n }\n matchIndex++;\n }\n if (!hasMatch) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the TypedArray instances are equal in value.\n */\nfunction areTypedArraysEqual(a, b) {\n let index = a.length;\n if (b.length !== index || a.byteOffset !== b.byteOffset) {\n return false;\n }\n while (index-- > 0) {\n if (a[index] !== b[index]) {\n return false;\n }\n }\n return true;\n}\n/**\n * Whether the URL instances are equal in value.\n */\nfunction areUrlsEqual(a, b) {\n return (a.hostname === b.hostname\n && a.pathname === b.pathname\n && a.protocol === b.protocol\n && a.port === b.port\n && a.hash === b.hash\n && a.username === b.username\n && a.password === b.password);\n}\nfunction isPropertyEqual(a, b, state, property) {\n if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE)\n && (a.$$typeof || b.$$typeof)) {\n return true;\n }\n return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state);\n}\n\n// eslint-disable-next-line @typescript-eslint/unbound-method\nconst toString = Object.prototype.toString;\n/**\n * Create a comparator method based on the type-specific equality comparators passed.\n */\nfunction createEqualityComparator(config) {\n const supportedComparatorMap = createSupportedComparatorMap(config);\n const { areArraysEqual, areDatesEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, areRegExpsEqual, areSetsEqual, getUnsupportedCustomComparator, } = config;\n /**\n * compare the value of the two objects and return true if they are equivalent in values\n */\n return function comparator(a, b, state) {\n // If the items are strictly equal, no need to do a value comparison.\n if (a === b) {\n return true;\n }\n // If either of the items are nullish and fail the strictly equal check\n // above, then they must be unequal.\n if (a == null || b == null) {\n return false;\n }\n const type = typeof a;\n if (type !== typeof b) {\n return false;\n }\n if (type !== 'object') {\n if (type === 'number' || type === 'bigint') {\n return areNumbersEqual(a, b, state);\n }\n if (type === 'function') {\n return areFunctionsEqual(a, b, state);\n }\n // If a primitive value that is not strictly equal, it must be unequal.\n return false;\n }\n const constructor = a.constructor;\n // Checks are listed in order of commonality of use-case:\n // 1. Common complex object types (plain object, array)\n // 2. Common data values (date, regexp)\n // 3. Less-common complex object types (map, set)\n // 4. Less-common data values (promise, primitive wrappers)\n // Inherently this is both subjective and assumptive, however\n // when reviewing comparable libraries in the wild this order\n // appears to be generally consistent.\n // Constructors should match, otherwise there is potential for false positives\n // between class and subclass or custom object and POJO.\n if (constructor !== b.constructor) {\n return false;\n }\n // Try to fast-path equality checks for other complex object types in the\n // same realm to avoid capturing the string tag. Strict equality is used\n // instead of `instanceof` because it is more performant for the common\n // use-case. If someone is creating a subclass from a native class, it will be\n // handled with the string tag comparison.\n if (constructor === Object) {\n return areObjectsEqual(a, b, state);\n }\n if (constructor === Array) {\n return areArraysEqual(a, b, state);\n }\n if (constructor === Date) {\n return areDatesEqual(a, b, state);\n }\n if (constructor === RegExp) {\n return areRegExpsEqual(a, b, state);\n }\n if (constructor === Map) {\n return areMapsEqual(a, b, state);\n }\n if (constructor === Set) {\n return areSetsEqual(a, b, state);\n }\n if (constructor === Promise) {\n // Avoid tag checks for promise values, since we know if they are not referentially equal\n // then they are not equal.\n return false;\n }\n // `isArray()` works on subclasses and is cross-realm, so we can avoid capturing\n // the string tag or doing an `instanceof` in edge cases.\n if (Array.isArray(a)) {\n return areArraysEqual(a, b, state);\n }\n // Since this is a custom object, capture the string tag to determining its type.\n // This is reasonably performant in modern environments like v8 and SpiderMonkey.\n const tag = toString.call(a);\n const supportedComparator = supportedComparatorMap[tag];\n if (supportedComparator) {\n return supportedComparator(a, b, state);\n }\n const unsupportedCustomComparator = getUnsupportedCustomComparator && getUnsupportedCustomComparator(a, b, state, tag);\n if (unsupportedCustomComparator) {\n return unsupportedCustomComparator(a, b, state);\n }\n // If not matching any tags that require a specific type of comparison, then we hard-code false because\n // the only thing remaining is strict equality, which has already been compared. This is for a few reasons:\n // - Certain types that cannot be introspected (e.g., `WeakMap`). For these types, this is the only\n // comparison that can be made.\n // - For types that can be introspected but do not have an objective definition of what\n // equality is (`Error`, etc.), the subjective decision is to be conservative and strictly compare.\n // In all cases, these decisions should be reevaluated based on changes to the language and\n // common development practices.\n return false;\n };\n}\n/**\n * Create the configuration object used for building comparators.\n */\nfunction createEqualityComparatorConfig({ circular, createCustomConfig, strict, }) {\n let config = {\n areArrayBuffersEqual,\n areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual,\n areDataViewsEqual,\n areDatesEqual: areDatesEqual,\n areErrorsEqual: areErrorsEqual,\n areFunctionsEqual: strictEqual,\n areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual,\n areNumbersEqual: sameValueEqual,\n areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual,\n arePrimitiveWrappersEqual: arePrimitiveWrappersEqual,\n areRegExpsEqual: areRegExpsEqual,\n areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual,\n areTypedArraysEqual: strict\n ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict)\n : areTypedArraysEqual,\n areUrlsEqual: areUrlsEqual,\n getUnsupportedCustomComparator: undefined,\n };\n if (createCustomConfig) {\n config = Object.assign({}, config, createCustomConfig(config));\n }\n if (circular) {\n const areArraysEqual = createIsCircular(config.areArraysEqual);\n const areMapsEqual = createIsCircular(config.areMapsEqual);\n const areObjectsEqual = createIsCircular(config.areObjectsEqual);\n const areSetsEqual = createIsCircular(config.areSetsEqual);\n config = Object.assign({}, config, {\n areArraysEqual,\n areMapsEqual,\n areObjectsEqual,\n areSetsEqual,\n });\n }\n return config;\n}\n/**\n * Default equality comparator pass-through, used as the standard `isEqual` creator for\n * use inside the built comparator.\n */\nfunction createInternalEqualityComparator(compare) {\n return function (a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) {\n return compare(a, b, state);\n };\n}\n/**\n * Create the `isEqual` function used by the consuming application.\n */\nfunction createIsEqual({ circular, comparator, createState, equals, strict }) {\n if (createState) {\n return function isEqual(a, b) {\n const { cache = circular ? new WeakMap() : undefined, meta } = createState();\n return comparator(a, b, {\n cache,\n equals,\n meta,\n strict,\n });\n };\n }\n if (circular) {\n return function isEqual(a, b) {\n return comparator(a, b, {\n cache: new WeakMap(),\n equals,\n meta: undefined,\n strict,\n });\n };\n }\n const state = {\n cache: undefined,\n equals,\n meta: undefined,\n strict,\n };\n return function isEqual(a, b) {\n return comparator(a, b, state);\n };\n}\n/**\n * Create a map of `toString()` values to their respective handlers for `tag`-based lookups.\n */\nfunction createSupportedComparatorMap({ areArrayBuffersEqual, areArraysEqual, areDataViewsEqual, areDatesEqual, areErrorsEqual, areFunctionsEqual, areMapsEqual, areNumbersEqual, areObjectsEqual, arePrimitiveWrappersEqual, areRegExpsEqual, areSetsEqual, areTypedArraysEqual, areUrlsEqual, }) {\n return {\n '[object Arguments]': areObjectsEqual,\n '[object Array]': areArraysEqual,\n '[object ArrayBuffer]': areArrayBuffersEqual,\n '[object AsyncGeneratorFunction]': areFunctionsEqual,\n '[object BigInt]': areNumbersEqual,\n '[object BigInt64Array]': areTypedArraysEqual,\n '[object BigUint64Array]': areTypedArraysEqual,\n '[object Boolean]': arePrimitiveWrappersEqual,\n '[object DataView]': areDataViewsEqual,\n '[object Date]': areDatesEqual,\n // If an error tag, it should be tested explicitly. Like RegExp, the properties are not\n // enumerable, and therefore will give false positives if tested like a standard object.\n '[object Error]': areErrorsEqual,\n '[object Float16Array]': areTypedArraysEqual,\n '[object Float32Array]': areTypedArraysEqual,\n '[object Float64Array]': areTypedArraysEqual,\n '[object Function]': areFunctionsEqual,\n '[object GeneratorFunction]': areFunctionsEqual,\n '[object Int8Array]': areTypedArraysEqual,\n '[object Int16Array]': areTypedArraysEqual,\n '[object Int32Array]': areTypedArraysEqual,\n '[object Map]': areMapsEqual,\n '[object Number]': arePrimitiveWrappersEqual,\n '[object Object]': (a, b, state) => \n // The exception for value comparison is custom `Promise`-like class instances. These should\n // be treated the same as standard `Promise` objects, which means strict equality, and if\n // it reaches this point then that strict equality comparison has already failed.\n typeof a.then !== 'function' && typeof b.then !== 'function' && areObjectsEqual(a, b, state),\n // For RegExp, the properties are not enumerable, and therefore will give false positives if\n // tested like a standard object.\n '[object RegExp]': areRegExpsEqual,\n '[object Set]': areSetsEqual,\n '[object String]': arePrimitiveWrappersEqual,\n '[object URL]': areUrlsEqual,\n '[object Uint8Array]': areTypedArraysEqual,\n '[object Uint8ClampedArray]': areTypedArraysEqual,\n '[object Uint16Array]': areTypedArraysEqual,\n '[object Uint32Array]': areTypedArraysEqual,\n };\n}\n\n/**\n * Whether the items passed are deeply-equal in value.\n */\nconst deepEqual = createCustomEqual();\n/**\n * Whether the items passed are deeply-equal in value based on strict comparison.\n */\nconst strictDeepEqual = createCustomEqual({ strict: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references.\n */\nconst circularDeepEqual = createCustomEqual({ circular: true });\n/**\n * Whether the items passed are deeply-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularDeepEqual = createCustomEqual({\n circular: true,\n strict: true,\n});\n/**\n * Whether the items passed are shallowly-equal in value.\n */\nconst shallowEqual = createCustomEqual({\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value based on strict comparison\n */\nconst strictShallowEqual = createCustomEqual({\n strict: true,\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references.\n */\nconst circularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueEqual,\n});\n/**\n * Whether the items passed are shallowly-equal in value, including circular references,\n * based on strict comparison.\n */\nconst strictCircularShallowEqual = createCustomEqual({\n circular: true,\n createInternalComparator: () => sameValueEqual,\n strict: true,\n});\n/**\n * Create a custom equality comparison method.\n *\n * This can be done to create very targeted comparisons in extreme hot-path scenarios\n * where the standard methods are not performant enough, but can also be used to provide\n * support for legacy environments that do not support expected features like\n * `RegExp.prototype.flags` out of the box.\n */\nfunction createCustomEqual(options = {}) {\n const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false, } = options;\n const config = createEqualityComparatorConfig(options);\n const comparator = createEqualityComparator(config);\n const equals = createCustomInternalComparator\n ? createCustomInternalComparator(comparator)\n : createInternalEqualityComparator(comparator);\n return createIsEqual({ circular, comparator, createState, equals, strict });\n}\n\nexport { circularDeepEqual, circularShallowEqual, createCustomEqual, deepEqual, sameValueEqual, sameValueZeroEqual, shallowEqual, strictCircularDeepEqual, strictCircularShallowEqual, strictDeepEqual, strictEqual, strictShallowEqual };\n","import {\n DataSourceDefinition,\n ResolvedDataSource,\n DEFAULT_DATA_SOURCE_KEY,\n getDataSourceCapabilities\n} from \"@rebasepro/types\";\n\n/**\n * The subset of a collection needed to resolve its data source. Accepting a\n * structural type (rather than the full `CollectionConfig`) keeps this usable\n * from anywhere — frontend router, backend registry, editor — without coupling\n * to the collection union.\n */\nexport interface DataSourceResolvable {\n /** Preferred routing key. */\n dataSource?: string;\n /** Engine type discriminant (set on variant collection types). */\n engine?: string;\n /** Within-engine instance. */\n databaseId?: string;\n}\n\n/** A lookup of data-source definitions by key. */\nexport type DataSourceRegistry = Record<string, DataSourceDefinition>;\n\n/**\n * Build a keyed registry from a list of {@link DataSourceDefinition}s.\n * Later entries win on key collision.\n */\nexport function createDataSourceRegistry(definitions?: DataSourceDefinition[]): DataSourceRegistry {\n const registry: DataSourceRegistry = {};\n for (const def of definitions ?? []) {\n registry[def.key] = def;\n }\n return registry;\n}\n\n/**\n * Resolve the effective data source for a collection — the single source of\n * truth shared by the frontend router, the backend driver registry, and the\n * editor's capability lookups.\n *\n * Resolution order:\n * 1. The routing **key** is `collection.dataSource`, else\n * {@link DEFAULT_DATA_SOURCE_KEY}.\n * 2. If a definition is registered for that key, it provides `engine`,\n * `transport`, and `databaseId`.\n * 3. Otherwise values are synthesized: `engine` from `collection.engine`\n * (or the key, or `\"postgres\"`), `transport` defaults to `\"server\"`,\n * and `databaseId` from the collection.\n *\n * `capabilities` are always derived from the resolved `engine`, so two\n * data sources sharing an engine share capabilities.\n *\n * @param collection the collection (or any object carrying the routing fields)\n * @param registry optional registry of declared data sources\n */\nexport function resolveDataSource(\n collection: DataSourceResolvable | undefined,\n registry?: DataSourceRegistry\n): ResolvedDataSource {\n const key = collection?.dataSource ?? DEFAULT_DATA_SOURCE_KEY;\n const def = registry?.[key];\n\n const engine = def?.engine\n ?? collection?.engine\n ?? (key !== DEFAULT_DATA_SOURCE_KEY ? key : \"postgres\");\n\n const transport = def?.transport ?? \"server\";\n const databaseId = collection?.databaseId ?? def?.databaseId;\n\n return {\n key,\n engine,\n transport,\n databaseId,\n capabilities: getDataSourceCapabilities(engine)\n };\n}\n\n/**\n * Does a SQL toolchain own this collection's storage?\n *\n * \"Owns the storage\" means: something generates a table for it, pushes that\n * table to a database, plans its RLS policies, and reports it as drifted when\n * the two disagree. That is true of a Postgres collection and false of a\n * Firestore or MongoDB one, whose documents live in a store Rebase never\n * migrates — and the two were never told apart. Every stage of the SQL\n * toolchain took \"the collections\" to mean *all* of them, so a Firestore\n * collection declared next to the Postgres ones got a `pgTable` in the\n * generated schema, a `CREATE TABLE` at boot, RLS policies, and a place in the\n * `db push` include list — where its name shielding a same-named real table\n * from Atlas's exclude list is the one that can lose data.\n *\n * The answer is the resolved engine's {@link DataSourceCapabilities}, not a\n * name check: an engine registered through `registerDataSourceCapabilities`\n * gets the same treatment as the built-in ones.\n *\n * Deliberately answers **true** for an engine nobody has heard of. Build-time\n * tooling (the CLI, the schema generator) has no data-source registry to\n * resolve a `dataSource` key against, so an unknown key resolves to an unknown\n * engine — and the cost of the two mistakes is not symmetric. Wrongly\n * including a collection generates a table nothing writes to; wrongly excluding\n * one silently stops generating a table the app is serving from. Declare\n * `engine` on a collection that is not SQL-backed and this is exact.\n */\nexport function isRelationalCollection(\n collection: DataSourceResolvable | undefined,\n registry?: DataSourceRegistry\n): boolean {\n // The collection's own `engine` wins over a registered definition's. That\n // is the opposite of {@link resolveDataSource}'s precedence, deliberately:\n // there a definition describes where the data *goes*, so it should override;\n // here the question is what the author said this collection is, and a\n // collection declaring `engine: \"firestore\"` with no `dataSource` must not\n // come back as the default source's engine and be handed a table.\n const engine = collection?.engine\n ?? (collection?.dataSource ? resolveDataSource(collection, registry).engine : undefined);\n return getDataSourceCapabilities(engine).supportsRelations;\n}\n\n/**\n * The subset of `collections` a SQL toolchain owns — see\n * {@link isRelationalCollection}.\n *\n * Every stage that generates SQL from collections starts by calling this, so\n * the rule lives in one place rather than being re-decided per generator. It\n * keeps the input order.\n */\nexport function relationalCollections<C extends DataSourceResolvable>(\n collections: readonly C[],\n registry?: DataSourceRegistry\n): C[] {\n return collections.filter(collection => isRelationalCollection(collection, registry));\n}\n","import {\n ArrayProperty,\n CollectionCallbacks,\n EngineProperties,\n CollectionConfig,\n getDataSourceCapabilities,\n getDeclaredSubcollections,\n NumberProperty,\n Properties,\n Property,\n Relation,\n RelationProperty,\n StringProperty\n} from \"@rebasepro/types\";\nimport { deepEqual } from \"fast-equals\";\n\nimport {\n enumToObjectEntries,\n findRelation,\n getSubcollections,\n getTableName,\n resolveCollectionRelations,\n resolveRelation\n} from \"../util\";\nimport { deepClone, mergeDeep, removeFunctions } from \"@rebasepro/utils\";\nimport { DataSourceRegistry, resolveDataSource } from \"../data/resolveDataSource\";\n\nexport class CollectionRegistry {\n\n /**\n * Declared data sources, used during normalization to resolve each\n * collection's engine (so `dataSource`-only collections get the right\n * capabilities). Empty by default.\n */\n private dataSources: DataSourceRegistry = {};\n\n /**\n * Global lifecycle callbacks applied to every collection.\n * Runs on all data paths (REST, WebSocket, `rebase.dataAsAdmin`).\n * Execution order: global → collection → property callbacks.\n */\n private _globalCallbacks?: CollectionCallbacks;\n\n /**\n * Set global lifecycle callbacks that apply to every collection.\n * Typically called once during backend initialization.\n */\n setGlobalCallbacks(callbacks: CollectionCallbacks): void {\n this._globalCallbacks = callbacks;\n }\n\n /**\n * Get the currently registered global callbacks, if any.\n */\n getGlobalCallbacks(): CollectionCallbacks | undefined {\n return this._globalCallbacks;\n }\n\n // Normalized runtime layer (used by Data Grid / UI)\n private collectionsByTableName = new Map<string, CollectionConfig>();\n private collectionsBySlug = new Map<string, CollectionConfig>();\n private rootCollections: CollectionConfig[] = [];\n private cachedCollectionsList: CollectionConfig[] | null = null;\n\n // Raw configuration layer (used by Collection Editor AST generator)\n private rawCollectionsByTableName = new Map<string, CollectionConfig>();\n private rawCollectionsBySlug = new Map<string, CollectionConfig>();\n private rawRootCollections: CollectionConfig[] = [];\n private cachedRawCollectionsList: CollectionConfig[] | null = null;\n\n // Entity of raw input for idempotency check — compared BEFORE normalization\n // to avoid the issue where normalization creates new objects that always fail equality.\n private lastRawInputEntity: ReturnType<typeof removeFunctions>[] | null = null;\n\n constructor(collections?: CollectionConfig[], dataSources?: DataSourceRegistry) {\n if (dataSources) this.dataSources = dataSources;\n if (collections) {\n this.registerMultiple(collections);\n }\n }\n\n /**\n * Provide the declared data sources used to resolve each collection's\n * engine during normalization. Set this before registering collections.\n * Returns true if the registry changed (callers may re-register).\n */\n setDataSources(dataSources: DataSourceRegistry): boolean {\n if (deepEqual(this.dataSources, dataSources)) return false;\n this.dataSources = dataSources ?? {};\n return true;\n }\n\n reset() {\n this.collectionsByTableName.clear();\n this.collectionsBySlug.clear();\n this.rootCollections = [];\n this.cachedCollectionsList = null;\n\n this.rawCollectionsByTableName.clear();\n this.rawCollectionsBySlug.clear();\n this.rawRootCollections = [];\n this.cachedRawCollectionsList = null;\n }\n\n /**\n * Registers a collection and its subcollections recursively.\n * Returns true if the collections have changed, false otherwise.\n *\n * Idempotent: compares the raw input (before normalization) against a stored\n * entity. Only re-normalizes and re-registers when the raw input actually changed.\n * @param collections\n */\n registerMultiple(collections: CollectionConfig[]): boolean {\n // Compare raw input BEFORE normalization to detect actual changes.\n // This avoids the old issue where normalization creates new objects\n // that always fail deep-equal even when the source data is identical.\n const rawEntity = collections.map(c => removeFunctions(c));\n if (this.lastRawInputEntity && deepEqual(this.lastRawInputEntity, rawEntity)) {\n return false;\n }\n\n this.reset();\n // Phase 0: Populate maps with raw collections first for string target resolution\n collections.forEach((c) => {\n if (c.slug) {\n this.collectionsBySlug.set(c.slug, c);\n }\n this.collectionsByTableName.set(getTableName(c), c);\n });\n\n const normalizedCollections = collections.map(c => this.normalizeCollection({ ...c }));\n\n // Phase 1: Register all top-level collections first (without recursion).\n // This ensures that injected entityViews (e.g. History tab) are preserved.\n // Without this, _registerRecursively could register a relation-target collection\n // (e.g. Tags from Posts.relations) using the raw module object (without injected views)\n // before the top-level Tags collection (with injected views) gets its turn.\n normalizedCollections.forEach((c, index) => {\n const raw = deepClone(collections[index]);\n this.rootCollections.push(c);\n this.rawRootCollections.push(raw);\n\n const normalized = this.normalizeCollection(c);\n this.collectionsByTableName.set(getTableName(normalized), normalized);\n this.rawCollectionsByTableName.set(getTableName(raw), raw);\n if (normalized.slug) {\n this.collectionsBySlug.set(normalized.slug, normalized);\n }\n if (raw.slug) {\n this.rawCollectionsBySlug.set(raw.slug, raw);\n }\n });\n\n // Phase 2: Now recurse into subcollections (relations, etc.)\n normalizedCollections.forEach((c) => {\n const subcollections = getSubcollections(c);\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n });\n\n // Store the entity for future comparisons\n this.lastRawInputEntity = rawEntity;\n\n return true;\n }\n\n register(collection: CollectionConfig, rawCollection?: CollectionConfig) {\n const raw = rawCollection ? deepClone(rawCollection) : deepClone(collection);\n\n this.rootCollections.push(collection);\n this.rawRootCollections.push(raw);\n\n this._registerRecursively(collection, raw);\n }\n\n private _registerRecursively(collection: CollectionConfig, rawCollection: CollectionConfig) {\n if (this.collectionsByTableName.has(getTableName(collection))) {\n return;\n }\n\n const normalizedCollection = this.normalizeCollection(collection);\n this.collectionsByTableName.set(getTableName(normalizedCollection), normalizedCollection);\n this.rawCollectionsByTableName.set(getTableName(rawCollection), rawCollection);\n\n if (normalizedCollection.slug) {\n this.collectionsBySlug.set(normalizedCollection.slug, normalizedCollection);\n }\n if (rawCollection.slug) {\n this.rawCollectionsBySlug.set(rawCollection.slug, rawCollection);\n }\n\n // Use the normalized collection for subcollection discovery so that\n // both inline-extracted and explicit relations are considered.\n const subcollections = getSubcollections(normalizedCollection);\n\n if (subcollections && subcollections.length > 0) {\n subcollections.forEach((subCollection) => {\n if (!subCollection) return;\n // Spread to avoid mutating the original target() return value\n this._registerRecursively(this.normalizeCollection({ ...subCollection }), deepClone(subCollection));\n });\n }\n }\n\n public normalizeCollection(collection: CollectionConfig): CollectionConfig {\n // Work on a shallow copy to avoid mutating the caller's reference.\n // This is critical for idempotency (the raw input must not be changed)\n // and for preventing mutation of module-level collection singletons.\n const result = { ...collection } as CollectionConfig;\n\n // 0. Resolve and stamp `dataSource` and `engine` on the normalized copy.\n // After this block every normalized collection has both fields set,\n // so downstream code can read them directly without calling\n // `resolveDataSource()`. Only the normalized layer is affected —\n // the raw layer used by the collection editor keeps the author's\n // original fields.\n {\n const resolved = resolveDataSource(result, this.dataSources);\n if (!result.dataSource) (result as { dataSource?: string }).dataSource = resolved.key;\n if (!result.engine) (result as { engine?: string }).engine = resolved.engine;\n }\n\n // Relations are left exactly as authored.\n //\n // This used to hoist every inline relation property into\n // `collection.relations`, merge it with the declared ones, and run each\n // through `sanitizeRelation` — a pass that guessed at missing fields and\n // fell back to the raw relation when it threw. `resolveCollectionRelations`\n // now reads both sources itself and defaults deterministically, so there\n // is nothing to hoist, nothing to merge and nothing to guess.\n //\n // The hoisting also had a defect worth not reinstating: it flattened\n // relations declared inside a `map` up to the collection's top level,\n // where they became child-view tabs keyed by the inner property key.\n\n // Stamp each relation property with its resolved relation.\n const properties: Properties = this.normalizeProperties(result.properties, result);\n result.properties = properties as EngineProperties;\n\n // `childCollections` is deliberately NOT populated here.\n //\n // It used to be, from the same many-relations `getEntityChildViews`\n // reads — but stamped with the *target's* slug rather than the relation\n // key, and then cached onto the collection, so the registry's version\n // shadowed the correct one for every consumer downstream. Deriving on\n // read leaves one implementation and keeps `childCollections` meaning\n // what it documents: a custom driver's explicit override.\n return result;\n }\n\n private normalizeProperties(properties: Properties, collection: CollectionConfig): Properties {\n const newProperties: Properties = {};\n for (const key in properties) {\n newProperties[key] = this.normalizeProperty(key, properties[key], collection);\n }\n return newProperties;\n }\n\n private normalizeProperty(key: string, property: Property, collection: CollectionConfig): Property {\n const newProperty = { ...property };\n\n if (newProperty.type === \"map\" && newProperty.properties) {\n newProperty.properties = this.normalizeProperties(newProperty.properties, collection);\n } else if (newProperty.type === \"array\") {\n // Cast to get a properly typed mutable reference\n const arrayProp = newProperty as ArrayProperty;\n if (arrayProp.of) {\n if (Array.isArray(arrayProp.of)) {\n (arrayProp as { of: Property | Property[] }).of = arrayProp.of.map((p, i) => this.normalizeProperty(`${key}[${i}]`, p, collection));\n } else {\n arrayProp.of = this.normalizeProperty(`${key}.of`, arrayProp.of, collection);\n }\n } else if (arrayProp.oneOf && arrayProp.oneOf.properties) {\n arrayProp.oneOf.properties = this.normalizeProperties(arrayProp.oneOf.properties, collection);\n }\n } else if ((newProperty.type === \"string\" || newProperty.type === \"number\") && newProperty.enum) {\n const stringOrNumberProperty = newProperty as StringProperty | NumberProperty;\n if (typeof stringOrNumberProperty.enum === \"object\" && !Array.isArray(stringOrNumberProperty.enum)) {\n stringOrNumberProperty.enum = enumToObjectEntries(stringOrNumberProperty.enum)?.filter((value) => value && (value.id || value.id === 0) && value.label) ?? [];\n }\n } else if (newProperty.type === \"relation\") {\n const relationProperty = newProperty as RelationProperty;\n\n // A property either declares its link inline, or names one the\n // collection declares. Resolve the first directly; look the second\n // up by name. Either way the property carries the fully-defaulted\n // relation, so no consumer has to re-derive it.\n if (relationProperty.relation) {\n relationProperty.resolvedRelation = resolveRelation(relationProperty.relation, collection, key);\n } else {\n const declared = resolveCollectionRelations(collection)[key];\n if (declared) {\n relationProperty.resolvedRelation = declared;\n } else {\n // The boot validator refuses this shape outright, naming the\n // property and both ways to fix it — see\n // `checkRelationPropertiesResolve` in @rebasepro/server. This\n // stays as the second line, for the registries built outside\n // a validated boot: the panel's, and the collection editor's\n // preview of a config being written.\n //\n // Still `console.warn`. There is no logger below\n // @rebasepro/server, and this package runs in the browser as\n // well as on the server, so acquiring one is a design\n // decision rather than a substitution.\n console.warn(\n `Relation property '${key}' on '${collection.slug}' names no relation: it has no ` +\n \"`relation` block, and the collection's `relations` array has no entry called \" +\n `'${key}'. The field will render no picker, generate no foreign key, and return ` +\n \"nothing from `include()`.\"\n );\n }\n }\n }\n\n return newProperty;\n }\n\n get(path: string): CollectionConfig | undefined {\n // First try slug lookup\n const bySlug = this.collectionsBySlug.get(path);\n if (bySlug) return bySlug;\n\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.collectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n // Fallback to table name lookup\n return this.collectionsByTableName.get(path);\n }\n\n /**\n * Gets the pristine, un-normalized collection exactly as it was provided.\n * Useful for the AST editor so it doesn't accidentally serialize injected metadata back to disk.\n */\n getRaw(path: string): CollectionConfig | undefined {\n const bySlug = this.rawCollectionsBySlug.get(path);\n if (bySlug) return bySlug;\n\n // Fallback: normalize hyphens → underscores (URLs use kebab-case, slugs use snake_case)\n if (path.includes(\"-\")) {\n const normalized = path.replace(/-/g, \"_\");\n const byNormalized = this.rawCollectionsBySlug.get(normalized);\n if (byNormalized) return byNormalized;\n }\n\n return this.rawCollectionsByTableName.get(path);\n }\n\n /**\n * Get collection by resolving multi-segment paths through relations\n * e.g., \"authors/70/posts\" resolves to the posts collection\n */\n getCollectionByPath(collectionPath: string): CollectionConfig | undefined {\n // Handle simple single collection path\n if (!collectionPath.includes(\"/\")) {\n return this.get(collectionPath);\n }\n\n // Handle multi-segment paths by resolving through relations\n const pathSegments = collectionPath.split(\"/\").filter(p => p);\n\n if (pathSegments.length < 3 || pathSegments.length % 2 === 0) {\n throw new Error(`Invalid relation path: ${collectionPath}. Expected format: collection/id/relation or collection/id/relation/id/relation`);\n }\n\n // Start with the root collection\n const rootCollectionPath = pathSegments[0];\n let currentCollection = this.get(rootCollectionPath);\n\n if (!currentCollection) {\n throw new Error(`Root collection not found: ${rootCollectionPath}`);\n }\n\n // Navigate through the path using relations\n for (let i = 2; i < pathSegments.length; i += 2) {\n const relationKey = pathSegments[i];\n\n // Get relations for current collection\n if (!getDataSourceCapabilities(currentCollection.engine).supportsRelations) {\n throw new Error(`Relation path navigation requires a collection that supports relations, but '${currentCollection.slug}' uses engine '${currentCollection.engine}'`);\n }\n const resolvedRelations = resolveCollectionRelations(currentCollection);\n const relation = findRelation(resolvedRelations, relationKey);\n\n if (!relation) {\n throw new Error(`Relation '${relationKey}' not found in collection '${currentCollection.slug}'`);\n }\n\n // Move to the target collection.\n //\n // By the relation's own target, never by a slug lookup on its\n // *name*: `this.get(relation.relationName)` searches the global slug\n // map, so a relation named `people` that targets `notes` resolved to\n // an unrelated root collection called `people` — and a nested write\n // then ran that collection's callbacks against its properties.\n // The registered instance is preferred, matched by table, to pick up\n // whatever normalization and injection it received.\n const target = relation.target();\n currentCollection = this.collectionsByTableName.get(getTableName(target))\n ?? this.normalizeCollection(target);\n\n // If there are more segments, continue navigation\n if (i + 1 < pathSegments.length) {\n // Skip entity ID segment\n }\n }\n\n return currentCollection;\n }\n\n getCollections(): CollectionConfig[] {\n if (!this.cachedCollectionsList) {\n this.cachedCollectionsList = Array.from(this.collectionsByTableName.values());\n }\n return this.cachedCollectionsList;\n }\n\n getRawCollections(): CollectionConfig[] {\n if (!this.cachedRawCollectionsList) {\n this.cachedRawCollectionsList = Array.from(this.rawCollectionsByTableName.values());\n }\n return this.cachedRawCollectionsList;\n }\n\n /**\n * Resolves a multi-segment path like \"products/123/locales\" and returns\n * information about the collections and entity IDs along the path\n */\n resolvePathToCollections(path: string): {\n collections: CollectionConfig[],\n entityIds: (string | number)[],\n finalCollection: CollectionConfig\n } {\n const pathSegments = path.split(\"/\").filter(p => p);\n\n if (pathSegments.length === 0) {\n throw new Error(`Invalid path: ${path}`);\n }\n\n if (pathSegments.length % 2 !== 1) {\n throw new Error(`Invalid collection path: ${path}. It must have an odd number of segments.`);\n }\n\n const collections: CollectionConfig[] = [];\n const entityIds: (string | number)[] = [];\n\n // Start with the first collection\n let currentCollection = this.get(pathSegments[0]);\n\n if (!currentCollection) {\n throw new Error(`Unknown collection path or slug: ${pathSegments[0]}`);\n }\n\n collections.push(currentCollection);\n\n // Process the rest of the path in pairs (entityId, subcollectionSlug)\n for (let i = 1; i < pathSegments.length; i += 2) {\n const entityId = pathSegments[i];\n entityIds.push(entityId);\n\n if (i + 1 < pathSegments.length) {\n const subcollectionSlug = pathSegments[i + 1];\n const subcollections: CollectionConfig[] | undefined = getSubcollections(currentCollection);\n if (!subcollections || subcollections.length === 0) {\n throw new Error(`No subcollections found for ${currentCollection.slug} in path: ${path}`);\n }\n\n const subcollection: CollectionConfig | undefined = subcollections.find(c => c.slug === subcollectionSlug);\n if (!subcollection) {\n throw new Error(`Subcollection '${subcollectionSlug}' not found in ${currentCollection.slug}`);\n }\n // The child as resolved, not whatever root collection happens to\n // share its slug. Re-looking it up globally both risked the wrong\n // collection and discarded the relation's `overrides`, which are\n // applied when the child view is built.\n currentCollection = this.normalizeCollection(subcollection);\n collections.push(currentCollection);\n }\n }\n\n return {\n collections,\n entityIds,\n finalCollection: currentCollection\n };\n }\n\n}\n\n","import { defineCollection } from \"../util/builders\";\n\n/**\n * Default users collection.\n *\n * Prepended to the developer's collections array by the admin and server.\n * Slug-based dedup (Map keyed by slug, last-write-wins) lets developers\n * override by defining their own collection with `slug: \"users\"`.\n *\n * Schema only — no `admin` block. This package is on the backend's dependency path,\n * where that field does not exist: `@rebasepro/cms-types` adds it by declaration\n * merging, and a BaaS install never installs that. The scaffolded\n * `config/collections/users.ts` carries the presentation for projects that want this\n * collection in their panel, which is also where it is editable.\n */\nexport const defaultUsersCollection = defineCollection({\n name: \"Users\",\n singularName: \"User\",\n slug: \"users\",\n auth: true,\n table: \"users\",\n schema: \"rebase\",\n securityRules: [\n { operation: \"select\",\nroles: [\"admin\"] },\n { operations: [\"insert\", \"update\", \"delete\"],\nroles: [\"admin\"] }\n ],\n properties: {\n id: {\n name: \"ID\",\n type: \"string\",\n isId: \"uuid\"\n },\n email: {\n name: \"Email\",\n type: \"string\",\n validation: { required: true,\nunique: true }\n },\n displayName: {\n name: \"Name\",\n type: \"string\",\n columnName: \"display_name\",\n validation: { required: true }\n },\n photoURL: {\n name: \"Photo URL\",\n type: \"string\",\n columnName: \"photo_url\"\n },\n roles: {\n name: \"Roles\",\n type: \"array\",\n columnType: \"text[]\",\n of: {\n name: \"Role\",\n type: \"string\",\n enum: {\n admin: \"Admin\",\n editor: \"Editor\",\n viewer: \"Viewer\"\n }\n }\n },\n passwordHash: {\n name: \"Password Hash\",\n type: \"string\",\n columnName: \"password_hash\",\n excludeFromApi: true\n },\n emailVerified: {\n name: \"Email Verified\",\n type: \"boolean\",\n columnName: \"email_verified\",\n defaultValue: false\n },\n emailVerificationToken: {\n name: \"Email Verification Token\",\n type: \"string\",\n columnName: \"email_verification_token\",\n excludeFromApi: true\n },\n emailVerificationSentAt: {\n name: \"Email Verification Sent At\",\n type: \"date\",\n columnName: \"email_verification_sent_at\"\n },\n metadata: {\n name: \"Metadata\",\n type: \"map\",\n keyValue: true,\n properties: {},\n defaultValue: {}\n },\n createdAt: {\n name: \"Created At\",\n type: \"date\",\n columnName: \"created_at\",\n autoValue: \"on_create\"\n },\n updatedAt: {\n name: \"Updated At\",\n type: \"date\",\n columnName: \"updated_at\",\n autoValue: \"on_update\"\n }\n }\n});\n","import type { CollectionConfig, FieldAccess, Property } from \"@rebasepro/types\";\n\n/**\n * Field-level access control: one mechanism, read by every enforcement point.\n *\n * A collection's `securityRules` decide which *rows* a caller reaches;\n * `property.access` decides which *fields* of a reached row they see and may\n * set. The two are independent — a field rule never widens row access, and a\n * row a caller cannot read has no fields to talk about.\n *\n * `excludeFromApi` is sugar for `access: { read: [], write: [] }` and is\n * normalised into it by {@link effectiveAccess}, which is the only place either\n * spelling is read. It used to be its own code path in five files — the read\n * strip, the write refusal, the SDK generator, the OpenAPI schema builder and\n * the filter-parameter builder — and the second rule would have made ten.\n * There is one predicate now, and the flag is a shorthand for it.\n *\n * @module\n */\n\n/**\n * The caller a field rule is judged against: whatever the call context carries\n * as the user's application roles.\n *\n * `undefined` is the trusted server plane — an in-process `rebase.data` call\n * with no request behind it, the auth adapter writing a password hash, a\n * migration. Every API boundary has a viewer: an unauthenticated REST request is\n * scoped as `{ uid: ANONYMOUS_USER_ID, roles: [\"anon\"] }` before it reaches a\n * driver, so \"no viewer\" cannot be reached from outside.\n */\nexport interface FieldViewer {\n roles?: readonly string[];\n}\n\n/**\n * The role that satisfies any non-empty list.\n *\n * The same arm every baseline policy carries: `security_rules` injects\n * `rolesOverlap(['admin'])` into the default read and write policies, and\n * `rebase.dataAsAdmin` is scoped with `{ uid: \"service\", roles: [\"admin\"] }`.\n * Without this an author could declare `access: { read: [\"hr\"] }` and lock the\n * administrator out of a column of their own database — and lock the Studio out\n * of rendering it.\n */\nexport const ADMIN_ROLE = \"admin\";\n\n/**\n * What a property's access rules actually are, with `excludeFromApi` expanded.\n *\n * Returns `undefined` when the property constrains nothing, so callers can skip\n * the whole check for the overwhelmingly common case.\n */\nexport function effectiveAccess(property: Property | undefined): FieldAccess | undefined {\n if (!property) return undefined;\n if (property.excludeFromApi) return EXCLUDED_ACCESS;\n const access = property.access;\n if (!access) return undefined;\n if (access.read === undefined && access.write === undefined) return undefined;\n return access;\n}\n\n/** The rule `excludeFromApi: true` expands to. Frozen: it is shared by every caller. */\nconst EXCLUDED_ACCESS: FieldAccess = Object.freeze({ read: Object.freeze([]), write: Object.freeze([]) });\n\n/**\n * Does a caller holding `roles` satisfy `allowed`?\n *\n * Three cases, and the middle one is the one worth stating out loud:\n *\n * - `allowed` omitted — the field carries no rule of its own, so the row's\n * policies have already answered. True.\n * - `allowed` empty — nobody, at any privilege, through any API. Not the admin,\n * not the service key, not the trusted plane reading on a caller's behalf.\n * This is what `excludeFromApi` has always meant on the read side, and\n * collapsing the two spellings means the empty list has to keep meaning it.\n * - `allowed` non-empty — one of the named roles, or `admin`, or no viewer at\n * all (the trusted server plane, which is not an API caller).\n */\nfunction satisfies(allowed: readonly string[] | undefined, viewer: FieldViewer | undefined): boolean {\n if (allowed === undefined) return true;\n if (allowed.length === 0) return false;\n if (!viewer) return true;\n const roles = viewer.roles;\n if (!roles || roles.length === 0) return false;\n return roles.includes(ADMIN_ROLE) || allowed.some(role => roles.includes(role));\n}\n\n/** May this caller receive this field's value? */\nexport function canReadField(property: Property | undefined, viewer: FieldViewer | undefined): boolean {\n const access = effectiveAccess(property);\n return access ? satisfies(access.read, viewer) : true;\n}\n\n/** May this caller set this field's value? */\nexport function canWriteField(property: Property | undefined, viewer: FieldViewer | undefined): boolean {\n const access = effectiveAccess(property);\n return access ? satisfies(access.write, viewer) : true;\n}\n\n/**\n * The names on this collection a caller may not touch, in the two spellings a\n * caller can write them in.\n *\n * `declared` is the property keys, which is what has to leave a *known-fields*\n * set. `refused` is those plus the physical column names behind them: a caller\n * who knows the table can send `password_hash` as readily as `passwordHash`, and\n * a rule that only knew the wire name would be one rename away from useless.\n *\n * `kind` picks which half of the rule is read; nothing else differs.\n */\nexport function restrictedFieldNames(\n collection: CollectionConfig,\n viewer: FieldViewer | undefined,\n kind: \"read\" | \"write\"\n): { declared: string[]; refused: Set<string> } {\n const declared: string[] = [];\n const refused = new Set<string>();\n const allowed = kind === \"read\" ? canReadField : canWriteField;\n\n for (const [name, property] of Object.entries(collection.properties ?? {})) {\n if (allowed(property as Property, viewer)) continue;\n declared.push(name);\n refused.add(name);\n const columnName = (property as Property).columnName;\n if (columnName) refused.add(columnName);\n }\n return { declared, refused };\n}\n\n/**\n * True when nothing on this collection restricts a field, for either direction.\n *\n * Every read of every row runs through the strip, so the collection that has no\n * rules — which is almost all of them — has to cost one property walk and no\n * allocation.\n */\nexport function hasFieldAccessRules(collection: CollectionConfig): boolean {\n for (const property of Object.values(collection.properties ?? {})) {\n if (effectiveAccess(property as Property)) return true;\n }\n return false;\n}\n","import type { OrderByTuple } from \"@rebasepro/types\";\n\n/**\n * The keyset-cursor wire codec.\n *\n * ## Why this is one module\n *\n * Keyset pagination was implemented three times and reachable once. The driver\n * has a NULL-correct multi-key comparison (`FetchService.buildKeysetComparison`)\n * that only a WebSocket `startAfter` could reach; REST could not seek at all;\n * and the SDK's `iterate({cursor})` re-implemented a *single*-column keyset as a\n * `where` clause, which threw on any multi-key sort and silently dropped rows\n * whose sort value was NULL. Three implementations, three answers to \"what is\n * page two\".\n *\n * There is now one. The driver's comparison is the implementation; this module\n * is the only thing that says how a cursor is written down, and every transport\n * — the REST `?after=`, the WebSocket `startAfter`, the SDK's `iterate()` —\n * carries the string this produces and hands it back unread.\n *\n * ## What a cursor holds\n *\n * The sort keys the query was ordered by, the last served row's value for each\n * of them, and that row's id. The keys travel *with* the values because a\n * cursor that carried only values would be silently reinterpretable: paging a\n * `created_at DESC` listing and then asking for `title ASC` would seek on the\n * dates as though they were titles. Carrying the keys makes that a refusal\n * ({@link CursorMismatchError}) rather than a page of arbitrary rows.\n *\n * ## Opacity\n *\n * The encoding is base64url of JSON, and it is **not** API. It is opaque so it\n * can change — adding a key, changing how a value is tagged — without every\n * client that learned to read it breaking. Nothing outside this file parses it.\n *\n * @module\n */\n\n/** The decoded contents of a cursor. */\nexport interface DecodedCursor {\n /** The sort keys the cursor was produced under, in order of significance. */\n orderBy: OrderByTuple[];\n /** The last served row's value for each sort key, by field name. */\n values: Record<string, unknown>;\n /** The last served row's id, which breaks ties on the last key. */\n id: unknown;\n}\n\n/** A cursor that cannot be read at all — truncated, re-encoded, or invented. */\nexport class CursorError extends Error {\n readonly code = \"INVALID_CURSOR\";\n constructor(detail: string) {\n super(\n `Invalid \\`after\\` cursor: ${detail}. Pass back the \\`meta.nextCursor\\` ` +\n \"from the previous page unchanged — it is opaque and must not be built by hand.\"\n );\n this.name = \"CursorError\";\n Object.setPrototypeOf(this, CursorError.prototype);\n }\n}\n\n/**\n * A cursor that reads fine but describes a different query.\n *\n * Separate from {@link CursorError} because the fix is different: this one is\n * not a corrupt string, it is a correct cursor used against a sort it was not\n * produced under. Seeking anyway would return rows in an order nobody asked\n * for, and — worse — would look like it worked.\n */\nexport class CursorMismatchError extends Error {\n readonly code = \"CURSOR_ORDER_MISMATCH\";\n constructor(cursorKeys: string[], queryKeys: string[]) {\n super(\n `The \\`after\\` cursor was produced by a query ordered by ` +\n `${cursorKeys.map(k => `\"${k}\"`).join(\", \") || \"(nothing)\"}, but this query orders by ` +\n `${queryKeys.map(k => `\"${k}\"`).join(\", \") || \"(nothing)\"}. A cursor only continues the ` +\n \"listing it came from — keep `orderBy` identical across pages, or drop `after` to start over.\"\n );\n this.name = \"CursorMismatchError\";\n Object.setPrototypeOf(this, CursorMismatchError.prototype);\n }\n}\n\n/**\n * Tag for a value whose JSON round-trip would otherwise lose its type.\n *\n * A `timestamp` column comes back from the driver as a `Date`; JSON turns it\n * into a string, and the string would then be compared against the column by\n * whatever cast Postgres chose. Round-tripping it as a `Date` keeps the\n * comparison the one the ORDER BY made.\n */\nconst DATE_TAG = \"$date\";\n\nfunction encodeValue(value: unknown): unknown {\n if (value instanceof Date) return { [DATE_TAG]: value.toISOString() };\n return value;\n}\n\nfunction decodeValue(value: unknown): unknown {\n if (value && typeof value === \"object\" && !Array.isArray(value)) {\n const tagged = (value as Record<string, unknown>)[DATE_TAG];\n if (typeof tagged === \"string\") {\n const date = new Date(tagged);\n return Number.isNaN(date.getTime()) ? tagged : date;\n }\n }\n return value;\n}\n\n/** base64url, without depending on Node's Buffer (this package runs in browsers). */\nfunction toBase64Url(text: string): string {\n const bytes = new TextEncoder().encode(text);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction fromBase64Url(encoded: string): string {\n const padded = encoded.replace(/-/g, \"+\").replace(/_/g, \"/\")\n + \"=\".repeat((4 - (encoded.length % 4)) % 4);\n const binary = atob(padded);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return new TextDecoder().decode(bytes);\n}\n\n/**\n * Encode \"everything strictly after this row, in this order\".\n *\n * @param orderBy the sort keys the listing ran under, in order of significance\n * @param row the last row served, which the next page picks up after\n * @param id that row's id — the tiebreaker every keyset comparison ends on\n * @returns the opaque cursor, or `undefined` when no cursor can describe the\n * page. That is not a failure: a listing sorted by relevance has no stored\n * value to compare a later page against (scores are computed per query and\n * are not on the same scale between two of them), so it pages by offset and\n * `meta.nextCursor` is simply absent.\n */\nexport function encodeCursor(\n orderBy: OrderByTuple[] | undefined,\n row: Record<string, unknown>,\n id: unknown\n): string | undefined {\n if (id === undefined || id === null) return undefined;\n const keys = orderBy ?? [];\n // A key whose value is not on the row cannot be seeked past. Rather than\n // emit a cursor that the next request would refuse, emit none — the caller\n // falls back to offset paging, which is what it did before cursors existed.\n const values: Record<string, unknown> = {};\n for (const [field] of keys) {\n if (!(field in row)) return undefined;\n values[field] = encodeValue(row[field]);\n }\n return toBase64Url(JSON.stringify({ k: keys, v: values, i: encodeValue(id) }));\n}\n\n/**\n * Read a cursor produced by {@link encodeCursor}.\n *\n * @throws {CursorError} when the string is not a cursor this codec wrote.\n */\nexport function decodeCursor(raw: string): DecodedCursor {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fromBase64Url(raw.trim()));\n } catch {\n throw new CursorError(\"it is not a cursor this API issued\");\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new CursorError(\"it does not decode to a cursor\");\n }\n const body = parsed as { k?: unknown; v?: unknown; i?: unknown };\n if (!Array.isArray(body.k)) throw new CursorError(\"it carries no sort keys\");\n if (body.i === undefined) throw new CursorError(\"it carries no row id\");\n\n const orderBy: OrderByTuple[] = [];\n for (const entry of body.k) {\n if (!Array.isArray(entry) || typeof entry[0] !== \"string\") {\n throw new CursorError(\"one of its sort keys is malformed\");\n }\n const direction = entry[1] === \"desc\" ? \"desc\" : \"asc\";\n orderBy.push(entry[2] === \"first\" || entry[2] === \"last\"\n ? [entry[0], direction, entry[2]]\n : [entry[0], direction]);\n }\n\n const rawValues = (body.v && typeof body.v === \"object\" && !Array.isArray(body.v))\n ? body.v as Record<string, unknown>\n : {};\n const values: Record<string, unknown> = {};\n for (const [field, value] of Object.entries(rawValues)) values[field] = decodeValue(value);\n\n return { orderBy, values, id: decodeValue(body.i) };\n}\n\n/**\n * The `orderBy` a request should run under, given a cursor and whatever sort\n * the request itself named.\n *\n * A request that names no sort **adopts the cursor's** — that is what makes\n * `find({ after })` work without restating the `orderBy` from the previous\n * call, and it cannot be wrong, since the cursor is the only sort in play.\n * A request that names one must name the *same* one, key for key, direction for\n * direction, nulls for nulls; anything else is {@link CursorMismatchError}.\n *\n * @throws {CursorMismatchError}\n */\nexport function reconcileCursorOrder(\n cursor: DecodedCursor,\n requested: OrderByTuple[] | undefined\n): OrderByTuple[] {\n if (!requested || requested.length === 0) return cursor.orderBy;\n const spell = (keys: OrderByTuple[]) =>\n keys.map(([field, direction, nulls]) => `${field}:${direction}${nulls ? `:${nulls}` : \"\"}`);\n const cursorKeys = spell(cursor.orderBy);\n const queryKeys = spell(requested);\n if (cursorKeys.length !== queryKeys.length\n || cursorKeys.some((key, i) => key !== queryKeys[i])) {\n throw new CursorMismatchError(cursorKeys, queryKeys);\n }\n return requested;\n}\n\n/**\n * The `startAfter` shape the driver contract takes, built from a cursor.\n *\n * The driver has always accepted `{ id, values }`; this is the one place that\n * shape is produced, so the REST route and the WebSocket ingress cannot drift\n * into two spellings of the same seek.\n */\nexport function cursorToStartAfter(cursor: DecodedCursor): Record<string, unknown> {\n return { id: cursor.id, values: cursor.values };\n}\n","import type { NullsPlacement, OrderBySortTuple, OrderBySpec, OrderByTuple } from \"@rebasepro/types\";\nimport { isRelationAggregateSort, sortKeyToString } from \"@rebasepro/types\";\n\n/**\n * Sort-order wire codec.\n *\n * This is the ONLY module that knows about the colon-delimited wire format\n * (`\"field:direction\"`) used in HTTP query parameters, and about the JSON-array\n * form that carries a multi-column sort over the same parameter.\n * Everything else speaks {@link OrderByTuple} exclusively.\n *\n * Mirrors the filter architecture in `filter-dialect.ts`.\n *\n * @module\n */\n\n/**\n * Collapse the one-key and many-key spellings of a sort into the list form.\n *\n * `[\"a\", \"desc\"]` and `[[\"a\", \"desc\"]]` mean the same thing and normalize to\n * the same value; the two are told apart by whether the first element is\n * itself an array, which no field name ever is.\n *\n * This is also where a {@link RelationAggregateSort} object stops being an\n * object. Above this function a sort key may be either spelling; below it,\n * every key is a string — which is what `OrderByTuple`, the REST parameter, the\n * driver contract and the cursor all already were. Doing it here means the one\n * place that already collapses the two *shapes* of a sort also collapses the\n * two *spellings* of a key, rather than every consumer learning about both.\n *\n * @returns The keys in order of significance, or `undefined` for no sort. An\n * empty list also returns `undefined` — \"sort by nothing\" is no sort, and\n * letting `[]` through would have every layer below re-deciding what it meant.\n */\nexport function normalizeOrderBy(orderBy?: OrderBySpec): OrderByTuple[] | undefined {\n if (!orderBy || orderBy.length === 0) return undefined;\n // An aggregate key is an object, so the first element being an array still\n // tells the list form from the single-tuple one — no field name is an\n // array, and neither is an aggregate key.\n const list = Array.isArray(orderBy[0])\n ? orderBy as OrderBySortTuple[]\n : [orderBy as OrderBySortTuple];\n if (list.length === 0) return undefined;\n // Through `toStrictTuple`, not a destructure. `([key, direction]) => …` over\n // whatever it was handed is only safe for a caller the types checked, and\n // this is reached straight from `find({ orderBy })` — where the plausible\n // mistakes are an object (`{ title: \"asc\" }`, which is how every other\n // query API spells a sort) and a bare number. Both used to come back as\n // `TypeError: object is not iterable`, from a package the caller has never\n // heard of, with no `code` and no field name, while the same call's `where`\n // clause answers with a `RebaseClientError` naming the field and the fix.\n return list.map((entry, index) => toStrictTuple(entry, index));\n}\n\n/**\n * The most significant sort key, for a caller that can only express one —\n * a column header's arrow, a URL parameter, a driver that has not been taught\n * the list form.\n */\nexport function primaryOrderBy(orderBy?: OrderBySpec): OrderByTuple | undefined {\n return normalizeOrderBy(orderBy)?.[0];\n}\n\n/**\n * Collapse the driver-level `{orderBy, order}` pair into the list form.\n *\n * The driver contract spells a single-column sort as a field name plus a\n * separate direction, and a multi-column one as a list of tuples that leaves\n * `order` meaningless. Every driver reads both through here so neither\n * spelling has to be handled twice.\n *\n * An absent direction means ascending — the same thing a bare `?orderBy=name`\n * has always meant over HTTP. The Postgres driver used to read the same pair as\n * *descending* while Mongo read it as ascending, so one field name and no\n * direction described two different queries depending on which database was\n * underneath. Neither had a caller: every path in the workspace passes a\n * direction, which is why the disagreement went unnoticed rather than being\n * load-bearing.\n */\nexport function normalizeDriverOrderBy(\n orderBy?: string | OrderByTuple[],\n order?: \"asc\" | \"desc\"\n): OrderByTuple[] | undefined {\n if (!orderBy) return undefined;\n if (typeof orderBy === \"string\") return [[orderBy, order === \"desc\" ? \"desc\" : \"asc\"]];\n return orderBy.length > 0 ? orderBy : undefined;\n}\n\n/** A sort whose *shape* is unusable, as opposed to one naming a field that does not exist. */\nexport class OrderBySpecError extends Error {\n readonly code = \"INVALID_ORDER_BY\";\n constructor(detail: string) {\n super(\n `Invalid \\`orderBy\\`: ${detail}. Expected a field name, or a list of ` +\n \"[field, direction] pairs like [[\\\"roles\\\",\\\"asc\\\"],[\\\"created_at\\\",\\\"desc\\\"]]\"\n );\n this.name = \"OrderBySpecError\";\n }\n}\n\n/**\n * Validate an `orderBy` that arrived from outside this process — a WebSocket\n * subscribe frame, a driver call from untyped JavaScript — and return it in the\n * list form.\n *\n * Strict on purpose, in the same way the REST `parseOrderByParam` is: the\n * failure mode for a shape nobody checks is not a crash but a *silently\n * different query*. A malformed entry read as a field name resolves to no\n * column, and under the lenient unknown-field mode the sort is then dropped and\n * the rows come back in whatever order the database pleased — sorted, as far as\n * the subscriber can tell, by whatever they asked for.\n */\nexport function parseOrderBySpecStrict(raw: unknown, order?: \"asc\" | \"desc\"): OrderByTuple[] | undefined {\n if (raw === undefined || raw === null || raw === \"\") return undefined;\n // The string spelling is the driver contract's, so it takes its direction\n // from the same companion `order` — and defaults the same way it does.\n if (typeof raw === \"string\") return normalizeDriverOrderBy(raw, order);\n if (!Array.isArray(raw) || raw.length === 0) {\n throw new OrderBySpecError(`${typeof raw} is not a field name or a list of sort keys`);\n }\n\n // The single-tuple spelling, `[\"created_at\", \"desc\"]` — or the same shape\n // with an aggregate key in place of the field name.\n if (typeof raw[0] === \"string\" || isRelationAggregateSort(raw[0])) return [toStrictTuple(raw, 0)];\n\n return raw.map(toStrictTuple);\n}\n\n/** `first`/`last`, or a refusal naming the entry — see {@link NullsPlacement}. */\nfunction toStrictNulls(raw: unknown, index: number): NullsPlacement | undefined {\n if (raw === undefined || raw === null) return undefined;\n if (raw !== \"first\" && raw !== \"last\") {\n throw new OrderBySpecError(\n `entry ${index} has nulls '${String(raw)}' — expected \"first\" or \"last\"`\n );\n }\n return raw;\n}\n\nfunction toStrictTuple(raw: unknown, index: number): OrderByTuple {\n if (!Array.isArray(raw)) {\n throw new OrderBySpecError(`entry ${index} has no field name`);\n }\n // The object spelling of an aggregate key, from an untyped caller that did\n // not go through `normalizeOrderBy`. Encoded rather than refused: it is a\n // sort this understands, and rejecting the shape a typed caller writes\n // would be a distinction between the two spellings that nothing else makes.\n const key = isRelationAggregateSort(raw[0]) ? sortKeyToString(raw[0]) : raw[0];\n if (typeof key !== \"string\" || key.trim() === \"\") {\n throw new OrderBySpecError(`entry ${index} has no field name`);\n }\n const direction = raw[1];\n if (direction !== undefined && direction !== \"asc\" && direction !== \"desc\") {\n throw new OrderBySpecError(`entry ${index} has direction '${String(direction)}'`);\n }\n const nulls = toStrictNulls(raw[2], index);\n // Omitted rather than defaulted: absent means \"the direction's convention\",\n // and writing one in here would make an explicit `NULLS LAST` on a\n // descending key indistinguishable from having said nothing — which the\n // keyset comparison and the ORDER BY both have to agree about.\n return nulls ? [key, direction ?? \"asc\", nulls] : [key, direction ?? \"asc\"];\n}\n\n/**\n * Serialize a sort to the wire.\n *\n * A single key keeps the `\"field:direction\"` shorthand it has always used —\n * short, readable in a URL, and what every existing client and test expects.\n * Several keys are emitted as the canonical JSON array the server already\n * accepts, because the shorthand has no separator to spare: a comma-joined\n * `\"a:asc,b:desc\"` parses as one field named `a` with the direction\n * `\"asc,b:desc\"`, which the server refuses.\n *\n * **Runtime tolerance:** if the input is already a well-formed wire string\n * (from an untyped JS caller), it is returned unchanged.\n * This is undocumented tolerance, not public API — don't rely on it.\n *\n * @param orderBy - A canonical tuple or list of tuples, or at runtime\n * possibly a pre-serialized string (undocumented tolerance).\n * @returns The wire-format string, or `undefined` if the input is falsy.\n *\n * @remarks\n * Field names containing `:` are representable in the tuple form but\n * **not** in the single-key wire encoding — this is an inherent limitation of\n * the colon-delimited shorthand and is not resolved here.\n */\nexport function serializeOrderBy(orderBy?: OrderBySpec | string): string | undefined {\n if (!orderBy) return undefined;\n // Runtime tolerance: pass through a pre-serialized wire string unchanged.\n if (typeof orderBy === \"string\") return orderBy;\n // `normalizeOrderBy` has already encoded any aggregate key to its string\n // spelling, which is why the shorthand below can assume a string: neither\n // `min(applications.created_at)` nor `count(applications)` contains a `:`.\n const list = normalizeOrderBy(orderBy);\n if (!list) return undefined;\n // `field:direction:nulls` — the third segment appears only when the key\n // asked for a placement, so every sort written before nulls existed still\n // serializes to exactly the string it always did.\n if (list.length === 1) {\n const [field, direction, nulls] = list[0];\n return nulls ? `${field}:${direction}:${nulls}` : `${field}:${direction}`;\n }\n return JSON.stringify(list.map(([field, direction, nulls]) => (nulls\n ? { field, direction, nulls }\n : { field, direction })));\n}\n\n/**\n * Deserialize a wire-format `\"field:direction\"` string into an {@link OrderByTuple}.\n *\n * Lenient parsing:\n * - Bare field name (no colon): `\"name\"` → `[\"name\", \"asc\"]`\n * - Unknown direction: `\"name:foo\"` → `[\"name\", \"asc\"]`\n * - Empty / falsy input, or a blank field name: → `undefined`\n *\n * The leniency is this end's alone; the *server* refuses the same value. This\n * used to say \"matches existing server behaviour\", and it stopped being true\n * when `parseOrderByParam` grew a strict direction check: `?orderBy=name:foo`\n * now answers `400 INVALID_ORDER_BY` (\"entry 0 has direction 'foo'\"). The split\n * is deliberate — see {@link parseOrderBySpecStrict} — because a value this\n * function is handed was produced by {@link serializeOrderBy} a moment earlier,\n * and one that reaches the server came from a stranger.\n *\n * A blank field is `undefined` rather than `[\" \", \"asc\"]`: whitespace is not a\n * field name, and the tuple it used to produce could not be re-encoded — the\n * only value in this codec that survived a decode and failed the next encode.\n *\n * Reads the single-key shorthand only. For a value that may carry several keys,\n * use {@link deserializeOrderByList} — handed a JSON array this returns the\n * whole array as one nonsensical field name.\n *\n * @param raw - The wire-format string from an HTTP query parameter.\n * @returns The canonical tuple, or `undefined` if the input names no field.\n */\nexport function deserializeOrderBy(raw?: string): OrderByTuple | undefined {\n if (!raw) return undefined;\n const idx = raw.indexOf(\":\");\n if (idx === -1) return raw.trim() === \"\" ? undefined : [raw, \"asc\"];\n const field = raw.slice(0, idx);\n if (field.trim() === \"\") return undefined;\n const rest = raw.slice(idx + 1);\n // `field:direction:nulls`. The nulls segment is optional, and — leniently,\n // as everything else on this end of the codec is — anything that is not\n // \"first\"/\"last\" is read as \"unspecified\" rather than refused. The *server*\n // end (`parseOrderByParam`) refuses it, for the reason in the docblock.\n const nullsIdx = rest.indexOf(\":\");\n const dir = nullsIdx === -1 ? rest : rest.slice(0, nullsIdx);\n const nulls = nullsIdx === -1 ? undefined : rest.slice(nullsIdx + 1);\n const direction = dir === \"desc\" ? \"desc\" : \"asc\";\n return nulls === \"first\" || nulls === \"last\"\n ? [field, direction, nulls]\n : [field, direction];\n}\n\n/**\n * Deserialize either wire spelling — the single-key shorthand or the JSON\n * array — into the list form.\n *\n * Lenient in the same way {@link deserializeOrderBy} is: this is the client end\n * of the codec, where the value was produced by {@link serializeOrderBy} a\n * moment earlier. The *server* end parses the same shapes strictly, in\n * `parseOrderByParam`, because there the value came from a stranger and a\n * direction it cannot read has to be refused rather than quietly turned into\n * `\"asc\"`.\n */\nexport function deserializeOrderByList(raw?: string): OrderByTuple[] | undefined {\n if (!raw) return undefined;\n const trimmed = raw.trim();\n if (trimmed.startsWith(\"[\")) {\n try {\n const parsed = JSON.parse(trimmed);\n if (Array.isArray(parsed)) {\n const list = parsed\n .map((entry): OrderByTuple | undefined => {\n if (typeof entry === \"string\") return deserializeOrderBy(entry);\n if (entry && typeof entry === \"object\" && typeof entry.field === \"string\") {\n const direction = entry.direction === \"desc\" ? \"desc\" : \"asc\";\n return entry.nulls === \"first\" || entry.nulls === \"last\"\n ? [entry.field, direction, entry.nulls]\n : [entry.field, direction];\n }\n return undefined;\n })\n .filter((entry): entry is OrderByTuple => entry !== undefined);\n return list.length > 0 ? list : undefined;\n }\n } catch {\n // Not JSON after all — fall through to the shorthand, which is what\n // a field name that merely begins with \"[\" would be.\n }\n }\n const single = deserializeOrderBy(trimmed);\n return single ? [single] : undefined;\n}\n","import { MAX_INCLUDE_DEPTH } from \"@rebasepro/types\";\nimport type { FilterValues, IncludeOptions, IncludeSpec, LogicalCondition, OrderByTuple } from \"@rebasepro/types\";\nimport { deserializeOrderByList, normalizeOrderBy } from \"./sort-dialect\";\n\n/**\n * The `include` codec: one shape, whatever spelling it arrived in.\n *\n * `include` reaches the driver by four routes — the REST `?include=` parameter,\n * a WebSocket subscribe frame, the SDK's `include(...)`, and the admin panel's\n * \"all relations\" — and each used to hand the driver something slightly\n * different. This normalises all four to one tree, so the fetch pipeline has a\n * single thing to read and `find()`, `findById()` and `listen()` cannot disagree\n * about what \"include the author\" means.\n *\n * @module\n */\n\n/**\n * One relation to load, and how.\n *\n * `children` is the nesting: `comments.author` is a `comments` node with an\n * `author` child. Every other field narrows the rows *of this relation* — the\n * same knobs a top-level query has, which is the point.\n */\nexport interface IncludeNode {\n /** Rows to load per parent row. */\n limit?: number;\n /** Filter over the related rows. */\n where?: FilterValues<string>;\n /** An `and`/`or`/`not` group over the related rows. */\n logical?: LogicalCondition;\n /** Sort for the related rows. */\n orderBy?: OrderByTuple[];\n /** Columns of the related row to return. */\n fields?: string[];\n /** Relations of the related row, loaded in turn. */\n children: Record<string, IncludeNode>;\n}\n\n/**\n * A whole `include` request: the tree, plus whether the caller asked for\n * *every* relation.\n *\n * The wildcard is kept as a flag rather than expanded into names here, because\n * expanding it needs the collection — which this package does not have. The\n * driver expands it against the relations it actually resolved.\n */\nexport interface NormalizedInclude {\n /** `include=*` — every relation of the collection, one hop deep. */\n wildcard: boolean;\n /** The named relations. Empty when `wildcard` is set alone. */\n tree: Record<string, IncludeNode>;\n}\n\n/** An `include` that cannot be read, as opposed to one naming a relation that does not exist. */\nexport class IncludeSpecError extends Error {\n readonly code: string;\n constructor(detail: string, code = \"INVALID_INCLUDE\") {\n super(`Invalid \\`include\\`: ${detail}`);\n this.name = \"IncludeSpecError\";\n this.code = code;\n Object.setPrototypeOf(this, IncludeSpecError.prototype);\n }\n}\n\nconst emptyNode = (): IncludeNode => ({ children: {} });\n\nfunction ensureNode(tree: Record<string, IncludeNode>, key: string): IncludeNode {\n return (tree[key] ??= emptyNode());\n}\n\n/**\n * Merge one dotted path (`\"comments.author\"`) into a tree.\n *\n * Merging rather than assigning is what makes `include=comments,comments.author`\n * mean the same thing as `include=comments.author`: the second path deepens the\n * node the first created instead of replacing it and losing its options.\n */\nfunction addPath(tree: Record<string, IncludeNode>, path: string): void {\n const segments = path.split(\".\").map(s => s.trim()).filter(Boolean);\n if (segments.length === 0) return;\n if (segments.length > MAX_INCLUDE_DEPTH) {\n throw new IncludeSpecError(\n `\"${path}\" nests ${segments.length} relations deep; the limit is ${MAX_INCLUDE_DEPTH}. ` +\n \"Each hop is another query, and an unbounded one walks a self-referencing relation forever.\",\n \"INCLUDE_TOO_DEEP\"\n );\n }\n let level = tree;\n for (const segment of segments) {\n level = ensureNode(level, segment).children;\n }\n}\n\nfunction normalizeOptions(key: string, options: IncludeOptions, depth: number): IncludeNode {\n if (depth > MAX_INCLUDE_DEPTH) {\n throw new IncludeSpecError(\n `\"${key}\" nests more than ${MAX_INCLUDE_DEPTH} relations deep.`,\n \"INCLUDE_TOO_DEEP\"\n );\n }\n if (options.limit !== undefined\n && (!Number.isInteger(options.limit) || options.limit < 1)) {\n throw new IncludeSpecError(\n `\"${key}\" has limit ${JSON.stringify(options.limit)} — expected a whole number of 1 or more.`\n );\n }\n const node: IncludeNode = { children: {} };\n if (options.limit !== undefined) node.limit = options.limit;\n if (options.where) node.where = options.where;\n if (options.logical) node.logical = options.logical;\n if (options.fields && options.fields.length > 0) node.fields = [...options.fields];\n // The same two spellings the top-level `?orderBy=` accepts: the\n // `field:direction[:nulls]` shorthand a caller writes into a query string,\n // and the tuple form a typed caller writes in code. Accepting only the\n // tuples made the JSON include form — the one that exists *because* it\n // travels over a query string — unable to express the shorthand beside it.\n const orderBy = typeof options.orderBy === \"string\"\n ? deserializeOrderByList(options.orderBy)\n : normalizeOrderBy(options.orderBy);\n if (orderBy) node.orderBy = orderBy;\n if (options.include) {\n const nested = normalizeIncludeAt(options.include, depth + 1);\n if (nested.wildcard) {\n // `*` inside a nested include has no bound: it would load every\n // relation of every related row, of every related row. The outer\n // wildcard is already the widest thing this API offers.\n throw new IncludeSpecError(\n `\"${key}\" asks for \\`*\\` inside a nested include. Name the relations you need.`\n );\n }\n node.children = nested.tree;\n }\n return node;\n}\n\nfunction normalizeIncludeAt(spec: IncludeSpec, depth: number): NormalizedInclude {\n if (Array.isArray(spec)) {\n const tree: Record<string, IncludeNode> = {};\n let wildcard = false;\n for (const raw of spec) {\n if (typeof raw !== \"string\") {\n throw new IncludeSpecError(`${typeof raw} is not a relation name`);\n }\n const name = raw.trim();\n if (!name) continue;\n if (name === \"*\") { wildcard = true; continue; }\n addPath(tree, name);\n }\n return { wildcard, tree };\n }\n if (typeof spec !== \"object\" || spec === null) {\n throw new IncludeSpecError(`${typeof spec} is not a list of relations or an include tree`);\n }\n\n const tree: Record<string, IncludeNode> = {};\n let wildcard = false;\n for (const [key, value] of Object.entries(spec)) {\n if (key === \"*\") {\n if (value) wildcard = true;\n continue;\n }\n if (value === true) { ensureNode(tree, key); continue; }\n // `false`/`null` are not in `IncludeSpec`, but this reads values that\n // arrived as JSON off a query string, where they are exactly what a\n // caller writes to turn one relation off in a tree they built by\n // spreading another. Skipping is what they mean.\n if ((value as unknown) === false || value === undefined || value === null) continue;\n if (typeof value !== \"object\" || Array.isArray(value)) {\n throw new IncludeSpecError(`\"${key}\" must be \\`true\\` or an options object`);\n }\n tree[key] = normalizeOptions(key, value as IncludeOptions, depth);\n }\n return { wildcard, tree };\n}\n\n/**\n * Collapse any {@link IncludeSpec} spelling into one tree.\n *\n * `[\"author\", \"comments.author\"]` and\n * `{ author: true, comments: { include: { author: true } } }` normalize to the\n * same value — which is the whole point: the REST parameter can only carry the\n * flat spelling, the SDK prefers the tree, and the driver should never learn\n * about either.\n *\n * @throws {IncludeSpecError} for a shape that is not an include at all, or one\n * that nests past {@link MAX_INCLUDE_DEPTH}.\n */\nexport function normalizeInclude(spec?: IncludeSpec): NormalizedInclude | undefined {\n if (spec === undefined || spec === null) return undefined;\n const normalized = normalizeIncludeAt(spec, 1);\n if (!normalized.wildcard && Object.keys(normalized.tree).length === 0) return undefined;\n return normalized;\n}\n\n/**\n * Every relation name a tree names, as dotted paths — `[\"comments\",\n * \"comments.author\"]`.\n *\n * Used to report which names an `include` asked for when one of them is not a\n * relation, and to serialize a tree that carries no per-relation options back\n * to the flat wire spelling.\n */\nexport function includePaths(tree: Record<string, IncludeNode>, prefix = \"\"): string[] {\n const out: string[] = [];\n for (const [key, node] of Object.entries(tree)) {\n const path = prefix ? `${prefix}.${key}` : key;\n out.push(path);\n out.push(...includePaths(node.children, path));\n }\n return out;\n}\n\n/**\n * The relation names an `include` asks for at the top level.\n *\n * `[\"author\", \"comments.author\"]` and `{author: true, comments: {...}}` both\n * answer `[\"author\", \"comments\"]` — a *hop*, not a path, because the only\n * consumer is `?fields=`, which names keys on the row being returned and a\n * nested relation is not one of those.\n *\n * Derived rather than passed: `include` has four spellings and three of them\n * are not a `string[]`, so every consumer that wants the plain names either\n * calls this or reimplements the flattening.\n */\nexport function topLevelIncludeNames(spec?: IncludeSpec): string[] {\n const normalized = normalizeInclude(spec);\n if (!normalized) return [];\n return Object.keys(normalized.tree);\n}\n\n/** Whether any node in the tree carries per-relation options. */\nfunction hasOptions(tree: Record<string, IncludeNode>): boolean {\n return Object.values(tree).some(node =>\n node.limit !== undefined || node.where !== undefined || node.logical !== undefined\n || node.orderBy !== undefined || node.fields !== undefined\n || hasOptions(node.children));\n}\n\n/**\n * Serialize an {@link IncludeSpec} for the REST `?include=` parameter.\n *\n * Two spellings, and which one is used is decided by the request rather than\n * chosen:\n *\n * - **Comma-separated dotted paths** — `include=author,comments.author`. What a\n * plain include is, what a human types, and what every existing client sends.\n * - **JSON**, when any relation carries options — `include={\"comments\":{\"limit\":5,\n * \"include\":{\"author\":true}}}`. The flat spelling has nowhere to put a\n * `limit`, and inventing a punctuation for it (`comments(limit:5)`) would be a\n * third grammar to learn beside the two this API already has.\n *\n * The server accepts both on every list and get route, and tells them apart the\n * same way this does: a value starting with `{` is JSON.\n */\nexport function serializeInclude(spec?: IncludeSpec): string | undefined {\n const normalized = normalizeInclude(spec);\n if (!normalized) return undefined;\n if (normalized.wildcard && Object.keys(normalized.tree).length === 0) return \"*\";\n if (!hasOptions(normalized.tree)) {\n const paths = includePaths(normalized.tree);\n // Only the leaves: `comments.author` already implies `comments`, and\n // sending both is the same request twice.\n const leaves = paths.filter(path => !paths.some(other => other.startsWith(`${path}.`)));\n const all = normalized.wildcard ? [\"*\", ...leaves] : leaves;\n return all.length > 0 ? all.join(\",\") : undefined;\n }\n return JSON.stringify(toWireTree(normalized));\n}\n\n/**\n * A normalized tree, back in the {@link IncludeSpec} spelling a caller writes.\n *\n * The round trip is what lets a builder accumulate `include` calls: normalize\n * each, merge, and hand the result back as a spec the next layer can normalize\n * again. Idempotent, so doing it twice changes nothing.\n */\nexport function denormalizeInclude(normalized: NormalizedInclude): IncludeSpec {\n return toWireTree(normalized) as IncludeSpec;\n}\n\nfunction mergeTrees(\n into: Record<string, IncludeNode>,\n from: Record<string, IncludeNode>\n): Record<string, IncludeNode> {\n for (const [key, node] of Object.entries(from)) {\n const existing = into[key];\n if (!existing) { into[key] = node; continue; }\n // The later call wins on each option it names, and says nothing about\n // the ones it does not — so `.include(\"comments\")` after\n // `.include({comments:{limit:5}})` keeps the limit rather than erasing\n // it, which is the behaviour that makes accumulating calls safe.\n if (node.limit !== undefined) existing.limit = node.limit;\n if (node.where !== undefined) existing.where = node.where;\n if (node.logical !== undefined) existing.logical = node.logical;\n if (node.orderBy !== undefined) existing.orderBy = node.orderBy;\n if (node.fields !== undefined) existing.fields = node.fields;\n existing.children = mergeTrees(existing.children, node.children);\n }\n return into;\n}\n\n/**\n * Combine several `include` requests into one.\n *\n * Repeated `.include(...)` calls on a query builder are additive: each names\n * more of the graph to load, and a later one must not discard what an earlier\n * one asked for. Assigning instead of merging is why `.include(\"author\")\n * .include(\"tags\")` used to load only tags.\n */\nexport function mergeIncludeSpecs(\n existing: IncludeSpec | undefined,\n additions: (string | IncludeSpec)[]\n): IncludeSpec | undefined {\n const merged: NormalizedInclude = { wildcard: false, tree: {} };\n const absorb = (spec?: IncludeSpec) => {\n const normalized = normalizeInclude(spec);\n if (!normalized) return;\n merged.wildcard ||= normalized.wildcard;\n mergeTrees(merged.tree, normalized.tree);\n };\n absorb(existing);\n // A bare string is one relation name; anything else is a spec in its own\n // right. `.include(\"a\", \"b\")` and `.include([\"a\",\"b\"])` are the same call.\n const names = additions.filter((a): a is string => typeof a === \"string\");\n if (names.length > 0) absorb(names);\n for (const addition of additions) {\n if (typeof addition !== \"string\") absorb(addition);\n }\n if (!merged.wildcard && Object.keys(merged.tree).length === 0) return undefined;\n return denormalizeInclude(merged);\n}\n\nfunction toWireTree(normalized: NormalizedInclude): Record<string, unknown> {\n const emit = (tree: Record<string, IncludeNode>): Record<string, unknown> => {\n const out: Record<string, unknown> = {};\n for (const [key, node] of Object.entries(tree)) {\n const options: Record<string, unknown> = {};\n if (node.limit !== undefined) options.limit = node.limit;\n if (node.where) options.where = node.where;\n if (node.logical) options.logical = node.logical;\n if (node.orderBy) options.orderBy = node.orderBy;\n if (node.fields) options.fields = node.fields;\n const children = emit(node.children);\n if (Object.keys(children).length > 0) options.include = children;\n out[key] = Object.keys(options).length > 0 ? options : true;\n }\n return out;\n };\n const tree = emit(normalized.tree);\n if (normalized.wildcard) tree[\"*\"] = true;\n return tree;\n}\n\n/**\n * Read the REST `?include=` parameter, in either spelling.\n *\n * @throws {IncludeSpecError} for malformed JSON or a tree that nests too deep.\n */\nexport function deserializeInclude(raw?: string): IncludeSpec | undefined {\n if (raw === undefined || raw === null) return undefined;\n const text = raw.trim();\n if (!text) return undefined;\n if (text.startsWith(\"{\")) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new IncludeSpecError(\n \"the parametrised form must be a JSON object, e.g. \"\n + \"{\\\"comments\\\":{\\\"limit\\\":5,\\\"include\\\":{\\\"author\\\":true}}}\"\n );\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new IncludeSpecError(\"the parametrised form must be a JSON object\");\n }\n return parsed as IncludeSpec;\n }\n return text.split(\",\").map(s => s.trim()).filter(Boolean);\n}\n","import {\n CollectionAccessor,\n FilterCondition,\n FindParams,\n FindResponse,\n LogicalCondition,\n OrderByTuple,\n QueryBuilderInterface,\n WhereFilterOp,\n WhereValueFor,\n type ComputedSortField\n} from \"@rebasepro/types\";\nimport { normalizeOrderBy } from \"./sort-dialect\";\n\nexport function or(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"or\",\nconditions };\n}\n\nexport function and(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"and\",\nconditions };\n}\n\n/**\n * Negate a group: `not(a)` is `NOT a`, and `not(a, b)` is `NOT (a AND b)`.\n *\n * The conjunction, not the disjunction — one rule, stated on\n * {@link LogicalCondition} and applied identically by the wire codec, the REST\n * `?not=` parameter and every driver compiler. Groups nest, so De Morgan's\n * other half is `not(or(a, b))`.\n *\n * It compiles to a real SQL `NOT (...)` rather than to inverted operators,\n * which matters more than it looks: SQL is three-valued, so `NOT (a AND b)` and\n * `(NOT a) OR (NOT b)` stop agreeing the moment a NULL is involved, and only\n * one of them is the query the caller wrote. It also means a negation includes\n * rows whose column is NULL — which is what `NOT` means.\n */\nexport function not(...conditions: (FilterCondition | LogicalCondition)[]): LogicalCondition {\n return { type: \"not\",\nconditions };\n}\n\nexport function cond(column: string, operator: WhereFilterOp, value: unknown): FilterCondition {\n return { column,\noperator,\nvalue };\n}\n\nexport class QueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements QueryBuilderInterface<M> {\n // Keyed by plain `string` on purpose: it is written in place by the\n // methods below, whose own parameters are typed against `M`, and a\n // `Partial<Record<FieldPath<M>, …>>` is read-only under a generic `M`\n // (TS2862). The typing users see is on the methods; this is the buffer\n // behind them, cast once at each handoff.\n private params: FindParams = { where: {} };\n\n constructor(private collection: CollectionAccessor<M>) {}\n\n /**\n * Add a filter condition to your query.\n * @example\n * client.collection('users').where('age', '>=', 18).find()\n */\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): this;\n where(logicalCondition: LogicalCondition): this;\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown): this {\n // Handle LogicalCondition signature\n if (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n // A second group narrows rather than replaces — see the SDK builder\n // in `@rebasepro/client`, which had the same defect: every other\n // `.where()` adds a condition, so the one that silently dropped the\n // previous group was also the one that widened the result set.\n const next = columnOrCondition as LogicalCondition;\n this.params.logical = this.params.logical\n ? { type: \"and\", conditions: [this.params.logical, next] }\n : next;\n return this;\n }\n\n if (!this.params.where) {\n this.params.where = {};\n }\n\n const column = columnOrCondition as string;\n const condition: [WhereFilterOp, unknown] = [operator!, value];\n const existing = this.params.where[column];\n\n if (existing === undefined) {\n this.params.where[column] = condition;\n } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {\n (this.params.where[column] as [WhereFilterOp, unknown][]).push(condition);\n } else {\n // Convert existing single tuple/value into array of tuples\n let firstCondition: [WhereFilterOp, unknown];\n if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") {\n firstCondition = existing as [WhereFilterOp, unknown];\n } else {\n firstCondition = [\"==\", existing];\n }\n this.params.where[column] = [firstCondition, condition];\n }\n\n return this;\n }\n\n /**\n * Order the results by a specific column.\n *\n * Called again, this adds a tie-breaker rather than replacing the sort:\n * keys apply in the order they were added.\n *\n * @example\n * client.collection('users').orderBy('createdAt', 'desc').find()\n * @example\n * client.collection('users').orderBy('roles').orderBy('createdAt', 'desc').find()\n */\n orderBy(column: (keyof M & string) | ComputedSortField, direction: \"asc\" | \"desc\" = \"asc\"): this {\n const existing = normalizeOrderBy(this.params.orderBy) ?? [];\n this.params.orderBy = [...existing, [column, direction] as OrderByTuple];\n return this;\n }\n\n /**\n * Limit the number of results returned.\n */\n limit(count: number): this {\n this.params.limit = count;\n return this;\n }\n\n /**\n * Skip the first N results.\n */\n offset(count: number): this {\n this.params.offset = count;\n return this;\n }\n\n /**\n * Set a free-text search string if supported by the backend.\n */\n search(searchString: string, options?: { explain?: boolean }): this {\n this.params.searchString = searchString;\n if (options?.explain !== undefined) this.params.searchExplain = options.explain;\n return this;\n }\n\n /**\n * Order rows by nearest-neighbour distance to `vector`, closest first.\n *\n * Postgres only, over a property declared as `type: \"vector\"`. Rows come\n * back with a `_distance`; `where` filters before the ordering.\n */\n vectorSearch(\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): this {\n this.params.vectorSearch = {\n property,\n vector,\n ...(options?.distance !== undefined && { distance: options.distance }),\n ...(options?.threshold !== undefined && { threshold: options.threshold })\n };\n return this;\n }\n\n /**\n * Include related entities in the response.\n * Relations will be populated with full entity data instead of just IDs.\n *\n * @param relations - Relation names to include, or \"*\" for all.\n * @example\n * // Include specific relations\n * client.data.posts.include(\"tags\", \"author\").find()\n *\n * // Include all relations\n * client.data.posts.include(\"*\").find()\n */\n include(...relations: string[]): this {\n this.params.include = relations;\n return this;\n }\n\n /**\n * Execute the find query and return the results.\n */\n async find(): Promise<FindResponse<M>> {\n return this.collection.find(this.params as FindParams<M>) as Promise<FindResponse<M>>;\n }\n\n /**\n * Listen to realtime updates matching this query.\n */\n listen(onUpdate: (data: FindResponse<M>) => void, onError?: (error: Error) => void): () => void {\n if (!this.collection.listen) {\n throw new Error(\"Listen is only available when RebaseClient is configured with a websocketUrl.\");\n }\n return this.collection.listen(this.params as FindParams<M>, onUpdate, onError);\n }\n}\n","import {\n DEFAULT_LIST_LIMIT,\n FindAllParams,\n FindParams,\n FindResult,\n IterateParams\n} from \"@rebasepro/types\";\nimport { normalizeOrderBy } from \"./sort-dialect\";\n\n/**\n * The pagination engine behind `iterate()` / `findAll()`.\n *\n * It lives here, above both transports, on purpose: the HTTP client and the\n * in-process accessor implement the same `SDKCollectionClient` contract, and a\n * helper written twice is a helper that drifts. Both call into this file, so\n * \"the SDK paginates like *this*\" has exactly one definition.\n *\n * Everything below is expressed in terms of a single `find(params)` function,\n * which is all either transport has to supply.\n */\n\n/** Rows requested per page when the caller does not say. */\nexport const DEFAULT_PAGE_SIZE = 200;\n\n/** Rows `findAll()` will materialise before it refuses to continue. */\nexport const DEFAULT_FIND_ALL_MAX_ROWS = 10_000;\n\n/**\n * Requests one walk may make before it gives up on the server ever saying\n * `hasMore: false`. At the default page size that is two million rows — far\n * past any legitimate walk, and short of running forever.\n */\nexport const DEFAULT_MAX_PAGES = 10_000;\n\n/** Why a pagination walk refused to continue. */\nexport type PaginationErrorCode =\n /** `findAll()` matched more rows than its ceiling allows. */\n | \"max-rows\"\n /** The walk made its maximum number of requests without the server finishing. */\n | \"max-pages\"\n /**\n * The server said there was another page but issued no cursor to reach it.\n *\n * A query whose ordering has no stored value to seek on — relevance — is the\n * case that produces this. Page it by offset instead.\n */\n | \"cursor-missing\"\n /** Two consecutive pages returned the same cursor, so the walk cannot advance. */\n | \"cursor-stalled\";\n\n/**\n * Thrown when a walk stops for a reason the caller needs to know about.\n *\n * Every one of these is a case where the alternative would be silent: a\n * truncated array that looks complete, or a loop that never returns. Check\n * {@link code} to tell them apart.\n */\nexport class RebasePaginationError extends Error {\n readonly code: PaginationErrorCode;\n\n constructor(code: PaginationErrorCode, message: string) {\n super(message);\n this.name = \"RebasePaginationError\";\n this.code = code;\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, RebasePaginationError.prototype);\n }\n}\n\n/** The one thing a transport has to provide to be paginated. */\nexport type PageFinder<M extends Record<string, unknown> = Record<string, unknown>> =\n (params: FindParams<M>) => Promise<FindResult<M>>;\n\n/**\n * Resolve `limit`/`offset`/`page` into the window a read will actually use.\n *\n * Lives here, next to the walk, for the reason at the top of this file: every\n * transport has to mean the same thing by \"page two\". Four of them did not —\n * the REST layer strode by {@link DEFAULT_LIST_LIMIT}, the local-first\n * evaluator by {@link DEFAULT_PAGE_SIZE}, the in-process accessor by 20, and\n * the published type documented a fourth number. Pages that overlap or skip\n * rows are the mildest of those outcomes.\n *\n * `page` wins over `offset`, as {@link FindParams} documents. `driverOffset`\n * is the value to hand a driver: it stays `undefined` when the caller named no\n * offset, because keyset pagination seeks with a `where` clause and must not\n * look like it is paging by offset.\n */\nexport function resolveFindWindow(\n params?: Pick<FindParams, \"limit\" | \"offset\" | \"page\">\n): { limit: number; offset: number; driverOffset: number | undefined } {\n const limit = params?.limit ?? DEFAULT_LIST_LIMIT;\n const offset = params?.page != null\n ? Math.max(0, (params.page - 1) * limit)\n : (params?.offset ?? 0);\n return {\n limit,\n offset,\n driverOffset: params?.page != null ? offset : params?.offset\n };\n}\n\nfunction normalizePageSize(raw: number | undefined): number {\n if (raw === undefined || !Number.isFinite(raw)) return DEFAULT_PAGE_SIZE;\n return Math.max(1, Math.floor(raw));\n}\n\nfunction normalizeMaxPages(raw: number | undefined): number {\n if (raw === undefined) return DEFAULT_MAX_PAGES;\n if (raw === Number.POSITIVE_INFINITY) return raw;\n if (!Number.isFinite(raw)) return DEFAULT_MAX_PAGES;\n return Math.max(1, Math.floor(raw));\n}\n\nfunction normalizeMaxRows(raw: number | undefined): number {\n if (raw === undefined) return DEFAULT_FIND_ALL_MAX_ROWS;\n if (raw === Number.POSITIVE_INFINITY) return raw;\n if (!Number.isFinite(raw)) return DEFAULT_FIND_ALL_MAX_ROWS;\n return Math.max(0, Math.floor(raw));\n}\n\n/**\n * Walk every row a query matches, yielding one row at a time and fetching the\n * next page only when the consumer asks for it.\n *\n * See {@link SDKCollectionClient.iterate} for the caller-facing contract,\n * including the offset-drift caveat and the `cursor` alternative.\n *\n * @param find the transport's single-page read\n * @param params `find()` parameters minus the window, plus the walk options\n * @param label the collection name, so an error says which walk failed\n */\nexport async function* paginateFind<M extends Record<string, unknown> = Record<string, unknown>>(\n find: PageFinder<M>,\n params?: IterateParams<M>,\n label = \"collection\"\n): AsyncGenerator<M, void, undefined> {\n const {\n pageSize,\n cursor,\n maxPages,\n ...rest\n } = (params ?? {}) as IterateParams<M> & Record<string, unknown>;\n\n const findParams = { ...rest } as FindParams<M>;\n const size = normalizePageSize(pageSize as number | undefined);\n const pageCap = normalizeMaxPages(maxPages as number | undefined);\n\n // ── Cursor (keyset) setup ────────────────────────────────────────────────\n //\n // The walk no longer builds a keyset of its own. It used to: a `>`/`<` on\n // one column, expressed as an extra `where`, which threw on any multi-key\n // sort (\"keyset pagination advances along a single column\") and dropped\n // every row whose sort value was NULL, because `> value` answers *unknown*\n // against NULL. The driver has had a NULL-correct multi-key comparison all\n // along and nothing over HTTP could reach it.\n //\n // So this is now a *request* for seeking, not an implementation of it: the\n // server issues `meta.nextCursor` and the walk hands it back as `after`.\n // Multi-key sorts and nullable keys work because the comparison is the\n // driver's, and there is one of it.\n const seekRequested = cursor !== undefined && cursor !== null;\n if (seekRequested) {\n // A named column still means \"sort by this and seek along it\", which is\n // what every existing caller wrote. It is an `orderBy` now rather than\n // a second pagination mode — the seeking itself needs no column named,\n // since the cursor carries whatever keys the sort used.\n const field = typeof cursor === \"string\" ? cursor : cursor.field;\n const requested = (typeof cursor === \"object\" && cursor !== null) ? cursor.direction : undefined;\n const explicit = normalizeOrderBy(findParams.orderBy);\n // An explicit `orderBy` wins and the named column is redundant, not\n // wrong: seeking follows whatever the query is sorted by, so there is\n // no longer a mismatch to refuse.\n if (!explicit) {\n findParams.orderBy = [field, requested ?? \"asc\"] as FindParams<M>[\"orderBy\"];\n }\n }\n\n let offset = 0;\n let pages = 0;\n let after: string | undefined;\n\n for (;;) {\n if (pages >= pageCap) {\n throw new RebasePaginationError(\n \"max-pages\",\n `Iterating \"${label}\" made ${pages} requests without the server reporting the end of ` +\n `the collection. Stopping rather than looping forever — raise \\`maxPages\\` if the walk ` +\n `is genuinely this long, or check that the backend sets \\`meta.hasMore\\`.`\n );\n }\n\n const pageParams: FindParams<M> = { ...findParams, limit: size };\n if (seekRequested) {\n if (after) pageParams.after = after;\n } else {\n pageParams.offset = offset;\n }\n\n const page = await find(pageParams);\n pages += 1;\n\n const rows = page?.data ?? [];\n // A page with nothing on it always ends the walk, whatever the server\n // claims about `hasMore` — there is no cursor to advance and no offset\n // that would ever move past it.\n if (rows.length === 0) return;\n\n for (const row of rows) {\n yield row;\n }\n\n // The server is the only authority on whether more rows exist. Never\n // infer it from `rows.length >= size`: a last page that happens to be\n // exactly full is indistinguishable from a middle one, and guessing\n // there drops every row after it.\n if (page?.meta?.hasMore !== true) return;\n\n if (seekRequested) {\n const next = page.meta.nextCursor;\n if (!next) {\n throw new RebasePaginationError(\n \"cursor-missing\",\n `Cannot seek past the last row of \"${label}\": the server reported another page but ` +\n `issued no cursor for it. An ordering with no stored value to compare against — ` +\n `relevance (\\`_score\\`) — cannot key a cursor. Drop \\`cursor\\` to page by offset.`\n );\n }\n if (next === after) {\n throw new RebasePaginationError(\n \"cursor-stalled\",\n `Iterating \"${label}\" is stuck: two pages in a row ended on the same cursor, so the ` +\n `walk cannot advance. Continuing would loop forever. Page by offset instead, or ` +\n `report this — a cursor that does not move is a server-side bug.`\n );\n }\n after = next;\n } else {\n // Advance by what actually arrived, not by the page size: a server\n // free to return fewer rows than asked for would otherwise leave a\n // hole in the walk.\n offset += rows.length;\n }\n }\n}\n\n/**\n * {@link paginateFind}, collected into an array under a ceiling.\n *\n * See {@link SDKCollectionClient.findAll}.\n */\nexport async function collectAllPages<M extends Record<string, unknown> = Record<string, unknown>>(\n find: PageFinder<M>,\n params?: FindAllParams<M>,\n label = \"collection\"\n): Promise<M[]> {\n const { maxRows, ...rest } = (params ?? {}) as FindAllParams<M> & Record<string, unknown>;\n const cap = normalizeMaxRows(maxRows as number | undefined);\n\n const out: M[] = [];\n for await (const row of paginateFind<M>(find, rest as IterateParams<M>, label)) {\n out.push(row);\n if (out.length > cap) {\n throw new RebasePaginationError(\n \"max-rows\",\n `findAll(\"${label}\") matched more than ${cap} rows. Returning the first ${cap} would ` +\n `look like the whole answer and quietly not be one, so this throws instead. Raise ` +\n `\\`maxRows\\` if you meant to load them all, or stream with \\`iterate()\\`.`\n );\n }\n }\n return out;\n}\n\n/**\n * Build the `iterate` / `findAll` pair for one collection from its `find`.\n *\n * Both transports call this, which is what keeps the two implementations from\n * being two implementations.\n */\nexport function createPaginationHelpers<M extends Record<string, unknown> = Record<string, unknown>>(\n find: PageFinder<M>,\n label: string\n): {\n iterate: (params?: IterateParams<M>) => AsyncIterableIterator<M>;\n findAll: (params?: FindAllParams<M>) => Promise<M[]>;\n} {\n return {\n iterate: (params?: IterateParams<M>) => paginateFind<M>(find, params, label),\n findAll: (params?: FindAllParams<M>) => collectAllPages<M>(find, params, label)\n };\n}\n","/**\n * REST wire-format adapter for the unified filter system.\n *\n * This module is the ONLY code in the entire codebase that knows about\n * PostgREST-style dot-syntax strings (`eq.active`, `gt.18`, `in.(a,b)`).\n * Everything else speaks `FilterValues` exclusively.\n *\n * Wire-format values are always strings — the wire format carries no type\n * metadata, so type coercion is the responsibility of the server-side data\n * driver which has access to the collection schema.\n *\n * Structural characters inside a value are backslash-escaped: `,` → `\\,`,\n * `(` → `\\(`, `)` → `\\)`, and a literal backslash as `\\\\`. Decoding is\n * deliberately conservative — only those four sequences are decoded, so a\n * backslash that arrives unescaped from an older client survives intact.\n *\n * @module\n */\n\nimport {\n WhereFilterOp,\n FilterValues,\n ALL_WHERE_FILTER_OPS,\n CANONICAL_TO_REST,\n REST_TO_CANONICAL,\n RestFilterOp,\n toCanonicalOp,\n LogicalCondition,\n FilterCondition,\n LIST_OPS,\n NULL_OPS\n} from \"@rebasepro/types\";\nimport { normalizeToEntityRelation } from \"../util/entities\";\n\n// ---------------------------------------------------------------------------\n// Value stringification\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a JS value to its querystring representation.\n * `null` is serialized as the literal string `\"null\"`.\n * Relation values (`EntityRelation` instances or `{ __type: \"relation\", id, path }`\n * objects) are serialized as their raw id — the wire format only carries the\n * value to compare against the FK column.\n */\nfunction stringifyValue(value: unknown): string {\n if (value === null) return \"null\";\n const relation = normalizeToEntityRelation(value);\n if (relation) return String(relation.id);\n return String(value);\n}\n\n// ---------------------------------------------------------------------------\n// Comma escaping for list values\n// ---------------------------------------------------------------------------\n\n/**\n * Characters that carry structure in the wire format and must therefore be\n * escaped inside a value: the separator, the group delimiters, and the escape\n * character itself.\n *\n * Parentheses are here because `and(...)`/`or(...)` groups are parsed by\n * tracking paren depth. A value containing one is not merely ambiguous, it\n * moves where the parser thinks the group ends.\n */\nconst WIRE_SPECIALS = /[\\\\,()]/g;\n\n/**\n * Escape a value for the wire format: `\\` → `\\\\`, `,` → `\\,`, `(` → `\\(`,\n * `)` → `\\)`.\n */\n/**\n * The wire spelling of an empty list.\n *\n * A lone backslash: unproducible by {@link escapeWireValue}, which doubles\n * every backslash it emits, so it cannot collide with any real item.\n */\nconst EMPTY_LIST_TOKEN = \"\\\\\";\n\nfunction escapeWireValue(value: string): string {\n return value.replace(WIRE_SPECIALS, ch => `\\\\${ch}`);\n}\n\n/**\n * Unescape a wire-format value.\n *\n * **Conservative**, and deliberately so: only the four sequences\n * {@link escapeWireValue} actually produces are decoded. A backslash followed\n * by anything else is left exactly as it is.\n *\n * This used to consume the backslash before *any* character, which is\n * indistinguishable for anything this codec emitted — it only ever emits those\n * four — but not for input arriving from elsewhere. A client on an older\n * release sends a Windows path or a LIKE pattern with a literal `C:\\x`\n * unescaped, and greedy unescaping silently turned it into `C:x`, changing\n * which rows matched. Decoding only what the encoder can produce makes the two\n * directions agree across versions.\n */\nfunction unescapeWireValue(value: string): string {\n let result = \"\";\n for (let i = 0; i < value.length; i++) {\n const next = value[i + 1];\n if (value[i] === \"\\\\\" && (next === \"\\\\\" || next === \",\" || next === \"(\" || next === \")\")) {\n result += next;\n i++;\n continue;\n }\n result += value[i];\n }\n return result;\n}\n\n/**\n * Split a parenthesized list string on unescaped commas.\n * Input is the content between `(` and `)`.\n *\n * @example\n * splitListItems(\"admin,editor\") // [\"admin\", \"editor\"]\n * splitListItems(\"hello\\\\, world,foo\") // [\"hello, world\", \"foo\"]\n */\nfunction splitListItems(inner: string): string[] {\n const items: string[] = [];\n let current = \"\";\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === \"\\\\\" && i + 1 < inner.length) {\n // Escaped pair — consume both chars so the comma in `\\,` is not\n // read as a separator. Kept verbatim; decoding happens once, below.\n current += inner[i] + inner[i + 1];\n i++;\n } else if (inner[i] === \",\") {\n items.push(unescapeWireValue(current));\n current = \"\";\n } else {\n current += inner[i];\n }\n }\n items.push(unescapeWireValue(current));\n return items;\n}\n\n/**\n * Split a group body on commas at paren depth 0, honouring escapes.\n *\n * The escape-awareness is the point. The splitter used to track only paren\n * depth, so a comma inside a scalar value ended a condition:\n * `or(name.eq.Doe, John,age.gte.18)` parsed as *three* conditions, the middle\n * one a fabricated `\" John\" == true`. On an `or` that widens the result set,\n * and nothing anywhere reports an error — the query simply stops meaning what\n * the caller wrote.\n */\nfunction splitGroupItems(inner: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let start = 0;\n for (let i = 0; i < inner.length; i++) {\n const ch = inner[i];\n if (ch === \"\\\\\" && i + 1 < inner.length) { i++; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") depth--;\n else if (ch === \",\" && depth === 0) {\n parts.push(inner.slice(start, i));\n start = i + 1;\n }\n }\n parts.push(inner.slice(start));\n return parts;\n}\n\n// ---------------------------------------------------------------------------\n// Typed operator map lookups (no `as any`)\n// ---------------------------------------------------------------------------\n\n/**\n * Operator tables as `Map`s, because the key comes off the wire.\n *\n * Indexed as plain objects, every `Object.prototype` member answered: a query\n * string of `?f=valueOf.x` found a truthy \"operator\" — the inherited function —\n * and `deserializeTuple` returned it *as the operator*, so a function object\n * travelled on into the compilers in place of a `WhereFilterOp`. The guard one\n * line below (`if (!canonicalOp)`) reads as though it rejects anything unknown,\n * and does not: `Object.prototype` is not unknown to a plain object.\n *\n * Same shape as the prototype-key defects swept out of `setIn`, `getIn`,\n * `mergeDeep`, `unflattenObject` and `FOREIGN_CONVENTION_UIDS`.\n */\nconst REST_OP_LOOKUP = new Map<string, WhereFilterOp>(\n Object.entries(REST_TO_CANONICAL) as [string, WhereFilterOp][]\n);\nconst CANONICAL_OP_LOOKUP = new Map<string, RestFilterOp>(\n Object.entries(CANONICAL_TO_REST) as [string, RestFilterOp][]\n);\n\n// ---------------------------------------------------------------------------\n// Unknown operators\n// ---------------------------------------------------------------------------\n\n/** The operator spellings a rejection lists back to the caller. */\nconst VALID_OPERATOR_LIST = ALL_WHERE_FILTER_OPS.join(\", \");\n\n/**\n * A filter condition named an operator this dialect does not have.\n *\n * ## Why this throws, rather than returning a typed rejection\n *\n * `deserializeFilter` is the *shared* codec: the REST ingress\n * (`packages/server/src/api/rest/query-parser.ts`), the browser SDK and the\n * admin panel (`buildRebaseData.ts`) all decode through it. Two constraints\n * follow.\n *\n * - It cannot throw the server's `ApiError`. `@rebasepro/common` does not\n * depend on `@rebasepro/server` (the dependency runs the other way), and a\n * browser client has no error handler to render an `ApiError` with. So the\n * rejection is this plain `Error` subclass, whose `message` reads correctly\n * wherever it surfaces — a rejected promise in an app, a 400 body over HTTP.\n * - It cannot be a returned rejection *value*. Every caller assigns the result\n * straight into a query it is about to run; a sentinel that none of them\n * check would be ignored, which is exactly the silently-wrong-filter failure\n * this exists to stop. Throwing is also what this file already does for the\n * sibling cases — `serializeTuple` on an unknown canonical operator,\n * `deserializeLogicalCondition` past the nesting bound — and the REST parser\n * already converts the latter into a 400.\n *\n * `statusCode`, `code` and `details` are carried as fields because the server's\n * Hono error handler duck-types those off any thrown error: a decode path that\n * forgets to convert still answers 400 with the canonical envelope instead of a\n * 500 that says \"An unexpected error occurred\". `query-parser.ts` converts\n * explicitly all the same — that is the path the contract is stated on, and an\n * incidental 400 is not a contract.\n */\nexport class UnknownFilterOperatorError extends Error {\n /** The field the condition was written against. */\n public readonly field: string;\n /** The operator string as it arrived, verbatim. */\n public readonly operator: string;\n /** Every operator this dialect accepts, in canonical spelling. */\n public readonly validOperators: readonly WhereFilterOp[] = ALL_WHERE_FILTER_OPS;\n /** See the class docblock: read by the server's error handler. */\n public readonly statusCode = 400;\n public readonly code = \"UNKNOWN_FILTER_OPERATOR\";\n public readonly details: { field: string; operator: string; validOperators: readonly WhereFilterOp[] };\n\n constructor(field: string, operator: string) {\n super(\n `Unknown filter operator '${operator}' on field '${field}'. `\n + `Valid operators: ${VALID_OPERATOR_LIST}`\n );\n this.name = \"UnknownFilterOperatorError\";\n this.field = field;\n this.operator = operator;\n this.details = { field, operator, validOperators: ALL_WHERE_FILTER_OPS };\n }\n}\n\n/**\n * Two to three characters of ASCII punctuation and nothing else — the shape\n * every symbolic operator has (`==`, `>=`, `<>`, `~~`, `!!`, `>>`, `===`), and\n * one a column value effectively never has.\n *\n * Two characters minimum on purpose. A *single* punctuation character is a\n * perfectly ordinary value — `{ grade: [\"-\", \"+\"] }` is a two-item list, not a\n * condition — and the only single-character operator anyone actually mistypes\n * is `=`, which is named separately below. `<` and `>` need no special case:\n * they are real operators and resolve.\n */\nconst SYMBOLIC_OPERATOR = /^[^\\p{L}\\p{N}\\s]{2,3}$/u;\n\n/** Lowercase, strip everything that is not a letter or digit. */\nfunction normalizeOperatorName(op: string): string {\n return op.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\n/**\n * Every real operator name with its case and separators removed, so a\n * respelling of one — `arrayContains`, `not_in`, `NOT-LIKE`, `isNull` — is\n * recognised as an attempt at an operator rather than read as a value.\n *\n * These are rejected rather than accepted: admitting a second spelling of an\n * operator would leave two wire spellings of one thing, and the rejection\n * message names the one that works.\n */\nconst RESPELLED_OPERATORS: ReadonlySet<string> = new Set(\n [...ALL_WHERE_FILTER_OPS, ...Object.keys(REST_TO_CANONICAL)].map(normalizeOperatorName)\n);\n\n/**\n * Operator names *other* query dialects use, which this one does not have.\n *\n * This list is curated, and deliberately so. For a word-shaped string there is\n * no rule that separates \"an operator the caller guessed\" from \"a value that\n * happens to be a word\": `{ tags: [\"a\", \"b\"] }` has to keep meaning a two-item\n * `in` list, so the codec cannot simply refuse every unrecognised word in\n * position 0. The line is therefore drawn by name, and only around names whose\n * use as an operator is far more likely than their use as one of two sibling\n * values. `contains` is the motivating case — the first thing a developer\n * reaches for, and until now it compiled to `title IN ('contains', 'Hell')`.\n *\n * Genuinely ambiguous single words (`any`, `all`, `exists`, `search`, `not`)\n * are left off: as operators they are rare, and as enum values they are common.\n * Everywhere else the tie goes to *rejecting*, because a 400 naming the\n * supported set costs the caller one round trip, and the alternative — which is\n * what every name on this list used to produce — is a query that runs, returns\n * rows, and is wrong.\n */\nconst NEAR_MISS_OPERATORS: ReadonlySet<string> = new Set([\n \"contains\", \"notcontains\", \"doesnotcontain\", \"doesnotcontains\",\n \"includes\", \"notincludes\",\n \"startswith\", \"notstartswith\", \"beginswith\", \"startingwith\",\n \"endswith\", \"notendswith\",\n \"matches\", \"notmatches\", \"regex\", \"regexp\",\n \"between\", \"notbetween\",\n \"equals\", \"notequals\", \"equalto\", \"isequalto\", \"isnotequalto\",\n \"greaterthan\", \"greaterthanorequal\", \"greaterthanorequalto\",\n \"lessthan\", \"lessthanorequal\", \"lessthanorequalto\",\n \"isempty\", \"isnotempty\",\n \"oneof\", \"noneof\", \"anyof\", \"allof\",\n \"null\", \"isnullorempty\"\n]);\n\n/**\n * Was this string *meant* as an operator?\n *\n * Only consulted after {@link toCanonicalOp} has already failed to resolve it,\n * so a `true` here is always a rejection.\n */\nfunction isOperatorShaped(op: string): boolean {\n if (op === \"=\") return true;\n if (SYMBOLIC_OPERATOR.test(op)) return true;\n const normalized = normalizeOperatorName(op);\n if (!normalized) return false;\n return RESPELLED_OPERATORS.has(normalized) || NEAR_MISS_OPERATORS.has(normalized);\n}\n\n/**\n * Read a `[op, value]` tuple, if that is what this is.\n *\n * Three outcomes, and the middle one is the defect this function exists for:\n *\n * - the operator resolves (canonical *or* REST spelling) → the canonical tuple;\n * - the operator does not resolve but was plainly meant as one → throw;\n * - it does not look like an operator at all → `undefined`, and the caller\n * falls back to reading the array as a list of values.\n *\n * The old test was `toCanonicalOp(raw[0]) === raw[0]`, i.e. canonical spelling\n * only, with *everything else* — including every REST short-code — dropping\n * through to `[\"in\", raw]`. So the operator string itself became a value in a\n * membership test: `[\"!!\", \"Hello\"]` compiled to `title IN ('!!','Hello')`,\n * which matches, and the caller got back rows their filter was written to\n * exclude. `[\"eq\", \"active\"]` had the same shape of failure.\n */\nfunction readTuple(field: string, raw: unknown): [WhereFilterOp, unknown] | undefined {\n if (!Array.isArray(raw) || raw.length !== 2) return undefined;\n const [op, value] = raw;\n if (typeof op !== \"string\") return undefined;\n\n const canonical = toCanonicalOp(op);\n if (canonical) return [canonical, value];\n\n // A dot means this is a *wire* string, not an operator token: two repeated\n // query params arrive as `[\"gte.18\", \"lt.65\"]`, which is a two-element array\n // of strings and therefore tuple-shaped. Deferred with exactly the test the\n // repeated-dot-string branch below uses, so the two cannot disagree.\n //\n // The property test found this: `[\"ilike\", \"\"]` serializes to `\"ilike.\"`,\n // whose normalized form is a real operator name, so a well-formed\n // round-trip was being rejected as a bad operator.\n if (op.includes(\".\")) return undefined;\n\n if (isOperatorShaped(op)) throw new UnknownFilterOperatorError(field, op);\n\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Serialize: FilterValues → REST querystring\n// ---------------------------------------------------------------------------\n\n/**\n * Encode the `<op>.<value>` half of a wire condition.\n *\n * This is the single leaf encoder. Both wire positions that carry a condition\n * — a top-level query parameter (`?status=eq.active`) and a leaf inside an\n * `and(...)`/`or(...)` group (`or(status.eq.active,…)`) — go through it, so a\n * rule expressed here holds in both. The group serializer used to carry its\n * own copy, and the copy had drifted on every rule that matters: `null` went\n * out as the four-character string, the empty list as `()`, and an operator\n * this dialect does not have was silently rewritten to `eq` — a filter that\n * ran, returned rows, and answered a different question than the one asked.\n *\n * `escapeScalar` is the one thing the two positions legitimately disagree\n * about. A scalar in a query parameter owns the whole value and needs no\n * escaping; a scalar inside a group sits between the same commas a list item\n * does, so a comma in it would end the condition early.\n */\nfunction serializeOperatorAndValue(\n op: WhereFilterOp,\n value: unknown,\n { escapeScalar, where }: { escapeScalar: boolean; where: string }\n): string {\n if (typeof op !== \"string\") {\n throw new TypeError(\n `${where}: operator must be a string, got ${typeof op}`\n );\n }\n\n // Canonical spellings only, on purpose: this codec parses liberally and\n // emits strictly. `deserializeFilter` accepts a REST short-code because one\n // arrives off the wire; a *caller* handing one to the serializer has a\n // condition object built by hand, and the spelling it wants is the one the\n // types name.\n //\n // The throw is the fix. `serializeLogicalCondition` used to end this lookup\n // with `?? \"eq\"`, so `{ operator: \"gte\" }` — the spelling the wire uses, and\n // therefore the one most often guessed — was sent as `age.eq.18`: a query\n // that ran, returned rows, and answered a different question.\n const restOp = CANONICAL_OP_LOOKUP.get(op);\n if (!restOp) {\n throw new TypeError(\n `${where}: unknown operator \"${op}\". Valid operators: ${Object.keys(CANONICAL_TO_REST).join(\", \")}`\n );\n }\n\n // `== null` and `!= null` go out as the null-testing operators.\n //\n // They used to serialize as `eq.null`, and `deserializeTuple` had no way to\n // tell that from a search for the four-character string \"null\" — so it\n // returned the string, and `.where(\"deleted_at\", \"==\", null)` compiled to\n // `deleted_at = 'null'` over HTTP. The typed builder allows it, the Postgres\n // compiler implements it as IS NULL, and only the wire trip broke it.\n //\n // These are the same query: SQL `= NULL` is never true, so `== null` can\n // only mean IS NULL. Emitting it as such is unambiguous in both directions\n // and leaves `eq.null` free to mean the literal string, which it now does.\n if (value === null && (op === \"==\" || op === \"!=\")) {\n return op === \"==\" ? \"isnull.null\" : \"notnull.null\";\n }\n\n // A null test has no operand. Whatever was parked in `value` is dropped\n // here rather than on the way back, so the encoding is stable: both\n // deserializers normalize `isnull.<anything>` to `null`, and re-encoding\n // that must land on the same string it came from.\n if (NULL_OPS.has(op)) return `${restOp}.null`;\n\n if (Array.isArray(value)) {\n // The empty list needs a spelling of its own.\n //\n // A comma-joined format has no way to write \"zero items\": `()` is the\n // empty string between the parens, which splits to `[\"\"]`. So\n // `.where(\"id\", \"in\", [])` — which matches nothing — used to arrive as\n // a search for the empty string: a 500 on a uuid column, silently the\n // wrong rows on a text one.\n //\n // `EMPTY_LIST_TOKEN` is a single unescaped backslash, which no real\n // value can produce: `escapeWireValue` doubles every backslash, so a\n // one-item list holding `\\` serializes as `(\\\\)`. That keeps both\n // directions exact — `[]` and `[\"\"]` stay distinct — rather than\n // trading one lossy reading for another.\n if (value.length === 0) return `${restOp}.(${EMPTY_LIST_TOKEN})`;\n const items = value.map(v => escapeWireValue(stringifyValue(v))).join(\",\");\n return `${restOp}.(${items})`;\n }\n\n const scalar = stringifyValue(value);\n return `${restOp}.${escapeScalar ? escapeWireValue(scalar) : scalar}`;\n}\n\n/**\n * Serialize a single canonical condition tuple to a PostgREST dot-string.\n *\n * Throws `TypeError` if the input is not a valid `[WhereFilterOp, unknown]` tuple.\n *\n * @example\n * serializeTuple([\"==\", \"active\"]) // \"eq.active\"\n * serializeTuple([\"in\", [\"admin\",\"editor\"]]) // \"in.(admin,editor)\"\n * serializeTuple([\">=\", 18]) // \"gte.18\"\n */\nfunction serializeTuple(tuple: [WhereFilterOp, unknown]): string {\n if (!Array.isArray(tuple) || tuple.length !== 2) {\n throw new TypeError(\n `serializeTuple: expected a [WhereFilterOp, value] tuple, got ${JSON.stringify(tuple)}`\n );\n }\n\n const [op, value] = tuple;\n return serializeOperatorAndValue(op, value, {\n escapeScalar: false,\n where: \"serializeTuple\"\n });\n}\n\n/**\n * Convert `FilterValues` (or `WireFilterValues`) to a PostgREST-style\n * querystring record.\n *\n * - Canonical `[WhereFilterOp, value]` tuples are serialized strictly.\n * - Pre-serialized PostgREST strings (e.g. `\"eq.published\"`) are passed through.\n * - Single conditions produce a string value.\n * - Multiple conditions on the same field produce a string array (repeated params).\n *\n * @example\n * serializeFilter({ status: [\"==\", \"active\"] })\n * // → { status: \"eq.active\" }\n *\n * serializeFilter({ age: [[\">=\", 18], [\"<\", 65]] })\n * // → { age: [\"gte.18\", \"lt.65\"] }\n *\n * // Pre-serialized strings pass through unchanged:\n * serializeFilter({ status: \"eq.published\" })\n * // → { status: \"eq.published\" }\n */\nexport function serializeFilter(\n filter: FilterValues<string> | Record<string, unknown>\n): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n\n for (const [field, condition] of Object.entries(filter)) {\n if (condition === undefined) continue;\n\n // Pre-serialized PostgREST string — pass through unchanged.\n // This supports WireFilterValues where values may already be\n // serialized dot-strings like \"eq.active\" or raw strings like \"true\".\n if (typeof condition === \"string\") {\n result[field] = condition;\n continue;\n }\n\n // Multiple conditions on the same field: array of tuples\n // We detect this by checking if the first element is also an array.\n if (Array.isArray(condition) && condition.length > 0 && Array.isArray(condition[0])) {\n result[field] = (condition as [WhereFilterOp, unknown][]).map(serializeTuple);\n } else {\n // Single condition — must be a [WhereFilterOp, value] tuple\n result[field] = serializeTuple(condition as [WhereFilterOp, unknown]);\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Deserialize: REST querystring → FilterValues\n// ---------------------------------------------------------------------------\n\n/**\n * The spellings a null-testing operator's operand may take.\n *\n * The serializer writes `isnull.null`; a hand-written `isnull.true` means the\n * same thing and has always been accepted. Anything else after the operator is\n * not an operand it has — `notnull.reason` is a *value* — see\n * {@link deserializeSingle}.\n */\nconst NULL_OPERANDS: ReadonlySet<string> = new Set([\"null\", \"true\", \"false\", \"\"]);\n\n/**\n * Parse a single PostgREST dot-string into a `[WhereFilterOp, unknown]` tuple.\n *\n * All values are returned as strings — the wire format carries no type\n * metadata, so coercion is the data driver's responsibility.\n *\n * ## When a leading segment is an operator, and when it is part of the value\n *\n * `?status=in.progress` and `?status=in.(a,b)` differ by one character and mean\n * entirely different things, and the reading here decides which. The rule, in\n * full:\n *\n * > A dot-string is read as `operator.operand` **only** when its first segment\n * > names a known REST operator **and** what follows is a well-formed operand\n * > *for that operator's arity*. Otherwise the whole string is the value.\n *\n * Arity, per operator family:\n *\n * - **List** operators (`in`, `nin`, `csa` — `LIST_OPS`) take a parenthesised\n * list and nothing else. `in.(draft,review)` is the operator; `in.progress`\n * is the *value* `\"in.progress\"`, because there is no list there and so no\n * `in` filter that could have been written. That case used to compile to\n * `status IN ('progress')` — a filter the caller never wrote, quietly\n * matching the wrong rows and, on a status field, hiding every row they were\n * looking for.\n * - **Null** operators (`isnull`, `notnull` — {@link NULL_OPS}) take no\n * operand: only {@link NULL_OPERANDS}. `notnull.reason` is the value\n * `\"notnull.reason\"`, not \"reason is not null\".\n * - **Everything else** takes one scalar, and any remainder is one — including\n * the empty string, so `eq.` really is \"equals the empty string\".\n *\n * ### The one ambiguity that remains, and how to write past it\n *\n * A scalar operator's operand is unconstrained, so `?status=like.that` is a\n * `LIKE 'that'` and no rule at this layer can tell it from the literal value\n * `\"like.that\"` — both are well-formed encodings, and picking either by guess\n * would break the other. Two spellings say \"value\" unambiguously, and both\n * round-trip:\n *\n * - `?status=eq.like.that` — name the operator. The *first* segment is consumed\n * as the operator and everything after it is the value, dots and all. This is\n * what `serializeFilter` emits, which is why the SDK never meets the\n * ambiguity at all.\n * - `?where={\"status\":[\"==\",\"like.that\"]}` — the JSON dialect's tuple form.\n *\n * Values that merely *contain* dots (`user@host.com`, `1.2.3`) were never\n * ambiguous: their first segment names no operator to begin with.\n */\nfunction deserializeSingle(raw: string): [WhereFilterOp, unknown] {\n const dotIndex = raw.indexOf(\".\");\n if (dotIndex === -1) {\n // No dot → equality on the raw value (kept as string)\n return [\"==\", raw];\n }\n\n const prefix = raw.substring(0, dotIndex);\n const rest = raw.substring(dotIndex + 1);\n\n // Check if the prefix is a known REST operator.\n // This is the key defense against values like \"eq.something\" or \"gt.foo\"\n // being misinterpreted — only known REST short-codes are treated as operators.\n const canonicalOp = REST_OP_LOOKUP.get(prefix);\n if (!canonicalOp) {\n // Not a known operator (e.g., email \"user@host.com\" or version \"1.2.3\")\n // Treat the entire string as an equality value\n return [\"==\", raw];\n }\n\n // Null-testing operators ignore their serialized value — normalize to null\n // so the tuple round-trips stably (`isnull.null` → [\"is-null\", null]).\n if (NULL_OPS.has(canonicalOp)) {\n // ...but only when what follows is an operand this operator has. See\n // the docblock: `notnull.reason` names no null test, so it is a value.\n if (!NULL_OPERANDS.has(rest)) return [\"==\", raw];\n return [canonicalOp, null];\n }\n\n // Parse list values: \"(admin,editor)\" → [\"admin\", \"editor\"]\n if (rest.startsWith(\"(\") && rest.endsWith(\")\")) {\n const inner = rest.slice(1, -1);\n // See EMPTY_LIST_TOKEN: `(\\)` is the empty list. `()` remains a list\n // holding one empty string, which is what splitting it yields anyway.\n const items = inner === EMPTY_LIST_TOKEN ? [] : splitListItems(inner);\n return [canonicalOp, items];\n }\n\n // A list operator with no list is not that operator — see the docblock.\n // `?status=in.progress` is the value \"in.progress\"; the `in` filter it used\n // to compile to was never written by anyone.\n if (LIST_OPS.has(canonicalOp)) return [\"==\", raw];\n\n return [canonicalOp, rest];\n}\n\n/**\n * Convert a PostgREST-style querystring record to `FilterValues`.\n *\n * - String values are parsed as single conditions.\n * - String arrays (repeated query params) become multiple conditions on the same field.\n *\n * @example\n * deserializeFilter({ status: \"eq.active\" })\n * // → { status: [\"==\", \"active\"] }\n *\n * deserializeFilter({ age: [\"gte.18\", \"lt.65\"] })\n * // → { age: [[\">=\", \"18\"], [\"<\", \"65\"]] }\n *\n * @throws {UnknownFilterOperatorError} when a condition names an operator this\n * dialect does not have. See that class for why a rejection here is a throw.\n */\nexport function deserializeFilter(\n query: Record<string, unknown>\n): FilterValues<string> {\n const result: FilterValues<string> = {};\n\n for (const [field, raw] of Object.entries(query)) {\n if (raw === undefined) continue;\n\n // A single `[op, value]` condition.\n const tuple = readTuple(field, raw);\n if (tuple) {\n result[field] = tuple;\n continue;\n }\n\n if (Array.isArray(raw)) {\n if (raw.length === 0) continue;\n\n // An array of tuples: several conditions on the same field. Every\n // element is checked, not just the first — the old test read\n // `raw[0]` and cast the whole array, so one bad operator among\n // several travelled on untouched.\n if (Array.isArray(raw[0])) {\n const tuples = raw.map(item => readTuple(field, item));\n if (tuples.every((t): t is [WhereFilterOp, unknown] => t !== undefined)) {\n result[field] = tuples;\n continue;\n }\n }\n\n if (raw.length === 1) {\n result[field] = typeof raw[0] === \"string\" ? deserializeSingle(raw[0]) : [\"==\", raw[0]];\n } else {\n // If the elements are strings, they might be PostgREST dot-strings (repeated params)\n if (typeof raw[0] === \"string\" && raw[0].includes(\".\")) {\n result[field] = raw.map(r => typeof r === \"string\" ? deserializeSingle(r) : ([\"==\", r] as [WhereFilterOp, unknown])) as [WhereFilterOp, unknown][];\n } else {\n // Otherwise assume it's a list of values for an implicit\n // \"in\" — `{ tags: [\"a\",\"b\"] }`, and `?tags=a&tags=b`, which\n // arrives here identically.\n //\n // A two-element array reaches this line only after\n // `readTuple` has decided its first element was not meant\n // as an operator. Everything longer never had the\n // ambiguity: an operator tuple has exactly two slots.\n result[field] = [\"in\", raw];\n }\n }\n } else if (typeof raw === \"string\") {\n result[field] = deserializeSingle(raw);\n } else {\n result[field] = [\"==\", raw];\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Logical conditions: serialize / deserialize\n// ---------------------------------------------------------------------------\n\n/**\n * Serialize a `LogicalCondition` or `FilterCondition` to its wire-format string.\n *\n * Leaf encoding is {@link serializeOperatorAndValue}, the same function\n * `serializeTuple` uses, so `null`, the empty list and an unknown operator\n * behave identically inside a group and in a query parameter.\n *\n * @throws {TypeError} when a leaf names an operator this dialect does not have.\n * It used to fall back to `eq`, which turned `age >= 18` into `age = 18` with\n * no diagnostic anywhere.\n *\n * @example\n * serializeLogicalCondition({ column: \"status\", operator: \"==\", value: \"active\" })\n * // → \"status.eq.active\"\n *\n * serializeLogicalCondition({ column: \"deleted_at\", operator: \"==\", value: null })\n * // → \"deleted_at.isnull.null\"\n *\n * serializeLogicalCondition({ type: \"or\", conditions: [...] })\n * // → \"or(status.eq.active,status.eq.pending)\"\n */\nexport function serializeLogicalCondition(\n cond: LogicalCondition | FilterCondition\n): string {\n if (\"type\" in cond) {\n // LogicalCondition (and/or)\n const inner = (cond.conditions ?? [])\n .map(serializeLogicalCondition)\n .join(\",\");\n return `${cond.type}(${inner})`;\n }\n\n // FilterCondition. The leaf goes through the shared encoder, so a group\n // condition and a query parameter agree on nulls, empty lists and unknown\n // operators — see `serializeOperatorAndValue`.\n //\n // The column is escaped like a value: it is not one, but it shares the\n // delimiters, and a comma or paren in it would move where the group parser\n // thinks the condition ends. Dots are deliberately *not* escaped — a\n // relation path is `author.name` on the wire, and the parser below finds\n // the operator rather than assuming it is the second segment.\n return `${escapeWireValue(cond.column)}.${serializeOperatorAndValue(cond.operator, cond.value, {\n escapeScalar: true,\n where: \"serializeLogicalCondition\"\n })}`;\n}\n\n/**\n * Split a leaf condition into `column`, operator token and value.\n *\n * The naive reading — column is everything before the first dot, operator is\n * everything up to the second — cannot express a relation path. A filter on\n * `author.name` serializes to `author.name.eq.bob` and came back as the column\n * `author` with the operator `name`, which resolves to nothing, so the\n * fallback made it `author == \"eq.bob\"`: a condition that runs and matches\n * nothing, on a column the caller never named.\n *\n * So the operator is found rather than assumed: it is the first dot-separated\n * segment after the column that resolves to a real operator. Everything before\n * it is the column, everything after is the value. `version.eq.1.2.3` reads as\n * `version == \"1.2.3\"` because the scan stops at the first match — the `eq` at\n * offset 1, not a later segment — and `metadata->>x.eq.5` never had dots in the\n * column to begin with.\n *\n * Returns `undefined` when no segment resolves — `status.active`, an equality\n * written without an operator, which the caller handles.\n */\nfunction splitLeafCondition(str: string): { column: string; operator: WhereFilterOp; value: string } | undefined {\n // Dots inside a list value (`in.(1.5,2.5)`) are not separators. The value\n // always follows the operator, so the search only needs the region before\n // the first unescaped paren.\n let limit = str.length;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === \"\\\\\") { i++; continue; }\n if (str[i] === \"(\") { limit = i; break; }\n }\n\n const dots: number[] = [];\n for (let i = 0; i < limit; i++) {\n if (str[i] === \"\\\\\") { i++; continue; }\n if (str[i] === \".\") dots.push(i);\n }\n\n // Segment 0 is always the column, and an operator needs a value after it,\n // so a candidate is bounded on both sides by a dot.\n for (let i = 1; i < dots.length; i++) {\n const operator = toCanonicalOp(str.substring(dots[i - 1] + 1, dots[i]));\n if (!operator) continue;\n return {\n column: unescapeWireValue(str.substring(0, dots[i - 1])),\n operator,\n value: str.substring(dots[i] + 1)\n };\n }\n\n return undefined;\n}\n\n/**\n * Parse a logical condition wire-format string back into a\n * `LogicalCondition` or `FilterCondition`.\n *\n * @example\n * deserializeLogicalCondition(\"status.eq.active\")\n * // → { column: \"status\", operator: \"==\", value: \"active\" }\n *\n * deserializeLogicalCondition(\"or(status.eq.active,age.gte.18)\")\n * // → { type: \"or\", conditions: [...] }\n */\n/**\n * How deeply `or(...)`/`and(...)` groups may nest.\n *\n * This parser recurses once per level, on a value that arrives in a query\n * string. Unbounded, twenty thousand levels reached `RangeError: Maximum call\n * stack size exceeded`, which a caller sees as a 500 about the call stack\n * rather than a 400 about their filter. Node's 16 KB header cap keeps a GET\n * below that in practice, but \"the HTTP layer happens to stop it\" is not a\n * bound this parser should rely on.\n *\n * Thirty-two is far past anything a real filter expresses; the deepest in this\n * repository's own tests is three.\n */\nexport const MAX_LOGICAL_NESTING_DEPTH = 32;\n\nexport function deserializeLogicalCondition(\n str: string,\n // Not `depth`: the body already uses that name for paren tracking, inside a\n // block that shadows a parameter of the same name — so the recursion\n // counter silently became the paren counter and never grew.\n nesting = 0\n): LogicalCondition | FilterCondition {\n if (nesting > MAX_LOGICAL_NESTING_DEPTH) {\n throw new Error(\n `Filter groups nest more than ${MAX_LOGICAL_NESTING_DEPTH} levels deep. ` +\n \"Flatten the condition — `or(a,or(b,c))` is `or(a,b,c)`.\"\n );\n }\n // Check for logical group: \"and(...)\", \"or(...)\" or \"not(...)\"\n const logicalMatch = str.match(/^(and|or|not)\\((.+)\\)$/);\n if (logicalMatch) {\n const type = logicalMatch[1] as \"and\" | \"or\" | \"not\";\n const innerStr = logicalMatch[2];\n\n const conditions = splitGroupItems(innerStr)\n .map(part => deserializeLogicalCondition(part, nesting + 1));\n\n return { type, conditions };\n }\n\n // FilterCondition: \"column.op.value\"\n const leaf = splitLeafCondition(str);\n if (!leaf) {\n const firstDot = str.indexOf(\".\");\n if (firstDot === -1) {\n return { column: unescapeWireValue(str), operator: \"==\", value: true };\n }\n // \"column.value\" — no segment resolved as an operator, so this is an\n // equality written without one. The value keeps its dots.\n return {\n column: unescapeWireValue(str.substring(0, firstDot)),\n operator: \"==\",\n value: unescapeWireValue(str.substring(firstDot + 1))\n };\n }\n\n const { column, operator, value: valueStr } = leaf;\n\n // A null test has no operand: `isnull.null` is what the serializer writes,\n // but a hand-written `isnull.true` means the same thing. Normalizing here\n // is what makes the tuple stable through a re-encode, and it matches\n // `deserializeSingle`, which has done it for query parameters all along.\n if (NULL_OPS.has(operator)) {\n return { column, operator, value: null };\n }\n\n // Parse list values with escape-aware splitting. The wrapping parens are\n // written by the serializer *after* the items are escaped, so an escaped\n // paren inside an item can never be mistaken for them.\n if (valueStr.startsWith(\"(\") && valueStr.endsWith(\")\")) {\n const inner = valueStr.slice(1, -1);\n // See EMPTY_LIST_TOKEN: `(\\)` is the empty list, which is not the same\n // query as a search for the empty string.\n const items = inner === EMPTY_LIST_TOKEN ? [] : splitListItems(inner);\n return { column, operator, value: items };\n }\n\n return { column, operator, value: unescapeWireValue(valueStr) };\n}\n","import { CollectionAccessor, DataDriver, Entity, EntityValues, FindAllParams, FindParams, FindResponse, FindResult, IterateParams, LogicalCondition, OrderByTuple, PageWalkOptions, RebaseApiError, RebaseData, RebaseSdkData, RelationAggregateSort, SDKCollectionClient, SDKQueryBuilderInterface, sortKeyToString, type AggregateParams, type AggregateRow, type AggregateSelect, type ComputedSortField, type FieldPath, type IncludeSpec, type NonColumnFieldPath, type NullsPlacement, type SearchMatch, type UpdateValues, type UpsertOptions, WhereFilterOp, WhereValueFor, isUnsupported, unsupportedMethod } from \"@rebasepro/types\";\nimport { toSnakeCase, toWireKey } from \"@rebasepro/utils\";\nimport { cursorToStartAfter, decodeCursor, reconcileCursorOrder } from \"./cursor\";\nimport { mergeIncludeSpecs } from \"./include-spec\";\nimport { QueryBuilder } from \"./query_builder\";\nimport { collectAllPages, paginateFind, resolveFindWindow } from \"./paginate\";\nimport { normalizeOrderBy } from \"./sort-dialect\";\nimport { deserializeFilter } from \"./filter-dialect\";\nimport { buildCompositeId, resolvePrimaryKeys, PrimaryKeyInfo } from \"../util/identity\";\nimport { resolveCollectionRelations } from \"../util/relations\";\nimport { EntityRelation } from \"@rebasepro/types\";\n\n/**\n * What a client says when its data source cannot subscribe.\n *\n * Named rather than inlined so the sentence a caller sees does not depend on\n * which of the two adapters below happened to build the client.\n */\nconst noRealtime = (slug: string): string =>\n `Realtime is not available for \"${slug}\": its data source does not support subscriptions.`;\n\n/** What a client says when its data source cannot count. */\nconst noCount = (slug: string): string =>\n `Counting is not available for \"${slug}\": its data source does not support it.`;\n\n/**\n * Derive the response key an aggregate comes back under.\n *\n * `sum(total)` → `sum_total`, `count()` → `count`. Written once, here, because\n * the REST parser derives the same alias from `?select=sum(total)` and the two\n * have to agree — a caller reading `row.sum_total` off an SDK result and off an\n * HTTP response is reading the same key or the SDK is broken.\n */\nexport function aggregateAlias(fn: string, field?: string): string {\n return field ? `${fn}_${field}` : fn;\n}\n\nfunction toDriverAggregate(\n select: AggregateSelect<Record<string, unknown>>\n): { fn: \"count\" | \"sum\" | \"avg\" | \"min\" | \"max\"; field?: string; alias: string } {\n const field = select.field as string | undefined;\n return { fn: select.fn, field, alias: aggregateAlias(select.fn, field) };\n}\n\n/**\n * What a client says when its data source cannot aggregate.\n *\n * A stub rather than a fallback that fetches and reduces in JavaScript: that\n * would be wrong under a `limit` and unaffordable without one, and it would look\n * like it had worked.\n */\nconst noAggregate = (slug: string): string =>\n `Aggregates are not available for \"${slug}\": its data source does not implement them.`;\n\nexport interface EntityDataOptions {\n /**\n * Look up a collection's config by slug, to derive row addresses from its\n * primary keys.\n *\n * Called lazily rather than up front: the data layer is created by `Rebase`,\n * which sits *above* the admin that owns the collections, so a resolver\n * registered on mount would otherwise arrive too late to be seen.\n */\n resolveCollection?: (slug: string) => { properties?: Record<string, unknown>; relations?: unknown[]; slug?: string } | undefined;\n}\n\nfunction createPrimaryKeyResolver(options?: EntityDataOptions) {\n const cache = new Map<string, PrimaryKeyInfo[]>();\n const warned = new Set<string>();\n\n return function primaryKeysFor(slug: string): PrimaryKeyInfo[] {\n const cached = cache.get(slug);\n if (cached) return cached;\n\n const collection = options?.resolveCollection?.(slug);\n if (!collection) {\n // The registry may not have been registered yet. Don't memoize a\n // miss, or the collection would stay address-less for this session.\n return [];\n }\n\n const keys = resolvePrimaryKeys(collection);\n if (keys.length > 0) {\n // Memoized for the session: a collection's key does not change\n // while the app runs, and this is called once per row. Editing\n // `isId` in the schema editor needs a reload to take effect here.\n cache.set(slug, keys);\n return keys;\n }\n\n if (!warned.has(slug)) {\n warned.add(slug);\n // Silence here surfaces much later as rows that cannot be opened,\n // linked, or saved, with nothing pointing back at the cause.\n console.warn(\n `[rebase] Collection '${slug}' declares no primary key, so its rows have no address: ` +\n `detail links, caching and relations will not work for it. ` +\n `Mark the key property with \\`isId\\` in its collection config — the server logs which ` +\n `column to mark at boot, if its schema knows the key.`\n );\n }\n return keys;\n };\n}\n\n/**\n * Build the admin's view model out of the row the wire serves.\n *\n * The wire has ONE shape, for every consumer: flat columns, typed the way the\n * database typed them, and a relation rendered as the target's own columns (or\n * only its foreign key, when nothing asked for it). That is the REST contract,\n * what `find()` returns, what `listen()` pushes, and what the generated types\n * describe.\n *\n * The admin renders neither of those directly. Its date field requires a real\n * `Date` and rejects a string outright; its relation cells read `.data.values`\n * off a relation ref. Those requirements are the *admin's*, so they are met\n * here — in the browser, from the collection config the panel already has —\n * rather than by asking the server for a second wire shape.\n *\n * That second shape is what this replaces. Until 2026-09-09 the realtime wire\n * carried the view model and every other read carried flat rows, so `find()`\n * and `listen()` answered one query two ways; unifying the wire without doing\n * this conversion is what left every date cell reading \"Invalid date value\"\n * and every relation cell \"Unexpected value\".\n *\n * Values already in view-model form pass through untouched: a driver that\n * still sends `{ __type: \"date\" }` or a relation ref (the client revives both)\n * is served by the same walk.\n */\nfunction toViewModelValues(\n values: Record<string, unknown>,\n properties: Record<string, unknown> | undefined,\n collection: { properties?: Record<string, unknown>; relations?: unknown[]; slug?: string } | undefined,\n resolveCollection?: EntityDataOptions[\"resolveCollection\"]\n): Record<string, unknown> {\n if (!properties) return values;\n\n const relations = collection\n ? resolveCollectionRelations(collection as never)\n : {};\n let out: Record<string, unknown> | undefined;\n const write = (key: string, value: unknown) => {\n out = out ?? { ...values };\n out[key] = value;\n };\n\n for (const [key, rawProperty] of Object.entries(properties)) {\n const property = rawProperty as { type?: string; of?: { type?: string }; properties?: Record<string, unknown> } | undefined;\n if (!property) continue;\n\n // A relation nobody included is still a relation: the row carries only\n // its foreign key, and an addressable ref with no data attached is what\n // lets the preview fetch the one record it needs. Without this the\n // record form showed an empty chip where the customer goes — the panel\n // reads a form through `listenById`, which takes no `include`.\n if (!(key in values)) {\n const fkRelation = relations[key];\n // `localKey` is the column; the row is keyed the way the wire keys\n // it, which is that column camelCased (`customer_id` → `customerId`).\n const column = fkRelation && \"localKey\" in fkRelation ? fkRelation.localKey : undefined;\n const fk = column !== undefined\n ? values[column] ?? values[toWireKey(column)]\n : undefined;\n const fkTarget = fkRelation?.targetSlug;\n if (fkTarget && (typeof fk === \"string\" || typeof fk === \"number\")) {\n write(key, new EntityRelation(fk, fkTarget));\n }\n continue;\n }\n\n const value = values[key];\n if (value === null || value === undefined) continue;\n\n // A relation, under the property key or the relation name.\n const relation = relations[key];\n if (relation && (property.type === \"relation\" || property.of?.type === \"relation\" || property.type === \"array\")) {\n const target = relation.targetSlug;\n if (!target) continue;\n const targetProperties = resolveCollection?.(target)?.properties;\n const targetCollection = resolveCollection?.(target);\n const toRef = (item: unknown): unknown => {\n if (item instanceof EntityRelation) return item;\n if (typeof item === \"object\" && item !== null && \"__type\" in item) return item;\n // The target's own columns: the id it is addressed by, and the\n // values a relation cell renders without a second fetch.\n if (typeof item === \"object\" && item !== null) {\n const row = item as Record<string, unknown>;\n const keys = targetCollection ? resolvePrimaryKeys(targetCollection as never) : [];\n const id = keys.length > 0 ? buildCompositeId(row, keys) : row.id as string | number;\n if (id === undefined || id === null || id === \"\") return item;\n return new EntityRelation(id, target, {\n id,\n path: target,\n values: toViewModelValues(row, targetProperties, targetCollection, resolveCollection)\n });\n }\n // Only the foreign key came back — nothing asked for the\n // relation. Addressable, with nothing to render but its id.\n if (typeof item === \"string\" || typeof item === \"number\") {\n return new EntityRelation(item, target);\n }\n return item;\n };\n write(key, Array.isArray(value) ? value.map(toRef) : toRef(value));\n continue;\n }\n\n if (property.type === \"date\" && !(value instanceof Date)) {\n if (typeof value === \"string\" || typeof value === \"number\") {\n const date = new Date(value);\n write(key, isNaN(date.getTime()) ? null : date);\n }\n continue;\n }\n\n // A map's children are declared too, and a date two levels down is\n // still a date.\n if (property.type === \"map\" && property.properties && typeof value === \"object\" && !Array.isArray(value)) {\n write(key, toViewModelValues(value as Record<string, unknown>, property.properties, undefined, resolveCollection));\n }\n }\n\n return out ?? values;\n}\n\n/**\n * Give a flat row the Entity view-model the admin renders.\n *\n * The address is *derived here* — it is not a column, and the row it came from\n * does not contain one. Rows carry exactly what the table has, with the types\n * Postgres returned; the id is this layer's invention, and this is the only\n * place it is minted.\n *\n * `primaryKeys` empty falls back to a literal `id` on the row: drivers other\n * than postgres still serve rows with one, and this keeps them working.\n */\nfunction rowToEntity<M extends Record<string, unknown>>(\n row: Record<string, unknown>,\n slug: string,\n primaryKeys: PrimaryKeyInfo[] = [],\n /**\n * Turns the wire's row into the view model — see\n * {@link toViewModelValues}. Absent when the collections cannot be\n * resolved, which is every consumer that is not the admin: the flat SDK\n * derives itself from this layer and must keep the wire's own types.\n */\n toViewModel?: (values: Record<string, unknown>) => Record<string, unknown>\n): Entity<M> {\n // Query-computed metadata rides in on the row because that is how the wire\n // carries it, but it is not a column: it belongs beside `values`, not in\n // them. Left inside, `_matches` would show up in the record inspector as a\n // field the collection never declared.\n const { _matches, ...values } = row as Record<string, unknown> & { _matches?: SearchMatch[] };\n\n return {\n id: primaryKeys.length > 0\n ? buildCompositeId(row, primaryKeys)\n : row.id as string | number,\n path: slug,\n values: (toViewModel ? toViewModel(values) : values) as EntityValues<M>,\n ...(_matches ? { searchMatches: _matches } : {})\n };\n}\n\n/**\n * The relation envelope `toFlatRow` writes where a relation was:\n * `{ id, path, __type: \"relation\", data: { id, path, values } }`. It is the\n * admin's view-model, and the only pipeline that produces one is postgres'.\n */\nfunction isRelationEnvelope(\n value: unknown\n): value is { __type: \"relation\"; data?: { values?: Record<string, unknown> } } {\n return typeof value === \"object\"\n && value !== null\n && !Array.isArray(value)\n && (value as { __type?: unknown }).__type === \"relation\";\n}\n\n/** The target's own columns, as `toRestRow` would have inlined them. */\nfunction inlineEnvelope(envelope: { data?: { values?: Record<string, unknown> } }): Record<string, unknown> {\n return envelope.data?.values ?? {};\n}\n\n/**\n * Replace every relation envelope on a row with the target's flat columns.\n *\n * The SDK serves one relation shape — the inlined one (see\n * {@link RestFetchService}) — and Postgres now serves it on every read, so\n * against that driver this walk finds nothing to do. It stays for the drivers\n * whose own `fetchCollection` still answers with refs: a developer reading\n * through this accessor gets one shape whichever driver is underneath.\n *\n * Only applied where the REST pipeline is the contract (see `find`); a driver\n * without a `restFetchService` keeps whatever it returns.\n *\n * Note this is NOT how the admin gets its view model — that is built in the\n * browser by {@link toViewModelValues}, from the same flat row.\n */\nfunction inlineRelationRefs(row: Record<string, unknown>): Record<string, unknown> {\n let out: Record<string, unknown> | undefined;\n for (const [key, value] of Object.entries(row)) {\n if (isRelationEnvelope(value)) {\n out = out ?? { ...row };\n out[key] = inlineEnvelope(value);\n } else if (Array.isArray(value) && value.some(isRelationEnvelope)) {\n out = out ?? { ...row };\n out[key] = value.map((item) => isRelationEnvelope(item) ? inlineEnvelope(item) : item);\n }\n }\n return out ?? row;\n}\n\nfunction createDriverAccessor<M extends Record<string, unknown> = Record<string, unknown>>(\n driver: DataDriver,\n slug: string,\n getPks: () => PrimaryKeyInfo[] = () => [],\n toViewModel?: (values: Record<string, unknown>) => Record<string, unknown>\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams<M>): Promise<FindResponse<M>> {\n // Ensure filters are in canonical [op, value] format even if passed as PostgREST strings\n const filter = params?.where ? deserializeFilter(params.where as Record<string, unknown>) : undefined;\n const { limit, offset, driverOffset } = resolveFindWindow(params);\n\n // Keyset paging, through the same codec and the same driver\n // comparison the HTTP route uses. The in-process accessor is a\n // transport like any other: a walk that seeked differently here\n // than over the wire would be a difference the types cannot see.\n const cursor = params?.after ? decodeCursor(params.after) : undefined;\n const orderBy = cursor\n ? reconcileCursorOrder(cursor, normalizeOrderBy(params?.orderBy))\n : normalizeOrderBy(params?.orderBy);\n const startAfter = cursor ? cursorToStartAfter(cursor) : undefined;\n\n // One relation shape, whatever the call looks like.\n //\n // This used to fork on `include`: asking for one ran the REST\n // pipeline, which inlines a relation as the target's own columns;\n // not asking ran the driver's own fetch, which eagerly loaded\n // *every* relation and put a `{ __type: \"relation\" }` envelope\n // where the foreign key was. The same method answered in two\n // shapes, the generated types described only one, and a column\n // typed `string` arrived as an object.\n //\n // The REST pipeline is the published contract — the shape the HTTP\n // API serves for this same query, and what `RestFetchService`\n // documents — so every read goes through it when the driver has\n // one. Drivers without one (every browser driver, and so the\n // admin's own path through `buildRebaseData`) are untouched.\n //\n // One row past the page, when seeking.\n //\n // `hasMore` on an offset page is `offset + rows.length < total`, and\n // under a cursor that arithmetic is simply false: every seeked page\n // runs at offset 0, so it compares one page against the whole\n // collection and says \"more\" forever. Asking for `limit + 1` and\n // looking at whether the extra row arrived is the answer keyset\n // paging actually has — and it costs nothing, where the count it\n // replaces was a second query per page.\n const probeLimit = startAfter ? limit + 1 : limit;\n\n const fetchService = driver.restFetchService;\n const fetched = fetchService\n ? await fetchService.fetchCollectionForRest(\n slug,\n {\n filter,\n // Without this the group was dropped and the read ran\n // unfiltered — every row the caller's policies allow,\n // in place of the ones they asked for.\n logical: params?.logical,\n limit: probeLimit,\n // A cursor and an offset describe the same window two\n // incompatible ways; seeking wins and the offset is not\n // sent, or the page would start `offset` rows past\n // where the cursor pointed.\n offset: startAfter ? undefined : driverOffset,\n startAfter,\n orderBy,\n searchString: params?.searchString,\n fields: params?.fields,\n distinct: params?.distinct\n },\n params?.include\n )\n : await driver.fetchCollection<M>({\n path: slug,\n limit: probeLimit,\n offset: startAfter ? undefined : driverOffset,\n startAfter,\n filter,\n logical: params?.logical,\n orderBy,\n searchString: params?.searchString,\n include: params?.include,\n fields: params?.fields,\n distinct: params?.distinct\n });\n\n // The probe row is evidence, not data — it is never served.\n const seeking = startAfter !== undefined;\n const rows = seeking ? fetched.slice(0, limit) : fetched;\n\n // Compute real total when count is available\n let total = rows.length + offset;\n let hasMore = seeking ? fetched.length > limit : rows.length >= limit;\n if (driver.count) {\n // The same narrowing the rows were read with. Counting only by\n // `filter` reported the whole collection beside a narrowed\n // page, and `hasMore` is derived from it — so the list offered\n // a next page that did not exist.\n total = await driver.count({\n path: slug,\n filter,\n logical: params?.logical,\n searchString: params?.searchString\n });\n // ...but only for an *offset* page. `offset` is 0 on every\n // seeked page, so this arithmetic compares one page against the\n // whole collection and says \"more\" forever; the probe row above\n // is what answers it under a cursor.\n if (!seeking) hasMore = offset + rows.length < total;\n }\n\n // The cursor for the *next* page, from the last row served. Issued\n // by the driver, which is the only layer that knows which columns\n // address a row; absent where it cannot describe one, and the\n // caller then pages by offset.\n const last = rows[rows.length - 1] as Record<string, unknown> | undefined;\n const nextCursor = (hasMore && last && driver.restFetchService?.cursorFor)\n ? driver.restFetchService.cursorFor(slug, last, orderBy)\n : undefined;\n\n return {\n data: rows.map((row: Record<string, unknown>) => rowToEntity<M>(row, slug, getPks(), toViewModel)),\n meta: { total, limit, offset, hasMore, ...(nextCursor && { nextCursor }) }\n };\n },\n\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n // Same contract as `find` above: one row read the same way the\n // collection read is, so `find()[0]` and `findById()` agree.\n const fetchService = driver.restFetchService;\n const row = fetchService\n ? await fetchService.fetchOneForRest(slug, id)\n : await driver.fetchOne<M>({ path: slug, id: id });\n return row ? rowToEntity<M>(row, slug, getPks(), toViewModel) : undefined;\n },\n\n // Present only when the driver's fetch service implements it — the SDK\n // wrapper turns an absent one into a stub that names the capability.\n aggregate: driver.restFetchService?.aggregate\n ? async (params: AggregateParams<M>): Promise<AggregateRow[]> =>\n driver.restFetchService!.aggregate!(slug, {\n aggregates: params.select.map(toDriverAggregate),\n groupBy: params.groupBy as string[] | undefined,\n filter: params.where\n ? deserializeFilter(params.where as Record<string, unknown>)\n : undefined,\n logical: params.logical,\n searchString: params.searchString,\n limit: params.limit\n })\n : undefined,\n\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n const row = await driver.save<M>({\n path: slug,\n values: data,\n id: id,\n status: \"new\"\n });\n return rowToEntity<M>(row, slug, getPks(), toViewModel);\n },\n\n createMany: driver.saveMany\n ? async (\n data: Partial<EntityValues<M>>[],\n options?: { upsert?: boolean; onConflict?: readonly string[] }\n ): Promise<Entity<M>[]> => {\n const rows = await driver.saveMany!<M>({\n path: slug,\n rows: data,\n upsert: options?.upsert,\n // Dropped here, an `upsert` on a natural key silently\n // became an upsert on the primary key — which for a serial\n // id is a plain insert, so the re-runnable import the\n // option exists for duplicated every row instead.\n onConflict: options?.onConflict\n });\n return rows.map((row) => rowToEntity<M>(row, slug, getPks(), toViewModel));\n }\n : undefined,\n\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n const row = await driver.save<M>({\n path: slug,\n values: data,\n id: id,\n status: \"existing\"\n });\n return rowToEntity<M>(row, slug, getPks(), toViewModel);\n },\n\n async delete(id: string | number): Promise<void> {\n return driver.delete({\n row: { id,\npath: slug,\nvalues: {} as Record<string, unknown> }\n });\n },\n\n // Present only when the driver is: exposing these unconditionally and\n // looping single writes underneath would give a caller neither the\n // atomicity nor the single round trip they reached for a batch to get,\n // while looking exactly like it had.\n updateMany: driver.updateMany\n ? async (updates: { id: string | number; data: Partial<EntityValues<M>> }[]): Promise<Entity<M>[]> => {\n const rows = await driver.updateMany!<M>({\n path: slug,\n updates: updates.map(u => ({ id: u.id,\nvalues: u.data })),\n });\n return rows.map(row => rowToEntity<M>(row, slug, getPks(), toViewModel));\n }\n : undefined,\n\n deleteMany: driver.deleteMany\n ? async (ids: (string | number)[]): Promise<void> => {\n await driver.deleteMany!<M>({ path: slug,\nids });\n }\n : undefined,\n\n count: driver.count\n ? async (params?: FindParams<M>): Promise<number> => {\n const filter = params?.where ? deserializeFilter(params.where as Record<string, unknown>) : undefined;\n // Every narrowing `find()` applies has to apply here too, or\n // the count describes a different query than the one it is\n // reported against.\n return driver.count!({\n path: slug,\n filter,\n logical: params?.logical,\n searchString: params?.searchString\n });\n }\n : undefined,\n\n listen: driver.listenCollection\n ? (params: FindParams<M> | undefined, onUpdate: (response: FindResponse<M>) => void, onError?: (error: Error) => void) => {\n const { limit, offset, driverOffset } = resolveFindWindow(params);\n // Belt and braces. Postgres serves one shape on every read now,\n // realtime included, so this flattens nothing there — but a\n // driver whose `listen` still answers with refs is normalized\n // to the shape the rest of this accessor serves rather than\n // handing a developer two.\n const normalize = driver.restFetchService ? inlineRelationRefs : (row: Record<string, unknown>) => row;\n return driver.listenCollection!<M>({\n path: slug,\n limit,\n offset: driverOffset,\n filter: params?.where,\n logical: params?.logical,\n orderBy: normalizeOrderBy(params?.orderBy),\n searchString: params?.searchString,\n searchExplain: params?.searchExplain,\n // Forwarded so the SERVER can refuse it. `realtimeService`\n // rejects a subscription carrying `vectorSearch` — a\n // subscription is re-run on every matching write and\n // nothing there computes distances — and the docs promise\n // that refusal. Both producers hand-list their fields and\n // both omitted this one, so the guard could not fire and\n // `.vectorSearch(…).listen()` returned an ordinary\n // `id DESC` listing with no `_distance` and no error.\n vectorSearch: params?.vectorSearch,\n onUpdate: (entities) => {\n onUpdate({\n data: entities.map((row: Record<string, unknown>) => rowToEntity<M>(normalize(row), slug, getPks(), toViewModel)),\n meta: {\n // No count is issued on this path, so the total\n // is unknown; the lower bound is the rows in\n // hand plus the ones paged past to reach them.\n // Reporting `entities.length` claimed a read at\n // offset 100 had found a collection of two.\n total: offset + entities.length,\n limit,\n offset,\n hasMore: entities.length >= limit\n }\n });\n },\n onError\n });\n } : undefined,\n\n listenById: driver.listenOne\n ? (id: string | number, onUpdate: (entity: Entity<M> | undefined) => void, onError?: (error: Error) => void) => {\n const normalize = driver.restFetchService ? inlineRelationRefs : (row: Record<string, unknown>) => row;\n return driver.listenOne!<M>({\n path: slug,\n id: id,\n onUpdate: (entity) => onUpdate(entity ? rowToEntity<M>(normalize(entity), slug, getPks(), toViewModel) : undefined),\n onError\n });\n } : undefined,\n\n // Fluent Query Builder\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new QueryBuilder<M>(accessor);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValueFor<WhereFilterOp, M[keyof M & string]>);\n },\n orderBy(column: (keyof M & string) | ComputedSortField, ascending?: \"asc\" | \"desc\") {\n return new QueryBuilder<M>(accessor).orderBy(column, ascending);\n },\n limit(count: number) {\n return new QueryBuilder<M>(accessor).limit(count);\n },\n offset(count: number) {\n return new QueryBuilder<M>(accessor).offset(count);\n },\n search(searchString: string, options?: { explain?: boolean }) {\n return new QueryBuilder<M>(accessor).search(searchString, options);\n },\n vectorSearch(\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ) {\n return new QueryBuilder<M>(accessor).vectorSearch(property, vector, options);\n },\n include(...relations: string[]) {\n return new QueryBuilder<M>(accessor).include(...relations);\n }\n };\n\n return accessor;\n}\n\n/**\n * Build a `RebaseData` object from a `DataDriver` using JavaScript Proxy.\n *\n * This is the key bridge: any property access like `data.products` returns\n * a `CollectionAccessor` backed by the underlying DataDriver, without\n * needing per-collection code generation.\n *\n * @example\n * const data = buildRebaseData(driver);\n * await data.products.create({ name: \"Camera\", price: 299 });\n * const { data: items } = await data.products.find({ where: { status: [\"==\", \"published\"] } });\n */\n/**\n * The view-model converter for one collection, or `undefined` when there is no\n * collection config to build it from.\n *\n * Absent is the honest answer for every consumer that is not the admin: the\n * flat SDK derives itself from this same layer (`buildSdkData`) and must keep\n * the wire's own types, and it registers no collection resolver.\n */\nfunction createViewModelConverter(options?: EntityDataOptions) {\n if (!options?.resolveCollection) return () => undefined;\n return function converterFor(slug: string) {\n return (values: Record<string, unknown>): Record<string, unknown> => {\n // Resolved per call rather than memoized: the resolver is\n // late-bound (see `createPrimaryKeyResolver`) and a collection\n // edited in the schema editor should not need a reload here.\n const collection = options.resolveCollection?.(slug);\n if (!collection) return values;\n return toViewModelValues(values, collection.properties, collection, options.resolveCollection);\n };\n };\n}\n\nexport function buildRebaseData(driver: DataDriver, options?: EntityDataOptions): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n const primaryKeysFor = createPrimaryKeyResolver(options);\n const viewModelFor = createViewModelConverter(options);\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = createDriverAccessor(driver, slug, () => primaryKeysFor(slug), viewModelFor(slug));\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = {\n collection: getAccessor\n } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n // Ignore Symbol properties (e.g. Symbol.toPrimitive, Symbol.iterator)\n if (typeof prop === \"symbol\") return undefined;\n // Ignore internal JS properties\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n\n // Convert camelCase property names to snake_case slugs\n const slug = toSnakeCase(prop);\n return getAccessor(slug);\n }\n });\n}\n\n// =============================================================================\n// SDK data — flat rows (symmetric with the frontend SDK client)\n// =============================================================================\n\n/**\n * Unwrap a Entity back into the flat row it was built from. `rowToEntity` keeps\n * the row untouched under `.values` and derives `.id` alongside it, so dropping\n * the wrapper is the whole operation — the address was never part of the row.\n */\nfunction entityToRow<M extends Record<string, unknown>>(entity: Entity<M>): M {\n return entity.values as unknown as M;\n}\n\n/**\n * Fluent query builder for the flat SDK data layer. Mirrors {@link QueryBuilder}\n * but resolves to `FindResult<M>` (flat rows) instead of Entity-wrapped\n * `FindResponse<M>`.\n */\nclass SdkQueryBuilder<M extends Record<string, unknown> = Record<string, unknown>> implements SDKQueryBuilderInterface<M> {\n private params: FindParams = { where: {} };\n\n constructor(private client: SDKCollectionClient<M>) {}\n\n where<K extends keyof M & string, Op extends WhereFilterOp>(column: K, operator: Op, value: WhereValueFor<Op, M[K]>): this;\n /** A relation path (`author.name`) or a JSON path (`metadata->>tier`). */\n where(column: NonColumnFieldPath, operator: WhereFilterOp, value: unknown): this;\n where(logicalCondition: LogicalCondition): this;\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown): this {\n if (typeof columnOrCondition === \"object\" && columnOrCondition !== null && \"type\" in columnOrCondition) {\n // A second group narrows rather than replaces — see the SDK\n // builder in `@rebasepro/client`, which had the same defect.\n const next = columnOrCondition as LogicalCondition;\n this.params.logical = this.params.logical\n ? { type: \"and\", conditions: [this.params.logical, next] }\n : next;\n return this;\n }\n if (!this.params.where) this.params.where = {};\n const column = columnOrCondition as string;\n const condition: [WhereFilterOp, unknown] = [operator!, value];\n const existing = this.params.where[column];\n if (existing === undefined) {\n this.params.where[column] = condition;\n } else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) {\n (this.params.where[column] as [WhereFilterOp, unknown][]).push(condition);\n } else {\n let firstCondition: [WhereFilterOp, unknown];\n if (Array.isArray(existing) && existing.length === 2 && typeof existing[0] === \"string\") {\n firstCondition = existing as [WhereFilterOp, unknown];\n } else {\n firstCondition = [\"==\", existing];\n }\n this.params.where[column] = [firstCondition, condition];\n }\n return this;\n }\n\n /** Called again, this adds a tie-breaker rather than replacing the sort. */\n orderBy(\n column: FieldPath<M> | ComputedSortField | RelationAggregateSort,\n direction: \"asc\" | \"desc\" = \"asc\",\n nulls?: NullsPlacement\n ): this {\n const existing = normalizeOrderBy(this.params.orderBy) ?? [];\n const key = sortKeyToString(column);\n this.params.orderBy = [...existing, (nulls\n ? [key, direction, nulls]\n : [key, direction]) as OrderByTuple];\n return this;\n }\n\n limit(count: number): this { this.params.limit = count; return this; }\n offset(count: number): this { this.params.offset = count; return this; }\n search(searchString: string, options?: { explain?: boolean }): this { this.params.searchString = searchString; if (options?.explain !== undefined) this.params.searchExplain = options.explain; return this; }\n vectorSearch(\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ): this {\n this.params.vectorSearch = {\n property,\n vector,\n ...(options?.distance !== undefined && { distance: options.distance }),\n ...(options?.threshold !== undefined && { threshold: options.threshold })\n };\n return this;\n }\n /**\n * Load relations. Merges rather than replaces, so `.include(\"author\")` then\n * `.include({ comments: { limit: 5 } })` asks for both — a builder call that\n * silently discarded an earlier one is the same defect `where` had.\n */\n include(...relations: (string | IncludeSpec)[]): this {\n this.params.include = mergeIncludeSpecs(this.params.include, relations);\n return this;\n }\n\n fields(...columns: (FieldPath<M> | string)[]): this {\n this.params.fields = [...(this.params.fields ?? []), ...columns as string[]];\n return this;\n }\n\n distinct(enabled = true): this { this.params.distinct = enabled; return this; }\n\n after(cursor: string): this { this.params.after = cursor; return this; }\n\n async find(): Promise<FindResult<M>> {\n return this.client.find(this.params as FindParams<M>);\n }\n\n /** Aggregate the matching rows. See {@link SDKCollectionClient.aggregate}. */\n async aggregate(\n params: Omit<AggregateParams<M>, \"where\" | \"logical\" | \"searchString\">\n ): Promise<AggregateRow[]> {\n return this.client.aggregate({\n ...params,\n where: this.params.where as AggregateParams<M>[\"where\"],\n logical: this.params.logical,\n searchString: this.params.searchString\n });\n }\n\n /**\n * Page through everything this query matches, one row at a time.\n *\n * `.limit()` on the builder becomes the page size, so the ceiling on a\n * single `find()` is not a ceiling on what the query can read.\n */\n iterate(options?: PageWalkOptions<M>): AsyncIterableIterator<M> {\n return this.client.iterate({\n ...(this.params as FindParams<M>),\n ...(this.params.limit !== undefined && { pageSize: this.params.limit }),\n ...options\n } as IterateParams<M>);\n }\n\n /** Collect everything this query matches into one array. */\n findAll(options?: PageWalkOptions<M> & { maxRows?: number }): Promise<M[]> {\n return this.client.findAll({\n ...(this.params as FindParams<M>),\n ...(this.params.limit !== undefined && { pageSize: this.params.limit }),\n ...options\n } as FindAllParams<M>);\n }\n\n /**\n * Count the records matching this query.\n *\n * This used to answer `0` when the client had no `count` — a number, from a\n * source that had not counted anything, indistinguishable from an empty\n * collection. It now does what the client does, which on a source that\n * cannot count is throw and say so.\n */\n async count(): Promise<number> {\n return this.client.count(this.params as FindParams<M>);\n }\n\n listen(onUpdate: (data: FindResult<M>) => void, onError?: (error: Error) => void): () => void {\n return this.client.listen(this.params as FindParams<M>, onUpdate, onError);\n }\n}\n\n/**\n * Wrap a Entity-shaped {@link CollectionAccessor} into a flat\n * {@link SDKCollectionClient}. Every returned record is unwrapped to a flat row\n * so the backend SDK is byte-for-byte the same shape as the frontend client.\n */\nfunction toSdkCollectionClient<M extends Record<string, unknown>>(\n snap: CollectionAccessor<M>,\n slug = \"collection\"\n): SDKCollectionClient<M> {\n const client: SDKCollectionClient<M> = {\n async find(params?: FindParams<M>): Promise<FindResult<M>> {\n const res = await snap.find(params);\n return { data: res.data.map(entityToRow), meta: res.meta };\n },\n // Pagination is shared with the HTTP client rather than reimplemented:\n // both transports satisfy the same `SDKCollectionClient`, so a walk that\n // behaved differently in-process than over the wire would be a bug the\n // type system could not see.\n iterate(params?: IterateParams<M>) {\n return paginateFind<M>((p) => client.find(p), params, slug);\n },\n findAll(params?: FindAllParams<M>) {\n return collectAllPages<M>((p) => client.find(p), params, slug);\n },\n async findById(id: string | number): Promise<M | undefined> {\n const s = await snap.findById(id);\n return s ? entityToRow(s) : undefined;\n },\n async get(id: string | number): Promise<M> {\n // The same contract server-side as in the browser SDK, deliberately:\n // a callback, a cron and an app all read a row by id, and the shape\n // of \"it is not there\" should not depend on which one is asking.\n const s = await snap.findById(id);\n if (!s) {\n throw new RebaseApiError(\n `No record with id ${JSON.stringify(String(id))} in \"${slug}\".`,\n { status: 404, code: \"NOT_FOUND\" }\n );\n }\n return entityToRow(s);\n },\n async create(data: Partial<M>, id?: string | number): Promise<M> {\n return entityToRow(await snap.create(data as Partial<EntityValues<M>>, id));\n },\n async createMany(data: Partial<M>[], options?: { upsert?: boolean }): Promise<M[]> {\n if (!Array.isArray(data)) {\n throw new TypeError(\"createMany expects an array of records.\");\n }\n if (data.length === 0) return [];\n if (!snap.createMany) {\n throw new Error(\n \"Bulk writes are not supported by this collection's data source. \" +\n \"Fall back to create() per record.\"\n );\n }\n const rows = await snap.createMany(data as Partial<EntityValues<M>>[], options);\n return rows.map(entityToRow);\n },\n /**\n * One row through the bulk path, because the bulk path is where the\n * conflict target lives.\n *\n * `CollectionAccessor` has no single-row upsert and adding one would\n * mean a second way to say the same thing to the same driver method —\n * `saveMany` already takes `upsert` and `onConflict`, and a batch of\n * one is exactly an upsert of one.\n */\n async upsert(data: Partial<M>, options?: UpsertOptions): Promise<M> {\n if (!snap.createMany) {\n throw new Error(\n \"Upsert is not supported by this collection's data source: it needs a bulk write, \" +\n \"which this driver does not implement. Fall back to create() or update().\"\n );\n }\n const rows = await snap.createMany(\n [data as Partial<EntityValues<M>>],\n { upsert: true, onConflict: options?.onConflict }\n );\n const row = rows[0];\n if (!row) throw new Error(`Upsert into \"${slug}\" returned no row.`);\n return entityToRow(row);\n },\n async update(id: string | number, data: Partial<M> | UpdateValues<Partial<M>>): Promise<M> {\n return entityToRow(await snap.update(id, data as Partial<EntityValues<M>>));\n },\n async updateMany(updates: { id: string | number; data: Partial<M> | UpdateValues<Partial<M>> }[]): Promise<M[]> {\n if (!Array.isArray(updates)) {\n throw new TypeError(\"updateMany expects an array of { id, data } entries.\");\n }\n if (updates.length === 0) return [];\n if (!snap.updateMany) {\n throw new Error(\n \"Bulk updates are not supported by this collection's data source. \" +\n \"Fall back to update() per record.\"\n );\n }\n const rows = await snap.updateMany(\n updates.map(u => ({ id: u.id,\ndata: u.data as Partial<EntityValues<M>> }))\n );\n return rows.map(entityToRow);\n },\n delete(id: string | number): Promise<void> {\n return snap.delete(id);\n },\n async deleteMany(ids: (string | number)[]): Promise<void> {\n if (!Array.isArray(ids)) {\n throw new TypeError(\"deleteMany expects an array of ids.\");\n }\n if (ids.length === 0) return;\n if (!snap.deleteMany) {\n throw new Error(\n \"Bulk deletes are not supported by this collection's data source. \" +\n \"Fall back to delete() per record.\"\n );\n }\n await snap.deleteMany(ids);\n },\n // The three are non-optional on `SDKCollectionClient`: where the\n // underlying accessor cannot serve one, a stub says so when called\n // rather than being absent. `isUnsupported()` is how an adapter asks\n // the capability question — see `toEntityAccessor` below, which has to.\n count: snap.count\n ? (params?: FindParams<M>) => snap.count!(params)\n : unsupportedMethod(noCount(slug)),\n listen: snap.listen\n ? (params: FindParams<M> | undefined, onUpdate: (r: FindResult<M>) => void, onError?: (e: Error) => void) =>\n snap.listen!(params, (res) => onUpdate({ data: res.data.map(entityToRow), meta: res.meta }), onError)\n : unsupportedMethod(noRealtime(slug)),\n listenById: snap.listenById\n ? (id: string | number, onUpdate: (r: M | undefined) => void, onError?: (e: Error) => void) =>\n snap.listenById!(id, (s) => onUpdate(s ? entityToRow(s) : undefined), onError)\n : unsupportedMethod(noRealtime(slug)),\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new SdkQueryBuilder<M>(client);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValueFor<WhereFilterOp, M[keyof M & string]>);\n },\n orderBy: (\n column: FieldPath<M> | ComputedSortField | RelationAggregateSort,\n direction?: \"asc\" | \"desc\",\n nulls?: NullsPlacement\n ) => new SdkQueryBuilder<M>(client).orderBy(column, direction, nulls),\n limit: (count: number) => new SdkQueryBuilder<M>(client).limit(count),\n offset: (count: number) => new SdkQueryBuilder<M>(client).offset(count),\n search: (searchString: string) => new SdkQueryBuilder<M>(client).search(searchString),\n vectorSearch: (\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ) => new SdkQueryBuilder<M>(client).vectorSearch(property, vector, options),\n include: (...relations: (string | IncludeSpec)[]) => new SdkQueryBuilder<M>(client).include(...relations),\n fields: (...columns: (FieldPath<M> | string)[]) => new SdkQueryBuilder<M>(client).fields(...columns),\n distinct: (enabled?: boolean) => new SdkQueryBuilder<M>(client).distinct(enabled),\n after: (cursor: string) => new SdkQueryBuilder<M>(client).after(cursor),\n aggregate: snap.aggregate\n ? (params: AggregateParams<M>) => snap.aggregate!(params)\n : unsupportedMethod(noAggregate(slug))\n };\n return client;\n}\n\n/**\n * Wrap a flat {@link SDKCollectionClient} into a Entity-shaped\n * {@link CollectionAccessor}. Every returned row is re-wrapped into the\n * `{ id, path, values }` view-model the admin panel renders.\n */\nfunction toEntityAccessor<M extends Record<string, unknown>>(\n sdk: SDKCollectionClient<M>,\n slug: string,\n getPks: () => PrimaryKeyInfo[] = () => [],\n toViewModel?: (values: Record<string, unknown>) => Record<string, unknown>\n): CollectionAccessor<M> {\n const accessor: CollectionAccessor<M> = {\n async find(params?: FindParams<M>): Promise<FindResponse<M>> {\n const res = await sdk.find(params);\n return { data: res.data.map((row) => rowToEntity<M>(row, slug, getPks(), toViewModel)), meta: res.meta };\n },\n async findById(id: string | number): Promise<Entity<M> | undefined> {\n const row = await sdk.findById(id);\n return row ? rowToEntity<M>(row, slug, getPks(), toViewModel) : undefined;\n },\n async create(data: Partial<EntityValues<M>>, id?: string | number): Promise<Entity<M>> {\n return rowToEntity<M>(await sdk.create(data as Partial<M>, id), slug, getPks(), toViewModel);\n },\n // Declared on `CollectionAccessor` and, until now, never implemented on\n // this side of the boundary — so the admin's own import wrote one HTTP\n // request per row and could neither be atomic nor upsert. It forwards to\n // the same `/bulk` route the SDK client uses.\n createMany: sdk.createMany\n ? async (\n data: Partial<EntityValues<M>>[],\n options?: { upsert?: boolean; onConflict?: readonly string[] }\n ): Promise<Entity<M>[]> => {\n const rows = await sdk.createMany!(data as Partial<M>[], options);\n return rows.map((row) => rowToEntity<M>(row, slug, getPks(), toViewModel));\n }\n : undefined,\n async update(id: string | number, data: Partial<EntityValues<M>>): Promise<Entity<M>> {\n const row = await sdk.update(id, data as Partial<M>);\n if (!row) throw new Error(`Update returned no data for id ${id}`);\n return rowToEntity<M>(row, slug, getPks(), toViewModel);\n },\n delete(id: string | number): Promise<void> {\n return sdk.delete(id);\n },\n // `CollectionAccessor` keeps these optional, and the optionality is\n // load-bearing: the admin panel picks between subscribing and a\n // one-shot `find()` on exactly this property, and a UI that subscribes\n // into a throw is worse than one that polls. The client's method is\n // always present now, so the capability is read off the stub instead.\n count: isUnsupported(sdk.count) ? undefined : (params?: FindParams<M>) => sdk.count(params),\n aggregate: isUnsupported(sdk.aggregate)\n ? undefined\n : (params: AggregateParams<M>) => sdk.aggregate(params),\n listen: isUnsupported(sdk.listen)\n ? undefined\n : (params: FindParams<M> | undefined, onUpdate: (r: FindResponse<M>) => void, onError?: (e: Error) => void) =>\n sdk.listen(params, (res) => onUpdate({ data: res.data.map((row) => rowToEntity<M>(row, slug, getPks(), toViewModel)), meta: res.meta }), onError),\n listenById: isUnsupported(sdk.listenById)\n ? undefined\n : (id: string | number, onUpdate: (s: Entity<M> | undefined) => void, onError?: (e: Error) => void) =>\n sdk.listenById(id, (row) => onUpdate(row ? rowToEntity<M>(row, slug, getPks(), toViewModel) : undefined), onError),\n where(columnOrCondition: string | LogicalCondition, operator?: WhereFilterOp, value?: unknown) {\n const builder = new QueryBuilder<M>(accessor);\n if (typeof columnOrCondition === \"object\") {\n return builder.where(columnOrCondition);\n }\n return builder.where(columnOrCondition as keyof M & string, operator!, value as WhereValueFor<WhereFilterOp, M[keyof M & string]>);\n },\n orderBy: (column: keyof M & string, direction?: \"asc\" | \"desc\") => new QueryBuilder<M>(accessor).orderBy(column, direction),\n limit: (count: number) => new QueryBuilder<M>(accessor).limit(count),\n offset: (count: number) => new QueryBuilder<M>(accessor).offset(count),\n search: (searchString: string) => new QueryBuilder<M>(accessor).search(searchString),\n vectorSearch: (\n property: string,\n vector: number[],\n options?: { distance?: \"cosine\" | \"l2\" | \"inner_product\"; threshold?: number }\n ) => new QueryBuilder<M>(accessor).vectorSearch(property, vector, options),\n include: (...relations: string[]) => new QueryBuilder<M>(accessor).include(...relations)\n };\n return accessor;\n}\n\n/**\n * Wrap a flat {@link RebaseSdkData} into a Entity-shaped {@link RebaseData}.\n *\n * This is the **admin boundary**: the SDK client (`client.data`) returns flat\n * rows, but the admin renders the `Entity` view-model (`entity.values.*`).\n * `core/Rebase.tsx` wraps `client.data` through this before handing it to the\n * admin `RebaseDataContext` — without it the admin renders rows with only their\n * `id`.\n */\n/**\n * Only the by-slug accessor is asked for, so only that is required.\n *\n * Taking a whole `RebaseSdkData` meant taking `RebaseSdkData<unknown>`, whose\n * dynamic branch is an index signature — and no `RebaseSdkData<DB>` satisfies\n * it, because its own `collection` method is not a `SDKCollectionClient`. So a\n * caller holding a *typed* client could not pass it to a function that reads\n * one method off it, and that method is identical on every instantiation.\n */\nexport function wrapAsEntityData(sdkData: Pick<RebaseSdkData, \"collection\">, options?: EntityDataOptions): RebaseData {\n const cache = new Map<string, CollectionAccessor>();\n const primaryKeysFor = createPrimaryKeyResolver(options);\n const viewModelFor = createViewModelConverter(options);\n\n function getAccessor(slug: string): CollectionAccessor {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = toEntityAccessor(sdkData.collection(slug), slug, () => primaryKeysFor(slug), viewModelFor(slug));\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = { collection: getAccessor } as RebaseData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n if (typeof prop === \"symbol\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n return getAccessor(toSnakeCase(prop));\n }\n });\n}\n\n/**\n * Wrap a Entity-shaped {@link RebaseData} into a flat {@link RebaseSdkData}.\n *\n * Every collection accessor is adapted to return flat rows. Use this to derive\n * the flat SDK data layer (`context.data`) from an existing Entity data layer\n * — e.g. the admin routes its Entity data via `useData()` and exposes the\n * same routing as flat `context.data` for callbacks by wrapping it here.\n */\nexport function wrapAsSdkData(entityData: RebaseData): RebaseSdkData {\n const cache = new Map<string, SDKCollectionClient>();\n\n function getAccessor(slug: string): SDKCollectionClient {\n let accessor = cache.get(slug);\n if (!accessor) {\n accessor = toSdkCollectionClient(entityData.collection(slug), slug);\n cache.set(slug, accessor);\n }\n return accessor;\n }\n\n const target = { collection: getAccessor } as RebaseSdkData;\n\n return new Proxy(target, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n if (typeof prop === \"symbol\") return undefined;\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n return getAccessor(toSnakeCase(prop));\n }\n });\n}\n\n/**\n * Build a flat {@link RebaseSdkData} from a `DataDriver`.\n *\n * This is the developer-facing SDK data layer used by backend framework\n * callbacks & scripts (`context.data` / `rebase.dataAsAdmin`). It returns flat rows —\n * identical in shape to the frontend SDK client, down to how a relation is\n * served: a foreign key stays a foreign key, and a relation named in `include`\n * arrives as the target's own columns. The `{ __type: \"relation\" }` envelope is\n * the admin's view-model and never reaches here.\n *\n * The admin uses {@link buildRebaseData} (Entity) over its own driver.\n */\nexport function buildSdkData(driver: DataDriver): RebaseSdkData {\n return wrapAsSdkData(buildRebaseData(driver));\n}\n","import { RebaseData, RebaseSdkData } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * The two data-layer shapes that can be routed: the Entity-shaped admin\n * {@link RebaseData} or the flat SDK {@link RebaseSdkData}. Both expose a\n * `.collection(slug)` accessor, which is all the router needs.\n */\nexport type RoutableData = RebaseData | RebaseSdkData;\n\n/**\n * Parameters for {@link buildRoutedRebaseData}.\n */\nexport interface RoutedRebaseDataParams<T extends RoutableData = RebaseData> {\n /**\n * The default data source. Handles every collection that does not\n * resolve to an entry in `sources` (i.e. server-transport collections,\n * which ride the Rebase client).\n */\n defaultData: T;\n\n /**\n * Per-data-source instances for direct and custom transports, keyed by\n * data-source key (e.g. `\"analytics\"`). Server-mediated sources are not\n * listed here — they fall through to `defaultData`.\n */\n sources: Record<string, T>;\n\n /**\n * Resolve the data-source key for a given collection slug or path.\n * Typically backed by the collection registry + `resolveDataSource`\n * (`resolveDataSource(registry.getCollection(path), defs).key`).\n *\n * Return `undefined` (or a key absent from `sources`) to route to the\n * default data source.\n */\n resolveKey: (slugOrPath: string) => string | undefined;\n}\n\n/**\n * Build a {@link RebaseData} that routes each collection to the right\n * backend based on its resolved data source.\n *\n * `.collection(path)` (and dynamic `data.products`-style access) resolves the\n * collection's data-source key via `resolveKey` and delegates to the matching\n * entry in `sources`, falling back to `defaultData` when there is no match.\n * Because routing keys off the *path being accessed*, a reference widget\n * inside a Firestore form that points at a Postgres collection is still\n * served by Postgres — routing follows the target, not the ancestor.\n *\n * When `sources` is empty this returns `defaultData` untouched, so the\n * single-driver setup keeps identical behaviour and identity (important for\n * effect dependencies that key off the data instance).\n *\n * @example\n * const data = buildRoutedRebaseData({\n * defaultData: client.data,\n * sources: { analytics: buildRebaseData(firestoreDriver) },\n * resolveKey: (path) => resolveDataSource(registry.getCollection(path), defs).key\n * });\n * await data.products.find(); // → default (server / Postgres)\n * await data.events.find(); // → Firestore, if `events.dataSource === \"analytics\"`\n */\nexport function buildRoutedRebaseData<T extends RoutableData = RebaseData>({\n defaultData,\n sources,\n resolveKey\n}: RoutedRebaseDataParams<T>): T {\n\n // Fast path: nothing to route → return the default untouched (preserves\n // referential identity for effect dependencies).\n if (!sources || Object.keys(sources).length === 0) {\n return defaultData;\n }\n\n function resolve(slugOrPath: string): T {\n const key = resolveKey(slugOrPath);\n if (key && sources[key]) return sources[key];\n return defaultData;\n }\n\n function getAccessor(slugOrPath: string) {\n return (resolve(slugOrPath) as RoutableData).collection(slugOrPath);\n }\n\n const target = {\n collection: getAccessor\n } as unknown as T;\n\n return new Proxy(target as object, {\n get(_target, prop: string | symbol) {\n if (prop === \"collection\") return getAccessor;\n // Ignore Symbol properties (e.g. Symbol.toPrimitive, Symbol.iterator)\n if (typeof prop === \"symbol\") return undefined;\n // Ignore internal JS properties\n if (prop === \"then\" || prop === \"toJSON\" || prop === \"$$typeof\") return undefined;\n\n // Convert camelCase property names to snake_case slugs, mirroring\n // buildRebaseData so dynamic access routes consistently.\n return getAccessor(toSnakeCase(prop));\n }\n }) as T;\n}\n"],"x_google_ignoreList":[6,20,22],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgHA,IAAa,iBAAb,cAAoC,MAAM;;CAEtC;;CAEA;;CAEA;;CAEA;;CAEA;CAEA,YAAY,SAAiB,OAAwB,CAAC,GAAG;EACrD,MAAM,OAAO;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