@rebasepro/types 0.30.0 → 0.31.0-canary.g59cd6fd

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.
Files changed (57) hide show
  1. package/README.md +16 -18
  2. package/dist/call_context.d.ts +3 -3
  3. package/dist/controllers/client.d.ts +29 -0
  4. package/dist/controllers/data.d.ts +85 -332
  5. package/dist/controllers/data_driver.d.ts +47 -57
  6. package/dist/controllers/index.d.ts +0 -3
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.es.js +2567 -1151
  9. package/dist/index.es.js.map +1 -1
  10. package/dist/schema/column_options.d.ts +336 -0
  11. package/dist/schema/column_type.d.ts +116 -0
  12. package/dist/schema/columns.d.ts +646 -0
  13. package/dist/schema/compiled.d.ts +114 -0
  14. package/dist/schema/descriptor.d.ts +349 -0
  15. package/dist/schema/hooks.d.ts +164 -0
  16. package/dist/schema/index.d.ts +13 -0
  17. package/dist/schema/infer.d.ts +340 -0
  18. package/dist/schema/json.d.ts +237 -0
  19. package/dist/schema/relations.d.ts +205 -0
  20. package/dist/schema/table.d.ts +304 -0
  21. package/dist/schema/table_options.d.ts +103 -0
  22. package/dist/schema/table_patch.d.ts +338 -0
  23. package/dist/types/auth_adapter.d.ts +12 -6
  24. package/dist/types/auth_hooks.d.ts +65 -0
  25. package/dist/types/backend.d.ts +85 -96
  26. package/dist/types/data_source.d.ts +4 -9
  27. package/dist/types/database_adapter.d.ts +30 -31
  28. package/dist/types/entities.d.ts +0 -162
  29. package/dist/types/filter-operators.d.ts +2 -26
  30. package/dist/types/history.d.ts +6 -9
  31. package/dist/types/index.d.ts +3 -9
  32. package/dist/types/mcp_app_modules.d.ts +0 -2
  33. package/dist/types/policy.d.ts +85 -10
  34. package/dist/types/project_manifest.d.ts +113 -46
  35. package/dist/types/read_query.d.ts +98 -0
  36. package/dist/types/register.d.ts +35 -5
  37. package/dist/types/relations.d.ts +0 -430
  38. package/dist/types/schema_editing.d.ts +54 -2
  39. package/dist/types/schema_version.d.ts +24 -4
  40. package/dist/types/security_rules.d.ts +225 -15
  41. package/dist/types/storage_authorize.d.ts +2 -2
  42. package/dist/types/tenancy.d.ts +3 -3
  43. package/dist/types/ui_preferences.d.ts +228 -0
  44. package/package.json +3 -2
  45. package/dist/controllers/auth_state.d.ts +0 -23
  46. package/dist/controllers/collection_registry.d.ts +0 -67
  47. package/dist/controllers/effective_role.d.ts +0 -4
  48. package/dist/types/admin_block.d.ts +0 -96
  49. package/dist/types/chips.d.ts +0 -16
  50. package/dist/types/collection_contract.d.ts +0 -43
  51. package/dist/types/collection_patch.d.ts +0 -74
  52. package/dist/types/collections.d.ts +0 -783
  53. package/dist/types/component_ref.d.ts +0 -81
  54. package/dist/types/conditions-contract.types.d.ts +0 -14
  55. package/dist/types/entity_callbacks.d.ts +0 -393
  56. package/dist/types/indexes.d.ts +0 -179
  57. package/dist/types/properties.d.ts +0 -1640
package/dist/index.es.js CHANGED
@@ -111,130 +111,6 @@ function isUnsupported(method) {
111
111
  return method[UNSUPPORTED_METHOD] === true;
112
112
  }
113
113
  //#endregion
114
- //#region src/types/entities.ts
115
- /**
116
- * Class used to create a reference to a entity in a different path.
117
- *
118
- * @example
119
- * // Simple reference (most common case - single driver, single db)
120
- * new EntityReference({ id: "123", path: "users" })
121
- *
122
- * // Reference to a different driver (e.g., Firestore)
123
- * new EntityReference({ id: "123", path: "analytics", driver: "firestore" })
124
- *
125
- * // Reference to a specific database within a driver
126
- * new EntityReference({ id: "123", path: "orders", driver: "postgres", databaseId: "orders_db" })
127
- */
128
- var EntityReference = class {
129
- __type = "reference";
130
- /**
131
- * ID of the entity
132
- */
133
- id;
134
- /**
135
- * A string representing the path of the referenced document (relative
136
- * to the root of the database).
137
- */
138
- path;
139
- /**
140
- * Which driver (e.g., 'postgres', 'firestore').
141
- * Defaults to "(default)" if not specified.
142
- */
143
- driver;
144
- /**
145
- * Which database within the driver.
146
- * Defaults to "(default)" if not specified.
147
- */
148
- databaseId;
149
- /**
150
- * Create a reference to a entity.
151
- *
152
- * @example
153
- * // Simple reference (most common case)
154
- * new EntityReference({ id: "123", path: "users" })
155
- *
156
- * // With driver
157
- * new EntityReference({ id: "123", path: "analytics", driver: "firestore" })
158
- */
159
- constructor(props) {
160
- this.id = props.id;
161
- this.path = props.path;
162
- this.driver = props.driver;
163
- this.databaseId = props.databaseId;
164
- }
165
- get pathWithId() {
166
- return `${this.path}/${this.id}`;
167
- }
168
- /**
169
- * Get the full path including driver and database prefixes if specified.
170
- * For the common case (single driver, single db), this just returns pathWithId.
171
- */
172
- get fullPath() {
173
- const parts = [];
174
- if (this.driver && this.driver !== "(default)") parts.push(this.driver);
175
- if (this.databaseId && this.databaseId !== "(default)") parts.push(this.databaseId);
176
- if (parts.length > 0) return `${parts.join(":")}:::${this.path}/${this.id}`;
177
- return this.pathWithId;
178
- }
179
- isEntityReference() {
180
- return true;
181
- }
182
- };
183
- /**
184
- * Class used to create a reference to a entity in a different path
185
- */
186
- var EntityRelation = class {
187
- __type = "relation";
188
- /**
189
- * ID of the entity
190
- */
191
- id;
192
- /**
193
- * A string representing the path of the referenced document (relative
194
- * to the root of the database).
195
- */
196
- path;
197
- /**
198
- * Pre-fetched data payload to eliminate N+1 queries.
199
- * When present, clients can use this directly instead of fetching.
200
- */
201
- data;
202
- constructor(id, path, data) {
203
- this.id = id;
204
- this.path = path;
205
- this.data = data;
206
- }
207
- get pathWithId() {
208
- return `${this.path}/${this.id}`;
209
- }
210
- isEntityReference() {
211
- return false;
212
- }
213
- isEntityRelation() {
214
- return true;
215
- }
216
- };
217
- var GeoPoint = class {
218
- /**
219
- * The latitude of this GeoPoint instance.
220
- */
221
- latitude;
222
- /**
223
- * The longitude of this GeoPoint instance.
224
- */
225
- longitude;
226
- constructor(latitude, longitude) {
227
- this.latitude = latitude;
228
- this.longitude = longitude;
229
- }
230
- };
231
- var Vector = class {
232
- value;
233
- constructor(value) {
234
- this.value = value;
235
- }
236
- };
237
- //#endregion
238
114
  //#region src/types/filter-operators.ts
239
115
  /** The wire spelling of a {@link RelationAggregateSort}: `min(applications.created_at)`. */
240
116
  var RELATION_AGGREGATE_SORT_PATTERN = /^(min|max|count|sum|avg)\(([^().]+)(?:\.([^()]+))?\)$/;
@@ -419,568 +295,186 @@ function toCanonicalOp(op) {
419
295
  return REST_OP_LOOKUP.get(op);
420
296
  }
421
297
  //#endregion
422
- //#region src/types/admin_block.ts
298
+ //#region src/types/search.ts
299
+ /** The column name used when {@link SearchConfig.column} is not given. */
300
+ var DEFAULT_SEARCH_COLUMN = "search_vector";
301
+ /** The matching strategy used when {@link SearchConfig.mode} is not given. */
302
+ var DEFAULT_SEARCH_MODE = "fts";
303
+ /** The text search configuration used when {@link SearchConfig.language} is not given. */
304
+ var DEFAULT_SEARCH_LANGUAGE = "simple";
305
+ /** The weight a field carries when it does not name one. */
306
+ var DEFAULT_SEARCH_WEIGHT = "B";
307
+ /** The similarity floor used when {@link SearchConfig.fuzzyThreshold} is not given. */
308
+ var DEFAULT_FUZZY_THRESHOLD = .3;
309
+ /**
310
+ * The relevance sort key. Valid only on a collection that declares a
311
+ * {@link SearchConfig} *and* on a query that carries a search string; anywhere
312
+ * else it is an unknown field and the request is refused.
313
+ */
314
+ var RELEVANCE_SORT_FIELD = "_score";
315
+ //#endregion
316
+ //#region src/types/relations.ts
423
317
  /**
424
- * The keys of a collection's admin block, as data.
318
+ * The key a junction row's own columns are carried under, in both directions.
319
+ *
320
+ * A read that includes a `manyToMany` relation serves each related row with its
321
+ * link's columns nested here — `{ id: 5, name: "ts", _pivot: { role: "owner" } }`
322
+ * — and a membership write may name the same key on an element to state what
323
+ * the link should hold. One constant because the two have to be the same word:
324
+ * a wire name that differs between the read and the write it round-trips
325
+ * through is a shape no client can echo back.
425
326
  *
426
- * There is no *type* for the block in this package any more, and that is the point:
427
- * `admin` is not declared on `BaseCollectionConfig` or on any property here, so a
428
- * BaaS install cannot even write one. `@rebasepro/cms-types` adds the field back by
429
- * declaration merging, which is why installing it is what makes the admin surface
430
- * appear.
327
+ * Leading underscore, like `_matches`: it reads as metadata about the row
328
+ * rather than as one of its columns. A payload property may not be named
329
+ * `_pivot` either — `checkJunctionPayload` refuses it — so the key means one
330
+ * thing wherever it appears.
431
331
  *
432
- * The *list* still has to live here, because three runtime consumers need it and two
433
- * of them are core — see below.
332
+ * @group Models
434
333
  */
334
+ var JUNCTION_PIVOT_KEY = "_pivot";
435
335
  /**
436
- * Every key that belongs inside a collection's `admin` block, as data.
437
- *
438
- * The type that describes these fields is `AdminCollectionOptions` in
439
- * `@rebasepro/cms-types`, and it is erased at build time — but three runtime
440
- * consumers need the list, and two of them are core:
336
+ * The key a row carries the totals of its counted relations under.
441
337
  *
442
- * - `serializeCollections`, to drop the block from the contract
443
- * - the ts-morph schema editor in `@rebasepro/server`, which rewrites collection
444
- * files on disk from the admin panel and has to know where each key goes. A key
445
- * missing from this list gets written to the *top level* of the file, where the
446
- * backend ignores it and the panel never finds it again.
447
- * - the `collections-admin-block` codemod
338
+ * An include that asks for a count — `include: { tags: { limit: 4, count: true } }`
339
+ * — serves, beside the (capped) `tags`, how many related rows there are in all:
340
+ * `{ id: 1, tags: [ …4 rows ], _count: { tags: 37 } }`. One object per row,
341
+ * keyed by relation name, so counting a second relation adds a key rather than
342
+ * a second top-level name.
448
343
  *
449
- * `@rebasepro/cms-types` re-exports this and asserts it names only real option
450
- * keys; the count is pinned by a test there.
344
+ * Leading underscore, like {@link JUNCTION_PIVOT_KEY} and `_matches`: it
345
+ * describes the read, not the record, and no column or form writes it. A
346
+ * collection with a property of this name cannot ask for a count — the read
347
+ * answers 400 rather than writing over the column.
451
348
  *
452
349
  * @group Models
453
350
  */
454
- var ADMIN_COLLECTION_KEYS = [
455
- "Actions",
456
- "additionalFields",
457
- "alwaysApplyDefaultValues",
458
- "browserCallbacks",
459
- "components",
460
- "customViews",
461
- "defaultEntityAction",
462
- "defaultFilter",
463
- "defaultSelectedView",
464
- "defaultSize",
465
- "defaultViewMode",
466
- "disableDefaultActions",
467
- "display",
468
- "enabledViews",
469
- "entityActions",
470
- "entityViews",
471
- "exportable",
472
- "filterPresets",
473
- "fixedFilter",
474
- "form",
475
- "formAutoSave",
476
- "formView",
477
- "group",
478
- "hideFromEntityViews",
479
- "hideFromNavigation",
480
- "hideIdFromCollection",
481
- "hideIdFromForm",
482
- "icon",
483
- "includeJsonView",
484
- "inlineEditing",
485
- "kanban",
486
- "listProperties",
487
- "localChangesBackup",
488
- "openEntityMode",
489
- "orderProperty",
490
- "pagination",
491
- "previewProperties",
492
- "propertiesOrder",
493
- "selectionController",
494
- "selectionEnabled",
495
- "sideDialogWidth",
496
- "sort"
497
- ];
351
+ var INCLUDE_COUNT_KEY = "_count";
352
+ /**
353
+ * The conditions of a join step, as a list: one entry for a plain step, one
354
+ * per alternative for a step that joins on any of several.
355
+ * @group Models
356
+ */
357
+ function joinConditions(step) {
358
+ return Array.isArray(step.on) ? step.on : [step.on];
359
+ }
360
+ /**
361
+ * The one condition of a step that has no alternatives — for the write paths,
362
+ * which only run on a writable chain and a chain with alternatives never is.
363
+ * Throws rather than pick one of several: writing a link into the wrong column
364
+ * is the mistake read-only exists to prevent.
365
+ * @group Models
366
+ */
367
+ function soleJoinCondition(step) {
368
+ if (Array.isArray(step.on)) {
369
+ if (step.on.length === 1) return step.on[0];
370
+ if (step.on.length === 0) throw new Error(`The join into '${step.table}' lists no conditions, so it joins nothing.`);
371
+ throw new Error(`The join into '${step.table}' matches any of ${step.on.length} conditions, so it is read-only: there is no one column to write a link into.`);
372
+ }
373
+ return step.on;
374
+ }
375
+ //#endregion
376
+ //#region src/types/policy.ts
498
377
  /**
499
- * Every key that belongs inside a *property's* `admin` block, as data.
378
+ * The id a request without a logged-in user reports as `rebase.uid()`.
500
379
  *
501
- * The union of `AdminPropertyOptions` and its per-type extensions
502
- * (`AdminStringOptions`, `AdminArrayOptions`, …) in `@rebasepro/cms-types`.
503
- * It lives here for the same reason {@link ADMIN_COLLECTION_KEYS} does: the
504
- * runtime consumers are core packages that the BaaS guard forbids from
505
- * importing `@rebasepro/cms-types`. Here it is the boot-time collection
506
- * validator in `@rebasepro/server`, which has to tell "you left `readOnly` at
507
- * the top of the property, where nothing reads it" apart from "you invented a
508
- * key we have never heard of".
380
+ * A user-context request always sets `app.uid`: blank would read back as
381
+ * `NULL`, and `NULL` is how the trusted server context is recognised, so an
382
+ * anonymous visitor would be promoted to server privileges. The driver
383
+ * therefore substitutes this sentinel at the single chokepoint where the GUC
384
+ * is set.
509
385
  *
510
- * `@rebasepro/cms-types` re-exports this and asserts it names only real
511
- * option keys.
386
+ * The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a
387
+ * tautology on the user path** — it is true for anonymous visitors too. Use
388
+ * {@link policy.authenticated} to mean "signed in", and
389
+ * {@link policy.serverContext} to mean "the trusted server context". Do not
390
+ * hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one
391
+ * literal is not enough.
512
392
  *
513
393
  * @group Models
514
394
  */
515
- var ADMIN_PROPERTY_KEYS = [
516
- "canAddElements",
517
- "clearable",
518
- "columnWidth",
519
- "customProps",
520
- "disabled",
521
- "expanded",
522
- "Field",
523
- "filledByServer",
524
- "Filter",
525
- "filterOperators",
526
- "fixedFilter",
527
- "format",
528
- "hideFromCollection",
529
- "includeEntityLink",
530
- "includeId",
531
- "markdown",
532
- "minimalistView",
533
- "multiline",
534
- "Preview",
535
- "previewAsTag",
536
- "previewProperties",
537
- "readOnly",
538
- "renderInForm",
539
- "sortable",
540
- "span",
541
- "spreadChildren",
542
- "urlPreview",
543
- "widget"
544
- ];
395
+ var ANONYMOUS_USER_ID = "anonymous";
545
396
  /**
546
- * Move flattened admin keys back down into the `admin` block.
397
+ * Every uid that has ever meant "nobody is signed in" — newest first.
547
398
  *
548
- * The admin panel works with a *flat* view model — the block merged onto the
549
- * collection — so what comes back from a form has `icon` and `defaultViewMode`
550
- * at the top level while `admin` still holds whatever the file was loaded with.
551
- * This is the way back.
399
+ * There are two because there were two. The types, the policy compiler, the
400
+ * JavaScript evaluator and the linter were all built on
401
+ * {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated
402
+ * callers as `'anon'` — so `policy.authenticated()`, which compiled to
403
+ * `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The
404
+ * sanctioned way to write "signed in" granted to everyone, and the linter
405
+ * flagged the spelling that actually worked as a foreign convention.
552
406
  *
553
- * **The top-level value wins.** It is the one the form just wrote; the block is
554
- * the copy the collection was loaded with, and preferring it resolves every edit
555
- * in favour of the value the user changed away from.
407
+ * The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here
408
+ * because policies outlive the server that generated them: a database still
409
+ * holding policies from before the fix, or a project whose server has not been
410
+ * upgraded yet, must not become a grant in either direction. Compile against
411
+ * this list, not against a single literal.
556
412
  *
557
- * This lives here, next to the key lists, because it had two implementations —
558
- * `toAdminCollectionConfig` in `@rebasepro/cms-types` and `nestAdminKeys` in
559
- * `@rebasepro/server`'s schema editor — that agreed on everything except that
560
- * precedence, which is the only part that decides whether a save is visible.
413
+ * No real user id is ever one of these, so a match is always "not signed in".
561
414
  *
562
415
  * @group Models
563
416
  */
564
- function nestAdminKeysOf(source, adminKeys) {
565
- const keys = new Set(adminKeys);
566
- const top = {};
567
- const block = { ...source.admin ?? {} };
568
- for (const [key, value] of Object.entries(source)) {
569
- if (key === "admin") continue;
570
- if (keys.has(key)) block[key] = value;
571
- else top[key] = value;
572
- }
573
- if (Object.keys(block).length > 0) top.admin = block;
574
- return top;
575
- }
417
+ var ANONYMOUS_USER_IDS = [ANONYMOUS_USER_ID, "anon"];
576
418
  /**
577
- * {@link nestAdminKeysOf} for a collection.
419
+ * Whether a uid stands for "no one is signed in", in any spelling rebase has
420
+ * used. `null`/`undefined` is the trusted server context, not an anonymous
421
+ * caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.
578
422
  *
579
423
  * @group Models
580
424
  */
