@rebasepro/server-postgres 0.11.1-canary.gfd39654 → 0.12.1-canary.g06f263c

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 (66) hide show
  1. package/dist/PostgresBootstrapper.d.ts +33 -1
  2. package/dist/auth/services.d.ts +16 -0
  3. package/dist/backup-service-vAKWJkYL.js +8867 -0
  4. package/dist/backup-service-vAKWJkYL.js.map +1 -0
  5. package/dist/cli-helpers.d.ts +24 -0
  6. package/dist/collections/buildRegistry.d.ts +1 -1
  7. package/dist/connection-BuZ97wsr.js +250 -0
  8. package/dist/connection-BuZ97wsr.js.map +1 -0
  9. package/dist/connection.d.ts +42 -0
  10. package/dist/ensure-collection-policies-BjSwj0FM.js +57 -0
  11. package/dist/ensure-collection-policies-BjSwj0FM.js.map +1 -0
  12. package/dist/ensure-collection-tables-D6-XhqnQ.js +590 -0
  13. package/dist/ensure-collection-tables-D6-XhqnQ.js.map +1 -0
  14. package/dist/history/HistoryService.d.ts +9 -29
  15. package/dist/index.es.js +965 -9705
  16. package/dist/index.es.js.map +1 -1
  17. package/dist/policy-CeA1JcxP.js +105 -0
  18. package/dist/policy-CeA1JcxP.js.map +1 -0
  19. package/dist/schema/auth-schema.d.ts +83 -144
  20. package/dist/schema/dynamic-tables.d.ts +1 -1
  21. package/dist/schema/ensure-collection-policies.d.ts +60 -0
  22. package/dist/schema/ensure-collection-tables.d.ts +24 -2
  23. package/dist/schema/generate-postgres-ddl-logic.d.ts +116 -1
  24. package/dist/schema/introspect-runtime.d.ts +1 -1
  25. package/dist/services/FetchService.d.ts +36 -1
  26. package/dist/services/row-pipeline.d.ts +3 -1
  27. package/dist/{src-3VmUJ8Xn.js → src-C_NHNVW2.js} +288 -168
  28. package/dist/src-C_NHNVW2.js.map +1 -0
  29. package/dist/{src-D5xBTl32.js → src-DoU9yPqq.js} +79 -189
  30. package/dist/src-DoU9yPqq.js.map +1 -0
  31. package/dist/utils/drizzle-conditions.d.ts +157 -3
  32. package/dist/utils/pg-error-utils.d.ts +25 -3
  33. package/dist/websocket-DB7TbFPT.js +529 -0
  34. package/dist/websocket-DB7TbFPT.js.map +1 -0
  35. package/package.json +14 -14
  36. package/src/PostgresAdapter.ts +14 -0
  37. package/src/PostgresBootstrapper.ts +212 -36
  38. package/src/auth/ensure-tables.ts +164 -9
  39. package/src/auth/services.ts +21 -2
  40. package/src/cli-helpers.ts +44 -0
  41. package/src/cli.ts +31 -3
  42. package/src/collections/buildRegistry.ts +1 -1
  43. package/src/connection.ts +73 -0
  44. package/src/databasePoolManager.ts +5 -2
  45. package/src/history/HistoryService.ts +13 -31
  46. package/src/schema/auth-schema.ts +30 -19
  47. package/src/schema/dynamic-tables.ts +1 -1
  48. package/src/schema/ensure-collection-policies.ts +105 -0
  49. package/src/schema/ensure-collection-tables.test.ts +105 -9
  50. package/src/schema/ensure-collection-tables.ts +142 -25
  51. package/src/schema/generate-drizzle-schema-logic.ts +26 -7
  52. package/src/schema/generate-postgres-ddl-logic.ts +335 -16
  53. package/src/schema/introspect-runtime.test.ts +56 -8
  54. package/src/schema/introspect-runtime.ts +32 -10
  55. package/src/services/FetchService.ts +79 -11
  56. package/src/services/RelationService.ts +38 -3
  57. package/src/services/realtimeService.ts +3 -3
  58. package/src/services/row-pipeline.ts +3 -1
  59. package/src/utils/drizzle-conditions.ts +509 -45
  60. package/src/utils/pg-error-utils.ts +98 -3
  61. package/src/websocket.ts +3 -3
  62. package/dist/chunk-DSJWtz9O.js +0 -40
  63. package/dist/ensure-collection-tables-DGMYK0fr.js +0 -304
  64. package/dist/ensure-collection-tables-DGMYK0fr.js.map +0 -1
  65. package/dist/src-3VmUJ8Xn.js.map +0 -1
  66. package/dist/src-D5xBTl32.js.map +0 -1
@@ -1,8 +1,61 @@
1
1
  import { createRequire as __createRequire } from "module";
2
2
  import "process";
3
3
  __createRequire(import.meta.url);