581
- function nestAdminCollectionKeys(collection) {
582
- return nestAdminKeysOf(collection, ADMIN_COLLECTION_KEYS);
583
- }
584
- /** A record of properties, keyed by name — a map's `properties`, or a `oneOf` block's. */
585
- function nestEachProperty(properties) {
586
- return Object.fromEntries(Object.entries(properties).map(([key, child]) => [key, isNestable(child) ? nestAdminPropertyKeys(child) : child]));
587
- }
588
- /** Anything the walk can descend into: a plain object, not an array. */
589
- function isNestable(value) {
590
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
425
+ function isAnonymousUid(uid) {
426
+ return typeof uid === "string" && ANONYMOUS_USER_IDS.includes(uid);
591
427
  }
592
428
  /**
593
- * {@link nestAdminKeysOf} for a property, applied to its children too.
594
- *
595
- * A map property carries `properties`, an array property carries `of`, and an
596
- * array of typed blocks carries `oneOf.properties` — a record of properties like
597
- * a map's. All of them hold properties with `admin` blocks of their own. A flat
598
- * `readOnly` left on a child is as dead — and as fatal at the next boot — as one
599
- * left on the parent, so the walk goes all the way down.
600
- *
601
- * `oneOf` was the container this walk did not know about, and it is the one the
602
- * block-based collection templates are built out of: every block inside them
603
- * kept its flat `markdown`, and the collection they created would not boot.
604
- *
429
+ * Every `kind` a {@link PolicyExpression} node can have — the discriminator
430
+ * {@link isPolicyShorthand} and {@link isPolicyExpressionKind} read.
605
431
  * @group Models
606
432
  */
607
- function nestAdminPropertyKeys(property) {
608
- const nested = nestAdminKeysOf(property, ADMIN_PROPERTY_KEYS);
609
- const children = nested.properties;
610
- if (isNestable(children)) nested.properties = nestEachProperty(children);
611
- const oneOf = nested.oneOf;
612
- if (isNestable(oneOf) && isNestable(oneOf.properties)) nested.oneOf = {
613
- ...oneOf,
614
- properties: nestEachProperty(oneOf.properties)
615
- };
616
- const of = nested.of;
617
- if (Array.isArray(of)) nested.of = of.map((entry) => isNestable(entry) ? nestAdminPropertyKeys(entry) : entry);
618
- else if (isNestable(of)) nested.of = nestAdminPropertyKeys(of);
619
- return nested;
620
- }
621
- //#endregion
622
- //#region src/types/data_source.ts
433
+ var POLICY_EXPRESSION_KINDS = [
434
+ "true",
435
+ "false",
436
+ "and",
437
+ "or",
438
+ "not",
439
+ "compare",
440
+ "rolesOverlap",
441
+ "rolesContain",
442
+ "authenticated",
443
+ "registered",
444
+ "serverContext",
445
+ "existsIn",
446
+ "raw"
447
+ ];
623
448
  /**
624
- * The default data-source key, used when a collection does not name a
625
- * `dataSource`. Shared by the frontend router and the backend driver
626
- * registry so both agree on "the default database".
449
+ * Whether `kind` names a {@link PolicyExpression} node.
627
450
  * @group Models
628
451
  */
629
- var DEFAULT_DATA_SOURCE_KEY = "(default)";
452
+ function isPolicyExpressionKind(kind) {
453
+ return typeof kind === "string" && POLICY_EXPRESSION_KINDS.includes(kind);
454
+ }
455
+ var isShorthandValue = (value) => value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
630
456
  /**
631
- * Relation kinds assumed filterable when a driver does not say.
457
+ * Whether a rule's `condition` / `check` is a {@link PolicyShorthand} rather
458
+ * than a {@link PolicyExpression}.
632
459
  *
633
- * `belongsTo` alone: its filter is a comparison on a column of the row being
634
- * filtered, the one shape that needs no query construction a driver might not
635
- * have. Everything else is a correlated subquery over another table.
460
+ * True only for a plain object with at least one key, none of them `kind`,
461
+ * whose every value is a string, a finite number, a boolean or `null`. Every
462
+ * expression node carries `kind`, so no expression is ever taken for a
463
+ * shorthand — and an object that has a `kind` key is never taken for a
464
+ * shorthand either, whatever its value: such an object is ambiguous (a column
465
+ * called `kind`, or a misspelt node) and the compiler refuses it rather than
466
+ * guessing.
636
467
  *
637
468
  * @group Models
638
469
  */
639
- var DEFAULT_FILTERABLE_RELATION_KINDS = ["belongsTo"];
640
- /** @group Models */
641
- var POSTGRES_CAPABILITIES = {
642
- key: "postgres",
643
- label: "PostgreSQL",
644
- supportsRelations: true,
645
- supportsSubcollections: false,
646
- supportsRLS: true,
647
- supportsReferences: false,
648
- supportsColumnTypes: true,
649
- supportsRealtime: true,
650
- supportsVectors: true,
651
- filterOperators: ALL_WHERE_FILTER_OPS,
652
- filterableRelationKinds: [
653
- "belongsTo",
654
- "manyToMany",
655
- "hasMany",
656
- "hasOne"
657
- ],
658
- supportsRelationFieldFilters: true,
659
- relationAggregateSorts: true,
660
- supportsSQLAdmin: true,
661
- supportsDocumentAdmin: false,
662
- supportsSchemaAdmin: true
663
- };
664
- /** @group Models */
665
- var FIREBASE_CAPABILITIES = {
666
- key: "firestore",
667
- label: "Firebase / Firestore",
668
- supportsRelations: false,
669
- supportsSubcollections: true,
670
- supportsRLS: false,
671
- supportsReferences: true,
672
- supportsColumnTypes: false,
673
- supportsRealtime: true,
674
- supportsVectors: false,
675
- filterOperators: ALL_WHERE_FILTER_OPS.filter((op) => op !== "like" && op !== "ilike" && op !== "not-like" && op !== "not-ilike" && op !== "array-contains-all" && op !== "array-contained-by"),
676
- filterableRelationKinds: [],
677
- supportsRelationFieldFilters: false,
678
- relationAggregateSorts: false,
679
- supportsSQLAdmin: false,
680
- supportsDocumentAdmin: false,
681
- supportsSchemaAdmin: false
682
- };
683
- /** @group Models */
684
- var MONGODB_CAPABILITIES = {
685
- key: "mongodb",
686
- label: "MongoDB",
687
- supportsRelations: false,
688
- supportsSubcollections: true,
689
- supportsRLS: false,
690
- supportsReferences: true,
691
- supportsColumnTypes: false,
692
- supportsRealtime: false,
693
- supportsVectors: false,
694
- filterOperators: ALL_WHERE_FILTER_OPS,
695
- filterableRelationKinds: [],
696
- supportsRelationFieldFilters: false,
697
- relationAggregateSorts: false,
698
- supportsSQLAdmin: false,
699
- supportsDocumentAdmin: true,
700
- supportsSchemaAdmin: true
701
- };
702
- /**
703
- * Fallback capabilities when the driver is unknown.
704
- * Enables everything so nothing is hidden unexpectedly.
705
- * @group Models
706
- */
707
- var DEFAULT_CAPABILITIES = {
708
- key: "(default)",
709
- label: "Default",
710
- supportsRelations: true,
711
- supportsSubcollections: true,
712
- supportsRLS: true,
713
- supportsReferences: true,
714
- supportsColumnTypes: true,
715
- supportsRealtime: true,
716
- supportsVectors: true,
717
- filterOperators: ALL_WHERE_FILTER_OPS,
718
- filterableRelationKinds: DEFAULT_FILTERABLE_RELATION_KINDS,
719
- supportsRelationFieldFilters: false,
720
- relationAggregateSorts: false,
721
- supportsSQLAdmin: true,
722
- supportsDocumentAdmin: true,
723
- supportsSchemaAdmin: true
724
- };
725
- var BUILT_IN_CAPABILITIES = /* @__PURE__ */ new Map([
726
- ["postgres", POSTGRES_CAPABILITIES],
727
- ["firestore", FIREBASE_CAPABILITIES],
728
- ["mongodb", MONGODB_CAPABILITIES],
729
- ["(default)", DEFAULT_CAPABILITIES]
730
- ]);
731
- /**
732
- * Capabilities registered at runtime, on `globalThis` rather than in a module
733
- * local: a third-party driver inlines its own copy of this package and
734
- * registers through it, while the app and the server read through theirs. A
735
- * module local made the registration land in a copy nobody else reads.
736
- * See `module-state-across-copies.test.ts`.
737
- */
738
- var REGISTERED_CAPABILITIES_KEY = Symbol.for("@rebasepro/types.dataSourceCapabilities.v1");
739
- function registeredCapabilities() {
740
- const g = globalThis;
741
- let registered = g[REGISTERED_CAPABILITIES_KEY];
742
- if (!registered) {
743
- registered = /* @__PURE__ */ new Map();
744
- g[REGISTERED_CAPABILITIES_KEY] = registered;
745
- }
746
- return registered;
747
- }
748
- /**
749
- * Look up capabilities for a given engine key.
750
- * If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.
751
- * @group Models
752
- */
753
- function getDataSourceCapabilities(engine) {
754
- if (!engine) return POSTGRES_CAPABILITIES;
755
- return registeredCapabilities().get(engine) ?? BUILT_IN_CAPABILITIES.get(engine) ?? DEFAULT_CAPABILITIES;
756
- }
757
- /**
758
- * Register custom capabilities for a third-party driver.
759
- * @group Models
760
- */
761
- function registerDataSourceCapabilities(capabilities) {
762
- registeredCapabilities().set(capabilities.key, capabilities);
763
- }
764
- //#endregion
765
- //#region src/types/collections.ts
766
- /**
767
- * Type guard for PostgreSQL collections.
768
- * Returns true if the collection uses the Postgres engine (or the default engine).
769
- *
770
- * Generic over the *input* type, and narrows by intersection rather than
771
- * replacement. Narrowing to a bare `PostgresCollectionConfig` discarded whatever
772
- * the caller actually had — most visibly the admin panel's view model, whose
773
- * flattened presentation fields vanished the moment a collection passed through
774
- * one of these guards.
775
- *
776
- * @group Models
777
- */
778
- function isPostgresCollectionConfig(collection) {
779
- return !collection.engine || collection.engine === "postgres";
780
- }
781
- /**
782
- * Narrows to the SQL collection fields — `table`, `relations`,
783
- * `disableDefaultPolicies` — by asking the engine's declared capabilities
784
- * rather than by naming Postgres.
785
- *
786
- * The two halves of this already existed and were never joined. The engine
787
- * split (`PostgresCollectionConfig` / `FirebaseCollectionConfig` /
788
- * `MongoDBCollectionConfig`) said which fields belong to which engine at the
789
- * type level; {@link DataSourceCapabilities} said the same thing at runtime,
790
- * down to a `supportsRelations` flag. So call sites guarded on the capability
791
- * and then read a field the base type had to declare for them — which is why
792
- * those fields were on the base, and why a MongoDB collection could be written
793
- * with a `table`.
794
- *
795
- * Prefer this over {@link isPostgresCollectionConfig} wherever the question is
796
- * "does this collection live in a SQL table", so a custom SQL engine
797
- * registered through `registerDataSourceCapabilities` is included.
798
- *
799
- * @group Models
800
- */
801
- function isRelationalCollectionConfig(collection) {
802
- return getDataSourceCapabilities(collection.engine).supportsRelations;
803
- }
804
- /**
805
- * Type guard for Firebase / Firestore collections.
806
- * @group Models
807
- */
808
- function isFirebaseCollectionConfig(collection) {
809
- return collection.engine === "firestore";
810
- }
811
- /**
812
- * Type guard for MongoDB collections.
813
- * @group Models
814
- */
815
- function isMongoDBCollectionConfig(collection) {
816
- return collection.engine === "mongodb";
817
- }
818
- /**
819
- * Returns the data path for a collection.
820
- * For Firestore or MongoDB collections with a `path`, returns that value;
821
- * otherwise falls back to `slug`.
822
- */
823
- function getCollectionDataPath(collection) {
824
- if (isFirebaseCollectionConfig(collection) && collection.path) return collection.path;
825
- if (isMongoDBCollectionConfig(collection) && collection.path) return collection.path;
826
- return collection.slug;
827
- }
828
- /**
829
- * Reads a collection's driver-declared subcollections thunk (the `subcollections`
830
- * field) independent of engine identity, so engine-agnostic code doesn't have to
831
- * type-guard against a specific driver. Returns `undefined` when the collection
832
- * declares none.
833
- *
834
- * Pair with `getDataSourceCapabilities(engine).supportsSubcollections` to decide
835
- * whether the engine honours subcollections at all before reading them.
836
- * @group Models
837
- */
838
- function getDeclaredSubcollections(collection) {
839
- return collection.subcollections;
840
- }
841
- //#endregion
842
- //#region src/types/search.ts
843
- /** The column name used when {@link SearchConfig.column} is not given. */
844
- var DEFAULT_SEARCH_COLUMN = "search_vector";
845
- /** The matching strategy used when {@link SearchConfig.mode} is not given. */
846
- var DEFAULT_SEARCH_MODE = "fts";
847
- /** The text search configuration used when {@link SearchConfig.language} is not given. */
848
- var DEFAULT_SEARCH_LANGUAGE = "simple";
849
- /** The weight a field carries when it does not name one. */
850
- var DEFAULT_SEARCH_WEIGHT = "B";
851
- /** The similarity floor used when {@link SearchConfig.fuzzyThreshold} is not given. */
852
- var DEFAULT_FUZZY_THRESHOLD = .3;
853
- /**
854
- * The relevance sort key. Valid only on a collection that declares a
855
- * {@link SearchConfig} *and* on a query that carries a search string; anywhere
856
- * else it is an unknown field and the request is refused.
857
- */
858
- var RELEVANCE_SORT_FIELD = "_score";
859
- //#endregion
860
- //#region src/types/relations.ts
861
- /**
862
- * The key a junction row's own columns are carried under, in both directions.
863
- *
864
- * A read that includes a `manyToMany` relation serves each related row with its
865
- * link's columns nested here — `{ id: 5, name: "ts", _pivot: { role: "owner" } }`
866
- * — and a membership write may name the same key on an element to state what
867
- * the link should hold. One constant because the two have to be the same word:
868
- * a wire name that differs between the read and the write it round-trips
869
- * through is a shape no client can echo back.
870
- *
871
- * Leading underscore, like `_matches`: it reads as metadata about the row
872
- * rather than as one of its columns. A payload property may not be named
873
- * `_pivot` either — `checkJunctionPayload` refuses it — so the key means one
874
- * thing wherever it appears.
875
- *
876
- * @group Models
877
- */
878
- var JUNCTION_PIVOT_KEY = "_pivot";
879
- /**
880
- * The key a row carries the totals of its counted relations under.
881
- *
882
- * An include that asks for a count — `include: { tags: { limit: 4, count: true } }`
883
- * — serves, beside the (capped) `tags`, how many related rows there are in all:
884
- * `{ id: 1, tags: [ …4 rows ], _count: { tags: 37 } }`. One object per row,
885
- * keyed by relation name, so counting a second relation adds a key rather than
886
- * a second top-level name.
887
- *
888
- * Leading underscore, like {@link JUNCTION_PIVOT_KEY} and `_matches`: it
889
- * describes the read, not the record, and no column or form writes it. A
890
- * collection with a property of this name cannot ask for a count — the read
891
- * answers 400 rather than writing over the column.
892
- *
893
- * @group Models
894
- */
895
- var INCLUDE_COUNT_KEY = "_count";
896
- /** @group Models */
897
- function hasForeignKeyOnTarget(relation) {
898
- return relation.kind === "hasOne" || relation.kind === "hasMany";
899
- }
900
- /** @group Models */
901
- function isManyToMany(relation) {
902
- return relation.kind === "manyToMany";
903
- }
904
- /** @group Models */
905
- function isToMany(relation) {
906
- return relation.cardinality === "many";
907
- }
908
- /**
909
- * The conditions of a join step, as a list: one entry for a plain step, one
910
- * per alternative for a step that joins on any of several.
911
- * @group Models
912
- */
913
- function joinConditions(step) {
914
- return Array.isArray(step.on) ? step.on : [step.on];
915
- }
916
- /**
917
- * The one condition of a step that has no alternatives — for the write paths,
918
- * which only run on a writable chain and a chain with alternatives never is.
919
- * Throws rather than pick one of several: writing a link into the wrong column
920
- * is the mistake read-only exists to prevent.
921
- * @group Models
922
- */
923
- function soleJoinCondition(step) {
924
- if (Array.isArray(step.on)) {
925
- if (step.on.length === 1) return step.on[0];
926
- if (step.on.length === 0) throw new Error(`The join into '${step.table}' lists no conditions, so it joins nothing.`);
927
- throw new Error(`The join into '${step.table}' matches any of ${step.on.length} conditions, so it is read-only: there is no one column to write a link into.`);
928
- }
929
- return step.on;
930
- }
931
- //#endregion
932
- //#region src/types/policy.ts
933
- /**
934
- * The id a request without a logged-in user reports as `rebase.uid()`.
935
- *
936
- * A user-context request always sets `app.uid`: blank would read back as
937
- * `NULL`, and `NULL` is how the trusted server context is recognised, so an
938
- * anonymous visitor would be promoted to server privileges. The driver
939
- * therefore substitutes this sentinel at the single chokepoint where the GUC
940
- * is set.
941
- *
942
- * The consequence for policy authors is that **`rebase.uid() IS NOT NULL` is a
943
- * tautology on the user path** — it is true for anonymous visitors too. Use
944
- * {@link policy.authenticated} to mean "signed in", and
945
- * {@link policy.serverContext} to mean "the trusted server context". Do not
946
- * hand-write the comparison: see {@link ANONYMOUS_USER_IDS} for why one
947
- * literal is not enough.
948
- *
949
- * @group Models
950
- */
951
- var ANONYMOUS_USER_ID = "anonymous";
952
- /**
953
- * Every uid that has ever meant "nobody is signed in" — newest first.
954
- *
955
- * There are two because there were two. The types, the policy compiler, the
956
- * JavaScript evaluator and the linter were all built on
957
- * {@link ANONYMOUS_USER_ID}, while the request path scoped unauthenticated
958
- * callers as `'anon'` — so `policy.authenticated()`, which compiled to
959
- * `rebase.uid() <> 'anonymous'`, was *true* for an anonymous visitor. The
960
- * sanctioned way to write "signed in" granted to everyone, and the linter
961
- * flagged the spelling that actually worked as a foreign convention.
962
- *
963
- * The request path now reports {@link ANONYMOUS_USER_ID}. `'anon'` stays here
964
- * because policies outlive the server that generated them: a database still
965
- * holding policies from before the fix, or a project whose server has not been
966
- * upgraded yet, must not become a grant in either direction. Compile against
967
- * this list, not against a single literal.
968
- *
969
- * No real user id is ever one of these, so a match is always "not signed in".
970
- *
971
- * @group Models
972
- */
973
- var ANONYMOUS_USER_IDS = [ANONYMOUS_USER_ID, "anon"];
974
- /**
975
- * Whether a uid stands for "no one is signed in", in any spelling rebase has
976
- * used. `null`/`undefined` is the trusted server context, not an anonymous
977
- * caller, and is therefore **not** anonymous — see {@link ANONYMOUS_USER_ID}.
978
- *
979
- * @group Models
980
- */
981
- function isAnonymousUid(uid) {
982
- return typeof uid === "string" && ANONYMOUS_USER_IDS.includes(uid);
983
- }
470
+ function isPolicyShorthand(value) {
471
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
472
+ const proto = Object.getPrototypeOf(value);
473
+ if (proto !== Object.prototype && proto !== null) return false;
474
+ if (Object.prototype.hasOwnProperty.call(value, "kind")) return false;
475
+ const entries = Object.entries(value);
476
+ return entries.length > 0 && entries.every(([, v]) => isShorthandValue(v));
477
+ }
984
478
  /** @group Models */
985
479
  var policy = {
986
480
  true: () => ({ kind: "true" }),
@@ -1016,7 +510,7 @@ var policy = {
1016
510
  serverContext: () => ({ kind: "serverContext" }),
1017
511
  existsIn: (args) => ({
1018
512
  kind: "existsIn",
1019
- collection: args.collection,
513
+ table: args.table,
1020
514
  where: args.where
1021
515
  }),
1022
516
  raw: (sql) => ({
@@ -1216,10 +710,21 @@ function usesLegacyRlsFunctions(sql) {
1216
710
  return /\bauth\.(uid|jwt|roles)\s*\(\s*\)/i.test(sql);
1217
711
  }
1218
712
  //#endregion
1219
- //#region src/types/tenancy.ts
1220
- /** Narrow a {@link TenantSource} to its claim form. @group Models */
1221
- function isTenantClaimSource(source) {
1222
- return typeof source.claim === "string";
713
+ //#region src/types/security_rules.ts
714
+ /**
715
+ * Whether a rule is the {@link RedactedSecurityRule} marker the server sends
716
+ * in place of a rule whose SQL it withheld.
717
+ *
718
+ * @group Models
719
+ */
720
+ function isRedactedSecurityRule(rule) {
721
+ return "redacted" in rule && rule.redacted === true;
722
+ }
723
+ //#endregion
724
+ //#region src/types/tenancy.ts
725
+ /** Narrow a {@link TenantSource} to its claim form. @group Models */
726
+ function isTenantClaimSource(source) {
727
+ return typeof source.claim === "string";
1223
728
  }
1224
729
  /** Narrow a {@link TenantSource} to its membership form. @group Models */
1225
730
  function isTenantMembershipSource(source) {
@@ -1260,13 +765,6 @@ function isSQLAdmin(admin) {
1260
765
  return !!admin && typeof admin.executeSql === "function";
1261
766
  }
1262
767
  /**
1263
- * Type guard: does this admin support document operations?
1264
- * @group Admin
1265
- */
1266
- function isDocumentAdmin(admin) {
1267
- return !!admin && (typeof admin.executeAggregate === "function" || typeof admin.fetchCollectionStats === "function");
1268
- }
1269
- /**
1270
768
  * Type guard: does this admin support schema management?
1271
769
  * @group Admin
1272
770
  */
@@ -1293,282 +791,137 @@ function isBranchAdmin(admin) {
1293
791
  */
1294
792
  var DEFAULT_COMMIT_PATHS = { schemaFile: "backend/src/schema.generated.ts" };
1295
793
  //#endregion
1296
- //#region src/types/collection_patch.ts
1297
- /**
1298
- * What changed about a collection, as opposed to what the collection is.
1299
- *
1300
- * ## Why a save is a patch
1301
- *
1302
- * The admin panel edits a collection as JSON — the only form a browser and a
1303
- * server can exchange it in — and JSON cannot carry most of what a collection
1304
- * file holds: an entity action's `onClick`, a computed field's `value`, a
1305
- * property shared from another module (`status: statusProperty`), an enum
1306
- * imported from elsewhere (`enum: LOCALE_ENUM`), the comments around all of
1307
- * them. A save that posted the whole collection and had it written back
1308
- * rewrote every key it carried and deleted everything JSON had dropped, so
1309
- * renaming a collection removed its actions' handlers, inlined its shared
1310
- * property without the custom `Field`, and froze a copy of the enum.
1311
- *
1312
- * So a save sends what the person changed: the difference between the JSON
1313
- * the editor loaded and the JSON it is saving. Anything JSON could not carry
1314
- * is identical on both sides of that difference — dropped from both — and
1315
- * cannot appear in it. The server applies the patch to the collection as it
1316
- * is (for the plan) and writes only the patched keys into the file.
1317
- *
1318
- * ## The shape
1319
- *
1320
- * Two operations on paths of object keys. Arrays are values: an array that
1321
- * changed is set whole. Positions in an array are not stable identities —
1322
- * element 2 of an enum is not "the third value" once a value is inserted —
1323
- * and the writer is the one place that can match an old element to its new
1324
- * self (by `key`/`id`/`name`) and keep what JSON dropped from it.
1325
- *
1326
- * Paths are in the AUTHORING shape — presentation keys under `admin`, the
1327
- * shape the file has — see {@link nestCollectionPatchPaths}.
1328
- */
1329
- /**
1330
- * Keys the runtime adds to a collection that must never be written into its
1331
- * source. `resolvedRelation` is the registry's resolved form of a relation; a
1332
- * file holding one does not type-check (`target` is missing from it).
1333
- */
1334
- var RUNTIME_ONLY_COLLECTION_KEYS = ["resolvedRelation"];
1335
- /** Path segments that reach an object's prototype rather than a key of it. */
1336
- var UNSAFE_SEGMENTS = /* @__PURE__ */ new Set([
1337
- "__proto__",
1338
- "constructor",
1339
- "prototype"
1340
- ]);
1341
- var isPlainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1342
- /** A JSON value as JSON would carry it: functions, `undefined` and symbols dropped. */
1343
- function toCollectionJson(value) {
1344
- if (value === void 0) return void 0;
1345
- const text = JSON.stringify(value);
1346
- return text === void 0 ? void 0 : JSON.parse(text);
1347
- }
1348
- function jsonEqual(a, b) {
1349
- if (a === b) return true;
1350
- if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, index) => jsonEqual(item, b[index]));
1351
- if (isPlainObject(a) && isPlainObject(b)) {
1352
- const keys = Object.keys(a);
1353
- if (keys.length !== Object.keys(b).length) return false;
1354
- return keys.every((key) => Object.prototype.hasOwnProperty.call(b, key) && jsonEqual(a[key], b[key]));
1355
- }
1356
- return false;
1357
- }
794
+ //#region src/types/channel_bus.ts
1358
795
  /**
1359
- * The operations that take `before` to `after`, both JSON values.
796
+ * Whether `setting` is an already-constructed transport rather than a request
797
+ * for a built-in one.
1360
798
  *
1361
- * Objects are compared key by key; anything else that differs — a primitive,
1362
- * an array, a change of kind — is set whole.
799
+ * Structural rather than nominal so that an instance from a *different copy* of
800
+ * `@rebasepro/types` — an entirely normal outcome of a separately versioned
801
+ * transport package — is still recognised.
1363
802
  */
1364
- function diffJsonValues(before, after, path = []) {
1365
- if (jsonEqual(before, after)) return [];
1366
- if (isPlainObject(before) && isPlainObject(after)) {
1367
- const ops = [];
1368
- for (const key of Object.keys(after)) if (!Object.prototype.hasOwnProperty.call(before, key)) ops.push({
1369
- op: "set",
1370
- path: [...path, key],
1371
- value: after[key]
1372
- });
1373
- else ops.push(...diffJsonValues(before[key], after[key], [...path, key]));
1374
- for (const key of Object.keys(before)) if (!Object.prototype.hasOwnProperty.call(after, key)) ops.push({
1375
- op: "remove",
1376
- path: [...path, key]
1377
- });
1378
- return ops;
1379
- }
1380
- return [{
1381
- op: "set",
1382
- path,
1383
- value: after
1384
- }];
1385
- }
1386
- function step(position, segment) {
1387
- switch (position) {
1388
- case "collection": return segment === "properties" ? "properties" : "other";
1389
- case "properties": return "property";
1390
- case "property":
1391
- if (segment === "properties") return "properties";
1392
- if (segment === "of") return "property";
1393
- if (segment === "oneOf") return "oneOf";
1394
- return "other";
1395
- case "oneOf": return segment === "properties" ? "properties" : "other";
1396
- default: return "other";
1397
- }
1398
- }
1399
- function nestPath(path) {
1400
- const nested = [];
1401
- let position = "collection";
1402
- for (const segment of path) {
1403
- const moved = position === "collection" && ADMIN_COLLECTION_KEYS.includes(segment) || position === "property" && ADMIN_PROPERTY_KEYS.includes(segment);
1404
- if (moved) nested.push("admin");
1405
- nested.push(segment);
1406
- position = moved ? "other" : step(position, segment);
1407
- }
1408
- return {
1409
- path: nested,
1410
- position
1411
- };
1412
- }
1413
- function nestValue(position, value) {
1414
- if (position === "property") {
1415
- if (Array.isArray(value)) return value.map((entry) => isPlainObject(entry) ? nestAdminPropertyKeys(entry) : entry);
1416
- return isPlainObject(value) ? nestAdminPropertyKeys(value) : value;
1417
- }
1418
- if (position === "properties" && isPlainObject(value)) return Object.fromEntries(Object.entries(value).map(([key, property]) => [key, isPlainObject(property) ? nestAdminPropertyKeys(property) : property]));
1419
- if (position === "oneOf" && isPlainObject(value)) return isPlainObject(value.properties) ? {
1420
- ...value,
1421
- properties: nestValue("properties", value.properties)
1422
- } : value;
1423
- if (position === "collection" && isPlainObject(value)) {
1424
- const nested = nestAdminCollectionKeys(value);
1425
- return isPlainObject(nested.properties) ? {
1426
- ...nested,
1427
- properties: nestValue("properties", nested.properties)
1428
- } : nested;
1429
- }
1430
- return value;
803
+ function isChannelBusInstance(setting) {
804
+ return typeof setting?.publish === "function";
1431
805
  }
806
+ //#endregion
807
+ //#region src/types/data_source.ts
1432
808
  /**
1433
- * The patch, with every flat presentation key moved into its `admin` block.
1434
- *
1435
- * The panel edits a flat view model — `icon` beside `name`, a property's
1436
- * `readOnly` beside its `type` — while the file keeps them under `admin`. The
1437
- * difference is taken on the flat model, because that is where a cleared field
1438
- * shows up as a removed key (the `admin` copy the model was loaded with still
1439
- * holds the old value), and moved here.
1440
- *
1441
- * The flat value wins over the `admin` copy, as in {@link nestAdminKeysOf}:
1442
- * operations that were already under `admin` are ordered first, so the flat
1443
- * one — what the form just wrote — is applied last.
809
+ * The default data-source key, used when a collection does not name a
810
+ * `dataSource`. Shared by the frontend router and the backend driver
811
+ * registry so both agree on "the default database".
812
+ * @group Models
1444
813
  */
1445
- function nestCollectionPatchPaths(patch) {
1446
- return patch.map((op, index) => {
1447
- const { path, position } = nestPath(op.path);
1448
- const wasNested = op.path.includes("admin");
1449
- return {
1450
- moved: op.op === "remove" ? {
1451
- op: "remove",
1452
- path
1453
- } : {
1454
- op: "set",
1455
- path,
1456
- value: nestValue(position, op.value)
1457
- },
1458
- wasNested,
1459
- index
1460
- };
1461
- }).sort((a, b) => a.wasNested === b.wasNested ? a.index - b.index : a.wasNested ? -1 : 1).map((entry) => entry.moved);
1462
- }
814
+ var DEFAULT_DATA_SOURCE_KEY = "(default)";
1463
815
  /**
1464
- * The patch that takes the collection the editor loaded to the one it is
1465
- * saving, in the authoring shape. Empty when nothing changed.
816
+ * Relation kinds assumed filterable when a driver does not say.
817
+ *
818
+ * `belongsTo` alone: its filter is a comparison on a column of the row being
819
+ * filtered, the one shape that needs no query construction a driver might not
820
+ * have. Everything else is a correlated subquery over another table.
1466
821
  *
1467
- * Both sides go through JSON first, so whatever JSON cannot carry — a
1468
- * function, a value it drops — is equally absent from both and never appears
1469
- * as a change.
822
+ * @group Models
1470
823
  */
1471
- function diffCollections(loaded, saving) {
1472
- return nestCollectionPatchPaths(diffJsonValues(toCollectionJson(loaded), toCollectionJson(saving)));
1473
- }
824
+ var DEFAULT_FILTERABLE_RELATION_KINDS = ["belongsTo"];
825
+ /** @group Models */
826
+ var POSTGRES_CAPABILITIES = {
827
+ key: "postgres",
828
+ label: "PostgreSQL",
829
+ supportsRelations: true,
830
+ supportsSubcollections: false,
831
+ supportsRLS: true,
832
+ supportsReferences: false,
833
+ supportsColumnTypes: true,
834
+ supportsRealtime: true,
835
+ supportsVectors: true,
836
+ filterOperators: ALL_WHERE_FILTER_OPS,
837
+ filterableRelationKinds: [
838
+ "belongsTo",
839
+ "manyToMany",
840
+ "hasMany",
841
+ "hasOne"
842
+ ],
843
+ supportsRelationFieldFilters: true,
844
+ relationAggregateSorts: true,
845
+ supportsSQLAdmin: true,
846
+ supportsSchemaAdmin: true
847
+ };
848
+ /** @group Models */
849
+ var FIREBASE_CAPABILITIES = {
850
+ key: "firestore",
851
+ label: "Firebase / Firestore",
852
+ supportsRelations: false,
853
+ supportsSubcollections: true,
854
+ supportsRLS: false,
855
+ supportsReferences: true,
856
+ supportsColumnTypes: false,
857
+ supportsRealtime: true,
858
+ supportsVectors: false,
859
+ filterOperators: ALL_WHERE_FILTER_OPS.filter((op) => op !== "like" && op !== "ilike" && op !== "not-like" && op !== "not-ilike" && op !== "array-contains-all" && op !== "array-contained-by"),
860
+ filterableRelationKinds: [],
861
+ supportsRelationFieldFilters: false,
862
+ relationAggregateSorts: false,
863
+ supportsSQLAdmin: false,
864
+ supportsSchemaAdmin: false
865
+ };
1474
866
  /**
1475
- * Why a patch may not be applied, or an empty list.
1476
- *
1477
- * Checked by every door that accepts one: a path is a list of non-empty object
1478
- * keys that cannot reach a prototype, and no runtime-only key may be written.
867
+ * Fallback capabilities when the driver is unknown.
868
+ * Enables everything so nothing is hidden unexpectedly.
869
+ * @group Models
1479
870
  */
1480
- function collectionPatchProblems(patch) {
1481
- if (!Array.isArray(patch)) return ["`patch` must be a list of operations."];
1482
- const problems = [];
1483
- patch.forEach((op, index) => {
1484
- const where = `patch[${index}]`;
1485
- if (!isPlainObject(op) || op.op !== "set" && op.op !== "remove") {
1486
- problems.push(`${where} must be { op: "set", path, value } or { op: "remove", path }.`);
1487
- return;
1488
- }
1489
- const path = op.path;
1490
- if (!Array.isArray(path) || path.length === 0 || !path.every((segment) => typeof segment === "string" && segment.length > 0)) {
1491
- problems.push(`${where}.path must be a non-empty list of object keys.`);
1492
- return;
1493
- }
1494
- const unsafe = path.find((segment) => UNSAFE_SEGMENTS.has(segment));
1495
- if (unsafe) problems.push(`${where}.path may not contain "${unsafe}".`);
1496
- const runtime = path.find((segment) => RUNTIME_ONLY_COLLECTION_KEYS.includes(segment));
1497
- if (runtime) problems.push(`${where} writes "${runtime}", which the runtime adds and a collection file must not hold.`);
1498
- if (op.op === "set") {
1499
- const key = keyIn(op.value, (key) => UNSAFE_SEGMENTS.has(key) || RUNTIME_ONLY_COLLECTION_KEYS.includes(key));
1500
- if (key) problems.push(`${where}.value holds "${key}", which a collection file must not hold.`);
1501
- }
1502
- });
1503
- return problems;
1504
- }
871
+ var DEFAULT_CAPABILITIES = {
872
+ key: "(default)",
873
+ label: "Default",
874
+ supportsRelations: true,
875
+ supportsSubcollections: true,
876
+ supportsRLS: true,
877
+ supportsReferences: true,
878
+ supportsColumnTypes: true,
879
+ supportsRealtime: true,
880
+ supportsVectors: true,
881
+ filterOperators: ALL_WHERE_FILTER_OPS,
882
+ filterableRelationKinds: DEFAULT_FILTERABLE_RELATION_KINDS,
883
+ supportsRelationFieldFilters: false,
884
+ relationAggregateSorts: false,
885
+ supportsSQLAdmin: true,
886
+ supportsSchemaAdmin: true
887
+ };
888
+ var BUILT_IN_CAPABILITIES = /* @__PURE__ */ new Map([
889
+ ["postgres", POSTGRES_CAPABILITIES],
890
+ ["firestore", FIREBASE_CAPABILITIES],
891
+ ["(default)", DEFAULT_CAPABILITIES]
892
+ ]);
1505
893
  /**
1506
- * The first runtime-only key (see {@link RUNTIME_ONLY_COLLECTION_KEYS}) found
1507
- * anywhere in a value, or `undefined`. For the doors that take a whole
1508
- * collection rather than a patch.
894
+ * Capabilities registered at runtime, on `globalThis` rather than in a module
895
+ * local: a third-party driver inlines its own copy of this package and
896
+ * registers through it, while the app and the server read through theirs. A
897
+ * module local made the registration land in a copy nobody else reads.
898
+ * See `module-state-across-copies.test.ts`.
1509
899
  */
1510
- function runtimeOnlyKeyIn(value) {
1511
- return keyIn(value, (key) => RUNTIME_ONLY_COLLECTION_KEYS.includes(key));
1512
- }
1513
- /** A patch every door may apply: {@link collectionPatchProblems} found nothing. */
1514
- function isCollectionPatch(patch) {
1515
- return collectionPatchProblems(patch).length === 0;
1516
- }
1517
- function keyIn(value, matches) {
1518
- if (Array.isArray(value)) {
1519
- for (const item of value) {
1520
- const found = keyIn(item, matches);
1521
- if (found) return found;
1522
- }
1523
- return;
1524
- }
1525
- if (!isPlainObject(value)) return void 0;
1526
- for (const key of Object.keys(value)) {
1527
- if (matches(key)) return key;
1528
- const found = keyIn(value[key], matches);
1529
- if (found) return found;
900
+ var REGISTERED_CAPABILITIES_KEY = Symbol.for("@rebasepro/types.dataSourceCapabilities.v1");
901
+ function registeredCapabilities() {
902
+ const g = globalThis;
903
+ let registered = g[REGISTERED_CAPABILITIES_KEY];
904
+ if (!registered) {
905
+ registered = /* @__PURE__ */ new Map();
906
+ g[REGISTERED_CAPABILITIES_KEY] = registered;
1530
907
  }
908
+ return registered;
1531
909
  }
1532
910
  /**
1533
- * `target` with the patch applied, copying only what it changes.
1534
- *
1535
- * Everything the patch does not reach is shared with `target` by reference —
1536
- * functions, thunks and all — which is what lets a planner see a relation's
1537
- * `target()` on the patched collection exactly as it was. Intermediate objects
1538
- * a `set` needs are created; a `remove` of a key that is not there is nothing
1539
- * to do.
911
+ * Look up capabilities for a given engine key.
912
+ * If `engine` is undefined or not found, returns `DEFAULT_CAPABILITIES`.
913
+ * @group Models
1540
914
  */
1541
- function applyCollectionPatch(target, patch) {
1542
- let root = target;
1543
- for (const op of patch) root = applyOp(root, op.path, op);
1544
- return root;
1545
- }
1546
- function applyOp(node, path, op) {
1547
- const [head, ...rest] = path;
1548
- if (UNSAFE_SEGMENTS.has(head)) throw new Error(`A collection patch may not reach "${head}".`);
1549
- const base = isPlainObject(node) ? { ...node } : {};
1550
- if (rest.length === 0) {
1551
- if (op.op === "remove") delete base[head];
1552
- else base[head] = op.value;
1553
- return base;
1554
- }
1555
- const child = Object.prototype.hasOwnProperty.call(base, head) ? base[head] : void 0;
1556
- if (op.op === "remove" && !isPlainObject(child)) return node;
1557
- base[head] = applyOp(child, rest, op);
1558
- return base;
915
+ function getDataSourceCapabilities(engine) {
916
+ if (!engine) return POSTGRES_CAPABILITIES;
917
+ return registeredCapabilities().get(engine) ?? BUILT_IN_CAPABILITIES.get(engine) ?? DEFAULT_CAPABILITIES;
1559
918
  }
1560
- //#endregion
1561
- //#region src/types/channel_bus.ts
1562
919
  /**
1563
- * Whether `setting` is an already-constructed transport rather than a request
1564
- * for a built-in one.
1565
- *
1566
- * Structural rather than nominal so that an instance from a *different copy* of
1567
- * `@rebasepro/types` — an entirely normal outcome of a separately versioned
1568
- * transport package — is still recognised.
920
+ * Register custom capabilities for a third-party driver.
921
+ * @group Models
1569
922
  */
1570
- function isChannelBusInstance(setting) {
1571
- return typeof setting?.publish === "function";
923
+ function registerDataSourceCapabilities(capabilities) {
924
+ registeredCapabilities().set(capabilities.key, capabilities);
1572
925
  }
1573
926
  //#endregion
1574
927
  //#region src/types/resources.ts
@@ -2495,15 +1848,6 @@ function parseEnvBoolean(value) {
2495
1848
  if (NO.has(spelled)) return false;
2496
1849
  }
2497
1850
  //#endregion
2498
- //#region src/types/component_ref.ts
2499
- /**
2500
- * Type guard: checks if a value is a `LazyComponentRef` produced by the
2501
- * Vite transform plugin.
2502
- */
2503
- function isLazyComponentRef(ref) {
2504
- return typeof ref === "object" && ref !== null && "__rebaseLazy" in ref && ref.__rebaseLazy === true;
2505
- }
2506
- //#endregion
2507
1851
  //#region src/types/auth_adapter.ts
2508
1852
  /**
2509
1853
  * The request header that asks for a data-plane request to run as another
@@ -2730,15 +2074,15 @@ var SCOPE_TARGETS = {
2730
2074
  var BUILT_IN_SCOPE_DESCRIPTIONS = {
2731
2075
  "data:read": {
2732
2076
  label: "Read data",
2733
- description: "Read rows from collections, through the caller's row-level security."
2077
+ description: "Read rows from tables, through the caller's row-level security."
2734
2078
  },
2735
2079
  "data:write": {
2736
2080
  label: "Create and update data",
2737
- description: "Create and update rows in collections, through the caller's row-level security."
2081
+ description: "Create and update rows in tables, through the caller's row-level security."
2738
2082
  },
2739
2083
  "data:delete": {
2740
2084
  label: "Delete data",
2741
- description: "Delete rows from collections, through the caller's row-level security."
2085
+ description: "Delete rows from tables, through the caller's row-level security."
2742
2086
  },
2743
2087
  "storage:read": {
2744
2088
  label: "Read files",
@@ -2766,11 +2110,11 @@ var BUILT_IN_SCOPE_DESCRIPTIONS = {
2766
2110
  },
2767
2111
  "schema:read": {
2768
2112
  label: "See the schema",
2769
- description: "Read the collection schema, plan schema changes and run the RLS audit."
2113
+ description: "Read the schema, plan schema changes and run the RLS audit."
2770
2114
  },
2771
2115
  "schema:write": {
2772
2116
  label: "Change the schema",
2773
- description: "Apply schema changes: edits collection files and alters the database."
2117
+ description: "Apply schema changes: edits schema files and alters the database."
2774
2118
  },
2775
2119
  "database:read": {
2776
2120
  label: "Inspect the database",
@@ -3199,8 +2543,30 @@ function isValidAppHost(host) {
3199
2543
  * one of these would find no `mode` and an array where it expects a string, so
3200
2544
  * the bump is what turns that into a refusal to boot instead of a bundle that
3201
2545
  * starts and serves nothing.
2546
+ * - **3** — the schema is `entry.tables` (the compiled `backend/schema`
2547
+ * directory, whose `index` exports the tables), beside `entry.resources`,
2548
+ * `entry.storage` and `entry.hooks`. There is no config package any more:
2549
+ * `entry.config`, `entry.collections` and `entry.usersCollection` are not
2550
+ * written. A format-2 runtime would find none of the keys it boots from and
2551
+ * introspect the database instead of serving the declared tables — so the
2552
+ * bump turns that into a refusal.
2553
+ *
2554
+ * **Format 2 bundles are refused, not upgraded.** Unlike 1 → 2, which was a
2555
+ * renaming, a format-2 bundle carries `config/collections` — `defineCollection`
2556
+ * objects — and a runtime that reads only `backend/schema` has nothing to read
2557
+ * them with. It refuses them at boot with {@link LEGACY_LAYOUT_REMEDY} in the
2558
+ * error: run the codemod on the project's source, then rebuild.
3202
2559
  */
3203
- var BUNDLE_FORMAT_VERSION = 2;
2560
+ var BUNDLE_FORMAT_VERSION = 3;
2561
+ /**
2562
+ * What to do about a project on the `config/collections` layout — the words
2563
+ * every refusal of that layout ends with.
2564
+ *
2565
+ * Shared because two parties refuse it and must say the same thing: the CLI,
2566
+ * for a `rebase.json` that still names `config` or `usersCollection`, and the
2567
+ * runtime, for a format-2 / contract-1 bundle built from `config/collections`.
2568
+ */
2569
+ var LEGACY_LAYOUT_REMEDY = "run `rebase migrate collections-to-tables` (in the Rebase repository: tooling/scripts/migrate-collections-to-tables.mts), which rewrites config/collections as backend/schema (and the admin presentation as frontend/src/cms), carries the collection callbacks into the tables as hooks, moves resources.ts and storage.ts to backend/, and proves the generated SQL unchanged; then rebuild";
3204
2570
  /**
3205
2571
  * The runtime contract major.
3206
2572
  *
@@ -3209,23 +2575,36 @@ var BUNDLE_FORMAT_VERSION = 2;
3209
2575
  * the bundle/runtime contract breaks compatibility, and a project's
3210
2576
  * `manifest.runtime` range is matched against *this*.
3211
2577
  *
3212
- * ## v2 — resources are declared, not configured
3213
- *
3214
- * `RebaseBackendConfig.dataSources` and `.storageSources` are gone. A project
3215
- * declares its databases and buckets with `database()` / `bucket()` in its
3216
- * config, and the runtime reads those declarations.
3217
- *
3218
- * This had to be a major, and the reason is the managed tier: it moves projects
3219
- * onto new images WITHOUT rebuilding them. A bundle built against v1 exports
3220
- * those keys, and a v2 runtime refuses them at boot — so without this bump, one
3221
- * image rollout would crash-loop every tenant that had ever declared a second
3222
- * database or bucket, in a wave, with the cause in a container log nobody is
3223
- * watching.
3224
- *
3225
- * With the bump, a v1 bundle on a v2 runtime is refused by
3226
- * `assertBundleCompatibility` with the remedy in the message, and the platform
3227
- * keeps it on a v1 image until it is rebuilt. That is the whole purpose of this
3228
- * number.
2578
+ * ## v2 — tables, not collections
2579
+ *
2580
+ * The runtime reads the project's schema from `backend/schema` (bundle format
2581
+ * 3, `entry.tables`): `defineTable` / `defineAuthTable` / `defineView` exports
2582
+ * and `defaultRls`. It no longer loads `config/collections`, and it no longer
2583
+ * reads a config package's `collections` / `callbacks` exports or a
2584
+ * `usersCollection` module; global table hooks come from `backend/hooks.ts`,
2585
+ * `storageAuthorize` from `backend/storage.ts`, declared resources from
2586
+ * `backend/resources.ts`.
2587
+ *
2588
+ * So, plainly: **a format-2 / contract-1 bundle — one built from
2589
+ * `config/collections` — is refused by a contract-2 runtime**, at boot, with
2590
+ * {@link LEGACY_LAYOUT_REMEDY} in the message. There is no in-runtime adapter
2591
+ * from collections to tables; the project's source is migrated once with the
2592
+ * codemod and rebuilt. On the managed tier that means the platform keeps such a
2593
+ * tenant on a contract-1 image until it is rebuilt — the release order below
2594
+ * applies unchanged.
2595
+ *
2596
+ * This has to be a major, and the reason is the managed tier: it moves projects
2597
+ * onto new images WITHOUT rebuilding them. Without the bump, one image rollout
2598
+ * would crash-loop every tenant whose bundle predates the change, in a wave,
2599
+ * with the cause in a container log nobody is watching. With it, an older
2600
+ * bundle on a newer runtime is refused by `readBundleManifest` with the remedy
2601
+ * in the message, and the platform keeps it on an image of its own major until
2602
+ * it is rebuilt. That is the whole purpose of this number.
2603
+ *
2604
+ * (Declared resources — `database()` / `bucket()` replacing
2605
+ * `RebaseBackendConfig.dataSources` / `.storageSources` — once took this number
2606
+ * to 2 and were taken back to 1 before launch, when there was no fleet for the
2607
+ * major to protect. They are part of v1.)
3229
2608
  *
3230
2609
  * **Release order matters and is not optional.** The control plane is the side
3231
2610
  * that rejects, so it ships FIRST: raise `SUPPORTED_RUNTIME_CONTRACT` in the
@@ -3234,7 +2613,7 @@ var BUNDLE_FORMAT_VERSION = 2;
3234
2613
  * runtime first turns every deploy into a rejected intake blaming the tenant's
3235
2614
  * bundle.
3236
2615
  */
3237
- var RUNTIME_CONTRACT_VERSION = 1;
2616
+ var RUNTIME_CONTRACT_VERSION = 2;
3238
2617
  /** Header carrying the schema version an SDK was generated from. */
3239
2618
  var SCHEMA_VERSION_HEADER = "x-rebase-schema";
3240
2619
  //#endregion
@@ -3273,169 +2652,23 @@ function looksLikeHash(text) {
3273
2652
  return /^[A-Za-z0-9_-]+$/.test(text) && /[0-9A-Z]/.test(text);
3274
2653
  }
3275
2654
  //#endregion
3276
- //#region src/types/collection_contract.ts
3277
- function isSerializedCollectionRef(value) {
3278
- return typeof value === "object" && value !== null && typeof value.__collectionRef === "string";
3279
- }
3280
- /** Depth limit for the walk — deep enough for real configs, finite for cyclic ones. */
3281
- var MAX_DEPTH = 64;
3282
- /**
3283
- * Resolve whatever a `target` thunk returns down to a collection.
3284
- *
3285
- * A target may be the collection, a module namespace (when the authoring file
3286
- * used `import * as`), or a default-export wrapper. All three appear in real
3287
- * projects, and the SDK generator already unwraps them the same way.
3288
- */
3289
- function unwrapTarget(value) {
3290
- if (!value || typeof value !== "object") return void 0;
3291
- const candidate = value;
3292
- if (candidate.default || candidate.__esModule) {
3293
- const inner = candidate.default;
3294
- if (inner && typeof inner === "object") return inner;
3295
- }
3296
- if (candidate.properties) return value;
3297
- }
3298
- /** The identity a serialized reference uses. Slug first — it is the routing key. */
3299
- function refFor(collection) {
3300
- if (!collection) return void 0;
3301
- const withPath = collection;
3302
- return collection.slug || withPath.path || collection.name;
3303
- }
3304
- function toSerializable(value, seen, depth, state, key) {
3305
- if (depth > MAX_DEPTH) {
3306
- state.truncations++;
3307
- return;
3308
- }
3309
- if (typeof value === "function") {
3310
- if (key === "target") try {
3311
- const ref = refFor(unwrapTarget(value()));
3312
- return ref ? { __collectionRef: ref } : void 0;
3313
- } catch {
3314
- return;
3315
- }
3316
- return;
3317
- }
3318
- if (value === null || typeof value !== "object") return value;
3319
- if (value instanceof Date) return value.toISOString();
3320
- if (value instanceof RegExp) return value.source;
3321
- if (seen.has(value)) {
3322
- state.truncations++;
3323
- return;
3324
- }
3325
- const cached = state.memo.get(value);
3326
- if (cached !== void 0) return cached;
3327
- seen.add(value);
3328
- const truncationsBefore = state.truncations;
3329
- const memoize = (result) => {
3330
- if (result !== void 0 && state.truncations === truncationsBefore) state.memo.set(value, result);
3331
- return result;
3332
- };
3333
- try {
3334
- if (Array.isArray(value)) {
3335
- const items = value.map((item) => toSerializable(item, seen, depth + 1, state)).filter((item) => item !== void 0);
3336
- return memoize(value.length > 0 && items.length === 0 ? void 0 : items);
3337
- }
3338
- if ("$$typeof" in value) return void 0;
3339
- const entries = Object.entries(value);
3340
- const out = {};
3341
- for (const [k, v] of entries) {
3342
- const converted = toSerializable(v, seen, depth + 1, state, k);
3343
- if (converted !== void 0) out[k] = converted;
3344
- }
3345
- if (entries.length > 0 && Object.keys(out).length === 0) return void 0;
3346
- return memoize(out);
3347
- } finally {
3348
- seen.delete(value);
3349
- }
3350
- }
3351
- /**
3352
- * Serialize collections for transport over the contract endpoint.
3353
- *
3354
- * Sorted by slug so the output — and therefore the schema hash computed from it
3355
- * — does not depend on filesystem ordering.
3356
- */
3357
- function serializeCollections(collections) {
3358
- return [...collections].sort((a, b) => String(a.slug ?? "").localeCompare(String(b.slug ?? ""))).map((collection) => toSerializable(withoutAdminBlock(collection), /* @__PURE__ */ new WeakSet(), 0, {
3359
- memo: /* @__PURE__ */ new WeakMap(),
3360
- truncations: 0
3361
- })).filter((c) => c !== void 0);
3362
- }
3363
- /**
3364
- * Drop the admin block before the walk.
3365
- *
3366
- * Nothing downstream of serialization is an admin panel. The contract endpoint
3367
- * feeds remote SDK generation, and `rebase build` writes the result into a bundle
3368
- * manifest that only the backend runtime reads. The block would survive the walk
3369
- * as a husk anyway — its React elements and component functions are dropped
3370
- * individually — and that husk has two costs worth avoiding: it puts every custom
3371
- * component's *file path* on an endpoint whose job is to describe data shapes, and
3372
- * it grows a payload that is fetched and cached per project.
3373
- *
3374
- * Removing it here rather than at each call site means one chokepoint, so a future
3375
- * consumer of `serializeCollections` cannot forget.
3376
- *
3377
- * Child collections carry their own block, so this recurses — stripping only the
3378
- * top level was the mistake `stripNonClientFields` in the contract routes already
3379
- * had to fix once for security rules.
3380
- */
3381
- function withoutAdminBlock(collection) {
3382
- const { admin: _admin, ...rest } = collection;
3383
- const nested = rest;
3384
- if (Array.isArray(nested.subcollections)) nested.subcollections = nested.subcollections.map((child) => withoutAdminBlock(child));
3385
- return rest;
3386
- }
3387
- /**
3388
- * Rebuild collections received from a contract endpoint.
3389
- *
3390
- * Relation refs become real thunks resolving through the returned set, so
3391
- * downstream consumers — the SDK generator above all — see exactly the shape
3392
- * they would have seen had the collections been imported from source.
3393
- *
3394
- * A ref naming a collection that is not in the payload resolves to `undefined`
3395
- * rather than throwing: the generator already tolerates an unresolvable target
3396
- * by falling back to a permissive key type, and a partial contract should still
3397
- * produce a usable SDK.
3398
- */
3399
- function deserializeCollections(payload) {
3400
- const collections = payload.filter((c) => typeof c === "object" && c !== null).map((c) => ({ ...c }));
3401
- const bySlug = /* @__PURE__ */ new Map();
3402
- for (const collection of collections) {
3403
- const ref = refFor(collection);
3404
- if (ref) bySlug.set(ref, collection);
3405
- }
3406
- const rehydrate = (value, depth) => {
3407
- if (depth > MAX_DEPTH || !value || typeof value !== "object") return;
3408
- if (Array.isArray(value)) {
3409
- for (const item of value) rehydrate(item, depth + 1);
3410
- return;
3411
- }
3412
- const record = value;
3413
- for (const [key, child] of Object.entries(record)) {
3414
- if (key === "target" && isSerializedCollectionRef(child)) {
3415
- const slug = child.__collectionRef;
3416
- record.target = () => bySlug.get(slug);
3417
- continue;
3418
- }
3419
- rehydrate(child, depth + 1);
3420
- }
3421
- };
3422
- for (const collection of collections) rehydrate(collection, 0);
3423
- return collections;
3424
- }
3425
- //#endregion
3426
2655
  //#region src/types/schema_version.ts
3427
2656
  /**
3428
2657
  * The schema version stamp.
3429
2658
  *
3430
2659
  * One function, used in three places that must agree or the whole drift-detection
3431
2660
  * story is noise: `rebase build` writes it into a bundle manifest, the runtime
3432
- * serves it from the contract endpoint, and a generated SDK records the value it
3433
- * was built from. If any two of those computed it differently, every client would
3434
- * look permanently out of date.
2661
+ * serves it from the contract endpoint and stamps it into the database it
2662
+ * provisions, and a generated SDK records the value it was built from. If any
2663
+ * two of those computed it differently, every client would look permanently out
2664
+ * of date.
3435
2665
  *
3436
- * It covers **collections only** — the client's contract is the shape of the
3437
- * data, so editing a hook or a server function must not invalidate every SDK in
3438
- * every repository. That is a deliberate narrowing, not an oversight.
2666
+ * It covers **tables only** — their compiled descriptors — so editing a hook's
2667
+ * code or a server function never invalidates every SDK in every repository.
2668
+ * That is a deliberate narrowing, not an oversight.
2669
+ *
2670
+ * Versions are prefixed `v2:` (descriptors, since 0.31); `v1:` versions were
2671
+ * computed from collections — see {@link LEGACY_SCHEMA_VERSION_PREFIX}.
3439
2672
  */
3440
2673
  /** Stable stringify: object keys sorted at every level, so key order cannot alter the hash. */
3441
2674
  function canonicalize(value) {
@@ -3444,41 +2677,33 @@ function canonicalize(value) {
3444
2677
  return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(",")}}`;
3445
2678
  }
3446
2679
  /**
3447
- * Reduce a collection to the parts a generated client is actually built from.
3448
- *
3449
- * The version answers one question — "is this SDK stale?" — so it must change
3450
- * exactly when the generated types could change, and never otherwise. Hashing a
3451
- * whole collection fails both halves of that:
2680
+ * The prefix of a version computed before 0.31, from collections.
3452
2681
  *
3453
- * - Security rules, callbacks, icons, groups and UI settings do not appear in a
3454
- * generated client, so including them reports perfectly current SDKs as stale.
3455
- * - Worse, they are not stable *inputs*. The runtime applies default security
3456
- * rules when it loads collections, so the same source hashed before and after
3457
- * loading produced two different answers — a build-time stamp that could never
3458
- * match the server that served it.
3459
- *
3460
- * Codegen reads the slug (for the `Database` key and type names), the properties,
3461
- * and the relations. That is the projection.
2682
+ * A database stamped with one was provisioned under the collection model. Its
2683
+ * version can never equal a descriptor version, so the first boot of a 0.31
2684
+ * runtime against it reports a mismatch once — and says why, and how to
2685
+ * restamp.
3462
2686
  */
3463
- function projectForCodegen(collection) {
3464
- const source = collection;
3465
- return {
3466
- slug: collection.slug ?? source.path,
3467
- properties: collection.properties,
3468
- relations: source.relations,
3469
- engine: source.engine,
3470
- dataSource: source.dataSource,
3471
- subcollections: source.subcollections?.map(projectForCodegen)
3472
- };
3473
- }
2687
+ var LEGACY_SCHEMA_VERSION_PREFIX = "v1:";
3474
2688
  /**
3475
- * Compute the canonical string a schema version hashes.
2689
+ * Compute the canonical string a schema version hashes: the tables'
2690
+ * descriptors, ordered by slug, every object's keys sorted.
2691
+ *
2692
+ * A descriptor is the compiled table — every default applied, every name
2693
+ * derived, `rls` resolved against `defaultRls` — so the same source compiles to
2694
+ * the same descriptor before or after anything loads it, and a build-time
2695
+ * stamp can match the server that serves it. It is plain JSON by
2696
+ * construction: hooks appear only as presence flags (`hooks.afterRead: true`),
2697
+ * so editing what a hook does never moves the version, while adding or
2698
+ * removing one does.
2699
+ *
2700
+ * Ordered by slug, so the order the tables were exported in cannot alter it.
3476
2701
  *
3477
2702
  * Exposed separately so the hashing itself can differ by environment: Node has
3478
2703
  * `crypto`, and callers without it can still compare canonical forms directly.
3479
2704
  */
3480
- function canonicalSchemaPayload(collections) {
3481
- return canonicalize(serializeCollections(collections).map((collection) => projectForCodegen(collection)));
2705
+ function canonicalSchemaPayload(tables) {
2706
+ return canonicalize([...tables].sort((a, b) => a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0));
3482
2707
  }
3483
2708
  /**
3484
2709
  * A short, non-cryptographic digest of the canonical payload.
@@ -3489,8 +2714,8 @@ function canonicalSchemaPayload(collections) {
3489
2714
  * module free of `node:crypto`, so the identical function runs in the browser,
3490
2715
  * in the CLI, and in the runtime — which is the property that actually matters.
3491
2716
  */
3492
- function computeSchemaVersion(collections) {
3493
- const payload = canonicalSchemaPayload(collections);
2717
+ function computeSchemaVersion(tables) {
2718
+ const payload = canonicalSchemaPayload(tables);
3494
2719
  let h1 = 2166136261;
3495
2720
  let h2 = 16777619;
3496
2721
  for (let i = 0; i < payload.length; i++) {
@@ -3501,7 +2726,7 @@ function computeSchemaVersion(collections) {
3501
2726
  h2 = h2 + ((h2 << 1) + (h2 << 5) + (h2 << 9) + (h2 << 15) + (h2 << 24)) >>> 0;
3502
2727
  }
3503
2728
  const hex = (n) => n.toString(16).padStart(8, "0");
3504
- return `v1:${hex(h1)}${hex(h2)}`;
2729
+ return `v2:${hex(h1)}${hex(h2)}`;
3505
2730
  }
3506
2731
  //#endregion
3507
2732
  //#region src/types/mcp_app_modules.ts
@@ -3548,23 +2773,353 @@ var MCP_APP_MODULES = {
3548
2773
  ]
3549
2774
  };
3550
2775
  //#endregion
3551
- //#region src/controllers/data.ts
2776
+ //#region src/types/ui_preferences.ts
3552
2777
  /**
3553
- * Hops an {@link IncludeSpec} may nest. `comments.author` is two.
2778
+ * Every key a {@link UiTablePreferences} may hold, as data: what the server
2779
+ * validates a stored preference by.
3554
2780
  *
3555
- * @group Data
2781
+ * @group UI preferences
3556
2782
  */
3557
- var MAX_INCLUDE_DEPTH = 3;
3558
- /**
3559
- * SDK collection client — returns flat rows, no Entity wrapper.
3560
- *
3561
- * This is the public API surface for app developers using
3562
- * `createRebaseClient()`. admin internals use `CollectionAccessor` instead.
3563
- *
3564
- * Type parameters:
3565
- * - `M` — the **Row** shape returned by reads (`find`, `findById`, `listen`).
3566
- * - `I` — the **Insert** shape accepted by {@link create}. Defaults to
3567
- * `Partial<M>`; the generated SDK supplies a dedicated `Insert` type where
2783
+ var UI_PREFERENCE_TABLE_KEYS = [
2784
+ "alwaysApplyDefaultValues",
2785
+ "customViews",
2786
+ "defaultEntityAction",
2787
+ "defaultFilter",
2788
+ "defaultSelectedView",
2789
+ "defaultSize",
2790
+ "defaultViewMode",
2791
+ "disableDefaultActions",
2792
+ "display",
2793
+ "enabledViews",
2794
+ "entityActions",
2795
+ "entityViews",
2796
+ "exportable",
2797
+ "fieldOrder",
2798
+ "fields",
2799
+ "formAutoSave",
2800
+ "group",
2801
+ "hideFromEntityViews",
2802
+ "hideFromNavigation",
2803
+ "hideIdFromCollection",
2804
+ "hideIdFromForm",
2805
+ "icon",
2806
+ "includeJsonView",
2807
+ "inlineEditing",
2808
+ "kanban",
2809
+ "listFields",
2810
+ "localChangesBackup",
2811
+ "name",
2812
+ "openEntityMode",
2813
+ "pagination",
2814
+ "previewFields",
2815
+ "selectionEnabled",
2816
+ "sideDialogWidth",
2817
+ "singularName",
2818
+ "sort"
2819
+ ];
2820
+ /**
2821
+ * Every key a {@link UiFieldPreferences} may hold, as data.
2822
+ *
2823
+ * @group UI preferences
2824
+ */
2825
+ var UI_PREFERENCE_FIELD_KEYS = [
2826
+ "canAddElements",
2827
+ "clearable",
2828
+ "columnWidth",
2829
+ "conditions",
2830
+ "disabled",
2831
+ "enumLabels",
2832
+ "enumOrder",
2833
+ "expanded",
2834
+ "fieldOrder",
2835
+ "fields",
2836
+ "hidden",
2837
+ "hiddenInForm",
2838
+ "includeEntityLink",
2839
+ "includeId",
2840
+ "keyValue",
2841
+ "markdown",
2842
+ "minimalistView",
2843
+ "mode",
2844
+ "multiline",
2845
+ "name",
2846
+ "of",
2847
+ "previewAsTag",
2848
+ "previewFields",
2849
+ "readOnly",
2850
+ "referenceTo",
2851
+ "sortable",
2852
+ "span",
2853
+ "spreadChildren",
2854
+ "timezone",
2855
+ "urlPreview",
2856
+ "widget"
2857
+ ];
2858
+ var isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2859
+ var isStringList = (value) => Array.isArray(value) && value.every((item) => typeof item === "string");
2860
+ var expect = (ok, what) => (value, path, out) => {
2861
+ if (!ok(value)) out.push({
2862
+ path,
2863
+ message: `must be ${what}.`
2864
+ });
2865
+ };
2866
+ var oneOf = (...allowed) => expect((value) => allowed.some((a) => a === value), allowed.map((a) => JSON.stringify(a)).join(" | "));
2867
+ var boolean = /*#__PURE__*/ expect((value) => typeof value === "boolean", "a boolean");
2868
+ var string = /*#__PURE__*/ expect((value) => typeof value === "string", "a string");
2869
+ var stringList = /*#__PURE__*/ expect(isStringList, "a list of strings");
2870
+ var positiveNumber = /*#__PURE__*/ expect((value) => typeof value === "number" && Number.isFinite(value) && value > 0, "a positive number");
2871
+ function isJson(value, depth = 0) {
2872
+ if (depth > 32) return false;
2873
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
2874
+ if (typeof value === "number") return Number.isFinite(value);
2875
+ if (Array.isArray(value)) return value.every((item) => isJson(item, depth + 1));
2876
+ if (isRecord$1(value)) return Object.values(value).every((item) => isJson(item, depth + 1));
2877
+ return false;
2878
+ }
2879
+ var enumLabels = (value, path, out) => {
2880
+ if (!isRecord$1(value)) {
2881
+ out.push({
2882
+ path,
2883
+ message: "must map enum values to labels."
2884
+ });
2885
+ return;
2886
+ }
2887
+ for (const [key, label] of Object.entries(value)) {
2888
+ if (typeof label === "string") continue;
2889
+ if (!isRecord$1(label) || typeof label.label !== "string" || label.color !== void 0 && typeof label.color !== "string" || label.disabled !== void 0 && typeof label.disabled !== "boolean" || Object.keys(label).some((k) => k !== "label" && k !== "color" && k !== "disabled")) out.push({
2890
+ path: `${path}.${key}`,
2891
+ message: "must be a label, or `{ label, color?, disabled? }` with a chip colour key."
2892
+ });
2893
+ }
2894
+ };
2895
+ var fieldMap = (value, path, out) => {
2896
+ if (!isRecord$1(value)) {
2897
+ out.push({
2898
+ path,
2899
+ message: "must map field keys to field preferences."
2900
+ });
2901
+ return;
2902
+ }
2903
+ for (const [key, field] of Object.entries(value)) fieldProblems(field, `${path}.${key}`, out);
2904
+ };
2905
+ /**
2906
+ * The checks, built on first use: module-level calls would keep this file in
2907
+ * every bundle that imports `@rebasepro/types`, whether it validates a
2908
+ * preference or not.
2909
+ */
2910
+ var builtChecks;
2911
+ function checks() {
2912
+ builtChecks ??= {
2913
+ field: fieldChecks(),
2914
+ table: tableChecks()
2915
+ };
2916
+ return builtChecks;
2917
+ }
2918
+ var fieldChecks = () => ({
2919
+ name: string,
2920
+ hidden: boolean,
2921
+ hiddenInForm: boolean,
2922
+ disabled: boolean,
2923
+ readOnly: boolean,
2924
+ columnWidth: positiveNumber,
2925
+ span: oneOf(1, 2, 3, 4),
2926
+ multiline: boolean,
2927
+ markdown: boolean,
2928
+ previewAsTag: boolean,
2929
+ clearable: boolean,
2930
+ urlPreview: oneOf(true, false, "image", "video", "audio", "file"),
2931
+ mode: oneOf("date", "date_time"),
2932
+ timezone: string,
2933
+ enumLabels,
2934
+ enumOrder: expect((value) => Array.isArray(value) && value.every((item) => typeof item === "string" || typeof item === "number"), "a list of enum values"),
2935
+ expanded: boolean,
2936
+ minimalistView: boolean,
2937
+ sortable: boolean,
2938
+ canAddElements: boolean,
2939
+ spreadChildren: boolean,
2940
+ keyValue: boolean,
2941
+ previewFields: stringList,
2942
+ fieldOrder: stringList,
2943
+ widget: oneOf("select", "dialog"),
2944
+ includeId: boolean,
2945
+ includeEntityLink: boolean,
2946
+ referenceTo: string,
2947
+ conditions: expect((value) => isRecord$1(value) && isJson(value), "an object of JSON-logic rules"),
2948
+ fields: fieldMap,
2949
+ of: (value, path, out) => fieldProblems(value, path, out)
2950
+ });
2951
+ var tableChecks = () => ({
2952
+ name: string,
2953
+ singularName: string,
2954
+ icon: string,
2955
+ group: string,
2956
+ hideFromNavigation: boolean,
2957
+ hideFromEntityViews: boolean,
2958
+ defaultViewMode: string,
2959
+ enabledViews: stringList,
2960
+ defaultSize: oneOf("xs", "s", "m", "l", "xl"),
2961
+ kanban: expect((value) => isRecord$1(value) && typeof value.columnField === "string" && (value.orderField === void 0 || typeof value.orderField === "string") && Object.keys(value).every((k) => k === "columnField" || k === "orderField"), "`{ columnField, orderField? }`"),
2962
+ fieldOrder: stringList,
2963
+ listFields: stringList,
2964
+ previewFields: stringList,
2965
+ display: expect((value) => isRecord$1(value) && Object.entries(value).every(([slot, field]) => [
2966
+ "title",
2967
+ "subtitle",
2968
+ "image",
2969
+ "status",
2970
+ "date",
2971
+ "tags"
2972
+ ].includes(slot) && typeof field === "string"), "an object naming a field for each of title, subtitle, image, status, date, tags"),
2973
+ hideIdFromCollection: boolean,
2974
+ sort: expect((value) => isSortTuple(value) || Array.isArray(value) && value.length > 0 && value.every(isSortTuple), "`[field, \"asc\" | \"desc\"]` or a list of them"),
2975
+ defaultFilter: expect((value) => isRecord$1(value) && Object.values(value).every((condition) => isCondition(condition) || Array.isArray(condition) && condition.length > 0 && condition.every(isCondition)), "an object of `[operator, value]` conditions by field"),
2976
+ pagination: expect((value) => typeof value === "boolean" || typeof value === "number" && Number.isInteger(value) && value > 0, "a boolean or a page size"),
2977
+ inlineEditing: boolean,
2978
+ selectionEnabled: boolean,
2979
+ exportable: boolean,
2980
+ openEntityMode: oneOf("side_panel", "full_screen", "split", "dialog"),
2981
+ defaultEntityAction: oneOf("view", "edit"),
2982
+ sideDialogWidth: expect((value) => typeof value === "string" || typeof value === "number" && value > 0, "a width"),
2983
+ defaultSelectedView: string,
2984
+ formAutoSave: boolean,
2985
+ alwaysApplyDefaultValues: boolean,
2986
+ includeJsonView: boolean,
2987
+ localChangesBackup: oneOf("manual_apply", "auto_apply", false),
2988
+ hideIdFromForm: boolean,
2989
+ entityActions: stringList,
2990
+ disableDefaultActions: expect((value) => Array.isArray(value) && value.every((item) => item === "edit" || item === "copy" || item === "delete"), "a list of \"edit\" | \"copy\" | \"delete\""),
2991
+ entityViews: stringList,
2992
+ customViews: stringList,
2993
+ fields: fieldMap
2994
+ });
2995
+ var FILTER_OPS = [
2996
+ "<",
2997
+ "<=",
2998
+ "==",
2999
+ "!=",
3000
+ ">=",
3001
+ ">",
3002
+ "array-contains",
3003
+ "in",
3004
+ "not-in",
3005
+ "array-contains-any",
3006
+ "array-contains-all",
3007
+ "array-contained-by",
3008
+ "like",
3009
+ "ilike",
3010
+ "not-like",
3011
+ "not-ilike",
3012
+ "is-null",
3013
+ "is-not-null"
3014
+ ];
3015
+ var isSortTuple = (value) => Array.isArray(value) && (value.length === 2 || value.length === 3) && typeof value[0] === "string" && (value[1] === "asc" || value[1] === "desc") && (value.length === 2 || value[2] === "first" || value[2] === "last");
3016
+ var isCondition = (value) => Array.isArray(value) && value.length === 2 && typeof value[0] === "string" && FILTER_OPS.includes(value[0]) && isJson(value[1]);
3017
+ var isFieldKey = (key) => UI_PREFERENCE_FIELD_KEYS.includes(key);
3018
+ var isTableKey = (key) => UI_PREFERENCE_TABLE_KEYS.includes(key);
3019
+ function fieldProblems(value, path, out) {
3020
+ if (!isRecord$1(value)) {
3021
+ out.push({
3022
+ path,
3023
+ message: "must be an object of field preferences."
3024
+ });
3025
+ return;
3026
+ }
3027
+ for (const [key, entry] of Object.entries(value)) {
3028
+ if (!isFieldKey(key)) {
3029
+ out.push({
3030
+ path: `${path}.${key}`,
3031
+ message: `is not a field preference. A field preference is one of ${UI_PREFERENCE_FIELD_KEYS.join(", ")}; schema facts (type, validation, enum values, description) are schema edits, and components are written in code.`
3032
+ });
3033
+ continue;
3034
+ }
3035
+ if (entry === void 0) continue;
3036
+ checks().field[key](entry, `${path}.${key}`, out);
3037
+ }
3038
+ }
3039
+ /**
3040
+ * Every problem with a table's preference delta as it arrived: a key that is
3041
+ * not a preference (a schema fact, a component, a misspelling) or a value of
3042
+ * the wrong shape. Empty when it may be stored.
3043
+ *
3044
+ * @group UI preferences
3045
+ */
3046
+ function uiTablePreferencesProblems(value) {
3047
+ const out = [];
3048
+ if (!isRecord$1(value)) return [{
3049
+ path: "",
3050
+ message: "must be an object of table preferences."
3051
+ }];
3052
+ for (const [key, entry] of Object.entries(value)) {
3053
+ if (!isTableKey(key)) {
3054
+ out.push({
3055
+ path: key,
3056
+ message: `is not a table preference. A table preference is one of ${UI_PREFERENCE_TABLE_KEYS.join(", ")}; schema facts (columns, rules, description, history) are schema edits, and code (actions, components, callbacks) is written in code.`
3057
+ });
3058
+ continue;
3059
+ }
3060
+ if (entry === void 0) continue;
3061
+ checks().table[key](entry, key, out);
3062
+ }
3063
+ return out;
3064
+ }
3065
+ /**
3066
+ * Whether a value is a well-formed {@link UiTablePreferences} delta.
3067
+ *
3068
+ * @group UI preferences
3069
+ */
3070
+ function isUiTablePreferences(value) {
3071
+ return uiTablePreferencesProblems(value).length === 0;
3072
+ }
3073
+ /**
3074
+ * One delta over another: what `over` names replaces what `base` says, key by
3075
+ * key, and `fields` (and a field's nested `fields` / `of`) field by field.
3076
+ *
3077
+ * @group UI preferences
3078
+ */
3079
+ function mergeUiTablePreferences(base, over) {
3080
+ const out = {
3081
+ ...base,
3082
+ ...over
3083
+ };
3084
+ if (base.fields || over.fields) out.fields = mergeFieldMaps(base.fields, over.fields);
3085
+ return out;
3086
+ }
3087
+ function mergeFieldMaps(base, over) {
3088
+ const out = { ...base };
3089
+ for (const [key, field] of Object.entries(over ?? {})) out[key] = out[key] ? mergeField(out[key], field) : field;
3090
+ return out;
3091
+ }
3092
+ function mergeField(base, over) {
3093
+ const out = {
3094
+ ...base,
3095
+ ...over
3096
+ };
3097
+ if (base.fields || over.fields) out.fields = mergeFieldMaps(base.fields, over.fields);
3098
+ if (base.of && over.of) out.of = mergeField(base.of, over.of);
3099
+ if (base.enumLabels && over.enumLabels) out.enumLabels = {
3100
+ ...base.enumLabels,
3101
+ ...over.enumLabels
3102
+ };
3103
+ return out;
3104
+ }
3105
+ //#endregion
3106
+ //#region src/controllers/data.ts
3107
+ /**
3108
+ * Hops an {@link IncludeSpec} may nest. `comments.author` is two.
3109
+ *
3110
+ * @group Data
3111
+ */
3112
+ var MAX_INCLUDE_DEPTH = 3;
3113
+ /**
3114
+ * SDK table client — returns flat rows, no Entity wrapper.
3115
+ *
3116
+ * This is the public API surface for app developers using
3117
+ * `createRebaseClient()`.
3118
+ *
3119
+ * Type parameters:
3120
+ * - `M` — the **Row** shape returned by reads (`find`, `findById`, `listen`).
3121
+ * - `I` — the **Insert** shape accepted by {@link create}. Defaults to
3122
+ * `Partial<M>`; the generated SDK supplies a dedicated `Insert` type where
3568
3123
  * required columns are required and auto-generated / read-only columns are
3569
3124
  * omitted, so `create({})` on a table with required fields is a compile error.
3570
3125
  * - `U` — the **Update** shape accepted by {@link update}. Defaults to
@@ -3630,7 +3185,7 @@ var BATCH_REF_KEY = "$ref";
3630
3185
  *
3631
3186
  * Except on a `map` (pass `propertyType`): a map's value is a JSON document,
3632
3187
  * and one may legitimately carry `$` keys — a JSON Schema's `$schema`, a
3633
- * MongoDB-style export. There, only a single-key object whose key is one of
3188
+ * document exported from another database. There, only a single-key object whose key is one of
3634
3189
  * {@link FIELD_OPERATORS} is an operation, and anything else is data. A caller
3635
3190
  * that does not know the property type gets the strict reading.
3636
3191
  *
@@ -4137,6 +3692,1867 @@ function toDriverAggregateGroup(group) {
4137
3692
  };
4138
3693
  }
4139
3694
  //#endregion
4140
- export { ADMIN_COLLECTION_KEYS, ADMIN_PROPERTY_KEYS, ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, EntityReference, EntityRelation, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, GeoPoint, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JUNCTION_PIVOT_KEY, KEY_MANAGEMENT_SCOPES, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, MONGODB_CAPABILITIES, NULL_OPS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RUNTIME_ONLY_COLLECTION_KEYS, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, Vector, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, applyCollectionPatch, bucket, buildResourceGraph, canonicalSchemaPayload, collectionPatchProblems, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, describeScope, deserializeCollections, diffCollections, diffJsonValues, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getCollectionDataPath, getDataSourceCapabilities, getDeclaredSubcollections, hasAdminRole, hasFieldOperation, hasForeignKeyOnTarget, holdsAdminRole, intersectScopes, isAdminScope, isAnonymousUid, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isCollectionPatch, isContentHashedFileName, isDataPlaneScope, isDocumentAdmin, isFieldOperation, isFirebaseCollectionConfig, isLazyComponentRef, isManyToMany, isMongoDBCollectionConfig, isPercentileFraction, isPostgresCollectionConfig, isPublicStorageKey, isPublicStoragePath, isRelationAggregateSort, isRelationalCollectionConfig, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSerializedCollectionRef, isStorageReference, isTenantClaimSource, isTenantMembershipSource, isTimeZoneName, isToMany, isUnsupported, isValidAppHost, isValidEngine, joinConditions, knownScopes, nestAdminCollectionKeys, nestAdminKeysOf, nestAdminPropertyKeys, nestCollectionPatchPaths, parseAppAddress, parseCaseFoldedFieldPath, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, policy, queue, registerDataSourceCapabilities, registerResourceKind, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, runtimeOnlyKeyIn, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, serializeCollections, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, toCanonicalOp, toCollectionJson, toDriverAggregate, toDriverAggregateGroup, topic, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
3695
+ //#region src/schema/column_type.ts
3696
+ var TEXT_KINDS = [
3697
+ "text",
3698
+ "varchar",
3699
+ "char"
3700
+ ];
3701
+ var NUMERIC_KINDS = [
3702
+ "smallint",
3703
+ "integer",
3704
+ "bigint",
3705
+ "smallserial",
3706
+ "serial",
3707
+ "bigserial",
3708
+ "real",
3709
+ "doublePrecision",
3710
+ "numeric"
3711
+ ];
3712
+ var TEMPORAL_KINDS = [
3713
+ "timestamptz",
3714
+ "date",
3715
+ "time"
3716
+ ];
3717
+ /**
3718
+ * Whether a column type is stored as text (`text`, `varchar`, `char`).
3719
+ *
3720
+ * @group Schema
3721
+ */
3722
+ function isTextColumnType(type) {
3723
+ return TEXT_KINDS.includes(type.kind);
3724
+ }
3725
+ /**
3726
+ * Whether a column type is read and written as a JavaScript `number`.
3727
+ *
3728
+ * @group Schema
3729
+ */
3730
+ function isNumericColumnType(type) {
3731
+ return NUMERIC_KINDS.includes(type.kind);
3732
+ }
3733
+ /**
3734
+ * Whether a column type holds an instant, a day or a time of day.
3735
+ *
3736
+ * @group Schema
3737
+ */
3738
+ function isTemporalColumnType(type) {
3739
+ return TEMPORAL_KINDS.includes(type.kind);
3740
+ }
3741
+ /**
3742
+ * Whether a column type is a JSON document (`json`, `jsonb`).
3743
+ *
3744
+ * @group Schema
3745
+ */
3746
+ function isJsonColumnType(type) {
3747
+ return type.kind === "json" || type.kind === "jsonb";
3748
+ }
3749
+ /**
3750
+ * The SQL spelling of a column type, for messages and generated comments.
3751
+ *
3752
+ * Not the DDL renderer: an enum prints as `enum(a, b)` because its type name
3753
+ * belongs to the table it is planned in.
3754
+ *
3755
+ * @group Schema
3756
+ */
3757
+ function columnTypeLabel(type) {
3758
+ switch (type.kind) {
3759
+ case "varchar": return `varchar(${type.length})`;
3760
+ case "char": return `char(${type.length})`;
3761
+ case "enum": return type.name ?? `enum(${type.values.join(", ")})`;
3762
+ case "doublePrecision": return "double precision";
3763
+ case "numeric":
3764
+ if (type.precision === void 0) return "numeric";
3765
+ return type.scale === void 0 ? `numeric(${type.precision})` : `numeric(${type.precision}, ${type.scale})`;
3766
+ case "vector": return `vector(${type.dimensions})`;
3767
+ case "array": return `${columnTypeLabel(type.of)}[]`;
3768
+ case "other": return type.sqlType;
3769
+ default: return type.kind;
3770
+ }
3771
+ }
3772
+ //#endregion
3773
+ //#region src/schema/column_options.ts
3774
+ /**
3775
+ * Per-role access in its stored form, checked: `read` and `write` must each be
3776
+ * a list of non-empty role names, and nothing else may be given.
3777
+ *
3778
+ * Checked at runtime because a JavaScript caller writing
3779
+ * `.access({ read: "admin" })` would otherwise have the string spread into
3780
+ * one role per character, silently.
3781
+ *
3782
+ * @param where What is being configured, for the error: `column "title"`.
3783
+ *
3784
+ * @group Schema
3785
+ */
3786
+ function normalizeColumnAccess(access, where) {
3787
+ const expected = "Write `{ read?: [\"role\", …], write?: [\"role\", …] }`.";
3788
+ if (typeof access !== "object" || access === null || Array.isArray(access)) throw new Error(`The access of ${where} must be an object of role lists, got ${JSON.stringify(access)}. ${expected}`);
3789
+ const stored = {};
3790
+ for (const [key, value] of Object.entries(access)) {
3791
+ if (key !== "read" && key !== "write") throw new Error(`The access of ${where} has an unknown key "${key}". ${expected}`);
3792
+ if (value === void 0) continue;
3793
+ if (!Array.isArray(value) || value.some((role) => typeof role !== "string" || role.length === 0)) throw new Error(`\`access.${key}\` of ${where} must be a list of role names, got ${JSON.stringify(value)}. ${expected}`);
3794
+ stored[key] = value.filter((role) => typeof role === "string");
3795
+ }
3796
+ return stored;
3797
+ }
3798
+ var isoOf = (value) => value instanceof Date ? value.toISOString() : value;
3799
+ /**
3800
+ * Validation rules in their stored form: a `RegExp` becomes its source and
3801
+ * flags, a `Date` bound becomes an ISO string. What a builder keeps is then
3802
+ * exactly what the wire carries.
3803
+ *
3804
+ * @group Schema
3805
+ */
3806
+ function normalizeValidation(rules) {
3807
+ const out = {};
3808
+ for (const [key, value] of Object.entries(rules)) {
3809
+ if (value === void 0) continue;
3810
+ if (key === "matches" && value instanceof RegExp) {
3811
+ out.matches = value.source;
3812
+ if (value.flags) out.matchesFlags = value.flags;
3813
+ continue;
3814
+ }
3815
+ if ((key === "min" || key === "max") && value instanceof Date) {
3816
+ out[key] = isoOf(value);
3817
+ continue;
3818
+ }
3819
+ Object.assign(out, { [key]: Array.isArray(value) ? [...value] : value });
3820
+ }
3821
+ return out;
3822
+ }
3823
+ var BYTE_UNITS = {
3824
+ b: 1,
3825
+ kb: 1024,
3826
+ mb: 1024 ** 2,
3827
+ gb: 1024 ** 3,
3828
+ tb: 1024 ** 4
3829
+ };
3830
+ /**
3831
+ * A size in bytes, from a number or from `"10MB"` / `"512 kb"` / `"1.5GB"`.
3832
+ *
3833
+ * Binary multiples (1 MB = 1,048,576 bytes), the unit a storage limit is
3834
+ * enforced in. Throws on anything else: a limit that silently parsed to `NaN`
3835
+ * is a limit that is never applied.
3836
+ *
3837
+ * @group Schema
3838
+ */
3839
+ function parseByteSize(size) {
3840
+ if (typeof size === "number") {
3841
+ if (!Number.isFinite(size) || size < 0) throw new Error(`A byte size must be a non-negative number, got ${size}.`);
3842
+ return size;
3843
+ }
3844
+ const match = /^\s*(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?\s*$/i.exec(size);
3845
+ if (!match) throw new Error(`Cannot read "${size}" as a byte size. Write a number of bytes, or a size such as "10MB".`);
3846
+ const unit = (match[2] ?? "b").toLowerCase();
3847
+ return Math.round(Number(match[1]) * BYTE_UNITS[unit]);
3848
+ }
3849
+ /**
3850
+ * Storage options in their stored form.
3851
+ *
3852
+ * @group Schema
3853
+ */
3854
+ function normalizeStorage(options) {
3855
+ if (typeof options.path !== "string" || options.path.length === 0) throw new Error("A storage column needs a `path`: where its files go, e.g. `col.storage({ path: \"posts/heroes/\" })`.");
3856
+ const out = { path: options.path };
3857
+ if (options.source !== void 0) out.source = resourceKeyOf(options.source);
3858
+ if (options.accept !== void 0) out.accept = [...options.accept];
3859
+ if (options.maxBytes !== void 0) out.maxBytes = parseByteSize(options.maxBytes);
3860
+ if (options.imageResize !== void 0) out.imageResize = { ...options.imageResize };
3861
+ if (options.public !== void 0) out.public = options.public;
3862
+ if (options.fileName !== void 0) out.fileName = options.fileName;
3863
+ if (options.metadata !== void 0) out.metadata = { ...options.metadata };
3864
+ if (options.includeBucketUrl !== void 0) out.includeBucketUrl = options.includeBucketUrl;
3865
+ if (options.storeUrl !== void 0) out.storeUrl = options.storeUrl;
3866
+ return out;
3867
+ }
3868
+ //#endregion
3869
+ //#region src/schema/json.ts
3870
+ /** The brand every JSON field builder carries, so one built by another copy of this package is still recognised. */
3871
+ var JSON_FIELD_BRAND = "rebase.json-field";
3872
+ /**
3873
+ * One field of a JSON document: `json.string()`, `json.object({...})`, ….
3874
+ *
3875
+ * Immutable: every modifier returns a new field.
3876
+ *
3877
+ * @group Schema
3878
+ */
3879
+ var JsonField = class JsonField {
3880
+ shape;
3881
+ brand = JSON_FIELD_BRAND;
3882
+ constructor(shape) {
3883
+ this.shape = shape;
3884
+ }
3885
+ with(patch) {
3886
+ return new JsonField(Object.assign({}, this.shape, patch));
3887
+ }
3888
+ /** The key must be present in the document. */
3889
+ required() {
3890
+ return this.with({ required: true });
3891
+ }
3892
+ /** The value written when the key is absent on create. */
3893
+ default(value) {
3894
+ return this.with({ default: value });
3895
+ }
3896
+ /** What the value is, for OpenAPI and MCP. */
3897
+ describe(description) {
3898
+ return this.with({ description });
3899
+ }
3900
+ /** Rules the API checks before a write. */
3901
+ validate(rules) {
3902
+ const input = rules;
3903
+ return this.with({ validate: normalizeValidation(input) });
3904
+ }
3905
+ /** A closed set of accepted values. */
3906
+ oneOf(values) {
3907
+ return this.with({ oneOf: [...values] });
3908
+ }
3909
+ /** The server writes the current time into the field when the row is created. */
3910
+ onCreateNow() {
3911
+ return this.with({ stamp: "create" });
3912
+ }
3913
+ /** The server writes the current time into the field on every write. */
3914
+ onUpdateNow() {
3915
+ return this.with({ stamp: "update" });
3916
+ }
3917
+ /** The server writes the caller's user id into the field when the row is created. */
3918
+ onCreateUser() {
3919
+ return this.with({ stamp: "createUser" });
3920
+ }
3921
+ /** The server writes the caller's user id into the field on every write. */
3922
+ onUpdateUser() {
3923
+ return this.with({ stamp: "updateUser" });
3924
+ }
3925
+ /**
3926
+ * The field holds the id of a user. The panel offers a user picker for it,
3927
+ * and callers who may write the table may look users up to fill it.
3928
+ * Only on `json.string()`; anything else throws.
3929
+ */
3930
+ userId() {
3931
+ if (this.shape.kind !== "string" || this.shape.storage !== void 0) {
3932
+ const what = this.shape.kind === "string" ? "`json.storage()`" : `a \`json.${this.shape.kind}()\` field`;
3933
+ throw new Error(`\`.userId()\` on ${what}: a user's id is held by \`json.string()\`.`);
3934
+ }
3935
+ return this.with({ semantic: "user" });
3936
+ }
3937
+ /**
3938
+ * Field-level hooks. They run on the server only.
3939
+ *
3940
+ * The value is `TData | undefined` on a field not (yet) marked
3941
+ * `.required()` — the key can be absent from the document — and `TData` on
3942
+ * one that is; see {@link JsonTransformValue}. Chain `.required()` before
3943
+ * `.transform()` to get the narrower type.
3944
+ */
3945
+ transform(transform) {
3946
+ const erased = transform;
3947
+ return this.with({ transform: erased });
3948
+ }
3949
+ };
3950
+ var shapesOf = (fields) => {
3951
+ const out = {};
3952
+ for (const [key, field] of Object.entries(fields)) out[key] = field.shape;
3953
+ return out;
3954
+ };
3955
+ /**
3956
+ * Builders for the shape of a `json`/`jsonb` document.
3957
+ *
3958
+ * ```ts
3959
+ * metadata: col.jsonb(json.object({
3960
+ * seoTitle: json.string().validate({ max: 60 }),
3961
+ * canonicalUrl: json.string().validate({ url: true }),
3962
+ * })),
3963
+ * content: col.jsonb(json.array(json.oneOf({
3964
+ * text: json.string(),
3965
+ * image: json.storage({ path: "posts/content/" }),
3966
+ * }))),
3967
+ * ```
3968
+ *
3969
+ * `col.jsonb().$type<T>()` on its own types the document statically; a shape also
3970
+ * tells the server what is inside it.
3971
+ *
3972
+ * @group Schema
3973
+ */
3974
+ var json = {
3975
+ /** A string. */
3976
+ string() {
3977
+ return new JsonField({ kind: "string" });
3978
+ },
3979
+ /** A number. */
3980
+ number() {
3981
+ return new JsonField({ kind: "number" });
3982
+ },
3983
+ /** A boolean. */
3984
+ boolean() {
3985
+ return new JsonField({ kind: "boolean" });
3986
+ },
3987
+ /** An instant, stored as an ISO string. */
3988
+ date() {
3989
+ return new JsonField({ kind: "date" });
3990
+ },
3991
+ /** A point on Earth: `{ latitude, longitude }`. */
3992
+ geopoint() {
3993
+ return new JsonField({ kind: "geopoint" });
3994
+ },
3995
+ /** The path of a stored file. Counted by the orphan sweep like a `col.storage()` column. */
3996
+ storage(options) {
3997
+ return new JsonField({
3998
+ kind: "string",
3999
+ storage: normalizeStorage(options)
4000
+ });
4001
+ },
4002
+ /** An object with known keys. `additional: true` also accepts keys it does not name. */
4003
+ object(fields, options = {}) {
4004
+ const shape = {
4005
+ kind: "object",
4006
+ fields: shapesOf(fields)
4007
+ };
4008
+ if (options.additional) shape.additional = true;
4009
+ return new JsonField(shape);
4010
+ },
4011
+ /** An array of one shape. */
4012
+ array(of) {
4013
+ return new JsonField({
4014
+ kind: "array",
4015
+ of: of.shape
4016
+ });
4017
+ },
4018
+ /**
4019
+ * A typed block: `{ type: "<variant>", value: <its shape> }`. The keys are
4020
+ * `type` and `value` unless `typeField` / `valueField` say otherwise.
4021
+ */
4022
+ oneOf(variants, options = {}) {
4023
+ return new JsonField({
4024
+ kind: "oneOf",
4025
+ typeField: options.typeField ?? "type",
4026
+ valueField: options.valueField ?? "value",
4027
+ variants: shapesOf(variants)
4028
+ });
4029
+ },
4030
+ /** Anything. */
4031
+ unknown() {
4032
+ return new JsonField({ kind: "unknown" });
4033
+ }
4034
+ };
4035
+ /**
4036
+ * Whether a value is a JSON field builder, from this copy of the package or
4037
+ * another.
4038
+ *
4039
+ * @group Schema
4040
+ */
4041
+ function isJsonField(value) {
4042
+ return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.json-field";
4043
+ }
4044
+ /**
4045
+ * A JSON shape without its hooks: what the wire carries.
4046
+ *
4047
+ * @group Schema
4048
+ */
4049
+ function describeJsonShape(shape) {
4050
+ const { transform: _transform, ...rest } = shape;
4051
+ switch (rest.kind) {
4052
+ case "object": {
4053
+ const fields = {};
4054
+ for (const [key, field] of Object.entries(rest.fields)) fields[key] = describeJsonShape(field);
4055
+ return {
4056
+ ...rest,
4057
+ fields
4058
+ };
4059
+ }
4060
+ case "array": return {
4061
+ ...rest,
4062
+ of: describeJsonShape(rest.of)
4063
+ };
4064
+ case "oneOf": {
4065
+ const variants = {};
4066
+ for (const [key, variant] of Object.entries(rest.variants)) variants[key] = describeJsonShape(variant);
4067
+ return {
4068
+ ...rest,
4069
+ variants
4070
+ };
4071
+ }
4072
+ default: return rest;
4073
+ }
4074
+ }
4075
+ //#endregion
4076
+ //#region src/schema/columns.ts
4077
+ /**
4078
+ * Every Drizzle spelling Rebase refuses, with the instruction it shows.
4079
+ *
4080
+ * Each text is used twice: as a string-literal *type* placed where the
4081
+ * developer wrote the refused thing (a `this` parameter, a config key, an
4082
+ * argument), so TypeScript prints the instruction verbatim; and as the message
4083
+ * thrown at run time, for a JavaScript caller the types do not reach. See
4084
+ * `drizzle-alignment.md` for the table of Drizzle spellings.
4085
+ *
4086
+ * @group Schema
4087
+ */
4088
+ var DRIZZLE_REFUSALS = {
4089
+ /** `col.timestamp()` without `withTimezone: true`: Drizzle's timestamp WITHOUT time zone. */
4090
+ timestamp: "Rebase stores instants as timestamptz: write `col.timestamp({ withTimezone: true })`. For a timestamp without time zone write `col.custom({ dataType: \"timestamp\" })`.",
4091
+ /** `col.timestamp({ mode: "date" })`: Drizzle's Date-typed mode. */
4092
+ timestampMode: "Rebase serves a timestamp as an ISO string: leave `mode` out or write `mode: \"string\"`.",
4093
+ /** `col.timestamp({ precision })`. */
4094
+ timestampPrecision: "Rebase does not state a timestamp's precision: leave `precision` out, or write `col.custom({ dataType: \"timestamp(3) with time zone\" })`.",
4095
+ /** `col.date({ mode: "date" })`: Drizzle's Date-typed mode. */
4096
+ dateMode: "Rebase serves a date as a `YYYY-MM-DD` string: leave `mode` out or write `mode: \"string\"`.",
4097
+ /** `col.time({ withTimezone: true })`: a `timetz`. */
4098
+ timeZone: "`col.time()` is a time without time zone: leave `withTimezone` out, or write `col.custom({ dataType: \"timetz\" })`.",
4099
+ /** `col.time({ precision })`. */
4100
+ timePrecision: "Rebase does not state a time's precision: leave `precision` out, or write `col.custom({ dataType: \"time(3)\" })`.",
4101
+ /** `col.numeric({ mode: "string" | "bigint" })`: our value is a JSON number. */
4102
+ numericMode: "Rebase reads and writes numeric as a JSON number: leave `mode` out or write `mode: \"number\"`. For exact decimals kept as text write `col.text()`.",
4103
+ /** `col.bigint({ mode: "bigint" })`: our value is a JSON number. */
4104
+ bigintMode: "Rebase serves bigint as a JSON number: write `{ mode: \"number\" }`. For exact 64-bit values write `col.numeric()` or `col.text()`.",
4105
+ /** `col.varchar("name")` / `col.varchar({ enum })` without a length. */
4106
+ varcharLength: "`col.varchar()` needs a length (a bare varchar is unbounded in Postgres and Drizzle): write `col.varchar({ length: 255 })`, or `col.text()` for text of any length.",
4107
+ /** `col.char("name")` / `col.char({ enum })` without a length. */
4108
+ charLength: "`col.char()` needs a length (a bare char is char(1) in Postgres and Drizzle): write `col.char({ length: 2 })`.",
4109
+ /** `.generatedAlwaysAsIdentity()`: the planner creates BY DEFAULT identities only. */
4110
+ identityAlways: "Rebase creates identity columns GENERATED BY DEFAULT: write `.generatedByDefaultAsIdentity()`.",
4111
+ /** `.generatedByDefaultAsIdentity({ … })`: sequence options. */
4112
+ identityOptions: "Rebase does not take sequence options: write `.generatedByDefaultAsIdentity()` with no argument.",
4113
+ /** `.references(() => …)`: a foreign key is a `rel.belongsTo`. */
4114
+ references: "A foreign key is a relation in Rebase: write `relations: { author: rel.belongsTo(() => users, { localKey: \"author_id\", onDelete: \"cascade\" }) }`. The relation's key is what `include` names.",
4115
+ /** `.$defaultFn()` / `.$default()`: a run-time default function. */
4116
+ defaultFn: "Rebase's schema is data, not code: a default is `.default(value)` or `.default(sql`…`)`; the time is `.defaultNow()` or `.onCreateNow()`, the caller `.onCreateUser()`; anything else belongs in `hooks.beforeSave`.",
4117
+ /** `.$onUpdate()` / `.$onUpdateFn()`: a run-time update function. */
4118
+ onUpdateFn: "Rebase's schema is data, not code: write `.onUpdateNow()` for the time, `.onUpdateUser()` for the caller; anything else belongs in `hooks.beforeSave`.",
4119
+ /** `.unique(name, { nulls })`: a named or NULLS NOT DISTINCT constraint. */
4120
+ uniqueName: "Rebase derives constraint names and keeps NULLs distinct: write `.unique()`, or a unique index under `indexes`.",
4121
+ /** `.generatedAlwaysAs(value)` with something other than a `sql` expression. */
4122
+ generatedValue: "`.generatedAlwaysAs()` takes a SQL expression: write `.generatedAlwaysAs(sql`…`)`.",
4123
+ /** `.array(size)`. */
4124
+ arraySize: "Postgres ignores array sizes: write `.array()`.",
4125
+ /** `.notNull()` & co. before `.array()`. */
4126
+ arrayOrder: "`.notNull()`, a default, `.primaryKey()`, `.readOnly()` and `.private()` before `.array()` would describe each item: write them after it, as in `col.text().array().notNull()`.",
4127
+ /** `.array().array()`. */
4128
+ arrayOfArray: "An array of arrays is not supported: use `col.jsonb()` for nested lists.",
4129
+ /** `sql` with an interpolation. */
4130
+ sqlInterpolation: "`sql` writes its text into the DDL verbatim: write the expression inline, without `${…}`.",
4131
+ /** `col.bigint()` / `col.bigserial()` without `{ mode }`. */
4132
+ bigintModeMissing: "`col.bigint()` and `col.bigserial()` take Drizzle's `{ mode: \"number\" }`: write `col.bigint({ mode: \"number\" })`.",
4133
+ /** `col.numeric(10, 2)`: positional precision and scale. */
4134
+ numericPositional: "`col.numeric()` takes a config object: write `col.numeric({ precision: 10, scale: 2 })`.",
4135
+ /** `col.vector(1536)`: positional dimensions. */
4136
+ vectorPositional: "`col.vector()` takes a config object: write `col.vector({ dimensions: 1536 })`.",
4137
+ /** `col.enum(values, { name })`: a named enum type. */
4138
+ enumName: "A named Postgres enum type is declared once with `pgEnum`: write `const postStatus = pgEnum(\"post_status\", [...])`, then `postStatus()` in the column.",
4139
+ /** `col.custom("inet")`: a lone string is the SQL column name. */
4140
+ customDataType: "`col.custom()` names its Postgres type in a config object: write `col.custom({ dataType: \"inet\" })`, or `col.custom(\"ip\", { dataType: \"inet\" })` with a SQL column name.",
4141
+ /** `pgEnum(name, { A: "a" })`: Drizzle's object form. */
4142
+ pgEnumObject: "`pgEnum(name, values)` takes the list of labels: write `pgEnum(\"post_status\", [\"draft\", \"published\"])`."
4143
+ };
4144
+ function unsupportedMessage(type) {
4145
+ return `Rebase has no \`col.${type}()\`: write \`col.custom({ dataType: "${type}" })\`. The value passes through as the driver returns it (a string).`;
4146
+ }
4147
+ /** The brand of a {@link sql} expression. */
4148
+ var SQL_BRAND = "rebase.sql";
4149
+ /**
4150
+ * A SQL expression for a default or a generated column, as Drizzle writes it:
4151
+ * `.default(sql\`gen_short_id()\`)`, `.generatedAlwaysAs(sql\`lower(email)\`)`.
4152
+ *
4153
+ * The text goes into the DDL verbatim, so it takes no interpolation: write the
4154
+ * expression inline.
4155
+ *
4156
+ * @group Schema
4157
+ */
4158
+ function sql(strings, ...values) {
4159
+ if (values.length > 0 || strings.length !== 1) throw new Error(DRIZZLE_REFUSALS.sqlInterpolation);
4160
+ const text = strings[0] ?? strings.raw[0];
4161
+ if (text.trim().length === 0) throw new Error("`sql``` is empty: write the expression, e.g. sql`now()`.");
4162
+ return {
4163
+ brand: SQL_BRAND,
4164
+ text
4165
+ };
4166
+ }
4167
+ /**
4168
+ * Whether a value is a {@link sql} expression, from this copy of the package or another.
4169
+ *
4170
+ * @group Schema
4171
+ */
4172
+ function isSqlTemplate(value) {
4173
+ return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.sql" && "text" in value && typeof value.text === "string";
4174
+ }
4175
+ var STAMP_METHODS = {
4176
+ "create:now": ".onCreateNow",
4177
+ "update:now": ".onUpdateNow",
4178
+ "create:user": ".onCreateUser",
4179
+ "update:user": ".onUpdateUser"
4180
+ };
4181
+ /** The brand every column builder carries, so one built by another copy of this package is still recognised. */
4182
+ var COLUMN_BRAND = "rebase.column";
4183
+ var baseDef = (type) => ({
4184
+ type,
4185
+ notNull: false,
4186
+ primaryKey: false,
4187
+ unique: false,
4188
+ readOnly: false,
4189
+ private: false
4190
+ });
4191
+ /**
4192
+ * One column of a table: `col.text()`, `col.uuid().primaryKey()`, ….
4193
+ *
4194
+ * Immutable — every modifier returns a new builder — so a column can be shared
4195
+ * between tables. Columns are nullable until `.notNull()` or `.primaryKey()`
4196
+ * says otherwise, as in SQL.
4197
+ *
4198
+ * @typeParam TData The TypeScript type of a value on the wire.
4199
+ * @typeParam TKind Which builder made it; decides which modifiers apply.
4200
+ * @typeParam F What has been said about it so far.
4201
+ *
4202
+ * @group Schema
4203
+ */
4204
+ var ColumnBuilder = class ColumnBuilder {
4205
+ def;
4206
+ brand = COLUMN_BRAND;
4207
+ constructor(def) {
4208
+ this.def = def;
4209
+ }
4210
+ with(patch) {
4211
+ return new ColumnBuilder({
4212
+ ...this.def,
4213
+ ...patch
4214
+ });
4215
+ }
4216
+ /**
4217
+ * The patch that sets a stamp, refusing a second, different one: a column
4218
+ * holds one stamp, so `.onCreateNow().onUpdateNow()` would otherwise keep
4219
+ * whichever came last without a word.
4220
+ */
4221
+ stamped(stamp, method) {
4222
+ const current = this.def.stamp;
4223
+ if (current && (current.on !== stamp.on || current.value !== stamp.value)) throw new Error(`\`.${method}()\` on a column that already has \`${STAMP_METHODS[`${current.on}:${current.value}`]}()\`: a column holds one stamp. \`.onUpdateNow()\` alone also stamps the row when it is created.`);
4224
+ return { stamp };
4225
+ }
4226
+ /**
4227
+ * Types the value without changing the column, as Drizzle's `$type`:
4228
+ * `col.jsonb().$type<{ seoTitle?: string }>()`, `col.integer().$type<UserId>()`.
4229
+ * Nothing is checked at run time; use `col.jsonb(json.object({...}))` for
4230
+ * a shape the server enforces.
4231
+ */
4232
+ $type() {
4233
+ return this.with({});
4234
+ }
4235
+ /** `NOT NULL`. The API requires the column on create unless it has a default. */
4236
+ notNull() {
4237
+ return this.with({ notNull: true });
4238
+ }
4239
+ /**
4240
+ * Part of the primary key. Several columns marked this way form a composite
4241
+ * key, in declaration order.
4242
+ */
4243
+ primaryKey() {
4244
+ return this.with({
4245
+ primaryKey: true,
4246
+ notNull: true
4247
+ });
4248
+ }
4249
+ /**
4250
+ * A single-column `UNIQUE` constraint. Its name is derived; Drizzle's
4251
+ * `.unique(name, { nulls })` arguments are refused.
4252
+ */
4253
+ unique(name, config) {
4254
+ if (name !== void 0 || config !== void 0) throw new Error(DRIZZLE_REFUSALS.uniqueName);
4255
+ return this.with({ unique: true });
4256
+ }
4257
+ /**
4258
+ * A default: a value, written as the column's DDL default and applied by
4259
+ * the driver on create, so a row comes out the same whoever inserts it — or
4260
+ * an expression Postgres evaluates, `.default(sql\`gen_short_id()\`)`.
4261
+ */
4262
+ default(value) {
4263
+ if (isSqlTemplate(value)) return this.with({ default: {
4264
+ kind: "sql",
4265
+ expression: value.text
4266
+ } });
4267
+ const stored = value instanceof Date ? value.toISOString() : value;
4268
+ return this.with({ default: {
4269
+ kind: "literal",
4270
+ value: stored
4271
+ } });
4272
+ }
4273
+ /** Refused: Drizzle's run-time default function. See {@link DRIZZLE_REFUSALS}. */
4274
+ $defaultFn(..._args) {
4275
+ throw new Error(DRIZZLE_REFUSALS.defaultFn);
4276
+ }
4277
+ /** Refused: Drizzle's alias of `$defaultFn`. See {@link DRIZZLE_REFUSALS}. */
4278
+ $default(..._args) {
4279
+ throw new Error(DRIZZLE_REFUSALS.defaultFn);
4280
+ }
4281
+ /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */
4282
+ $onUpdate(..._args) {
4283
+ throw new Error(DRIZZLE_REFUSALS.onUpdateFn);
4284
+ }
4285
+ /** Refused: Drizzle's run-time update function. See {@link DRIZZLE_REFUSALS}. */
4286
+ $onUpdateFn(..._args) {
4287
+ throw new Error(DRIZZLE_REFUSALS.onUpdateFn);
4288
+ }
4289
+ /**
4290
+ * Refused: a foreign key is a relation, `rel.belongsTo(() => users, {...})`
4291
+ * under `relations`, whose key is what `include` names.
4292
+ */
4293
+ references(..._args) {
4294
+ throw new Error(DRIZZLE_REFUSALS.references);
4295
+ }
4296
+ /**
4297
+ * The database already holds a default for this column that Rebase does not
4298
+ * state. A create may omit the column, and a schema push leaves the default
4299
+ * alone.
4300
+ */
4301
+ dbDefault() {
4302
+ return this.with({ default: { kind: "database" } });
4303
+ }
4304
+ /**
4305
+ * `GENERATED ALWAYS AS (<expression>) STORED`, as Drizzle writes it:
4306
+ * `.generatedAlwaysAs(sql\`lower(email)\`)`. Nobody writes the column.
4307
+ */
4308
+ generatedAlwaysAs(as) {
4309
+ const expression = typeof as === "function" ? as() : as;
4310
+ if (!isSqlTemplate(expression)) throw new Error(DRIZZLE_REFUSALS.generatedValue);
4311
+ return this.with({
4312
+ generatedAs: expression.text,
4313
+ readOnly: true
4314
+ });
4315
+ }
4316
+ /**
4317
+ * Client writes are refused on create and update. The database (a default,
4318
+ * a trigger) and the server's own code still fill it.
4319
+ */
4320
+ readOnly() {
4321
+ return this.with({ readOnly: true });
4322
+ }
4323
+ /**
4324
+ * Never leaves the server: absent from every row on the wire, from the SDK
4325
+ * and from OpenAPI, and refused in filters and sorts. Hooks and server code
4326
+ * still see it.
4327
+ */
4328
+ private() {
4329
+ return this.with({ private: true });
4330
+ }
4331
+ /**
4332
+ * Who may read and who may write the column, by role. Enforced on every
4333
+ * door into the table, not only in the panel. `read` and `write` are lists
4334
+ * of role names; anything else throws.
4335
+ */
4336
+ access(access) {
4337
+ return this.with({ access: normalizeColumnAccess(access, "a column (`.access()`)") });
4338
+ }
4339
+ /** What the column holds, for OpenAPI and MCP tool descriptions. */
4340
+ describe(description) {
4341
+ return this.with({ description });
4342
+ }
4343
+ /** Rules the API checks before a write. */
4344
+ validate(rules) {
4345
+ const input = rules;
4346
+ return this.with({ validate: {
4347
+ ...this.def.validate,
4348
+ ...normalizeValidation(input)
4349
+ } });
4350
+ }
4351
+ /**
4352
+ * Field-level hooks: `beforeSave` returns the value to store, `afterRead`
4353
+ * the value to serve. They run on the server, for every caller.
4354
+ *
4355
+ * The value is `TData | null` on a column not (yet) marked `.notNull()` /
4356
+ * `.primaryKey()` — a nullable column hands the hook `null` — and `TData`
4357
+ * on one that is; see {@link ColumnTransformValue}. Chain `.notNull()`
4358
+ * before `.transform()` to get the narrower type.
4359
+ */
4360
+ transform(transform) {
4361
+ const erased = transform;
4362
+ return this.with({ transform: erased });
4363
+ }
4364
+ /**
4365
+ * A closed set of accepted values that is *not* a Postgres enum type: the
4366
+ * API refuses anything else and the SDK types the column as their union.
4367
+ * Use `col.enum()` when the database should enforce it too.
4368
+ *
4369
+ * On a number column. On a text column write Drizzle's spelling,
4370
+ * `col.text({ enum: [...] })`.
4371
+ */
4372
+ oneOf(values) {
4373
+ const stored = [];
4374
+ for (const value of values) {
4375
+ if (typeof value !== "string" && typeof value !== "number") throw new Error("`.oneOf()` takes strings or numbers.");
4376
+ stored.push(value);
4377
+ }
4378
+ return this.with({ oneOf: stored });
4379
+ }
4380
+ /** `DEFAULT gen_random_uuid()`. */
4381
+ defaultRandom() {
4382
+ return this.with({ default: { kind: "random-uuid" } });
4383
+ }
4384
+ /** `GENERATED BY DEFAULT AS IDENTITY`. Sequence options are refused. */
4385
+ generatedByDefaultAsIdentity(sequence) {
4386
+ if (sequence !== void 0) throw new Error(DRIZZLE_REFUSALS.identityOptions);
4387
+ return this.with({ default: { kind: "identity" } });
4388
+ }
4389
+ /** Refused: Rebase creates identity columns `GENERATED BY DEFAULT`. See {@link DRIZZLE_REFUSALS}. */
4390
+ generatedAlwaysAsIdentity(..._args) {
4391
+ throw new Error(DRIZZLE_REFUSALS.identityAlways);
4392
+ }
4393
+ /**
4394
+ * A Postgres array of this column's type, as Drizzle writes it:
4395
+ * `col.text().array()` is `TEXT[]`. What is chained before `.array()`
4396
+ * describes each item (`col.text({ enum: [...] }).array()`,
4397
+ * `col.integer().validate({ min: 0 }).array()`); column modifiers come
4398
+ * after it (`.array().notNull().default([])`). A leading SQL name
4399
+ * (`col.text("tag_list").array()`) names the array column.
4400
+ */
4401
+ array(size) {
4402
+ if (size !== void 0) throw new Error(DRIZZLE_REFUSALS.arraySize);
4403
+ if (!isColumnBuilder(this)) throw new Error("`.array()` is called on a column builder.");
4404
+ const { column, ...item } = this.def;
4405
+ if (item.notNull || item.primaryKey || item.default !== void 0 || item.readOnly || item.private) throw new Error(DRIZZLE_REFUSALS.arrayOrder);
4406
+ const def = arrayDef(item);
4407
+ if (column !== void 0) def.column = column;
4408
+ return new ColumnBuilder(def);
4409
+ }
4410
+ /**
4411
+ * `DEFAULT now()`, as Drizzle's `defaultNow()`: a DDL default a client may
4412
+ * still override. `.onCreateNow()` is the server stamp the client cannot.
4413
+ */
4414
+ defaultNow() {
4415
+ return this.with({ default: {
4416
+ kind: "sql",
4417
+ expression: "now()"
4418
+ } });
4419
+ }
4420
+ /** The server stamps the current time when the row is created (`DEFAULT now()`). */
4421
+ onCreateNow() {
4422
+ return this.with(this.stamped({
4423
+ on: "create",
4424
+ value: "now"
4425
+ }, "onCreateNow"));
4426
+ }
4427
+ /**
4428
+ * The server stamps the current time on every write: `DEFAULT now()`, a
4429
+ * `BEFORE UPDATE` trigger, and the driver's own stamp.
4430
+ */
4431
+ onUpdateNow() {
4432
+ return this.with(this.stamped({
4433
+ on: "update",
4434
+ value: "now"
4435
+ }, "onUpdateNow"));
4436
+ }
4437
+ /** The server writes the caller's id when the row is created. */
4438
+ onCreateUser() {
4439
+ return this.with(this.stamped({
4440
+ on: "create",
4441
+ value: "user"
4442
+ }, "onCreateUser"));
4443
+ }
4444
+ /** The server writes the caller's id on every write. */
4445
+ onUpdateUser() {
4446
+ return this.with(this.stamped({
4447
+ on: "update",
4448
+ value: "user"
4449
+ }, "onUpdateUser"));
4450
+ }
4451
+ /**
4452
+ * The column holds the id of a user. The panel offers a user picker for it,
4453
+ * and callers who may write the table may look users up to fill it (the
4454
+ * user picker's read answers them even though row-level security hides
4455
+ * other users' rows).
4456
+ *
4457
+ * Only on `col.text()`, `col.varchar()`, `col.char()` and `col.uuid()`;
4458
+ * anything else throws. It declares no foreign key: use
4459
+ * `rel.belongsTo(() => users)` when the database should enforce one.
4460
+ */
4461
+ userId() {
4462
+ const kind = this.def.type.kind;
4463
+ if (kind !== "text" && kind !== "varchar" && kind !== "char" && kind !== "uuid" || this.def.storage !== void 0) {
4464
+ const what = this.def.storage !== void 0 ? "`col.storage()`" : `a \`${kind}\` column`;
4465
+ throw new Error(`\`.userId()\` on ${what}: a user's id is held by \`col.text()\`, \`col.varchar()\`, \`col.char()\` or \`col.uuid()\`.`);
4466
+ }
4467
+ return this.with({ semantic: "user" });
4468
+ }
4469
+ /** The column holds several files: `TEXT[]` of paths. */
4470
+ multiple() {
4471
+ const { storage, validate, ...rest } = this.def;
4472
+ return new ColumnBuilder({
4473
+ ...rest,
4474
+ type: {
4475
+ kind: "array",
4476
+ of: { kind: "text" }
4477
+ },
4478
+ storage,
4479
+ element: {
4480
+ ...baseDef({ kind: "text" }),
4481
+ storage,
4482
+ validate
4483
+ }
4484
+ });
4485
+ }
4486
+ };
4487
+ /** The SQL column name a builder's leading argument gives, checked. */
4488
+ function sqlName(name, builder) {
4489
+ if (name === void 0) return void 0;
4490
+ if (typeof name !== "string" || name.length === 0) throw new Error(`\`col.${builder}(name, …)\`: the leading argument is the SQL column name, a non-empty string.`);
4491
+ return name;
4492
+ }
4493
+ /** A fresh definition, named by the builder's leading argument when it has one. */
4494
+ function namedDef(type, name, builder) {
4495
+ const def = baseDef(type);
4496
+ const column = sqlName(name, builder);
4497
+ if (column !== void 0) def.column = column;
4498
+ return def;
4499
+ }
4500
+ /** Drizzle's `(name?, config?)` arguments, either of which may be left out. */
4501
+ function nameAndConfig(first, second) {
4502
+ return typeof first === "string" ? [first, second] : [void 0, first];
4503
+ }
4504
+ /** A config object, checked at run time: JavaScript callers bypass the types. */
4505
+ function configOf(value, builder) {
4506
+ if (value === void 0) return {};
4507
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`\`col.${builder}()\` takes an optional SQL column name and a config object, got ${JSON.stringify(value)}.`);
4508
+ return { ...value };
4509
+ }
4510
+ /** The definition of an array of `item`: what `col.text().array()` builds. */
4511
+ function arrayDef(item) {
4512
+ if (item.type.kind === "array") throw new Error(DRIZZLE_REFUSALS.arrayOfArray);
4513
+ const def = baseDef({
4514
+ kind: "array",
4515
+ of: item.type
4516
+ });
4517
+ def.element = item;
4518
+ if (item.storage) def.storage = item.storage;
4519
+ return def;
4520
+ }
4521
+ /** A list of string labels: an enum's values, Drizzle's `{ enum: [...] }`. */
4522
+ function labelsOf(values, where) {
4523
+ if (!Array.isArray(values) || values.length === 0 || values.some((value) => typeof value !== "string")) throw new Error(`${where} takes a non-empty list of strings, got ${JSON.stringify(values)}.`);
4524
+ return values.filter((value) => typeof value === "string");
4525
+ }
4526
+ var checkMode = (value, allowed, message) => {
4527
+ if (value !== void 0 && value !== allowed) throw new Error(message);
4528
+ };
4529
+ function jsonColumn(kind, first, second) {
4530
+ const [name, shape] = nameAndConfig(first, second);
4531
+ const def = namedDef({ kind }, name, kind);
4532
+ if (shape) def.json = shape.shape;
4533
+ return new ColumnBuilder(def);
4534
+ }
4535
+ function jsonb(first, second) {
4536
+ return jsonColumn("jsonb", first, second);
4537
+ }
4538
+ function json$1(first, second) {
4539
+ return jsonColumn("json", first, second);
4540
+ }
4541
+ var lengthOf = (length, builder) => {
4542
+ if (typeof length !== "number" || !Number.isInteger(length) || length <= 0) throw new Error(`\`col.${builder}({ length })\` takes a positive whole number of characters, got ${String(length)}.`);
4543
+ return length;
4544
+ };
4545
+ function text(first, second) {
4546
+ const [name, rawConfig] = nameAndConfig(first, second);
4547
+ const config = configOf(rawConfig, "text");
4548
+ const def = namedDef({ kind: "text" }, name, "text");
4549
+ if (config.enum !== void 0) def.oneOf = labelsOf(config.enum, "`col.text({ enum })`");
4550
+ return new ColumnBuilder(def);
4551
+ }
4552
+ /** `varchar` / `char`: Drizzle's `(name?, { length, enum? })`. A length is required. */
4553
+ function stringColumn(kind, first, second) {
4554
+ const name = typeof first === "string" ? first : void 0;
4555
+ const raw = typeof first === "string" ? second : first;
4556
+ if (raw === void 0 || typeof raw === "number") throw new Error(kind === "varchar" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);
4557
+ const config = configOf(raw, kind);
4558
+ if (config.length === void 0) throw new Error(kind === "varchar" ? DRIZZLE_REFUSALS.varcharLength : DRIZZLE_REFUSALS.charLength);
4559
+ const length = lengthOf(config.length, kind);
4560
+ const def = namedDef(kind === "varchar" ? {
4561
+ kind: "varchar",
4562
+ length
4563
+ } : {
4564
+ kind: "char",
4565
+ length
4566
+ }, name, kind);
4567
+ if (config.enum !== void 0) def.oneOf = labelsOf(config.enum, `\`col.${kind}({ enum })\``);
4568
+ return new ColumnBuilder(def);
4569
+ }
4570
+ function varchar(first, second) {
4571
+ return stringColumn("varchar", first, second);
4572
+ }
4573
+ function char(first, second) {
4574
+ return stringColumn("char", first, second);
4575
+ }
4576
+ function enumColumn(first, second) {
4577
+ if (typeof first === "string") return new ColumnBuilder(namedDef({
4578
+ kind: "enum",
4579
+ values: labelsOf(second, "`col.enum(name, values)`")
4580
+ }, first, "enum"));
4581
+ if (second !== void 0) throw new Error(DRIZZLE_REFUSALS.enumName);
4582
+ if (first.length === 0) throw new Error("`col.enum([...])` needs at least one value.");
4583
+ return new ColumnBuilder(baseDef({
4584
+ kind: "enum",
4585
+ values: [...first]
4586
+ }));
4587
+ }
4588
+ /** `numeric`, Drizzle's `(name?, { precision, scale, mode })`. */
4589
+ function numericColumn(builder, first, second) {
4590
+ if (typeof first === "number" || typeof second === "number") throw new Error(DRIZZLE_REFUSALS.numericPositional);
4591
+ const name = typeof first === "string" ? first : void 0;
4592
+ const config = configOf(typeof first === "string" ? second : first, builder);
4593
+ checkMode(config.mode, "number", DRIZZLE_REFUSALS.numericMode);
4594
+ const precision = config.precision;
4595
+ const scale = config.scale;
4596
+ if (scale !== void 0 && precision === void 0) throw new Error(`\`col.${builder}({ precision, scale })\`: a scale needs a precision.`);
4597
+ for (const [what, value] of [["precision", precision], ["scale", scale]]) if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 0)) throw new Error(`\`col.${builder}()\`: \`${what}\` is a whole number, got ${String(value)}.`);
4598
+ return new ColumnBuilder(namedDef(typeof precision !== "number" ? { kind: "numeric" } : typeof scale !== "number" ? {
4599
+ kind: "numeric",
4600
+ precision
4601
+ } : {
4602
+ kind: "numeric",
4603
+ precision,
4604
+ scale
4605
+ }, name, builder));
4606
+ }
4607
+ function numeric(first, second) {
4608
+ return numericColumn("numeric", first, second);
4609
+ }
4610
+ function decimal(first, second) {
4611
+ return numericColumn("decimal", first, second);
4612
+ }
4613
+ /** `bigint` / `bigserial`, Drizzle's `(name?, { mode })`. */
4614
+ function bigColumn(kind, first, second) {
4615
+ const name = typeof first === "string" ? first : void 0;
4616
+ const raw = typeof first === "string" ? second : first;
4617
+ if (raw === void 0) throw new Error(DRIZZLE_REFUSALS.bigintModeMissing);
4618
+ checkMode(configOf(raw, kind).mode, "number", DRIZZLE_REFUSALS.bigintMode);
4619
+ return new ColumnBuilder(namedDef(kind === "bigint" ? { kind: "bigint" } : { kind: "bigserial" }, name, kind));
4620
+ }
4621
+ function bigint(first, second) {
4622
+ return bigColumn("bigint", first, second);
4623
+ }
4624
+ function bigserial(first, second) {
4625
+ return new ColumnBuilder(bigColumn("bigserial", first, second).def);
4626
+ }
4627
+ function timestamp(first, second) {
4628
+ const [name, raw] = nameAndConfig(first, second);
4629
+ const config = configOf(raw, "timestamp");
4630
+ if (config.withTimezone !== true) throw new Error(DRIZZLE_REFUSALS.timestamp);
4631
+ checkMode(config.mode, "string", DRIZZLE_REFUSALS.timestampMode);
4632
+ if (config.precision !== void 0) throw new Error(DRIZZLE_REFUSALS.timestampPrecision);
4633
+ return new ColumnBuilder(namedDef({ kind: "timestamptz" }, name, "timestamp"));
4634
+ }
4635
+ function date(first, second) {
4636
+ const [name, raw] = nameAndConfig(first, second);
4637
+ checkMode(configOf(raw, "date").mode, "string", DRIZZLE_REFUSALS.dateMode);
4638
+ return new ColumnBuilder(namedDef({ kind: "date" }, name, "date"));
4639
+ }
4640
+ function time(first, second) {
4641
+ const [name, raw] = nameAndConfig(first, second);
4642
+ const config = configOf(raw, "time");
4643
+ if (config.withTimezone !== void 0 && config.withTimezone !== false) throw new Error(DRIZZLE_REFUSALS.timeZone);
4644
+ if (config.precision !== void 0) throw new Error(DRIZZLE_REFUSALS.timePrecision);
4645
+ return new ColumnBuilder(namedDef({ kind: "time" }, name, "time"));
4646
+ }
4647
+ function vector(first, second) {
4648
+ if (typeof first === "number") throw new Error(DRIZZLE_REFUSALS.vectorPositional);
4649
+ const name = typeof first === "string" ? first : void 0;
4650
+ const config = configOf(typeof first === "string" ? second : first, "vector");
4651
+ const dimensions = config.dimensions;
4652
+ const index = config.index;
4653
+ if (typeof dimensions !== "number" || !Number.isInteger(dimensions) || dimensions <= 0) throw new Error(`\`col.vector({ dimensions })\` takes a positive whole number, got ${String(dimensions)}.`);
4654
+ const def = namedDef({
4655
+ kind: "vector",
4656
+ dimensions
4657
+ }, name, "vector");
4658
+ if (index === false) def.vectorIndex = false;
4659
+ else if (typeof index === "object" && index !== null) def.vectorIndex = { ...index };
4660
+ else if (index !== void 0) throw new Error("`col.vector({ index })` takes index options or `false`.");
4661
+ return new ColumnBuilder(def);
4662
+ }
4663
+ function storage(first, second) {
4664
+ const [name, options] = nameAndConfig(first, second);
4665
+ if (options === void 0) throw new Error("`col.storage()` takes its options: `col.storage({ path: \"posts/heroes/\" })`.");
4666
+ const def = namedDef({ kind: "text" }, name, "storage");
4667
+ def.storage = normalizeStorage(options);
4668
+ return new ColumnBuilder(def);
4669
+ }
4670
+ function custom(first, second) {
4671
+ if (typeof first === "string" && second === void 0) throw new Error(DRIZZLE_REFUSALS.customDataType);
4672
+ const [name, raw] = nameAndConfig(first, second);
4673
+ const config = configOf(raw, "custom");
4674
+ if (typeof config.dataType !== "string") throw new Error("`col.custom()` names its Postgres type: `col.custom({ dataType: \"inet\" })`.");
4675
+ return new ColumnBuilder(namedDef({
4676
+ kind: "other",
4677
+ sqlType: customSqlType(config.dataType)
4678
+ }, name, "custom"));
4679
+ }
4680
+ /** A builder for a Drizzle column type Rebase serves only through `col.custom()`: refused with the spelling. */
4681
+ function unsupported(type) {
4682
+ return () => {
4683
+ throw new Error(unsupportedMessage(type));
4684
+ };
4685
+ }
4686
+ /** A builder that takes only the optional SQL column name. */
4687
+ function simple(kind, type) {
4688
+ return (name) => new ColumnBuilder(namedDef(type, name, kind));
4689
+ }
4690
+ /**
4691
+ * The column builders, spelled as Drizzle's `pg-core` spells them: the
4692
+ * optional SQL column name first, then Drizzle's config object, then the
4693
+ * chain.
4694
+ *
4695
+ * ```ts
4696
+ * columns: {
4697
+ * id: col.uuid().primaryKey().defaultRandom(),
4698
+ * title: col.text().notNull().validate({ min: 3, max: 200 }),
4699
+ * slug: col.varchar({ length: 160 }).notNull().unique(),
4700
+ * status: postStatus().notNull().default("draft"), // const postStatus = pgEnum("post_status", [...])
4701
+ * tags: col.text().array().notNull().default([]),
4702
+ * heroImage: col.storage({ path: "posts/heroes/", accept: ["image/*"], maxBytes: "10MB" }),
4703
+ * createdAt: col.timestamp({ withTimezone: true }).notNull().defaultNow(),
4704
+ * }
4705
+ * ```
4706
+ *
4707
+ * @group Schema
4708
+ */
4709
+ var col = {
4710
+ /** `UUID`. */
4711
+ uuid: simple("uuid", { kind: "uuid" }),
4712
+ /** `TEXT`. `col.text({ enum: [...] })` accepts only those values. */
4713
+ text,
4714
+ /** `VARCHAR(n)`: `col.varchar({ length: n })`. */
4715
+ varchar,
4716
+ /** `CHAR(n)`: `col.char({ length: n })`. */
4717
+ char,
4718
+ /**
4719
+ * A Postgres enum type of its own, created as `<table>_<column>`. A type
4720
+ * with a stated name, shared by several columns, is `pgEnum(name, values)`.
4721
+ */
4722
+ enum: enumColumn,
4723
+ /** `SMALLINT`. */
4724
+ smallint: simple("smallint", { kind: "smallint" }),
4725
+ /** `INTEGER`. */
4726
+ integer: simple("integer", { kind: "integer" }),
4727
+ /** `BIGINT`, read and written as a JavaScript number: `col.bigint({ mode: "number" })`. */
4728
+ bigint,
4729
+ /** `SMALLSERIAL`. Prefer `col.smallint().generatedByDefaultAsIdentity()` in a new schema. */
4730
+ smallserial(name) {
4731
+ return new ColumnBuilder(namedDef({ kind: "smallserial" }, name, "smallserial"));
4732
+ },
4733
+ /** `SERIAL`. Prefer `col.integer().generatedByDefaultAsIdentity()` in a new schema. */
4734
+ serial(name) {
4735
+ return new ColumnBuilder(namedDef({ kind: "serial" }, name, "serial"));
4736
+ },
4737
+ /** `BIGSERIAL`: `col.bigserial({ mode: "number" })`. Prefer an identity column in a new schema. */
4738
+ bigserial,
4739
+ /** `REAL`. */
4740
+ real: simple("real", { kind: "real" }),
4741
+ /** `DOUBLE PRECISION`. */
4742
+ doublePrecision: simple("doublePrecision", { kind: "doublePrecision" }),
4743
+ /** `NUMERIC`, `NUMERIC(p)` or `NUMERIC(p, s)`: `col.numeric({ precision, scale })`. A JSON number. */
4744
+ numeric,
4745
+ /** Drizzle's alias of `col.numeric()`. */
4746
+ decimal,
4747
+ /** `BOOLEAN`. */
4748
+ boolean: simple("boolean", { kind: "boolean" }),
4749
+ /** `TIMESTAMPTZ`: `col.timestamp({ withTimezone: true })`. An ISO string on the wire. */
4750
+ timestamp,
4751
+ /** `DATE`. `YYYY-MM-DD` on the wire. */
4752
+ date,
4753
+ /** `TIME`. `HH:MM:SS` on the wire. */
4754
+ time,
4755
+ /**
4756
+ * `JSONB`. `col.jsonb().$type<T>()` types the document;
4757
+ * `col.jsonb(json.object({...}))` also tells the server its shape, so
4758
+ * nested fields are validated, stamped and searchable.
4759
+ */
4760
+ jsonb,
4761
+ /** `JSON`. As `col.jsonb`, for a column that must keep the text it was given. */
4762
+ json: json$1,
4763
+ /**
4764
+ * `vector(dimensions)` (pgvector): `col.vector({ dimensions: 1536 })`. An
4765
+ * HNSW cosine index is created unless `index` says otherwise; `index: false`
4766
+ * creates none.
4767
+ */
4768
+ vector,
4769
+ /** `BYTEA`. Base64 on the wire. */
4770
+ bytea: simple("bytea", { kind: "bytea" }),
4771
+ /** A point on Earth, stored as `JSONB` `{ latitude, longitude }`. */
4772
+ geopoint(name) {
4773
+ const def = namedDef({ kind: "jsonb" }, name, "geopoint");
4774
+ def.semantic = "geopoint";
4775
+ return new ColumnBuilder(def);
4776
+ },
4777
+ /**
4778
+ * The path of a stored file, as `TEXT` — or several with `.multiple()`. The
4779
+ * upload route enforces `accept` and `maxBytes`, and the orphan sweep counts
4780
+ * the file as referenced.
4781
+ */
4782
+ storage,
4783
+ /**
4784
+ * A column of a Postgres type no other builder names —
4785
+ * `col.custom({ dataType: "inet" })`, `col.custom({ dataType: "citext" })`,
4786
+ * `col.custom({ dataType: "geometry(Point, 4326)" })`. What
4787
+ * `rebase schema introspect` writes for a column of such a type, so a
4788
+ * project generated from an existing database keeps it.
4789
+ *
4790
+ * Rebase names the type in DDL, verbatim, and does nothing else with it: it
4791
+ * does not create, alter or drop the type's definition (an extension or a
4792
+ * `CREATE TYPE` the database already holds provides it), it does not
4793
+ * validate values, and it passes every value through exactly as the
4794
+ * driver returns it — a string for most types. `.$type<T>()` types it for
4795
+ * the SDK when the driver returns something else.
4796
+ */
4797
+ custom,
4798
+ /** Refused: write `col.custom({ dataType: "interval" })`. */
4799
+ interval: unsupported("interval"),
4800
+ /** Refused: write `col.custom({ dataType: "inet" })`. */
4801
+ inet: unsupported("inet"),
4802
+ /** Refused: write `col.custom({ dataType: "cidr" })`. */
4803
+ cidr: unsupported("cidr"),
4804
+ /** Refused: write `col.custom({ dataType: "macaddr" })`. */
4805
+ macaddr: unsupported("macaddr"),
4806
+ /** Refused: write `col.custom({ dataType: "macaddr8" })`. */
4807
+ macaddr8: unsupported("macaddr8"),
4808
+ /** Refused: write `col.custom({ dataType: "point" })`. */
4809
+ point: unsupported("point"),
4810
+ /** Refused: write `col.custom({ dataType: "line" })`. */
4811
+ line: unsupported("line"),
4812
+ /** Refused: write `col.custom({ dataType: "halfvec" })`. */
4813
+ halfvec: unsupported("halfvec"),
4814
+ /** Refused: write `col.custom({ dataType: "sparsevec" })`. */
4815
+ sparsevec: unsupported("sparsevec"),
4816
+ /** Refused: write `col.custom({ dataType: "bit" })`. */
4817
+ bit: unsupported("bit")
4818
+ };
4819
+ function pgEnum(enumName, values) {
4820
+ if (typeof enumName !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(enumName)) throw new Error(`\`pgEnum(name, values)\`: the name is a plain SQL identifier, got ${JSON.stringify(enumName)}.`);
4821
+ if (!isLabelTuple(values)) throw new Error(DRIZZLE_REFUSALS.pgEnumObject);
4822
+ const labels = [...values];
4823
+ const factory = (name) => new ColumnBuilder(namedDef({
4824
+ kind: "enum",
4825
+ values: labels,
4826
+ name: enumName
4827
+ }, name, "enum"));
4828
+ return Object.assign(factory, {
4829
+ enumName,
4830
+ enumValues: values
4831
+ });
4832
+ }
4833
+ function isLabelTuple(values) {
4834
+ return Array.isArray(values) && values.length > 0 && values.every((value) => typeof value === "string");
4835
+ }
4836
+ /**
4837
+ * The type name `col.custom()` puts into DDL: trimmed, and refused when it is
4838
+ * empty or could end the statement it is written into.
4839
+ */
4840
+ function customSqlType(sqlType) {
4841
+ const trimmed = typeof sqlType === "string" ? sqlType.trim() : "";
4842
+ if (trimmed.length === 0) throw new Error("`col.custom()` takes the Postgres type, e.g. `col.custom({ dataType: \"inet\" })`.");
4843
+ if (/;|--|\/\*/.test(trimmed)) throw new Error(`\`col.custom({ dataType: ${JSON.stringify(sqlType)} })\`: a type name holds no \`;\` and no comment.`);
4844
+ return trimmed;
4845
+ }
4846
+ /**
4847
+ * Whether a value is a column builder, from this copy of the package or
4848
+ * another.
4849
+ *
4850
+ * @group Schema
4851
+ */
4852
+ function isColumnBuilder(value) {
4853
+ return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.column";
4854
+ }
4855
+ //#endregion
4856
+ //#region src/schema/relations.ts
4857
+ /** The brand every relation builder result carries. */
4858
+ var RELATION_BRAND = "rebase.relation";
4859
+ /** The options with `access` checked and copied: a role list, never a string spread into characters. */
4860
+ function withCheckedAccess(kind, options) {
4861
+ if (options.access === void 0) return options;
4862
+ return {
4863
+ ...options,
4864
+ access: normalizeColumnAccess(options.access, `a relation (\`rel.${kind}(…, { access })\`)`)
4865
+ };
4866
+ }
4867
+ function belongsTo(target, options = {}) {
4868
+ return {
4869
+ ...withCheckedAccess("belongsTo", options),
4870
+ brand: RELATION_BRAND,
4871
+ kind: "belongsTo",
4872
+ target
4873
+ };
4874
+ }
4875
+ /**
4876
+ * The relation builders. All five kinds; the target is a thunk, so two tables
4877
+ * can point at each other whatever order their modules load in — and, being a
4878
+ * {@link TableThunk}, without a type annotation on either side.
4879
+ *
4880
+ * ```ts
4881
+ * relations: {
4882
+ * author: rel.belongsTo(() => users, { localKey: "author_id", notNull: true, onDelete: "restrict" }),
4883
+ * tags: rel.manyToMany(() => tags, { through: "posts_tags", pivot: { sortOrder: col.integer().default(0) } }),
4884
+ * }
4885
+ * ```
4886
+ *
4887
+ * @group Schema
4888
+ */
4889
+ var rel = {
4890
+ /**
4891
+ * This table holds the foreign key. Binds to the column in `columns` whose
4892
+ * SQL name is `localKey`, or derives that column and indexes it.
4893
+ */
4894
+ belongsTo,
4895
+ /** The target holds a unique foreign key pointing here. */
4896
+ hasOne(target, options = {}) {
4897
+ return {
4898
+ ...withCheckedAccess("hasOne", options),
4899
+ brand: RELATION_BRAND,
4900
+ kind: "hasOne",
4901
+ target
4902
+ };
4903
+ },
4904
+ /** The target holds a foreign key pointing here. */
4905
+ hasMany(target, options = {}) {
4906
+ return {
4907
+ ...withCheckedAccess("hasMany", options),
4908
+ brand: RELATION_BRAND,
4909
+ kind: "hasMany",
4910
+ target
4911
+ };
4912
+ },
4913
+ /**
4914
+ * Linked through a junction table, which is created with its own row-level
4915
+ * security. `pivot` columns are read and written as `_pivot`.
4916
+ */
4917
+ manyToMany(target, options = {}) {
4918
+ return {
4919
+ ...withCheckedAccess("manyToMany", options),
4920
+ brand: RELATION_BRAND,
4921
+ kind: "manyToMany",
4922
+ target
4923
+ };
4924
+ },
4925
+ /** A read-only traversal across several joins. */
4926
+ via(target, options) {
4927
+ if (!options.steps || options.steps.length === 0) throw new Error("`rel.via(target, { steps })` needs at least one join step.");
4928
+ return {
4929
+ ...withCheckedAccess("via", options),
4930
+ brand: RELATION_BRAND,
4931
+ kind: "via",
4932
+ target
4933
+ };
4934
+ }
4935
+ };
4936
+ /**
4937
+ * Whether a value is the result of a `rel.*` call.
4938
+ *
4939
+ * @group Schema
4940
+ */
4941
+ function isRelationDef(value) {
4942
+ return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.relation";
4943
+ }
4944
+ //#endregion
4945
+ //#region src/schema/table.ts
4946
+ /** The brand of a `defineTable` / `defineAuthTable` result. */
4947
+ var TABLE_BRAND = "rebase.table";
4948
+ /** The brand of a `defineView` result. */
4949
+ var VIEW_BRAND = "rebase.view";
4950
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
4951
+ function assertTableShape(builder, name, config) {
4952
+ if (typeof name !== "string" || name.length === 0) throw new Error(`\`${builder}(name, config)\` needs the table's name as its first argument.`);
4953
+ if (typeof config !== "object" || config === null) throw new Error(`\`${builder}("${name}", config)\` needs a config object.`);
4954
+ const columns = "columns" in config ? config.columns : void 0;
4955
+ if (typeof columns !== "object" || columns === null || Object.keys(columns).length === 0) throw new Error(`Table "${name}" declares no columns. Add \`columns: { id: col.uuid().primaryKey().defaultRandom(), … }\`.`);
4956
+ for (const [key, column] of Object.entries(columns)) if (!isColumnBuilder(column)) throw new Error(`Column "${key}" of table "${name}" is not a \`col.*\` builder.`);
4957
+ const relations = "relations" in config ? config.relations : void 0;
4958
+ if (relations !== void 0) {
4959
+ if (typeof relations !== "object" || relations === null) throw new Error(`\`relations\` of table "${name}" must be an object of \`rel.*\` results.`);
4960
+ for (const [key, relation] of Object.entries(relations)) {
4961
+ if (!isRelationDef(relation)) throw new Error(`Relation "${key}" of table "${name}" is not a \`rel.*\` result.`);
4962
+ if (key in columns) throw new Error(`Table "${name}" has both a column and a relation named "${key}". A relation's key is what \`include\` names; give the foreign-key column its own key.`);
4963
+ }
4964
+ }
4965
+ for (const key of ["schema", "table"]) {
4966
+ const value = key in config ? Reflect.get(config, key) : void 0;
4967
+ if (value !== void 0 && (typeof value !== "string" || !IDENTIFIER.test(value))) throw new Error(`\`${key}\` of table "${name}" must be a plain SQL identifier, got ${JSON.stringify(value)}.`);
4968
+ }
4969
+ }
4970
+ function assertRlsDeclared(builder, name, config) {
4971
+ const rls = "rls" in config ? config.rls : void 0;
4972
+ if (rls === "admin-only" || rls === "inherit" || Array.isArray(rls) && rls.length > 0) return;
4973
+ throw new Error(`\`${builder}("${name}", …)\` has no usable \`rls\`. ${Array.isArray(rls) ? "`rls: []` grants nothing and says nothing. Write `rls: \"admin-only\"` to lock the table to admins." : "Every table needs an explicit row-level security posture."} Accepted: \`"admin-only"\`, \`"inherit"\` (the \`defaultRls\` exported from backend/schema/index.ts), or a non-empty list of rules.`);
4974
+ }
4975
+ /**
4976
+ * Define a Postgres table.
4977
+ *
4978
+ * The name is the SQL table and the API slug; `rls` is mandatory. The result
4979
+ * is what the backend reads from `backend/schema/index.ts` — it generates the
4980
+ * DDL and the policies, serves the REST, realtime and MCP surfaces, and types
4981
+ * the SDK.
4982
+ *
4983
+ * ```ts
4984
+ * export const posts = defineTable("posts", {
4985
+ * columns: {
4986
+ * id: col.uuid().primaryKey().defaultRandom(),
4987
+ * title: col.text().notNull(),
4988
+ * },
4989
+ * rls: [
4990
+ * { operation: "select", access: "public" },
4991
+ * { operations: ["insert", "update", "delete"], roles: ["editor"] },
4992
+ * ],
4993
+ * });
4994
+ * ```
4995
+ *
4996
+ * @group Schema
4997
+ */
4998
+ function defineTable(name, config) {
4999
+ assertTableShape("defineTable", name, config);
5000
+ assertRlsDeclared("defineTable", name, config);
5001
+ return {
5002
+ brand: TABLE_BRAND,
5003
+ name,
5004
+ config
5005
+ };
5006
+ }
5007
+ /**
5008
+ * Define the table users are stored in.
5009
+ *
5010
+ * A `defineTable` that auth reads and writes: the columns auth needs are added
5011
+ * when the table does not declare them, a signed-in user can read their own
5012
+ * row, and the privilege columns (`roles`) can only be written by an admin —
5013
+ * whatever `rls` says. A project has at most one.
5014
+ *
5015
+ * @group Schema
5016
+ */
5017
+ function defineAuthTable(name, config) {
5018
+ assertTableShape("defineAuthTable", name, config);
5019
+ assertRlsDeclared("defineAuthTable", name, config);
5020
+ const { auth, ...table } = config;
5021
+ return {
5022
+ brand: TABLE_BRAND,
5023
+ name,
5024
+ config: table,
5025
+ auth: auth ?? {}
5026
+ };
5027
+ }
5028
+ /**
5029
+ * Define a SQL view, served read-only.
5030
+ *
5031
+ * A plain view is created `WITH (security_invoker = true)`: the row-level
5032
+ * security of the tables it reads decides what each caller sees. A
5033
+ * materialized view stores its rows, so it is gated by `roles` instead.
5034
+ *
5035
+ * @group Schema
5036
+ */
5037
+ function defineView(name, config) {
5038
+ assertTableShape("defineView", name, config);
5039
+ if (typeof config.query !== "string" || config.query.trim().length === 0) throw new Error(`View "${name}" needs a \`query\`: the SELECT that defines it.`);
5040
+ if (config.roles !== void 0 && !config.materialized) throw new Error(`View "${name}" lists \`roles\` but is not materialized. A plain view is governed by the row-level security of the tables it reads; \`roles\` gates a materialized view only.`);
5041
+ return {
5042
+ brand: VIEW_BRAND,
5043
+ name,
5044
+ config
5045
+ };
5046
+ }
5047
+ /**
5048
+ * Whether a value is the result of `defineTable` or `defineAuthTable`, from
5049
+ * this copy of the package or another.
5050
+ *
5051
+ * @group Schema
5052
+ */
5053
+ function isTableDef(value) {
5054
+ return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.table";
5055
+ }
5056
+ /**
5057
+ * Whether a value is the result of `defineAuthTable`.
5058
+ *
5059
+ * @group Schema
5060
+ */
5061
+ function isAuthTableDef(value) {
5062
+ return isTableDef(value) && value.auth !== void 0;
5063
+ }
5064
+ /**
5065
+ * Whether a value is the result of `defineView`.
5066
+ *
5067
+ * @group Schema
5068
+ */
5069
+ function isViewDef(value) {
5070
+ return typeof value === "object" && value !== null && "brand" in value && value.brand === "rebase.view";
5071
+ }
5072
+ //#endregion
5073
+ //#region src/schema/table_patch.ts
5074
+ /** The keys of {@link TableOptionValues}, in the order a table prints them. */
5075
+ var TABLE_OPTION_KEYS = [
5076
+ "description",
5077
+ "defaultPolicies",
5078
+ "tenant",
5079
+ "softDelete",
5080
+ "history",
5081
+ "search",
5082
+ "indexes",
5083
+ "strictWrites",
5084
+ "metadata"
5085
+ ];
5086
+ /**
5087
+ * A list of table edits that cannot be applied, with every problem found.
5088
+ *
5089
+ * @group Schema
5090
+ */
5091
+ var TablePatchError = class TablePatchError extends Error {
5092
+ problems;
5093
+ code = "TABLE_PATCH_INVALID";
5094
+ constructor(problems) {
5095
+ super(TablePatchError.describe(problems));
5096
+ this.problems = problems;
5097
+ this.name = "TablePatchError";
5098
+ }
5099
+ static describe(problems) {
5100
+ const lines = problems.map((problem) => {
5101
+ const table = problem.table || "(no table)";
5102
+ const where = problem.key ? `${table}.${problem.key}` : table;
5103
+ return ` - edit ${problem.index} (${where}): ${problem.message}`;
5104
+ });
5105
+ return `The schema edit cannot be applied (${problems.length === 1 ? "1 problem" : `${problems.length} problems`}):\n${lines.join("\n")}`;
5106
+ }
5107
+ };
5108
+ /**
5109
+ * A name that reaches SQL as an identifier, or becomes a file name: letters,
5110
+ * digits, underscores and dollar signs, not starting with a digit. The same
5111
+ * alphabet the DDL builders accept, so a name accepted here is one they take.
5112
+ */
5113
+ var SQL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;
5114
+ /** A key on the JSON row: any non-empty string without control characters. */
5115
+ var isRowKey = (key) => key.length > 0 && [...key].every((char) => char.charCodeAt(0) >= 32);
5116
+ var COLUMN_KINDS = /* @__PURE__ */ new Set([
5117
+ "text",
5118
+ "varchar",
5119
+ "char",
5120
+ "uuid",
5121
+ "enum",
5122
+ "smallint",
5123
+ "integer",
5124
+ "bigint",
5125
+ "smallserial",
5126
+ "serial",
5127
+ "bigserial",
5128
+ "real",
5129
+ "doublePrecision",
5130
+ "numeric",
5131
+ "boolean",
5132
+ "timestamptz",
5133
+ "date",
5134
+ "time",
5135
+ "json",
5136
+ "jsonb",
5137
+ "vector",
5138
+ "bytea",
5139
+ "array",
5140
+ "other"
5141
+ ]);
5142
+ var RELATION_OPTION_KEYS = {
5143
+ belongsTo: [
5144
+ "localKey",
5145
+ "notNull",
5146
+ "unique",
5147
+ "onDelete",
5148
+ "onUpdate",
5149
+ "index",
5150
+ "constraint",
5151
+ "access",
5152
+ "private"
5153
+ ],
5154
+ hasOne: [
5155
+ "foreignKey",
5156
+ "sourceKey",
5157
+ "access",
5158
+ "private"
5159
+ ],
5160
+ hasMany: [
5161
+ "foreignKey",
5162
+ "sourceKey",
5163
+ "orderBy",
5164
+ "access",
5165
+ "private"
5166
+ ],
5167
+ manyToMany: [
5168
+ "through",
5169
+ "sourceKey",
5170
+ "targetKey",
5171
+ "pivot",
5172
+ "onDelete",
5173
+ "access",
5174
+ "private"
5175
+ ],
5176
+ via: [
5177
+ "steps",
5178
+ "cardinality",
5179
+ "access",
5180
+ "private"
5181
+ ]
5182
+ };
5183
+ /** The relation options that name a SQL column or table. */
5184
+ var RELATION_IDENTIFIER_KEYS = [
5185
+ "localKey",
5186
+ "foreignKey",
5187
+ "sourceKey",
5188
+ "targetKey",
5189
+ "through"
5190
+ ];
5191
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5192
+ var MIGRATION_KEYS = {
5193
+ slug: "The slug is the table's address in the API, the SDK, scopes and foreign-key names; renaming it moves data, which is a migration, not an edit. Create a new table and migrate the rows, or rename it in code with a migration.",
5194
+ table: "Renaming the SQL table moves its rows, which is a migration, not an edit. Write the rename in code together with a migration.",
5195
+ schema: "Moving the table to another Postgres schema moves its rows, which is a migration, not an edit. Write it in code together with a migration.",
5196
+ name: "The table's name is its file and its default SQL name; renaming it moves data, which is a migration, not an edit. Write the rename in code together with a migration.",
5197
+ database: "Moving the table to another database moves its rows, which is a migration, not an edit."
5198
+ };
5199
+ /** Problems with a column definition sent on the wire. */
5200
+ function columnProblems(value, where) {
5201
+ if (!isRecord(value)) return [`${where} must be a column definition object.`];
5202
+ const problems = [];
5203
+ const type = value.type;
5204
+ if (!isRecord(type) || typeof type.kind !== "string" || !COLUMN_KINDS.has(type.kind)) problems.push(`${where}.type must be a column type, \`{ kind: "text" }\`, \`{ kind: "varchar", length: 160 }\` …`);
5205
+ else if (type.kind === "array") {
5206
+ if (!isRecord(type.of)) problems.push(`${where}.type.of must be the type of each item.`);
5207
+ } else if ((type.kind === "varchar" || type.kind === "char") && typeof type.length !== "number") problems.push(`${where}.type.length must be a number.`);
5208
+ else if (type.kind === "enum" && (!Array.isArray(type.values) || type.values.length === 0 || !type.values.every((v) => typeof v === "string"))) problems.push(`${where}.type.values must be a non-empty list of strings.`);
5209
+ else if (type.kind === "vector" && typeof type.dimensions !== "number") problems.push(`${where}.type.dimensions must be a number.`);
5210
+ else if (type.kind === "other" && typeof type.sqlType !== "string") problems.push(`${where}.type.sqlType must be a string.`);
5211
+ for (const flag of [
5212
+ "notNull",
5213
+ "primaryKey",
5214
+ "unique",
5215
+ "readOnly",
5216
+ "private"
5217
+ ]) if (value[flag] !== void 0 && typeof value[flag] !== "boolean") problems.push(`${where}.${flag} must be a boolean.`);
5218
+ if (value.column !== void 0 && (typeof value.column !== "string" || !SQL_IDENTIFIER.test(value.column))) problems.push(`${where}.column must be a SQL identifier (letters, digits, underscores; not starting with a digit).`);
5219
+ if (value.transform !== void 0) problems.push(`${where}.transform is code: write it in the table's file. A transform already on the column is kept.`);
5220
+ if (value.element !== void 0) problems.push(...columnProblems(value.element, `${where}.element`));
5221
+ if (value.json !== void 0 && !isRecord(value.json)) problems.push(`${where}.json must be a JSON shape.`);
5222
+ return problems;
5223
+ }
5224
+ /** Problems with a table description sent to be adopted. */
5225
+ function adoptedTableProblems(spec) {
5226
+ const out = [];
5227
+ for (const key of [
5228
+ "name",
5229
+ "slug",
5230
+ "table",
5231
+ "schema"
5232
+ ]) {
5233
+ const named = spec[key];
5234
+ if (typeof named !== "string" || !SQL_IDENTIFIER.test(named)) out.push({
5235
+ key,
5236
+ message: `\`${key}\` must be a SQL identifier.`
5237
+ });
5238
+ }
5239
+ if (spec.kind !== "table") out.push({
5240
+ key: "kind",
5241
+ message: "only a table can be adopted (`kind: \"table\"`)."
5242
+ });
5243
+ if (!Array.isArray(spec.columns) || spec.columns.length === 0) out.push({
5244
+ key: "columns",
5245
+ message: "`columns` must list the table's columns, as introspection described them."
5246
+ });
5247
+ else for (const [index, column] of spec.columns.entries()) {
5248
+ const key = isRecord(column) && typeof column.key === "string" ? column.key : `columns[${index}]`;
5249
+ if (!isRecord(column) || typeof column.key !== "string" || !isRowKey(column.key)) out.push({
5250
+ key,
5251
+ message: "a column must have a `key`."
5252
+ });
5253
+ else if (typeof column.nullable !== "boolean") out.push({
5254
+ key,
5255
+ message: "`nullable` must be a boolean."
5256
+ });
5257
+ for (const message of columnProblems(column, `columns.${key}`)) out.push({
5258
+ key,
5259
+ message
5260
+ });
5261
+ }
5262
+ if (!Array.isArray(spec.primaryKey) || spec.primaryKey.length === 0 || !spec.primaryKey.every((key) => typeof key === "string")) out.push({
5263
+ key: "primaryKey",
5264
+ message: "`primaryKey` must name the key column (or columns): a table without one cannot be declared."
5265
+ });
5266
+ if (!Array.isArray(spec.relations) || !spec.relations.every(isRecord)) out.push({
5267
+ key: "relations",
5268
+ message: "`relations` must be a list of relations."
5269
+ });
5270
+ const rls = spec.rls;
5271
+ if (!isRecord(rls) || rls.posture !== "admin-only" && rls.posture !== "rules" || !Array.isArray(rls.rules) || !rls.rules.every(isRecord)) out.push({
5272
+ key: "rls",
5273
+ message: "`rls` must be `{ posture, rules }`, as introspection described it."
5274
+ });
5275
+ if (spec.hooks !== void 0) out.push({
5276
+ key: "hooks",
5277
+ message: "hooks are code: write them in the table's file once it is adopted."
5278
+ });
5279
+ if (spec.auth !== void 0 || spec.view !== void 0) out.push({ message: "an auth table or a view is not adopted here: declare it in code." });
5280
+ return out;
5281
+ }
5282
+ /** Problems with a relation sent on the wire. */
5283
+ function relationProblems(value, where) {
5284
+ if (!isRecord(value)) return [`${where} must be a relation object.`];
5285
+ const kind = value.kind;
5286
+ if (kind !== "belongsTo" && kind !== "hasOne" && kind !== "hasMany" && kind !== "manyToMany" && kind !== "via") return [`${where}.kind must be one of belongsTo, hasOne, hasMany, manyToMany, via.`];
5287
+ const problems = [];
5288
+ if (typeof value.target !== "string" || value.target.trim() === "") problems.push(`${where}.target must be the slug of the table it points at.`);
5289
+ const known = RELATION_OPTION_KEYS[kind];
5290
+ for (const key of Object.keys(value)) {
5291
+ if (key === "kind" || key === "target") continue;
5292
+ if (!known.includes(key)) problems.push(`${where}.${key} is not an option of \`rel.${kind}\`.`);
5293
+ }
5294
+ for (const key of RELATION_IDENTIFIER_KEYS) {
5295
+ const named = value[key];
5296
+ if (named !== void 0 && (typeof named !== "string" || !SQL_IDENTIFIER.test(named))) problems.push(`${where}.${key} must be a SQL identifier.`);
5297
+ }
5298
+ if (kind === "via" && (!Array.isArray(value.steps) || value.steps.length === 0)) problems.push(`${where}.steps must list at least one join step.`);
5299
+ if (kind === "manyToMany" && value.pivot !== void 0) if (!isRecord(value.pivot)) problems.push(`${where}.pivot must map column keys to column definitions.`);
5300
+ else for (const [key, column] of Object.entries(value.pivot)) problems.push(...columnProblems(column, `${where}.pivot.${key}`));
5301
+ return problems;
5302
+ }
5303
+ /** Problems with an `rls` value sent on the wire. */
5304
+ function rlsProblems(value, where) {
5305
+ if (value === "admin-only" || value === "inherit") return [];
5306
+ if (!Array.isArray(value)) return [`${where} must be "admin-only", "inherit" or a list of rules.`];
5307
+ if (value.length === 0) return [`${where} is an empty list of rules, which leaves nobody a policy. Send "admin-only" instead.`];
5308
+ return value.flatMap((rule, index) => isRecord(rule) ? [] : [`${where}[${index}] must be a rule object.`]);
5309
+ }
5310
+ /** Problems with a table-level option's value. */
5311
+ function optionProblems(option, value, where) {
5312
+ if (value === null) return [];
5313
+ switch (option) {
5314
+ case "description": return typeof value === "string" ? [] : [`${where} must be a string.`];
5315
+ case "history": return typeof value === "boolean" ? [] : [`${where} must be a boolean.`];
5316
+ case "defaultPolicies": return typeof value === "boolean" ? [] : [`${where} must be a boolean (or \`null\` to remove it).`];
5317
+ case "strictWrites": return value === false ? [] : [`${where} can only be \`false\` (or \`null\` to remove it).`];
5318
+ case "softDelete": return typeof value === "boolean" || isRecord(value) ? [] : [`${where} must be a boolean or \`{ field }\`.`];
5319
+ case "tenant": return isRecord(value) && typeof value.field === "string" && isRecord(value.from) ? [] : [`${where} must be \`{ field, from }\`.`];
5320
+ case "search":
5321
+ case "metadata": return isRecord(value) ? [] : [`${where} must be an object.`];
5322
+ case "indexes": return Array.isArray(value) && value.every(isRecord) ? [] : [`${where} must be a list of indexes.`];
5323
+ }
5324
+ }
5325
+ var isOptionKey = (value) => typeof value === "string" && TABLE_OPTION_KEYS.includes(value);
5326
+ var isIndex = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
5327
+ /** The problems of one operation. */
5328
+ function operationProblems(value, index) {
5329
+ if (!isRecord(value)) return [{
5330
+ index,
5331
+ table: "",
5332
+ message: "an edit must be an object with an `op`."
5333
+ }];
5334
+ const table = typeof value.table === "string" ? value.table : "";
5335
+ const problem = (message, key) => ({
5336
+ index,
5337
+ table,
5338
+ ...key !== void 0 ? { key } : {},
5339
+ message
5340
+ });
5341
+ const op = value.op;
5342
+ if (op === "createTable") {
5343
+ const spec = value.table;
5344
+ if (!isRecord(spec)) return [{
5345
+ index,
5346
+ table: "",
5347
+ message: "`table` must describe the new table: `{ name, columns, rls }`."
5348
+ }];
5349
+ const name = typeof spec.name === "string" ? spec.name : "";
5350
+ const out = [];
5351
+ const at = (message, key) => {
5352
+ out.push({
5353
+ index,
5354
+ table: name,
5355
+ ...key !== void 0 ? { key } : {},
5356
+ message
5357
+ });
5358
+ };
5359
+ if (!SQL_IDENTIFIER.test(name)) at("`name` must be a SQL identifier: it names the table and its file.");
5360
+ for (const key of [
5361
+ "slug",
5362
+ "table",
5363
+ "schema"
5364
+ ]) {
5365
+ const named = spec[key];
5366
+ if (named !== void 0 && (typeof named !== "string" || !SQL_IDENTIFIER.test(named))) at(`\`${key}\` must be a SQL identifier.`, key);
5367
+ }
5368
+ if (!isRecord(spec.columns) || Object.keys(spec.columns).length === 0) at("`columns` must declare at least one column (one of them `primaryKey`).");
5369
+ else for (const [key, column] of Object.entries(spec.columns)) {
5370
+ if (!isRowKey(key)) at("a column key must be a non-empty string.", key);
5371
+ for (const message of columnProblems(column, `columns.${key}`)) at(message, key);
5372
+ }
5373
+ if (spec.relations !== void 0) if (!isRecord(spec.relations)) at("`relations` must map relation names to relations.");
5374
+ else for (const [key, relation] of Object.entries(spec.relations)) for (const message of relationProblems(relation, `relations.${key}`)) at(message, key);
5375
+ for (const message of rlsProblems(spec.rls, "rls")) at(message, "rls");
5376
+ for (const option of TABLE_OPTION_KEYS) {
5377
+ if (spec[option] === void 0) continue;
5378
+ for (const message of optionProblems(option, spec[option], option)) at(message, option);
5379
+ }
5380
+ const known = /* @__PURE__ */ new Set([
5381
+ "name",
5382
+ "slug",
5383
+ "table",
5384
+ "schema",
5385
+ "columns",
5386
+ "relations",
5387
+ "rls",
5388
+ ...TABLE_OPTION_KEYS
5389
+ ]);
5390
+ for (const key of Object.keys(spec)) if (!known.has(key)) at(`\`${key}\` is not something the schema editor writes${key === "hooks" ? ": hooks are code, write them in the file" : ""}.`, key);
5391
+ return out;
5392
+ }
5393
+ if (op === "adoptTable") {
5394
+ const spec = value.table;
5395
+ if (!isRecord(spec)) return [{
5396
+ index,
5397
+ table: "",
5398
+ message: "`table` must be the description of the table to adopt, as `GET …/unmapped-tables/:schema/:table` serves it."
5399
+ }];
5400
+ const name = typeof spec.slug === "string" ? spec.slug : "";
5401
+ return adoptedTableProblems(spec).map((found) => ({
5402
+ index,
5403
+ table: name,
5404
+ ...found.key !== void 0 ? { key: found.key } : {},
5405
+ message: found.message
5406
+ }));
5407
+ }
5408
+ if (table === "") return [problem("`table` must be the slug of the table to edit.")];
5409
+ switch (op) {
5410
+ case "deleteTable": return [];
5411
+ case "addColumn":
5412
+ case "changeColumn": {
5413
+ const out = [];
5414
+ const key = typeof value.key === "string" ? value.key : void 0;
5415
+ if (key === void 0 || !isRowKey(key)) out.push(problem("`key` must name the column."));
5416
+ for (const message of columnProblems(value.column, "column")) out.push(problem(message, key));
5417
+ if (op === "addColumn" && value.before !== void 0 && typeof value.before !== "string") out.push(problem("`before` must name a column.", key));
5418
+ return out;
5419
+ }
5420
+ case "renameColumn": {
5421
+ const out = [];
5422
+ const key = typeof value.key === "string" ? value.key : void 0;
5423
+ if (key === void 0) out.push(problem("`key` must name the column."));
5424
+ if (typeof value.to !== "string" || !isRowKey(value.to)) out.push(problem("`to` must be the column's new key.", key));
5425
+ for (const message of columnProblems(value.column, "column")) out.push(problem(message, key));
5426
+ return out;
5427
+ }
5428
+ case "removeColumn": return typeof value.key === "string" ? [] : [problem("`key` must name the column.")];
5429
+ case "moveColumn":
5430
+ if (typeof value.key !== "string") return [problem("`key` must name the column.")];
5431
+ return value.before === void 0 || typeof value.before === "string" ? [] : [problem("`before` must name a column.", value.key)];
5432
+ case "addRelation":
5433
+ case "changeRelation": {
5434
+ const name = typeof value.name === "string" ? value.name : void 0;
5435
+ return [...name === void 0 || !isRowKey(name) ? [problem("`name` must name the relation.")] : [], ...relationProblems(value.relation, "relation").map((message) => problem(message, name))];
5436
+ }
5437
+ case "removeRelation": return typeof value.name === "string" ? [] : [problem("`name` must name the relation.")];
5438
+ case "setRls": return rlsProblems(value.rls, "rls").map((message) => problem(message, "rls"));
5439
+ case "addRule": return [...isRecord(value.rule) ? [] : [problem("`rule` must be a rule object.", "rls")], ...value.index === void 0 || isIndex(value.index) ? [] : [problem("`index` must be a position in the rules.", "rls")]];
5440
+ case "replaceRule": return [...isRecord(value.rule) ? [] : [problem("`rule` must be a rule object.", "rls")], ...isIndex(value.index) ? [] : [problem("`index` must be a position in the rules.", "rls")]];
5441
+ case "removeRule": return isIndex(value.index) ? [] : [problem("`index` must be a position in the rules.", "rls")];
5442
+ case "setOption": {
5443
+ const option = value.option;
5444
+ if (typeof option === "string" && option in MIGRATION_KEYS) return [problem(MIGRATION_KEYS[option], option)];
5445
+ if (option === "hooks") return [problem("hooks are code: write them in the table's file.", option)];
5446
+ if (!isOptionKey(option)) return [problem(`\`option\` must be one of ${TABLE_OPTION_KEYS.join(", ")}.`, typeof option === "string" ? option : void 0)];
5447
+ if (!("value" in value)) return [problem("`value` is required: the new value, or `null` to remove the key.", option)];
5448
+ return optionProblems(option, value.value, "value").map((message) => problem(message, option));
5449
+ }
5450
+ default: return [problem(`\`op\` ${JSON.stringify(op)} is not a schema edit. Send one of createTable, adoptTable, deleteTable, addColumn, changeColumn, renameColumn, removeColumn, moveColumn, addRelation, changeRelation, removeRelation, setRls, addRule, replaceRule, removeRule, setOption.`)];
5451
+ }
5452
+ }
5453
+ /**
5454
+ * Every problem with a list of table edits as it arrived, in operation order.
5455
+ * Empty when the list is well formed — which says nothing about whether the
5456
+ * result compiles: the server compiles it before writing anything.
5457
+ *
5458
+ * @group Schema
5459
+ */
5460
+ function tablePatchProblems(value) {
5461
+ if (!Array.isArray(value)) return [{
5462
+ index: 0,
5463
+ table: "",
5464
+ message: "`patches` must be a list of schema edits."
5465
+ }];
5466
+ if (value.length === 0) return [{
5467
+ index: 0,
5468
+ table: "",
5469
+ message: "`patches` is empty: there is nothing to edit."
5470
+ }];
5471
+ return value.flatMap((operation, index) => operationProblems(operation, index));
5472
+ }
5473
+ /**
5474
+ * Whether a value is a well-formed list of {@link TablePatch} operations.
5475
+ *
5476
+ * @group Schema
5477
+ */
5478
+ function isTablePatchList(value) {
5479
+ return tablePatchProblems(value).length === 0;
5480
+ }
5481
+ /**
5482
+ * A list of edits as it arrived, checked: the list, or a
5483
+ * {@link TablePatchError} naming every problem.
5484
+ *
5485
+ * @group Schema
5486
+ */
5487
+ function parseTablePatches(value) {
5488
+ if (isTablePatchList(value)) return value;
5489
+ throw new TablePatchError(tablePatchProblems(value));
5490
+ }
5491
+ /**
5492
+ * The column definition a {@link WireColumnDef} stands for, the flags it left
5493
+ * out `false`.
5494
+ *
5495
+ * @group Schema
5496
+ */
5497
+ function columnDefFromWire(column) {
5498
+ const { element, json, notNull, primaryKey, unique, readOnly, private: isPrivate, ...rest } = column;
5499
+ const def = {
5500
+ ...rest,
5501
+ notNull: notNull === true,
5502
+ primaryKey: primaryKey === true,
5503
+ unique: unique === true,
5504
+ readOnly: readOnly === true,
5505
+ private: isPrivate === true
5506
+ };
5507
+ if (element !== void 0) def.element = columnDefFromWire(element);
5508
+ if (json !== void 0) def.json = json;
5509
+ return def;
5510
+ }
5511
+ /** Deep equality of JSON-like values: what a rule read from the wire is compared by. */
5512
+ function sameValue(a, b) {
5513
+ if (a === b) return true;
5514
+ if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => sameValue(item, b[i]));
5515
+ if (!isRecord(a) || !isRecord(b)) return false;
5516
+ const keys = Object.keys(a).filter((key) => a[key] !== void 0);
5517
+ const otherKeys = Object.keys(b).filter((key) => b[key] !== void 0);
5518
+ return keys.length === otherKeys.length && keys.every((key) => sameValue(a[key], b[key]));
5519
+ }
5520
+ /**
5521
+ * The rule operations that turn one list of rules into another, touching only
5522
+ * the rules that changed.
5523
+ *
5524
+ * A policy's name is a hash of its rule as written, so an editor that sends
5525
+ * the whole list back (one `setRls`) would rewrite every rule's text and risk
5526
+ * renaming policies it never changed. This pairs the lists by position: an
5527
+ * equal rule is left alone, a different one is replaced, a longer list adds
5528
+ * rules and a shorter one removes from the end. Positions are those of the
5529
+ * list as it is when each operation runs.
5530
+ *
5531
+ * @group Schema
5532
+ */
5533
+ function rulePatches(table, before, after) {
5534
+ const out = [];
5535
+ const shared = Math.min(before.length, after.length);
5536
+ for (let index = 0; index < shared; index++) if (!sameValue(before[index], after[index])) out.push({
5537
+ op: "replaceRule",
5538
+ table,
5539
+ index,
5540
+ rule: after[index]
5541
+ });
5542
+ for (let index = shared; index < after.length; index++) out.push({
5543
+ op: "addRule",
5544
+ table,
5545
+ rule: after[index],
5546
+ index
5547
+ });
5548
+ for (let index = before.length - 1; index >= after.length; index--) out.push({
5549
+ op: "removeRule",
5550
+ table,
5551
+ index
5552
+ });
5553
+ return out;
5554
+ }
5555
+ //#endregion
5556
+ export { ADMIN_ROLE, ADMIN_SCOPES, AGGREGATE_FUNCTIONS, AGGREGATE_GROUP_TRANSFORMS, ALL_WHERE_FILTER_OPS, ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, AUTH_FLOW_HEADER, BATCH_REF_KEY, BUILT_IN_SCOPES, BUILT_IN_SCOPE_DESCRIPTIONS, BUNDLE_FORMAT_VERSION, CANONICAL_TO_REST, COLUMN_BRAND, ColumnBuilder, DATA_PLANE_SCOPES, DEFAULT_CAPABILITIES, DEFAULT_COMMIT_PATHS, DEFAULT_DATA_SOURCE_KEY, DEFAULT_FILTERABLE_RELATION_KINDS, DEFAULT_FUZZY_THRESHOLD, DEFAULT_LIST_LIMIT, DEFAULT_RESOURCE_KEY, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, DEFAULT_STORAGE_SOURCE_KEY, DEFAULT_TENANT_BYPASS_ROLES, DEFAULT_VECTOR_LIST_LIMIT, EMPTY_ACCESS_MODEL, FIELDLESS_AGGREGATES, FIELD_OPERATORS, FIREBASE_CAPABILITIES, IMPERSONATE_HEADER, INCLUDE_COUNT_KEY, JSON_FIELD_BRAND, JUNCTION_PIVOT_KEY, JsonField, KEY_MANAGEMENT_SCOPES, LEGACY_LAYOUT_REMEDY, LEGACY_RLS_JWT_SQL, LEGACY_RLS_ROLES_SQL, LEGACY_RLS_SCHEMA, LEGACY_RLS_UID_SQL, LEGACY_SCHEMA_VERSION_PREFIX, LIST_OPS, ListLimitError, MAX_INCLUDE_DEPTH, MAX_LIST_LIMIT, MCP_APP_MODULES, NULL_OPS, POLICY_EXPRESSION_KINDS, POSTGRES_CAPABILITIES, PUBLIC_STORAGE_PREFIX, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, REBASE_SCHEMA, RELATION_BRAND, RELEVANCE_SORT_FIELD, RESERVED_BACKEND_PREFIXES, RESOURCE_GRAPH_VERSION, REST_TO_CANONICAL, RLS_IS_ANONYMOUS_SQL, RLS_IS_REQUEST_ROLE_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, RUNTIME_CONTRACT_VERSION, RebaseApiError, RebaseClientError, SCHEMA_VERSION_HEADER, SCOPE_TARGETS, SIMULATED_CONTEXT_HEADER, SIMULATE_API_KEY_ID_HEADER, SIMULATE_ROLE_HEADER, SIMULATE_USER_ID_HEADER, STORAGE_REFERENCE_SCHEME, TABLE_BRAND, TABLE_OPTION_KEYS, TablePatchError, UI_PREFERENCE_FIELD_KEYS, UI_PREFERENCE_TABLE_KEYS, VIEW_BRAND, adminRequestRoleFor, aggregateAlias, aggregateGroupKey, amendResourceKind, bucket, buildResourceGraph, canonicalSchemaPayload, col, columnDefFromWire, columnTypeLabel, computeSchemaVersion, database, declareCron, declareFunction, declareResource, declaredDataSources, declaredDatabaseExtensions, declaredDatabaseRls, declaredQueueConsumers, declaredResources, declaredRlsPolicyShape, declaredStorageSources, declaredSubscriptions, defineAuthTable, defineTable, defineView, describeJsonShape, describeScope, encodeRelationAggregateSort, envBasesForResource, findEnvSuffixCollision, findStorageSuffixCollision, formatSimulatedContext, getDataSourceCapabilities, hasAdminRole, hasFieldOperation, holdsAdminRole, intersectScopes, isAdminScope, isAnonymousUid, isAuthTableDef, isBranchAdmin, isBuiltInScope, isChannelBusInstance, isColumnBuilder, isContentHashedFileName, isDataPlaneScope, isFieldOperation, isJsonColumnType, isJsonField, isNumericColumnType, isPercentileFraction, isPolicyExpressionKind, isPolicyShorthand, isPublicStorageKey, isPublicStoragePath, isRedactedSecurityRule, isRelationAggregateSort, isRelationDef, isResourceHandle, isSQLAdmin, isSchemaAdmin, isSchemaEditingAdmin, isSqlTemplate, isStorageReference, isTableDef, isTablePatchList, isTemporalColumnType, isTenantClaimSource, isTenantMembershipSource, isTextColumnType, isTimeZoneName, isUiTablePreferences, isUnsupported, isValidAppHost, isValidEngine, isViewDef, joinConditions, json, knownScopes, mergeUiTablePreferences, normalizeColumnAccess, normalizeStorage, normalizeValidation, parseAppAddress, parseByteSize, parseCaseFoldedFieldPath, parseEnvBoolean, parseRelationAggregateSort, parseScope, parseSimulatedContext, parseStorageReference, parseTablePatches, pgEnum, policy, queue, registerDataSourceCapabilities, registerResourceKind, rel, reservedPrefixFor, resetDeclaredQueueConsumers, resetDeclaredResources, resetDeclaredSubscriptions, resolveClientListLimit, resolveResourceRefs, resolveStorageReferences, resourceEnvSuffix, resourceId, resourceKeyOf, resourceKind, resourceKinds, resourceToDataSource, resourceToStorageSource, rewriteLegacyRlsFunctions, roleNameProblem, rulePatches, scopeAcceptsTarget, scopeGrants, scopeGrantsAny, scopeTargets, scopesBeyond, scopesForRoles, setQueueRuntime, setTopicRuntime, simulationHeaders, soleJoinCondition, sortKeyToString, sql, storageEnvSuffix, storageObjectPath, storageReference, storageReferencesForDownloadUrls, storageTargetOfDownloadUrl, storageTargetsInText, summarizeRoles, summarizeScopes, tablePatchProblems, toCanonicalOp, toDriverAggregate, toDriverAggregateGroup, topic, uiTablePreferencesProblems, unsupportedMethod, usesLegacyRlsFunctions, validateScopes };
4141
5557
 
4142
5558
  //# sourceMappingURL=index.es.js.map