4
- import { r as __require, t as __commonJSMin } from "./chunk-DSJWtz9O.js";
5
- import { d as isPostgresCollectionConfig, f as NULL_OPS, h as EntityRelation, l as isManyToMany, m as toCanonicalOp, n as getDataSourceCapabilities, o as ANONYMOUS_USER_ID, p as REST_TO_CANONICAL, s as policy, u as getDeclaredSubcollections } from "./src-D5xBTl32.js";
4
+ import { l as __require, s as __commonJSMin } from "./connection-BuZ97wsr.js";
5
+ import { a as getDataSourceCapabilities, c as toCanonicalOp, n as isPostgresCollectionConfig, o as NULL_OPS, r as isRelationalCollectionConfig, s as REST_TO_CANONICAL, t as getDeclaredSubcollections } from "./src-DoU9yPqq.js";
6
+ import { n as ANONYMOUS_USER_IDS, r as policy, t as ANONYMOUS_USER_ID } from "./policy-CeA1JcxP.js";
7
+ //#region ../types/src/types/entities.ts
8
+ /**
9
+ * Class used to create a reference to a entity in a different path
10
+ */
11
+ var EntityRelation = class {
12
+ __type = "relation";
13
+ /**
14
+ * ID of the entity
15
+ */
16
+ id;
17
+ /**
18
+ * A string representing the path of the referenced document (relative
19
+ * to the root of the database).
20
+ */
21
+ path;
22
+ /**
23
+ * Pre-fetched data payload to eliminate N+1 queries.
24
+ * When present, clients can use this directly instead of fetching.
25
+ */
26
+ data;
27
+ constructor(id, path, data) {
28
+ this.id = id;
29
+ this.path = path;
30
+ this.data = data;
31
+ }
32
+ get pathWithId() {
33
+ return `${this.path}/${this.id}`;
34
+ }
35
+ isEntityReference() {
36
+ return false;
37
+ }
38
+ isEntityRelation() {
39
+ return true;
40
+ }
41
+ };
42
+ var Vector = class {
43
+ value;
44
+ constructor(value) {
45
+ this.value = value;
46
+ }
47
+ };
48
+ //#endregion
49
+ //#region ../types/src/types/relations.ts
50
+ /** @group Models */
51
+ function hasForeignKeyOnTarget(relation) {
52
+ return relation.kind === "hasOne" || relation.kind === "hasMany";
53
+ }
54
+ /** @group Models */
55
+ function isManyToMany(relation) {
56
+ return relation.kind === "manyToMany";
57
+ }
58
+ //#endregion
6
59
  //#region ../common/src/util/common.ts
7
60
  var DEFAULT_ONE_OF_TYPE = "type";
8
61
  var DEFAULT_ONE_OF_VALUE = "value";
@@ -1264,7 +1317,7 @@ function traverseValueProperty(inputValue, property, operation) {
1264
1317
  return value;
1265
1318
  }
1266
1319
  /**
1267
- * Create a lightweight relation stub for CMS views.
1320
+ * Create a lightweight relation stub for admin views.
1268
1321
  * Replaces inline `{ id, path, __type: "relation" }` object literals.
1269
1322
  */
1270
1323
  function createRelationRef(id, path) {
@@ -1527,7 +1580,7 @@ var _resolvedRelationsCache = /* @__PURE__ */ new WeakMap();
1527
1580
  function resolveCollectionRelations(collection) {
1528
1581
  const cached = _resolvedRelationsCache.get(collection);
1529
1582
  if (cached) return cached;
1530
- if (!getDataSourceCapabilities(collection.engine).supportsRelations) return {};
1583
+ if (!isRelationalCollectionConfig(collection)) return {};
1531
1584
  const relations = {};
1532
1585
  for (const relation of collection.relations ?? []) {
1533
1586
  const resolved = resolveRelation(relation, collection);
@@ -1543,7 +1596,7 @@ function resolveCollectionRelations(collection) {
1543
1596
  return relations;
1544
1597
  }
1545
1598
  function getTableName(collection) {
1546
- if (getDataSourceCapabilities(collection.engine).supportsRelations) return collection.table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
1599
+ if (isRelationalCollectionConfig(collection)) return collection.table ?? toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
1547
1600
  return toSnakeCase(collection.slug) ?? toSnakeCase(collection.name);
1548
1601
  }
1549
1602
  function getTableVarName(tableName) {
@@ -1811,7 +1864,12 @@ var UID_NOT_NULL = /auth\.uid\(\)\s+IS\s+NOT\s+NULL/i;
1811
1864
  * is how the trusted *server* context is recognised), so:
1812
1865
  *
1813
1866
  * - `auth.uid() IS NOT NULL` is a tautology on the user path, and
1814
- * - `auth.uid() != 'anon'` compares against a string no caller ever has.
1867
+ * - `auth.uid() != 'anon'` excludes one spelling of anonymous and admits the
1868
+ * other. This one is not hypothetical and was not only a foreign habit:
1869
+ * rebase's own request path reported `'anon'` while everything that compiled
1870
+ * or checked a policy used `'anonymous'`, so whichever literal an author
1871
+ * picked, half the anonymous callers walked through. See
1872
+ * {@link ANONYMOUS_USER_IDS}.
1815
1873
  *
1816
1874
  * Either one turns a lockdown into a full grant, and neither looks wrong. No
1817
1875
  * real user id is ever one of these literals, and a user-context request is
@@ -1849,7 +1907,7 @@ function findAnonymousGrants(expr) {
1849
1907
  found.push({
1850
1908
  pattern: "foreign-uid-literal",
1851
1909
  detail: literal.value,
1852
- explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for every caller. Use \`condition: policy.authenticated()\` to mean "signed in".`
1910
+ explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for every caller. Use \`condition: policy.authenticated()\` to mean "signed in" — it compiles to NOT IN (${ANONYMOUS_USER_IDS.map((v) => `'${v}'`).join(", ")}), covering every spelling rebase has reported rather than whichever one you remember.`
1853
1911
  });
1854
1912
  return;
1855
1913
  }
@@ -1944,7 +2002,7 @@ function compile(expr, scope) {
1944
2002
  }
1945
2003
  case "rolesOverlap": return `string_to_array(auth.roles(), ',') && ${rolesArraySql(expr.roles)}`;
1946
2004
  case "rolesContain": return `string_to_array(auth.roles(), ',') @> ${rolesArraySql(expr.roles)}`;
1947
- case "authenticated": return `auth.uid() IS NOT NULL AND auth.uid() <> ${quoteLiteral(ANONYMOUS_USER_ID)}`;
2005
+ case "authenticated": return `auth.uid() IS NOT NULL AND auth.uid() NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral).join(", ")})`;
1948
2006
  case "serverContext": return "auth.uid() IS NULL";
1949
2007
  case "existsIn": return compileExistsIn(expr, scope);
1950
2008
  case "raw": return expr.sql.replace(/\{(\w+)\}/g, (_, col) => `${outerQualifier(scope)}${resolveColumnName(col, scope.outerCollection)}`);
@@ -2016,75 +2074,6 @@ function rolesArraySql(roles) {
2016
2074
  return `ARRAY[${[...roles].sort().map((r) => `'${r}'`).join(",")}]`;
2017
2075
  }
2018
2076
  //#endregion
2019
- //#region ../common/src/util/callbacks.ts
2020
- /**
2021
- * Helper function to recursively check if there are any callbacks in the properties.
2022
- */
2023
- function hasPropertyCallbacks(properties, callbackName) {
2024
- if (!properties) return false;
2025
- for (const property of Object.values(properties)) {
2026
- if (property.callbacks?.[callbackName]) return true;
2027
- if (property.type === "map" && property.properties) {
2028
- if (hasPropertyCallbacks(property.properties, callbackName)) return true;
2029
- } else if (property.type === "array" && property.of) {
2030
- const ofs = Array.isArray(property.of) ? property.of : [property.of];
2031
- for (const of of ofs) {
2032
- if (of.callbacks?.[callbackName]) return true;
2033
- if (of.type === "map" && of.properties && hasPropertyCallbacks(of.properties, callbackName)) return true;
2034
- }
2035
- }
2036
- }
2037
- return false;
2038
- }
2039
- /**
2040
- * Recursively process properties to apply field-level hooks.
2041
- */
2042
- async function processProperties(properties, values, previousValues, propsContext, callbackName) {
2043
- if (!values || typeof values !== "object") return values;
2044
- const result = { ...values };
2045
- for (const [key, property] of Object.entries(properties)) {
2046
- if (result[key] === void 0) continue;
2047
- let currentValue = result[key];
2048
- const previousValue = previousValues?.[key];
2049
- if (property.type === "array" && Array.isArray(currentValue)) {
2050
- if (property.of && !Array.isArray(property.of)) currentValue = await Promise.all(currentValue.map(async (item, index) => {
2051
- const prevItem = Array.isArray(previousValue) ? previousValue[index] : void 0;
2052
- return (await processProperties({ "_tmp": property.of }, { "_tmp": item }, { "_tmp": prevItem }, propsContext, callbackName))["_tmp"];
2053
- }));
2054
- } else if (property.type === "map" && property.properties && typeof currentValue === "object") currentValue = await processProperties(property.properties, currentValue, previousValue ?? {}, propsContext, callbackName);
2055
- if (property.callbacks?.[callbackName]) {
2056
- const cbRes = await Promise.resolve(property.callbacks[callbackName]({
2057
- ...propsContext,
2058
- value: currentValue,
2059
- previousValue
2060
- }));
2061
- if (cbRes !== void 0) currentValue = cbRes;
2062
- }
2063
- result[key] = currentValue;
2064
- }
2065
- return result;
2066
- }
2067
- /**
2068
- * Helper function to extract field-level PropertyCallbacks from a properties schema
2069
- * and wrap them into an CollectionCallbacks object recursively.
2070
- */
2071
- var buildPropertyCallbacks = (properties) => {
2072
- if (!properties) return void 0;
2073
- const propertyCallbacks = {};
2074
- if (hasPropertyCallbacks(properties, "afterRead")) propertyCallbacks.afterRead = async (props) => {
2075
- const row = props.row;
2076
- const processedValues = await processProperties(properties, row, row, props, "afterRead");
2077
- return {
2078
- ...props.row,
2079
- ...processedValues
2080
- };
2081
- };
2082
- if (hasPropertyCallbacks(properties, "beforeSave")) propertyCallbacks.beforeSave = async (props) => {
2083
- return await processProperties(properties, props.values, props.previousValues ?? {}, props, "beforeSave");
2084
- };
2085
- return Object.keys(propertyCallbacks).length > 0 ? propertyCallbacks : void 0;
2086
- };
2087
- //#endregion
2088
2077
  //#region ../common/src/util/auth-default-policies.ts
2089
2078
  /**
2090
2079
  * Default RLS policies injected by the schema generator.
@@ -2152,8 +2141,8 @@ function getIdPropertyName$1(collection) {
2152
2141
  * Collections that opt out via `disableDefaultPolicies` are returned unchanged.
2153
2142
  */
2154
2143
  function getEffectiveSecurityRules(collection) {
2155
- const explicit = [...(isPostgresCollectionConfig(collection) ? collection.securityRules : void 0) ?? []];
2156
- if (collection.disableDefaultPolicies) return explicit;
2144
+ const explicit = [...collection.securityRules ?? []];
2145
+ if (isPostgresCollectionConfig(collection) && collection.disableDefaultPolicies) return explicit;
2157
2146
  const tableName = getTableName(collection);
2158
2147
  const injected = [];
2159
2148
  injected.push({
@@ -2324,7 +2313,7 @@ function coversUpdate(rule) {
2324
2313
  * stays locked (RLS is still enabled) until they write policies for it.
2325
2314
  */
2326
2315
  function getJunctionSecurityRules(spec) {
2327
- if (spec.declaringSides.every((side) => side.collection.disableDefaultPolicies)) return [];
2316
+ if (spec.declaringSides.every((side) => isPostgresCollectionConfig(side.collection) && side.collection.disableDefaultPolicies)) return [];
2328
2317
  const rules = [];
2329
2318
  rules.push({
2330
2319
  name: `${spec.table}_default_admin_read`,
@@ -2659,10 +2648,27 @@ function getJunctionSecurityRules(spec) {
2659
2648
  });
2660
2649
  })))();
2661
2650
  /**
2662
- * Apply PropertyConditions to a resolved property, evaluating all JSON Logic rules.
2651
+ * How wide a `varchar`/`char` column should be for a given property.
2652
+ *
2653
+ * One definition, three call sites, because they used to disagree. For the same
2654
+ * `columnType: "varchar"` property the DDL generator emitted `VARCHAR(255)`
2655
+ * while the Drizzle generator emitted a bare `varchar("col")` — which Postgres
2656
+ * reads as *unbounded* — so which of the two you ran decided whether the column
2657
+ * had a limit at all. Introspection then dropped the length entirely, so reading
2658
+ * an existing `character varying(500)` column back and regenerating it produced
2659
+ * a `VARCHAR(255)`: a silent narrowing of a column with data already in it.
2660
+ *
2661
+ * `validation.max` is the property's own statement about how long the value may
2662
+ * be, so it is the only sensible source for the column's width — and it keeps
2663
+ * the constraint the database enforces in step with the one the app enforces,
2664
+ * rather than inventing a second, different limit underneath it.
2663
2665
  */
2666
+ function resolveStringColumnLength(prop) {
2667
+ const max = prop.validation?.max;
2668
+ return typeof max === "number" && Number.isInteger(max) && max > 0 ? max : 255;
2669
+ }
2664
2670
  //#endregion
2665
- //#region ../../node_modules/.pnpm/fast-equals@6.0.0/node_modules/fast-equals/dist/es/index.mjs
2671
+ //#region ../../node_modules/.pnpm/fast-equals@6.0.2/node_modules/fast-equals/dist/es/index.mjs
2666
2672
  var { getOwnPropertyNames, getOwnPropertySymbols } = Object;
2667
2673
  var { hasOwnProperty } = Object.prototype;
2668
2674
  /**
@@ -2698,7 +2704,8 @@ function createIsCircular(areItemsEqual) {
2698
2704
  * not enumerable and symbol properties.
2699
2705
  */
2700
2706
  function getStrictProperties(object) {
2701
- return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object));
2707
+ const symbols = getOwnPropertySymbols(object);
2708
+ return symbols.length ? getOwnPropertyNames(object).concat(symbols) : getOwnPropertyNames(object);
2702
2709
  }
2703
2710
  /**
2704
2711
  * Whether the object contains the property passed as an own property.
@@ -2771,7 +2778,7 @@ function areMapsEqual(a, b, state) {
2771
2778
  const size = a.size;
2772
2779
  if (size !== b.size) return false;
2773
2780
  if (!size) return true;
2774
- const matchedIndices = new Array(size);
2781
+ const matchedIndices = new Uint8Array(size);
2775
2782
  const aIterable = a.entries();
2776
2783
  let aResult;
2777
2784
  let bResult;
@@ -2779,7 +2786,7 @@ function areMapsEqual(a, b, state) {
2779
2786
  while (aResult = aIterable.next()) {
2780
2787
  if (aResult.done) break;
2781
2788
  const bIterable = b.entries();
2782
- let hasMatch = false;
2789
+ let hasMatch = 0;
2783
2790
  let matchIndex = 0;
2784
2791
  while (bResult = bIterable.next()) {
2785
2792
  if (bResult.done) break;
@@ -2790,7 +2797,7 @@ function areMapsEqual(a, b, state) {
2790
2797
  const aEntry = aResult.value;
2791
2798
  const bEntry = bResult.value;
2792
2799
  if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state) && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) {
2793
- hasMatch = matchedIndices[matchIndex] = true;
2800
+ hasMatch = matchedIndices[matchIndex] = 1;
2794
2801
  break;
2795
2802
  }
2796
2803
  matchIndex++;
@@ -2848,19 +2855,19 @@ function areSetsEqual(a, b, state) {
2848
2855
  const size = a.size;
2849
2856
  if (size !== b.size) return false;
2850
2857
  if (!size) return true;
2851
- const matchedIndices = new Array(size);
2858
+ const matchedIndices = new Uint8Array(size);
2852
2859
  const aIterable = a.values();
2853
2860
  let aResult;
2854
2861
  let bResult;
2855
2862
  while (aResult = aIterable.next()) {
2856
2863
  if (aResult.done) break;
2857
2864
  const bIterable = b.values();
2858
- let hasMatch = false;
2865
+ let hasMatch = 0;
2859
2866
  let matchIndex = 0;
2860
2867
  while (bResult = bIterable.next()) {
2861
2868
  if (bResult.done) break;
2862
2869
  if (!matchedIndices[matchIndex] && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) {
2863
- hasMatch = matchedIndices[matchIndex] = true;
2870
+ hasMatch = matchedIndices[matchIndex] = 1;
2864
2871
  break;
2865
2872
  }
2866
2873
  matchIndex++;
@@ -2873,8 +2880,8 @@ function areSetsEqual(a, b, state) {
2873
2880
  * Whether the TypedArray instances are equal in value.
2874
2881
  */
2875
2882
  function areTypedArraysEqual(a, b) {
2876
- let index = a.byteLength;
2877
- if (b.byteLength !== index || a.byteOffset !== b.byteOffset) return false;
2883
+ let index = a.length;
2884
+ if (b.length !== index || a.byteOffset !== b.byteOffset) return false;
2878
2885
  while (index-- > 0) if (a[index] !== b[index]) return false;
2879
2886
  return true;
2880
2887
  }
@@ -3444,6 +3451,136 @@ var QueryBuilder = class {
3444
3451
  return this.collection.listen(this.params, onUpdate, onError);
3445
3452
  }
3446
3453
  };
3454
+ /** Rows `findAll()` will materialise before it refuses to continue. */
3455
+ var DEFAULT_FIND_ALL_MAX_ROWS = 1e4;
3456
+ /**
3457
+ * Requests one walk may make before it gives up on the server ever saying
3458
+ * `hasMore: false`. At the default page size that is two million rows — far
3459
+ * past any legitimate walk, and short of running forever.
3460
+ */
3461
+ var DEFAULT_MAX_PAGES = 1e4;
3462
+ /**
3463
+ * Thrown when a walk stops for a reason the caller needs to know about.
3464
+ *
3465
+ * Every one of these is a case where the alternative would be silent: a
3466
+ * truncated array that looks complete, or a loop that never returns. Check
3467
+ * {@link code} to tell them apart.
3468
+ */
3469
+ var RebasePaginationError = class RebasePaginationError extends Error {
3470
+ code;
3471
+ constructor(code, message) {
3472
+ super(message);
3473
+ this.name = "RebasePaginationError";
3474
+ this.code = code;
3475
+ Object.setPrototypeOf(this, RebasePaginationError.prototype);
3476
+ }
3477
+ };
3478
+ function normalizePageSize(raw) {
3479
+ if (raw === void 0 || !Number.isFinite(raw)) return 200;
3480
+ return Math.max(1, Math.floor(raw));
3481
+ }
3482
+ function normalizeMaxPages(raw) {
3483
+ if (raw === void 0) return DEFAULT_MAX_PAGES;
3484
+ if (raw === Number.POSITIVE_INFINITY) return raw;
3485
+ if (!Number.isFinite(raw)) return DEFAULT_MAX_PAGES;
3486
+ return Math.max(1, Math.floor(raw));
3487
+ }
3488
+ function normalizeMaxRows(raw) {
3489
+ if (raw === void 0) return DEFAULT_FIND_ALL_MAX_ROWS;
3490
+ if (raw === Number.POSITIVE_INFINITY) return raw;
3491
+ if (!Number.isFinite(raw)) return DEFAULT_FIND_ALL_MAX_ROWS;
3492
+ return Math.max(0, Math.floor(raw));
3493
+ }
3494
+ /**
3495
+ * Add one condition to a `where` map without disturbing what is already there.
3496
+ *
3497
+ * The caller's own filter on the cursor column has to survive — dropping it
3498
+ * would widen the query, which is the silent-filter-loss failure mode — so a
3499
+ * second condition on the same column becomes the array-of-tuples form that
3500
+ * `FindParams.where` already accepts, and both are AND-ed.
3501
+ */
3502
+ function appendCondition(where, column, condition) {
3503
+ const next = { ...where ?? {} };
3504
+ const existing = next[column];
3505
+ if (existing === void 0) next[column] = condition;
3506
+ else if (Array.isArray(existing) && existing.length > 0 && Array.isArray(existing[0])) next[column] = [...existing, condition];
3507
+ else next[column] = [existing, condition];
3508
+ return next;
3509
+ }
3510
+ function cursorEquals(a, b) {
3511
+ if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
3512
+ return Object.is(a, b);
3513
+ }
3514
+ /**
3515
+ * Walk every row a query matches, yielding one row at a time and fetching the
3516
+ * next page only when the consumer asks for it.
3517
+ *
3518
+ * See {@link SDKCollectionClient.iterate} for the caller-facing contract,
3519
+ * including the offset-drift caveat and the `cursor` alternative.
3520
+ *
3521
+ * @param find the transport's single-page read
3522
+ * @param params `find()` parameters minus the window, plus the walk options
3523
+ * @param label the collection name, so an error says which walk failed
3524
+ */
3525
+ async function* paginateFind(find, params, label = "collection") {
3526
+ const { pageSize, cursor, maxPages, ...rest } = params ?? {};
3527
+ const findParams = { ...rest };
3528
+ const size = normalizePageSize(pageSize);
3529
+ const pageCap = normalizeMaxPages(maxPages);
3530
+ const cursorField = typeof cursor === "string" ? cursor : cursor?.field;
3531
+ const requestedDirection = typeof cursor === "object" && cursor !== null ? cursor.direction : void 0;
3532
+ let direction = "asc";
3533
+ if (cursorField) {
3534
+ const orderBy = findParams.orderBy;
3535
+ if (orderBy && orderBy[0] !== cursorField) throw new RebasePaginationError("cursor-order-mismatch", `Cannot seek on "${cursorField}" while ordering "${label}" by "${orderBy[0]}": keyset pagination only advances along the column the query is sorted by. Order by "${cursorField}", or drop the cursor and page by offset.`);
3536
+ direction = requestedDirection ?? orderBy?.[1] ?? "asc";
3537
+ findParams.orderBy = [cursorField, direction];
3538
+ }
3539
+ const seekOp = direction === "desc" ? "<" : ">";
3540
+ const baseWhere = findParams.where;
3541
+ let offset = 0;
3542
+ let pages = 0;
3543
+ let cursorValue;
3544
+ let seeking = false;
3545
+ for (;;) {
3546
+ if (pages >= pageCap) throw new RebasePaginationError("max-pages", `Iterating "${label}" made ${pages} requests without the server reporting the end of the collection. Stopping rather than looping forever — raise \`maxPages\` if the walk is genuinely this long, or check that the backend sets \`meta.hasMore\`.`);
3547
+ const pageParams = {
3548
+ ...findParams,
3549
+ limit: size
3550
+ };
3551
+ if (cursorField) {
3552
+ if (seeking) pageParams.where = appendCondition(baseWhere, cursorField, [seekOp, cursorValue]);
3553
+ } else pageParams.offset = offset;
3554
+ const page = await find(pageParams);
3555
+ pages += 1;
3556
+ const rows = page?.data ?? [];
3557
+ if (rows.length === 0) return;
3558
+ for (const row of rows) yield row;
3559
+ if (page?.meta?.hasMore !== true) return;
3560
+ if (cursorField) {
3561
+ const nextValue = rows[rows.length - 1]?.[cursorField];
3562
+ if (nextValue === void 0 || nextValue === null) throw new RebasePaginationError("cursor-missing", `Cannot seek past the last row of "${label}": it has no value for the cursor column "${cursorField}". Pick a column that is present and non-null on every row.`);
3563
+ if (seeking && cursorEquals(nextValue, cursorValue)) throw new RebasePaginationError("cursor-stalled", `Iterating "${label}" is stuck: two pages in a row ended at ${cursorField}=${String(nextValue)}. The cursor column has to be unique — a repeated value cannot be seeked past, and continuing would either loop forever or skip the duplicates. Use the primary key, or page by offset.`);
3564
+ cursorValue = nextValue;
3565
+ seeking = true;
3566
+ } else offset += rows.length;
3567
+ }
3568
+ }
3569
+ /**
3570
+ * {@link paginateFind}, collected into an array under a ceiling.
3571
+ *
3572
+ * See {@link SDKCollectionClient.findAll}.
3573
+ */
3574
+ async function collectAllPages(find, params, label = "collection") {
3575
+ const { maxRows, ...rest } = params ?? {};
3576
+ const cap = normalizeMaxRows(maxRows);
3577
+ const out = [];
3578
+ for await (const row of paginateFind(find, rest, label)) {
3579
+ out.push(row);
3580
+ if (out.length > cap) throw new RebasePaginationError("max-rows", `findAll("${label}") matched more than ${cap} rows. Returning the first ${cap} would look like the whole answer and quietly not be one, so this throws instead. Raise \`maxRows\` if you meant to load them all, or stream with \`iterate()\`.`);
3581
+ }
3582
+ return out;
3583
+ }
3447
3584
  //#endregion
3448
3585
  //#region ../common/src/data/filter-dialect.ts
3449
3586
  /**
@@ -3593,6 +3730,42 @@ function rowToEntity(row, slug, primaryKeys = []) {
3593
3730
  values: row
3594
3731
  };
3595
3732
  }
3733
+ /**
3734
+ * The relation envelope `toCmsRow` writes where a relation was:
3735
+ * `{ id, path, __type: "relation", data: { id, path, values } }`. It is the
3736
+ * admin's view-model, and the only pipeline that produces one is postgres'.
3737
+ */
3738
+ function isRelationEnvelope(value) {
3739
+ return typeof value === "object" && value !== null && !Array.isArray(value) && value.__type === "relation";
3740
+ }
3741
+ /** The target's own columns, as `toRestRow` would have inlined them. */
3742
+ function inlineEnvelope(envelope) {
3743
+ return envelope.data?.values ?? {};
3744
+ }
3745
+ /**
3746
+ * Replace every relation envelope on a row with the target's flat columns.
3747
+ *
3748
+ * The SDK serves one relation shape — the inlined one (see
3749
+ * {@link RestFetchService}) — and reads that come back through a *driver*
3750
+ * method rather than the REST pipeline still carry envelopes. Realtime is the
3751
+ * one such read left: there is no `listenForRest`, so the rows arrive shaped
3752
+ * for the admin and are flattened here instead.
3753
+ *
3754
+ * Only applied where the REST pipeline is the contract (see `find`); a driver
3755
+ * without a `restFetchService` keeps whatever it returns, so the admin's own
3756
+ * path through {@link buildRebaseData} is untouched.
3757
+ */
3758
+ function inlineRelationRefs(row) {
3759
+ let out;
3760
+ for (const [key, value] of Object.entries(row)) if (isRelationEnvelope(value)) {
3761
+ out = out ?? { ...row };
3762
+ out[key] = inlineEnvelope(value);
3763
+ } else if (Array.isArray(value) && value.some(isRelationEnvelope)) {
3764
+ out = out ?? { ...row };
3765
+ out[key] = value.map((item) => isRelationEnvelope(item) ? inlineEnvelope(item) : item);
3766
+ }
3767
+ return out ?? row;
3768
+ }
3596
3769
  function createDriverAccessor(driver, slug, getPks = () => []) {
3597
3770
  const accessor = {
3598
3771
  async find(params) {
@@ -3600,14 +3773,14 @@ function createDriverAccessor(driver, slug, getPks = () => []) {
3600
3773
  const limit = params?.limit ?? 20;
3601
3774
  const offset = params?.offset ?? 0;
3602
3775
  const fetchService = driver.restFetchService;
3603
- const rows = fetchService && params?.include && params.include.length > 0 ? await fetchService.fetchCollectionForRest(slug, {
3776
+ const rows = fetchService ? await fetchService.fetchCollectionForRest(slug, {
3604
3777
  filter,
3605
3778
  limit: params?.limit,
3606
3779
  offset: params?.offset,
3607
3780
  orderBy: params?.orderBy?.[0],
3608
3781
  order: params?.orderBy?.[1],
3609
3782
  searchString: params?.searchString
3610
- }, params.include) : await driver.fetchCollection({
3783
+ }, params?.include) : await driver.fetchCollection({
3611
3784
  path: slug,
3612
3785
  limit: params?.limit,
3613
3786
  offset: params?.offset,
@@ -3636,7 +3809,8 @@ function createDriverAccessor(driver, slug, getPks = () => []) {
3636
3809
  };
3637
3810
  },
3638
3811
  async findById(id) {
3639
- const row = await driver.fetchOne({
3812
+ const fetchService = driver.restFetchService;
3813
+ const row = fetchService ? await fetchService.fetchOneForRest(slug, id) : await driver.fetchOne({
3640
3814
  path: slug,
3641
3815
  id
3642
3816
  });
@@ -3682,6 +3856,7 @@ function createDriverAccessor(driver, slug, getPks = () => []) {
3682
3856
  listen: driver.listenCollection ? (params, onUpdate, onError) => {
3683
3857
  const limit = params?.limit ?? 20;
3684
3858
  const offset = params?.offset ?? 0;
3859
+ const normalize = driver.restFetchService ? inlineRelationRefs : (row) => row;
3685
3860
  return driver.listenCollection({
3686
3861
  path: slug,
3687
3862
  limit: params?.limit,
@@ -3692,7 +3867,7 @@ function createDriverAccessor(driver, slug, getPks = () => []) {
3692
3867
  searchString: params?.searchString,
3693
3868
  onUpdate: (entities) => {
3694
3869
  onUpdate({
3695
- data: entities.map((row) => rowToEntity(row, slug, getPks())),
3870
+ data: entities.map((row) => rowToEntity(normalize(row), slug, getPks())),
3696
3871
  meta: {
3697
3872
  total: entities.length,
3698
3873
  limit,
@@ -3705,10 +3880,11 @@ function createDriverAccessor(driver, slug, getPks = () => []) {
3705
3880
  });
3706
3881
  } : void 0,
3707
3882
  listenById: driver.listenOne ? (id, onUpdate, onError) => {
3883
+ const normalize = driver.restFetchService ? inlineRelationRefs : (row) => row;
3708
3884
  return driver.listenOne({
3709
3885
  path: slug,
3710
3886
  id,
3711
- onUpdate: (entity) => onUpdate(entity ? rowToEntity(entity, slug, getPks()) : void 0),
3887
+ onUpdate: (entity) => onUpdate(entity ? rowToEntity(normalize(entity), slug, getPks()) : void 0),
3712
3888
  onError
3713
3889
  });
3714
3890
  } : void 0,
@@ -3839,7 +4015,7 @@ var SdkQueryBuilder = class {
3839
4015
  * {@link SDKCollectionClient}. Every returned record is unwrapped to a flat row
3840
4016
  * so the backend SDK is byte-for-byte the same shape as the frontend client.
3841
4017
  */
3842
- function toSdkCollectionClient(snap) {
4018
+ function toSdkCollectionClient(snap, slug = "collection") {
3843
4019
  const client = {
3844
4020
  async find(params) {
3845
4021
  const res = await snap.find(params);
@@ -3848,6 +4024,12 @@ function toSdkCollectionClient(snap) {
3848
4024
  meta: res.meta
3849
4025
  };
3850
4026
  },
4027
+ iterate(params) {
4028
+ return paginateFind((p) => client.find(p), params, slug);
4029
+ },
4030
+ findAll(params) {
4031
+ return collectAllPages((p) => client.find(p), params, slug);
4032
+ },
3851
4033
  async findById(id) {
3852
4034
  const s = await snap.findById(id);
3853
4035
  return s ? entityToRow(s) : void 0;
@@ -3899,7 +4081,7 @@ function wrapAsSdkData(entityData) {
3899
4081
  function getAccessor(slug) {
3900
4082
  let accessor = cache.get(slug);
3901
4083
  if (!accessor) {
3902
- accessor = toSdkCollectionClient(entityData.collection(slug));
4084
+ accessor = toSdkCollectionClient(entityData.collection(slug), slug);
3903
4085
  cache.set(slug, accessor);
3904
4086
  }
3905
4087
  return accessor;
@@ -3916,79 +4098,17 @@ function wrapAsSdkData(entityData) {
3916
4098
  *
3917
4099
  * This is the developer-facing SDK data layer used by backend framework
3918
4100
  * callbacks & scripts (`context.data` / `rebase.data`). It returns flat rows —
3919
- * identical in shape to the frontend SDK client — so the API is symmetric
3920
- * across front and back. The admin CMS uses {@link buildRebaseData} (Entity).
4101
+ * identical in shape to the frontend SDK client, down to how a relation is
4102
+ * served: a foreign key stays a foreign key, and a relation named in `include`
4103
+ * arrives as the target's own columns. The `{ __type: "relation" }` envelope is
4104
+ * the admin's view-model and never reaches here.
4105
+ *
4106
+ * The admin uses {@link buildRebaseData} (Entity) over its own driver.
3921
4107
  */
3922
4108
  function buildSdkData(driver) {
3923
4109
  return wrapAsSdkData(buildRebaseData(driver));
3924
4110
  }
3925
4111
  //#endregion
3926
- //#region ../common/src/table-classification.ts
3927
- /** Schemas that are always considered Rebase-internal. */
3928
- var REBASE_INTERNAL_SCHEMAS = ["rebase", "auth"];
3929
- /** Table-name prefixes that mark a table as Rebase-internal regardless of schema. */
3930
- var REBASE_INTERNAL_PREFIXES = [
3931
- "_rebase_",
3932
- "_auth_",
3933
- "drizzle_"
3934
- ];
3935
- /**
3936
- * Synchronously classify a table based on naming conventions.
3937
- *
3938
- * @param tableName - The unqualified name of the table.
3939
- * @param schemaName - The schema the table belongs to (e.g. `"public"`, `"rebase"`).
3940
- * @returns `"rebase-internal"` when the table belongs to a reserved schema or
3941
- * carries a reserved prefix; `"user"` otherwise.
3942
- *
3943
- * @remarks
3944
- * Junction-table detection requires an async database query and is therefore
3945
- * **not** handled by this function. Use {@link detectJunctionTables} to obtain
3946
- * the set of junction tables, then reclassify as needed.
3947
- */
3948
- function classifyTable(tableName, schemaName) {
3949
- if (REBASE_INTERNAL_SCHEMAS.includes(schemaName) || REBASE_INTERNAL_PREFIXES.some((prefix) => tableName.startsWith(prefix))) return "rebase-internal";
3950
- return "user";
3951
- }
3952
- /** SQL query that detects junction tables in the `public` schema. */
3953
- var JUNCTION_TABLES_SQL = `
3954
- SELECT t.table_name
3955
- FROM information_schema.tables t
3956
- WHERE t.table_schema = 'public'
3957
- AND t.table_type = 'BASE TABLE'
3958
- AND NOT EXISTS (
3959
- SELECT 1
3960
- FROM information_schema.columns c
3961
- WHERE c.table_schema = t.table_schema
3962
- AND c.table_name = t.table_name
3963
- AND c.column_name NOT IN (
3964
- SELECT kcu.column_name
3965
- FROM information_schema.key_column_usage kcu
3966
- JOIN information_schema.table_constraints tc
3967
- ON tc.constraint_name = kcu.constraint_name
3968
- AND tc.table_schema = kcu.table_schema
3969
- WHERE tc.constraint_type = 'FOREIGN KEY'
3970
- AND kcu.table_schema = t.table_schema
3971
- AND kcu.table_name = t.table_name
3972
- )
3973
- )
3974
- `;
3975
- /**
3976
- * Asynchronously detect junction (link) tables in the `public` schema.
3977
- *
3978
- * A junction table is defined as a table where **every** column participates in
3979
- * at least one foreign-key constraint.
3980
- *
3981
- * @param executeSql - A callback that executes a raw SQL string and returns the
3982
- * resulting rows.
3983
- * @returns A `Set` containing the names of all detected junction tables.
3984
- */
3985
- async function detectJunctionTables(executeSql) {
3986
- const rows = await executeSql(JUNCTION_TABLES_SQL);
3987
- const junctionTables = /* @__PURE__ */ new Set();
3988
- for (const row of rows) if (typeof row.table_name === "string") junctionTables.add(row.table_name);
3989
- return junctionTables;
3990
- }
3991
- //#endregion
3992
- export { DEFAULT_ONE_OF_TYPE as A, createRelationRefWithData as C, mergeDeep as D, getPolicyNamesForRule as E, camelCase as O, createRelationRef as S, updateDateAutoValues as T, getTableVarName as _, getJunctionCollectionConfig as a, getDeclaredPrimaryKeys as b, getEffectiveSecurityRules as c, securityRuleToConditions as d, findAnonymousGrants as f, getTableName as g, getEnumVarName as h, CollectionRegistry as i, DEFAULT_ONE_OF_VALUE as j, toSnakeCase as k, buildPropertyCallbacks as l, getColumnName as m, detectJunctionTables as n, getJunctionSecurityRules as o, findRelation as p, buildSdkData as r, resolveJunctionSpecs as s, classifyTable as t, policyToPostgres as u, resolveCollectionRelations as v, normalizeToEntityRelation as w, parseIdValues as x, buildCompositeId as y };
4112
+ export { DEFAULT_ONE_OF_VALUE as A, updateDateAutoValues as C, camelCase as D, mergeDeep as E, isManyToMany as M, Vector as N, toSnakeCase as O, normalizeToEntityRelation as S, getPolicyNamesForRule as T, buildCompositeId as _, getJunctionSecurityRules as a, createRelationRef as b, policyToPostgres as c, findRelation as d, getColumnName as f, resolveCollectionRelations as g, getTableVarName as h, getJunctionCollectionConfig as i, hasForeignKeyOnTarget as j, DEFAULT_ONE_OF_TYPE as k, securityRuleToConditions as l, getTableName as m, CollectionRegistry as n, resolveJunctionSpecs as o, getEnumVarName as p, resolveStringColumnLength as r, getEffectiveSecurityRules as s, buildSdkData as t, findAnonymousGrants as u, getDeclaredPrimaryKeys as v, generateForeignKeyName as w, createRelationRefWithData as x, parseIdValues as y };
3993
4113
 
3994
- //# sourceMappingURL=src-3VmUJ8Xn.js.map
4114
+ //# sourceMappingURL=src-C_NHNVW2.js.map