@rebasepro/server-postgres 0.31.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/{BranchService-USp1AvZB.js → BranchService-Bdin0Wxh.js} +3 -3
  2. package/dist/{BranchService-USp1AvZB.js.map → BranchService-Bdin0Wxh.js.map} +1 -1
  3. package/dist/PostgresBackendDriver.d.ts +3 -0
  4. package/dist/{backup-cli-DbKyEj6c.js → backup-cli-BEAMPWMs.js} +3 -3
  5. package/dist/{backup-cli-DbKyEj6c.js.map → backup-cli-BEAMPWMs.js.map} +1 -1
  6. package/dist/{boot-ddl-5H2bL_80.js → boot-ddl-Bu6gAY-2.js} +2 -2
  7. package/dist/{boot-ddl-5H2bL_80.js.map → boot-ddl-Bu6gAY-2.js.map} +1 -1
  8. package/dist/{cli-console-DsRgGSBR.js → cli-console-DjFiYlSe.js} +4 -4
  9. package/dist/{cli-console-DsRgGSBR.js.map → cli-console-DjFiYlSe.js.map} +1 -1
  10. package/dist/cli-errors.d.ts +12 -0
  11. package/dist/cli-helpers.d.ts +20 -0
  12. package/dist/{cli-schema-dir-CiN0ephV.js → cli-schema-dir-CjDH_31U.js} +115 -9
  13. package/dist/cli-schema-dir-CjDH_31U.js.map +1 -0
  14. package/dist/cli.js +129 -36
  15. package/dist/cli.js.map +1 -1
  16. package/dist/{database-preflight-bfnIBnjM.js → database-preflight-DKzsGnc4.js} +2 -2
  17. package/dist/{database-preflight-bfnIBnjM.js.map → database-preflight-DKzsGnc4.js.map} +1 -1
  18. package/dist/{deferred-index-build-CcSDA7wE.js → deferred-index-build-88bWtYgx.js} +4 -4
  19. package/dist/{deferred-index-build-CcSDA7wE.js.map → deferred-index-build-88bWtYgx.js.map} +1 -1
  20. package/dist/{ensure-policies-rRmXb5bt.js → ensure-policies-nIITKxud.js} +7 -7
  21. package/dist/{ensure-policies-rRmXb5bt.js.map → ensure-policies-nIITKxud.js.map} +1 -1
  22. package/dist/{ensure-tables-Bvm-F2wW.js → ensure-tables-Lm-77eM5.js} +7 -7
  23. package/dist/{ensure-tables-Bvm-F2wW.js.map → ensure-tables-Lm-77eM5.js.map} +1 -1
  24. package/dist/{ensure-tables-CC8p_AK3.js → ensure-tables-hQ5oAK_j.js} +3 -3
  25. package/dist/{ensure-tables-CC8p_AK3.js.map → ensure-tables-hQ5oAK_j.js.map} +1 -1
  26. package/dist/{enum-labels-kept-FlX9SHdf.js → enum-labels-kept-mesgEJWH.js} +2 -2
  27. package/dist/{enum-labels-kept-FlX9SHdf.js.map → enum-labels-kept-mesgEJWH.js.map} +1 -1
  28. package/dist/{generate-drizzle-schema-SJMXxzPI.js → generate-drizzle-schema-B-Mkf8UI.js} +2 -2
  29. package/dist/{generate-drizzle-schema-SJMXxzPI.js.map → generate-drizzle-schema-B-Mkf8UI.js.map} +1 -1
  30. package/dist/{generate-files-tlJ9_lGI.js → generate-files-8MUP8UHC.js} +2 -2
  31. package/dist/{generate-files-tlJ9_lGI.js.map → generate-files-8MUP8UHC.js.map} +1 -1
  32. package/dist/{generate-postgres-ddl-logic-B8huc03c.js → generate-postgres-ddl-logic-CQof4iFH.js} +89 -45
  33. package/dist/generate-postgres-ddl-logic-CQof4iFH.js.map +1 -0
  34. package/dist/index.d.ts +7 -0
  35. package/dist/index.es.js +14 -14
  36. package/dist/{migrate-baseline-DZmekgpD.js → migrate-baseline-Bzj5gSCM.js} +9 -2
  37. package/dist/{migrate-baseline-DZmekgpD.js.map → migrate-baseline-Bzj5gSCM.js.map} +1 -1
  38. package/dist/{migrate-policy-stamps-B_acrUQB.js → migrate-policy-stamps-C2WaOEsB.js} +5 -5
  39. package/dist/{migrate-policy-stamps-B_acrUQB.js.map → migrate-policy-stamps-C2WaOEsB.js.map} +1 -1
  40. package/dist/{open-rebase-4kisUF_k.js → open-rebase-OB4hhQuk.js} +549 -54
  41. package/dist/open-rebase-OB4hhQuk.js.map +1 -0
  42. package/dist/{pg-error-utils-BT5NzGFZ.js → pg-error-utils-CWopxboq.js} +2 -2
  43. package/dist/{pg-error-utils-BT5NzGFZ.js.map → pg-error-utils-CWopxboq.js.map} +1 -1
  44. package/dist/{policy-drift-BVMyqHSa.js → policy-drift-rVLKS2AG.js} +4 -4
  45. package/dist/{policy-drift-BVMyqHSa.js.map → policy-drift-rVLKS2AG.js.map} +1 -1
  46. package/dist/{push-index-adoption-hpHTyXMR.js → push-index-adoption-EcamXfW2.js} +2 -2
  47. package/dist/{push-index-adoption-hpHTyXMR.js.map → push-index-adoption-EcamXfW2.js.map} +1 -1
  48. package/dist/{push-index-prebuild-Bty9F7bD.js → push-index-prebuild-BPIns6wA.js} +3 -3
  49. package/dist/{push-index-prebuild-Bty9F7bD.js.map → push-index-prebuild-BPIns6wA.js.map} +1 -1
  50. package/dist/{push-legacy-renames-bB4bM6br.js → push-legacy-renames-lmYkb41I.js} +3 -3
  51. package/dist/{push-legacy-renames-bB4bM6br.js.map → push-legacy-renames-lmYkb41I.js.map} +1 -1
  52. package/dist/{push-policy-plan-BI8U4BOD.js → push-policy-plan-Dqu4FKWh.js} +3 -3
  53. package/dist/{push-policy-plan-BI8U4BOD.js.map → push-policy-plan-Dqu4FKWh.js.map} +1 -1
  54. package/dist/{request-role-cli-BdRzdE87.js → request-role-cli-Ay0v9oYZ.js} +8 -8
  55. package/dist/{request-role-cli-BdRzdE87.js.map → request-role-cli-Ay0v9oYZ.js.map} +1 -1
  56. package/dist/{request-role-migration-C8aq_TO3.js → request-role-migration-DTE3Owsh.js} +2 -2
  57. package/dist/{request-role-migration-C8aq_TO3.js.map → request-role-migration-DTE3Owsh.js.map} +1 -1
  58. package/dist/{rls-enforcement-DB5HHj96.js → rls-enforcement-Ck-d8zdJ.js} +2 -2
  59. package/dist/{rls-enforcement-DB5HHj96.js.map → rls-enforcement-Ck-d8zdJ.js.map} +1 -1
  60. package/dist/schema/doctor-cli.js +5 -5
  61. package/dist/schema/generate-drizzle-schema.js +1 -1
  62. package/dist/schema/generate-postgres-ddl-logic.d.ts +51 -8
  63. package/dist/schema/generate-postgres-ddl.js +1 -1
  64. package/dist/schema/introspect-db.js +1 -1
  65. package/dist/services/cdc/CdcListener.d.ts +12 -0
  66. package/dist/services/cdc/capture-consumers.d.ts +65 -0
  67. package/dist/services/cdc/pgoutput.d.ts +6 -0
  68. package/dist/services/cdc/wal-cdc.d.ts +13 -0
  69. package/dist/services/realtime-prefilter.d.ts +90 -0
  70. package/dist/services/realtimeService.d.ts +57 -3
  71. package/dist/utils/connection-string.d.ts +9 -1
  72. package/dist/{websocket-BevXvwfo.js → websocket-kZixcOXt.js} +3 -3
  73. package/dist/{websocket-BevXvwfo.js.map → websocket-kZixcOXt.js.map} +1 -1
  74. package/package.json +7 -7
  75. package/dist/cli-schema-dir-CiN0ephV.js.map +0 -1
  76. package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +0 -1
  77. package/dist/open-rebase-4kisUF_k.js.map +0 -1
@@ -3,23 +3,23 @@ __createRequire(import.meta.url);
3
3
  import { a as createPostgresDatabaseConnection, f as pooledTransactionSettings, h as transactionSettingsStatements, l as isPooledPool, m as transactionSettingsConfig, n as closeWithPool, p as searchPathList } from "./connection-C1zXTPJq.js";
4
4
  import { i as buildTableSearchColumnSpec, o as isSearchIndexColumn, r as SEARCH_UNACCENT_FN } from "./search-column-BO-WND-B.js";
5
5
  import { r as viewRowsName, t as DEFAULT_VIEW_ROLES } from "./view-names-Dscp6--B.js";
6
- import { a as closedDatabaseName, c as diagnoseDbError, ct as extractCauseMessage, d as isEconnrefused, o as deepestErrorMessage, p as parseHostInfo } from "./cli-schema-dir-CiN0ephV.js";
7
- import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BT5NzGFZ.js";
8
- import { t as BranchService } from "./BranchService-USp1AvZB.js";
6
+ import { a as closedDatabaseName, c as diagnoseDbError, d as isEconnrefused, m as parseHostInfo, o as deepestErrorMessage, p as isUntrustedServerCertificate, ut as extractCauseMessage } from "./cli-schema-dir-CjDH_31U.js";
7
+ import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-CWopxboq.js";
8
+ import { t as BranchService } from "./BranchService-Bdin0Wxh.js";
9
9
  import { i as rlsHandoverNotes, n as resolveRlsSettings, r as rlsConfigFromEnv } from "./rls-settings-CmGK2U0a.js";
10
- import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles, T as warnOnRoleSchemaCollision, _ as recordRequestRoles, a as assertRecordedRequestRoles, b as roleHoldsTableGrants, c as ensureAppRole, d as findExposedInternalTables, f as findOtherRoleMembers, g as readRecordedRequestRoles, h as proveRoleSwitch, i as assertAppRoleRestricted, l as ensureAppRoleGrants, o as authContextStatement, p as findUngrantableTables, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as ensureConnectionInheritsAdminRole, v as revokeUserRoleSql, w as warnOnLegacyRlsFunctions, x as settleAdminSwitch } from "./rls-enforcement-DB5HHj96.js";
10
+ import { C as warnOnAnonymousGrants, S as validatePolicyPgRoles, T as warnOnRoleSchemaCollision, _ as recordRequestRoles, a as assertRecordedRequestRoles, b as roleHoldsTableGrants, c as ensureAppRole, d as findExposedInternalTables, f as findOtherRoleMembers, g as readRecordedRequestRoles, h as proveRoleSwitch, i as assertAppRoleRestricted, l as ensureAppRoleGrants, o as authContextStatement, p as findUngrantableTables, r as applyAuthContext, s as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as ensureConnectionInheritsAdminRole, v as revokeUserRoleSql, w as warnOnLegacyRlsFunctions, x as settleAdminSwitch } from "./rls-enforcement-Ck-d8zdJ.js";
11
11
  import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-BpfgbkxZ.js";
12
12
  import { i as plannedColumnEntries, n as planSchema, r as quoteSqlLiteral } from "./plan-schema-Hbtjhge3.js";
13
13
  import { t as generateSchema } from "./generate-drizzle-schema-logic-DL7R1rAF.js";
14
14
  import { i as renderPgType } from "./render-ddl-D4n86NHz.js";
15
- import { u as planTablePolicies } from "./generate-postgres-ddl-logic-B8huc03c.js";
16
- import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-CcSDA7wE.js";
17
- import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-5H2bL_80.js";
18
- import { a as readSchemaFactsFor, r as planTableSchemaEnsure } from "./ensure-tables-Bvm-F2wW.js";
15
+ import { d as planTablePolicies } from "./generate-postgres-ddl-logic-CQof4iFH.js";
16
+ import { d as typesAgree, s as diffPlanAgainstCatalogue } from "./deferred-index-build-88bWtYgx.js";
17
+ import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-Bu6gAY-2.js";
18
+ import { a as readSchemaFactsFor, r as planTableSchemaEnsure } from "./ensure-tables-Lm-77eM5.js";
19
19
  import { n as introspectTables, t as describeUnmappedTables } from "./introspect-tables-Cw_A-kk4.js";
20
20
  import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
21
21
  import { t as DatabasePoolManager } from "./databasePoolManager-DIjzlTK4.js";
22
- import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-CC8p_AK3.js";
22
+ import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-hQ5oAK_j.js";
23
23
  import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as compileIntrospectedTables } from "./generated-schema-diff-DoT2dYDe.js";
24
24
  import pg, { Client, DatabaseError, Pool } from "pg";
25
25
  import { NodePgDatabase, NodePgSession, NodePgTransaction, drizzle } from "drizzle-orm/node-postgres";
@@ -12227,10 +12227,14 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12227
12227
  path,
12228
12228
  id: savedId,
12229
12229
  row: savedRow,
12230
- databaseId: void 0
12230
+ databaseId: void 0,
12231
+ image: {
12232
+ before: upserting ? void 0 : status === "existing" ? previousValuesForHistory : null,
12233
+ after: storedRow
12234
+ }
12231
12235
  }, ...this.childListNotifications(runtime, savedId, updatedValues)];
12232
12236
  if (this._deferNotifications) this._pendingNotifications.push(...notifications);
12233
- else for (const notification of notifications) await this.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId);
12237
+ else for (const notification of notifications) await this.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId, true, "app", notification.image);
12234
12238
  return savedRow;
12235
12239
  } catch (error) {
12236
12240
  if (hasRowHook(hooks, "afterSaveError")) {
@@ -12281,7 +12285,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
12281
12285
  return run(txDriver);
12282
12286
  });
12283
12287
  if (ownNotifications) for (const notification of pending) try {
12284
- await this.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId);
12288
+ await this.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId, true, "app", notification.image);
12285
12289
  } catch (error) {
12286
12290
  logger.error("[DataDriver] Error flushing deferred notification", { error });
12287
12291
  }
@@ -13481,7 +13485,7 @@ var AuthenticatedPostgresBackendDriver = class {
13481
13485
  writeScope?.committed();
13482
13486
  await writeScope?.settled();
13483
13487
  for (const notification of pendingNotifications) try {
13484
- await this.delegate.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId);
13488
+ await this.delegate.realtimeService.notifyUpdate(notification.path, notification.id, notification.row, notification.databaseId, true, "app", notification.image);
13485
13489
  } catch (e) {
13486
13490
  logger.error("[DataDriver] Error flushing deferred notification", { error: e });
13487
13491
  }
@@ -14811,6 +14815,175 @@ var CdcListener = class {
14811
14815
  }
14812
14816
  };
14813
14817
  //#endregion
14818
+ //#region src/services/realtime-prefilter.ts
14819
+ /** The canonical spelling of SQL `NULL` in an index. */
14820
+ var NULL_KEY = "\0null";
14821
+ var INTEGER_KINDS = /* @__PURE__ */ new Set([
14822
+ "smallint",
14823
+ "integer",
14824
+ "bigint",
14825
+ "smallserial",
14826
+ "serial",
14827
+ "bigserial"
14828
+ ]);
14829
+ var STRING_KINDS = /* @__PURE__ */ new Set([
14830
+ "text",
14831
+ "varchar",
14832
+ "enum"
14833
+ ]);
14834
+ var TRUE_SPELLINGS = /* @__PURE__ */ new Set([
14835
+ "t",
14836
+ "true",
14837
+ "y",
14838
+ "yes",
14839
+ "on",
14840
+ "1"
14841
+ ]);
14842
+ var FALSE_SPELLINGS = /* @__PURE__ */ new Set([
14843
+ "f",
14844
+ "false",
14845
+ "n",
14846
+ "no",
14847
+ "off",
14848
+ "0"
14849
+ ]);
14850
+ function judgedKind(kind) {
14851
+ return INTEGER_KINDS.has(kind) || STRING_KINDS.has(kind) || kind === "uuid" || kind === "boolean";
14852
+ }
14853
+ /**
14854
+ * A value as Postgres would compare it in a column of `kind`, as one string,
14855
+ * or `undefined` when that cannot be said with certainty — the caller then
14856
+ * treats the comparison as unknown. Accepts both a filter's JSON value and a
14857
+ * change's value (a JS value from the write path, or the text the WAL sends).
14858
+ */
14859
+ function canonicalValue(kind, value) {
14860
+ if (value === null) return NULL_KEY;
14861
+ if (INTEGER_KINDS.has(kind)) {
14862
+ if (typeof value === "number") return Number.isSafeInteger(value) ? String(value) : void 0;
14863
+ if (typeof value === "bigint") return value.toString();
14864
+ if (typeof value === "string" && /^\s*[+-]?\d{1,20}\s*$/.test(value)) return BigInt(value.trim()).toString();
14865
+ return;
14866
+ }
14867
+ if (kind === "boolean") {
14868
+ if (typeof value === "boolean") return value ? "t" : "f";
14869
+ if (typeof value !== "string") return void 0;
14870
+ const spelled = value.trim().toLowerCase();
14871
+ if (TRUE_SPELLINGS.has(spelled)) return "t";
14872
+ if (FALSE_SPELLINGS.has(spelled)) return "f";
14873
+ return;
14874
+ }
14875
+ if (kind === "uuid") {
14876
+ if (typeof value !== "string") return void 0;
14877
+ const hex = value.trim().replace(/^\{(.*)\}$/, "$1").replace(/-/g, "").toLowerCase();
14878
+ return /^[0-9a-f]{32}$/.test(hex) ? hex : void 0;
14879
+ }
14880
+ if (STRING_KINDS.has(kind)) return typeof value === "string" && value.length <= 256 ? value : void 0;
14881
+ }
14882
+ /** The `[op, value]` tuples of one filter entry: one tuple, or an array of them. */
14883
+ function filterTuples(param) {
14884
+ if (!Array.isArray(param) || param.length === 0) return [];
14885
+ if (Array.isArray(param[0])) return param.filter((tuple) => Array.isArray(tuple) && tuple.length >= 1).map((tuple) => [tuple[0], tuple[1]]);
14886
+ return [[param[0], param[1]]];
14887
+ }
14888
+ function equalityConjunct(field, kind, op, value) {
14889
+ if (op === "==") {
14890
+ const key = value === void 0 ? NULL_KEY : canonicalValue(kind, value);
14891
+ return key === void 0 ? void 0 : {
14892
+ field,
14893
+ kind,
14894
+ accepts: /* @__PURE__ */ new Set([key])
14895
+ };
14896
+ }
14897
+ if (op === "in") {
14898
+ if (value === null || value === void 0) return {
14899
+ field,
14900
+ kind,
14901
+ accepts: /* @__PURE__ */ new Set([NULL_KEY])
14902
+ };
14903
+ if (!Array.isArray(value)) return void 0;
14904
+ const accepts = /* @__PURE__ */ new Set();
14905
+ for (const item of value) {
14906
+ if (item === null) continue;
14907
+ const key = canonicalValue(kind, item);
14908
+ if (key === void 0) return void 0;
14909
+ accepts.add(key);
14910
+ }
14911
+ return {
14912
+ field,
14913
+ kind,
14914
+ accepts
14915
+ };
14916
+ }
14917
+ }
14918
+ /**
14919
+ * The pre-filter for a list read of `table`, or `undefined` when the list
14920
+ * must refetch on every change to the table.
14921
+ */
14922
+ function compileListPrefilter(table, request, tableHasReadHooks) {
14923
+ if (tableHasReadHooks) return void 0;
14924
+ const include = request.include;
14925
+ if (include !== void 0 && !(Array.isArray(include) && include.length === 0)) return void 0;
14926
+ const filter = request.filter;
14927
+ if (!filter) return void 0;
14928
+ const transformed = table.compiled.transforms ?? {};
14929
+ const conjuncts = [];
14930
+ for (const [field, param] of Object.entries(filter)) {
14931
+ const column = table.columnsByKey.get(field);
14932
+ if (!column || !judgedKind(column.type.kind)) continue;
14933
+ if (Object.prototype.hasOwnProperty.call(transformed, field)) continue;
14934
+ for (const [op, value] of filterTuples(param)) {
14935
+ const conjunct = equalityConjunct(field, column.type.kind, op, value);
14936
+ if (conjunct) conjuncts.push(conjunct);
14937
+ }
14938
+ }
14939
+ if (conjuncts.length === 0) return void 0;
14940
+ return {
14941
+ conjuncts,
14942
+ index: conjuncts.reduce((best, next) => next.accepts.size < best.accepts.size ? next : best)
14943
+ };
14944
+ }
14945
+ /**
14946
+ * Whether one version of a row matches the judged conditions: `false` only
14947
+ * when a condition is known to fail, `undefined` when one cannot be read.
14948
+ */
14949
+ function prefilterMatches(prefilter, values) {
14950
+ let known = true;
14951
+ for (const conjunct of prefilter.conjuncts) {
14952
+ if (!Object.prototype.hasOwnProperty.call(values, conjunct.field)) {
14953
+ known = false;
14954
+ continue;
14955
+ }
14956
+ const key = canonicalValue(conjunct.kind, values[conjunct.field]);
14957
+ if (key === void 0) {
14958
+ known = false;
14959
+ continue;
14960
+ }
14961
+ if (!conjunct.accepts.has(key)) return false;
14962
+ }
14963
+ return known ? true : void 0;
14964
+ }
14965
+ /**
14966
+ * Whether a change may alter a list with this pre-filter: unless both
14967
+ * versions of the row are known not to match it.
14968
+ */
14969
+ function changeMayReach(prefilter, image) {
14970
+ for (const version of [image.before, image.after]) {
14971
+ if (version === null) continue;
14972
+ if (version === void 0) return true;
14973
+ if (prefilterMatches(prefilter, version) !== false) return true;
14974
+ }
14975
+ return false;
14976
+ }
14977
+ /**
14978
+ * The index keys a version of a row is found under for `field`, or
14979
+ * `undefined` when the version cannot say — then every group indexed by the
14980
+ * field may be reached.
14981
+ */
14982
+ function imageIndexKey(version, field, kind) {
14983
+ if (!Object.prototype.hasOwnProperty.call(version, field)) return void 0;
14984
+ return canonicalValue(kind, version[field]);
14985
+ }
14986
+ //#endregion
14814
14987
  //#region src/services/cdc/pgoutput.ts
14815
14988
  /** Microseconds between the Unix epoch and Postgres's, 2000-01-01. */
14816
14989
  var PG_EPOCH_OFFSET_US = 946684800000000n;
@@ -15096,6 +15269,24 @@ function identityOf(relation, tuple, wanted, keyOnly) {
15096
15269
  return Object.keys(row).length > 0 ? row : void 0;
15097
15270
  }
15098
15271
  /**
15272
+ * A tuple's values by column name, as text. A column the tuple does not carry
15273
+ * (an unchanged TOASTed value, a non-key column of a key-only tuple) is left
15274
+ * out — unknown, not null — and so is a value longer than
15275
+ * `MAX_IMAGE_VALUE_LENGTH`: nothing compares one, and a backlog of changes
15276
+ * should not hold every large column of every row.
15277
+ */
15278
+ function tupleValues(relation, tuple, keyOnly) {
15279
+ const values = {};
15280
+ relation.columns.forEach((column, i) => {
15281
+ if (keyOnly && !column.isKey) return;
15282
+ const value = tuple[i];
15283
+ if (value === void 0) return;
15284
+ if (value !== null && value.length > 256) return;
15285
+ values[column.name] = value;
15286
+ });
15287
+ return values;
15288
+ }
15289
+ /**
15099
15290
  * Turns a `pgoutput` stream into the change events the trigger listener emits,
15100
15291
  * so `RealtimeService` cannot tell which one it is reading.
15101
15292
  *
@@ -15119,16 +15310,16 @@ var PgoutputChanges = class {
15119
15310
  case "relation":
15120
15311
  this.relations.set(message.relation.id, message.relation);
15121
15312
  return [];
15122
- case "insert": return this.change("INSERT", message.relationId, message.newTuple, false);
15313
+ case "insert": return this.withValues(this.change("INSERT", message.relationId, message.newTuple, false), message.relationId, null, message.newTuple, false);
15123
15314
  case "update": {
15124
- const events = this.change("UPDATE", message.relationId, message.newTuple, false);
15315
+ const events = this.withValues(this.change("UPDATE", message.relationId, message.newTuple, false), message.relationId, message.oldTuple ?? message.newTuple, message.newTuple, message.oldTuple ? message.oldIsKeyOnly === true : true);
15125
15316
  if (message.oldTuple) {
15126
15317
  const before = this.change("UPDATE", message.relationId, message.oldTuple, message.oldIsKeyOnly === true);
15127
15318
  if (before.length && JSON.stringify(before[0].row) !== JSON.stringify(events[0]?.row)) events.push(...before);
15128
15319
  }
15129
15320
  return events;
15130
15321
  }
15131
- case "delete": return this.change("DELETE", message.relationId, message.oldTuple, message.oldIsKeyOnly);
15322
+ case "delete": return this.withValues(this.change("DELETE", message.relationId, message.oldTuple, message.oldIsKeyOnly), message.relationId, message.oldTuple, null, message.oldIsKeyOnly);
15132
15323
  case "truncate": return message.relationIds.flatMap((id) => {
15133
15324
  const relation = this.relations.get(id);
15134
15325
  return relation ? [{
@@ -15142,6 +15333,23 @@ var PgoutputChanges = class {
15142
15333
  default: return [];
15143
15334
  }
15144
15335
  }
15336
+ /**
15337
+ * Put the column values of the row's two versions on the first event: see
15338
+ * `CdcChangeEvent.values`. `before` is read for its key columns alone when
15339
+ * `beforeKeyOnly`, which is all a default replica identity sends.
15340
+ */
15341
+ withValues(events, relationId, before, after, beforeKeyOnly) {
15342
+ const relation = this.relations.get(relationId);
15343
+ if (!relation || events.length === 0) return events;
15344
+ events[0] = {
15345
+ ...events[0],
15346
+ values: {
15347
+ before: before === null ? null : tupleValues(relation, before, beforeKeyOnly),
15348
+ after: after === null ? null : tupleValues(relation, after, false)
15349
+ }
15350
+ };
15351
+ return events;
15352
+ }
15145
15353
  change(op, relationId, tuple, keyOnly) {
15146
15354
  const relation = this.relations.get(relationId);
15147
15355
  if (!relation) throw new Error(`row for relation ${relationId}, which the stream never described`);
@@ -15568,6 +15776,24 @@ async function walCaptureBlocker(run) {
15568
15776
  if (version > 0 && version < 1e5) return `Postgres ${Math.floor(version / 1e4)} has no pgoutput (10 or later is needed)`;
15569
15777
  if (walLevel !== "logical") return `wal_level is "${walLevel || "unknown"}", and logical decoding needs wal_level=logical (a server restart)`;
15570
15778
  }
15779
+ /**
15780
+ * What a boot says when it tried WAL capture and could not use it, before it
15781
+ * falls back to the capture triggers.
15782
+ *
15783
+ * `REALTIME_CDC=wal` asked for the WAL, so not getting it is a warning.
15784
+ * `auto` — the default — tries the WAL wherever it might work, and most
15785
+ * databases are not set up for logical decoding: there, falling back is the
15786
+ * expected outcome and an info line.
15787
+ */
15788
+ function walFallbackNotice(mode) {
15789
+ return mode === "wal" ? {
15790
+ level: "warn",
15791
+ message: "⚠️ [CDC] REALTIME_CDC=wal, but changes cannot be streamed from the WAL — using trigger-based capture instead."
15792
+ } : {
15793
+ level: "info",
15794
+ message: "ℹ️ [CDC] Changes cannot be streamed from the WAL here — using trigger-based capture (REALTIME_CDC=auto)."
15795
+ };
15796
+ }
15571
15797
  async function readTableStates(run, tables) {
15572
15798
  const states = /* @__PURE__ */ new Map();
15573
15799
  if (tables.length === 0) return states;
@@ -15658,6 +15884,61 @@ function reportUnpublishedTables(result) {
15658
15884
  for (const table of result.skipped) logger.warn(`⚠️ [CDC] "${table.schema}.${table.table}" is not captured from the WAL — ${table.reason}.`);
15659
15885
  }
15660
15886
  //#endregion
15887
+ //#region src/services/cdc/capture-consumers.ts
15888
+ /** How every realtime LISTEN connection's `application_name` starts. */
15889
+ var REALTIME_LISTENER_APPLICATION_PREFIX = "rebase-realtime:";
15890
+ /** The `application_name` of one of an instance's realtime connections. */
15891
+ function realtimeListenerApplicationName(instanceName, role) {
15892
+ return `${instanceName}:${role}`;
15893
+ }
15894
+ /**
15895
+ * Whether a session may be hearing changes through the capture triggers.
15896
+ *
15897
+ * @param ownInstanceName This process's `rebase-realtime:<instance id>`; its
15898
+ * own connections never count.
15899
+ */
15900
+ function isTriggerCaptureConsumer(session, ownInstanceName) {
15901
+ const name = session.applicationName;
15902
+ if (!name || !name.startsWith("rebase-realtime:")) return false;
15903
+ if (name === ownInstanceName || name.startsWith(`${ownInstanceName}:`)) return false;
15904
+ if (session.backendType === "walsender") return false;
15905
+ const rest = name.slice(16);
15906
+ const role = rest.includes(":") ? rest.slice(rest.lastIndexOf(":") + 1) : void 0;
15907
+ if (role === "entity" || role === "wal") return false;
15908
+ return true;
15909
+ }
15910
+ /**
15911
+ * How many other sessions on this database may depend on the capture
15912
+ * triggers. A failed query answers `undefined` — the caller keeps the triggers.
15913
+ */
15914
+ async function countTriggerCaptureConsumers(run, ownInstanceName) {
15915
+ try {
15916
+ return (await run(`SELECT application_name, backend_type FROM pg_stat_activity WHERE datname = current_database() AND starts_with(application_name, '${REALTIME_LISTENER_APPLICATION_PREFIX}')`)).map((row) => ({
15917
+ applicationName: typeof row.application_name === "string" ? row.application_name : null,
15918
+ backendType: typeof row.backend_type === "string" ? row.backend_type : null
15919
+ })).filter((session) => isTriggerCaptureConsumer(session, ownInstanceName)).length;
15920
+ } catch {
15921
+ return;
15922
+ }
15923
+ }
15924
+ /** How often a WAL-streaming instance that kept the triggers for another one checks whether it is gone. */
15925
+ var TRIGGER_RETIREMENT_INTERVAL_MS = 300 * 1e3;
15926
+ /**
15927
+ * Take the capture triggers off the tables — unless another session may still
15928
+ * be hearing changes through them ({@link countTriggerCaptureConsumers}).
15929
+ *
15930
+ * For a process that streams changes from the WAL: it does not need them, and
15931
+ * every write pays a trigger and a NOTIFY while they stay.
15932
+ */
15933
+ async function retireTriggerCaptureIfUnused(run, ownInstanceName) {
15934
+ const consumers = await countTriggerCaptureConsumers(run, ownInstanceName);
15935
+ if (consumers === void 0 || consumers > 0) return {
15936
+ kept: true,
15937
+ consumers
15938
+ };
15939
+ return { removed: await removeTriggerCdc(run) };
15940
+ }
15941
+ //#endregion
15661
15942
  //#region src/services/socket-liveness.ts
15662
15943
  /**
15663
15944
  * Letting go of client sockets the server can no longer reach.
@@ -16670,12 +16951,6 @@ function createChannelBus(setting, deps) {
16670
16951
  /** Channel name used for Postgres LISTEN/NOTIFY cross-instance realtime. */
16671
16952
  var PG_NOTIFY_CHANNEL = "rebase_entity_changes";
16672
16953
  /**
16673
- * How every realtime LISTEN connection names itself (`application_name`,
16674
- * followed by the instance id), so an instance can count the others serving
16675
- * realtime on the same database.
16676
- */
16677
- var REALTIME_LISTENER_APPLICATION_PREFIX = "rebase-realtime:";
16678
- /**
16679
16954
  * The id of a change that names no row — a `TRUNCATE`, a key too large to
16680
16955
  * notify, a table with no key. Every list on the path refetches, and so does
16681
16956
  * every single-row subscription on it: the change may be to any row.
@@ -17010,6 +17285,13 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17010
17285
  */
17011
17286
  unscheduledListGroups = /* @__PURE__ */ new Map();
17012
17287
  /**
17288
+ * The subset of {@link unscheduledListGroups} with no pre-filter: what a
17289
+ * change that can be judged still schedules wholesale.
17290
+ */
17291
+ unscheduledPlainListGroups = /* @__PURE__ */ new Map();
17292
+ /** The pre-filtered list groups on each path. See {@link groupsReachedBy}. */
17293
+ prefilterIndex = /* @__PURE__ */ new Map();
17294
+ /**
17013
17295
  * Every path a subscription holds, with the collection it lands on and how
17014
17296
  * many hold it — the candidates `aliasPaths` considers, resolved once.
17015
17297
  */
@@ -17037,8 +17319,16 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17037
17319
  driver;
17038
17320
  /** Unique identifier for this process instance, used to skip own notifications. */
17039
17321
  instanceId = `inst_${randomUUID().slice(0, 8)}`;
17040
- /** What this instance's LISTEN connections report in `pg_stat_activity`. */
17041
- listenerApplicationName = `${REALTIME_LISTENER_APPLICATION_PREFIX}${this.instanceId}`;
17322
+ /**
17323
+ * The name this instance's realtime connections report in
17324
+ * `pg_stat_activity` (`application_name`), each followed by what the
17325
+ * connection is for — see {@link realtimeListenerApplicationName}. Other
17326
+ * instances count these, and a WAL-streaming one reads them to tell
17327
+ * whether anybody still LISTENs on the capture triggers.
17328
+ */
17329
+ listenerInstanceName = `${REALTIME_LISTENER_APPLICATION_PREFIX}${this.instanceId}`;
17330
+ /** While the capture triggers are kept for another instance, the timer that retires them once it is gone. */
17331
+ triggerRetirementTimer;
17042
17332
  /** The LISTEN connection on {@link PG_NOTIFY_CHANNEL}, outside the Drizzle pool. */
17043
17333
  crossInstanceListener;
17044
17334
  /** Whether cross-instance broadcasting is active. */
@@ -17207,6 +17497,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17207
17497
  lastChangeAt: 0
17208
17498
  };
17209
17499
  this.groups.set(group.key, group);
17500
+ if (group.type === "collection") this.indexPrefilter(group);
17210
17501
  const [index, address] = group.type === "collection" ? [this.collectionGroupsByPath, group.path] : [this.singleGroupsByAddress, `${group.path}\u0000${group.id}`];
17211
17502
  let bucket = index.get(address);
17212
17503
  if (!bucket) index.set(address, bucket = /* @__PURE__ */ new Set());
@@ -17269,17 +17560,90 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17269
17560
  }
17270
17561
  if (group.type === "collection") {
17271
17562
  this.unscheduledListGroups.get(group.path)?.delete(group);
17563
+ this.unscheduledPlainListGroups.get(group.path)?.delete(group);
17564
+ this.unindexPrefilter(group);
17272
17565
  if (!this.collectionGroupsByPath.has(group.path)) {
17273
17566
  this.unscheduledListGroups.delete(group.path);
17567
+ this.unscheduledPlainListGroups.delete(group.path);
17274
17568
  this.listPathChangedAt.delete(group.path);
17275
17569
  }
17276
17570
  }
17277
17571
  }
17572
+ /**
17573
+ * Compile `group`'s pre-filter and index it under its narrowest
17574
+ * condition. Only for a list on a table's own path: a nested list's rows
17575
+ * are chosen by its parent, which a change to the row does not describe.
17576
+ */
17577
+ indexPrefilter(group) {
17578
+ group.prefilter = void 0;
17579
+ if (isNestedPath(group.path)) return;
17580
+ let table;
17581
+ try {
17582
+ table = this.registry.tableAt(group.path);
17583
+ } catch {
17584
+ return;
17585
+ }
17586
+ if (!table) return;
17587
+ const prefilter = compileListPrefilter(table, group.collectionRequest ?? {}, afterReadApplies(this.registry, resolveTableHooks(this.registry, group.path)));
17588
+ if (!prefilter) return;
17589
+ group.prefilter = prefilter;
17590
+ let index = this.prefilterIndex.get(group.path);
17591
+ if (!index) this.prefilterIndex.set(group.path, index = /* @__PURE__ */ new Map());
17592
+ let entry = index.get(prefilter.index.field);
17593
+ if (!entry) index.set(prefilter.index.field, entry = {
17594
+ kind: prefilter.index.kind,
17595
+ buckets: /* @__PURE__ */ new Map()
17596
+ });
17597
+ for (const value of prefilter.index.accepts) {
17598
+ let bucket = entry.buckets.get(value);
17599
+ if (!bucket) entry.buckets.set(value, bucket = /* @__PURE__ */ new Set());
17600
+ bucket.add(group);
17601
+ }
17602
+ }
17603
+ unindexPrefilter(group) {
17604
+ const prefilter = group.prefilter;
17605
+ if (!prefilter) return;
17606
+ const index = this.prefilterIndex.get(group.path);
17607
+ const entry = index?.get(prefilter.index.field);
17608
+ if (!index || !entry) return;
17609
+ for (const value of prefilter.index.accepts) {
17610
+ const bucket = entry.buckets.get(value);
17611
+ bucket?.delete(group);
17612
+ if (bucket?.size === 0) entry.buckets.delete(value);
17613
+ }
17614
+ if (entry.buckets.size === 0) index.delete(prefilter.index.field);
17615
+ if (index.size === 0) this.prefilterIndex.delete(group.path);
17616
+ }
17617
+ /**
17618
+ * The pre-filtered list groups on `path` that `image` may reach, or
17619
+ * `undefined` when the change cannot say which value it had in a field
17620
+ * groups are indexed by — then every group on the path is asked, as for
17621
+ * a change with no image at all.
17622
+ */
17623
+ groupsReachedBy(index, image) {
17624
+ const reached = /* @__PURE__ */ new Set();
17625
+ for (const [field, entry] of index) {
17626
+ const keys = [];
17627
+ for (const version of [image.before, image.after]) {
17628
+ if (version === null) continue;
17629
+ if (version === void 0) return void 0;
17630
+ const key = imageIndexKey(version, field, entry.kind);
17631
+ if (key === void 0) return void 0;
17632
+ keys.push(key);
17633
+ }
17634
+ for (const key of keys) for (const group of entry.buckets.get(key) ?? []) if (group.prefilter && changeMayReach(group.prefilter, image)) reached.add(group);
17635
+ }
17636
+ return reached;
17637
+ }
17278
17638
  /** See {@link unscheduledListGroups}. */
17279
17639
  markListGroupUnscheduled(group) {
17280
17640
  let unscheduled = this.unscheduledListGroups.get(group.path);
17281
17641
  if (!unscheduled) this.unscheduledListGroups.set(group.path, unscheduled = /* @__PURE__ */ new Set());
17282
17642
  unscheduled.add(group);
17643
+ if (group.prefilter) return;
17644
+ let plain = this.unscheduledPlainListGroups.get(group.path);
17645
+ if (!plain) this.unscheduledPlainListGroups.set(group.path, plain = /* @__PURE__ */ new Set());
17646
+ plain.add(group);
17283
17647
  }
17284
17648
  /**
17285
17649
  * Ask for a refetch of `group` once changes have been quiet for the
@@ -17305,7 +17669,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17305
17669
  group.timer = void 0;
17306
17670
  if (this.groups.get(group.key) !== group) return;
17307
17671
  const now = Date.now();
17308
- const quietFor = now - (group.type === "collection" ? Math.max(group.lastChangeAt, this.listPathChangedAt.get(group.path) ?? 0) : group.lastChangeAt);
17672
+ const quietFor = now - (group.type === "collection" && !group.prefilter ? Math.max(group.lastChangeAt, this.listPathChangedAt.get(group.path) ?? 0) : group.lastChangeAt);
17309
17673
  const waitedFor = now - (group.firstPendingAt ?? now);
17310
17674
  if (quietFor < RealtimeService.REFETCH_DEBOUNCE_MS && waitedFor < this.refetchMaxWaitMs) {
17311
17675
  this.armGroupTimer(group, Math.min(RealtimeService.REFETCH_DEBOUNCE_MS - quietFor, this.refetchMaxWaitMs - waitedFor));
@@ -17919,7 +18283,12 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17919
18283
  * records the change so this instance can suppress the matching
17920
18284
  * CDC echo, while an unmatched CDC event is delivered normally.
17921
18285
  */
17922
- async notifyUpdate(path, id, row, databaseId, broadcast = true, origin = "app") {
18286
+ /**
18287
+ * @param image What the change is known to have done to the row, by column
18288
+ * key — see `realtime-prefilter.ts`. It narrows which list groups on
18289
+ * `path` refetch, never what any of them receives. Absent, all of them do.
18290
+ */
18291
+ async notifyUpdate(path, id, row, databaseId, broadcast = true, origin = "app", image) {
17923
18292
  this.debugLog("🔔 [RealtimeService] notifyUpdate called for path:", path, "id:", id, "isDelete:", row === null, "origin:", origin);
17924
18293
  const aliases = this.aliasPaths(path);
17925
18294
  if (this.cdcActive) {
@@ -17943,7 +18312,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17943
18312
  pathsToNotify.push(...parentPaths);
17944
18313
  this.debugLog(`🔗 [RealtimeService] Nested path detected. Will notify paths: ${pathsToNotify.join(", ")}`);
17945
18314
  }
17946
- for (const notifyPath of pathsToNotify) this.notifyPathUpdate(notifyPath, path, id);
18315
+ for (const notifyPath of pathsToNotify) this.notifyPathUpdate(notifyPath, path, id, notifyPath === path && !isNestedPath(path) ? image : void 0);
17947
18316
  for (const alias of aliases) this.notifyPathUpdate(alias, alias, id);
17948
18317
  if (broadcast && this.broadcasting && !this.cdcActive) this.broadcastChange(path, id, databaseId).catch((err) => {
17949
18318
  logger.error("❌ [RealtimeService] Failed to broadcast change via pg_notify", { error: err });
@@ -17985,14 +18354,30 @@ var RealtimeService = class RealtimeService extends EventEmitter {
17985
18354
  * being able to know, without asking the database as this subscriber,
17986
18355
  * whether this subscriber may see the row at all.
17987
18356
  */
17988
- notifyPathUpdate(notifyPath, originalPath, id) {
18357
+ notifyPathUpdate(notifyPath, originalPath, id, image) {
17989
18358
  this.debugLog(`📡 [RealtimeService] Notifying path: ${notifyPath} (original: ${originalPath})`);
17990
18359
  if (this.collectionGroupsByPath.has(notifyPath)) {
17991
18360
  this.listPathChangedAt.set(notifyPath, Date.now());
17992
- const unscheduled = this.unscheduledListGroups.get(notifyPath);
17993
- if (unscheduled?.size) {
17994
- for (const group of unscheduled) this.scheduleGroupRefetch(group);
17995
- unscheduled.clear();
18361
+ const index = image ? this.prefilterIndex.get(notifyPath) : void 0;
18362
+ const reached = index && image ? this.groupsReachedBy(index, image) : void 0;
18363
+ if (reached) {
18364
+ const plain = this.unscheduledPlainListGroups.get(notifyPath);
18365
+ if (plain?.size) {
18366
+ const unscheduled = this.unscheduledListGroups.get(notifyPath);
18367
+ for (const group of plain) {
18368
+ this.scheduleGroupRefetch(group);
18369
+ unscheduled?.delete(group);
18370
+ }
18371
+ plain.clear();
18372
+ }
18373
+ for (const group of reached) this.scheduleGroupRefetch(group);
18374
+ } else {
18375
+ const unscheduled = this.unscheduledListGroups.get(notifyPath);
18376
+ if (unscheduled?.size) {
18377
+ for (const group of unscheduled) this.scheduleGroupRefetch(group);
18378
+ unscheduled.clear();
18379
+ }
18380
+ this.unscheduledPlainListGroups.get(notifyPath)?.clear();
17996
18381
  }
17997
18382
  }
17998
18383
  if (notifyPath !== originalPath) return;
@@ -18577,7 +18962,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
18577
18962
  SELECT count(*)::int AS n FROM pg_stat_activity
18578
18963
  WHERE datname = current_database()
18579
18964
  AND starts_with(application_name, ${REALTIME_LISTENER_APPLICATION_PREFIX})
18580
- AND application_name <> ${this.listenerApplicationName}`);
18965
+ AND NOT starts_with(application_name, ${this.listenerInstanceName})`);
18581
18966
  if (Number((result.rows?.[0])?.n ?? 0) > 0) {
18582
18967
  this.foreignInstanceSeen = true;
18583
18968
  this.warnIfMemoryBusOnMultiplePods();
@@ -19183,6 +19568,8 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19183
19568
  group.recountTimer = void 0;
19184
19569
  }
19185
19570
  this.unscheduledListGroups.clear();
19571
+ this.unscheduledPlainListGroups.clear();
19572
+ this.prefilterIndex.clear();
19186
19573
  this.listPathChangedAt.clear();
19187
19574
  this.refetchQueue.clear();
19188
19575
  this._subscriptions.clear();
@@ -19304,7 +19691,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19304
19691
  * (bypass PgBouncer — LISTEN needs a session connection).
19305
19692
  */
19306
19693
  async enableCdc(connectionString) {
19307
- await this.activateCdc(() => new CdcListener(connectionString, (events) => this.handleCdcEvents(events), () => this.resyncSubscriptions(), this.listenerApplicationName));
19694
+ await this.activateCdc(() => new CdcListener(connectionString, (events) => this.handleCdcEvents(events), () => this.resyncSubscriptions(), realtimeListenerApplicationName(this.listenerInstanceName, "cdc")));
19308
19695
  }
19309
19696
  /**
19310
19697
  * Enable change capture read from the write-ahead log instead of NOTIFY —
@@ -19325,7 +19712,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19325
19712
  onEvents: (events) => this.handleCdcEvents(events),
19326
19713
  onReconnect: () => this.resyncSubscriptions(),
19327
19714
  identityColumns: (schema, table) => identity.get(`${schema}.${table}`),
19328
- applicationName: this.listenerApplicationName
19715
+ applicationName: realtimeListenerApplicationName(this.listenerInstanceName, "wal")
19329
19716
  }));
19330
19717
  }
19331
19718
  async activateCdc(create) {
@@ -19369,12 +19756,45 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19369
19756
  * change capture is off: the maps are built when it starts.
19370
19757
  */
19371
19758
  refreshTableMaps() {
19759
+ for (const group of this.groups.values()) {
19760
+ if (group.type !== "collection") continue;
19761
+ this.unindexPrefilter(group);
19762
+ this.unscheduledPlainListGroups.get(group.path)?.delete(group);
19763
+ this.indexPrefilter(group);
19764
+ if (this.unscheduledListGroups.get(group.path)?.has(group)) this.markListGroupUnscheduled(group);
19765
+ }
19372
19766
  if (!this.cdcTableMap) return;
19373
19767
  this.cdcTableMap = this.buildCdcTableMap();
19374
19768
  this.junctionLinkMap = buildJunctionLinkMap(this.registry);
19375
19769
  }
19770
+ /**
19771
+ * Try `retire` every `intervalMs` until it answers true — how a
19772
+ * WAL-streaming instance takes the capture triggers off once the last
19773
+ * instance still listening on them is gone. Replaces any earlier schedule;
19774
+ * stopped with the CDC listener.
19775
+ */
19776
+ scheduleTriggerCaptureRetirement(retire, intervalMs) {
19777
+ this.cancelTriggerCaptureRetirement();
19778
+ let running = false;
19779
+ const timer = setInterval(() => {
19780
+ if (running) return;
19781
+ running = true;
19782
+ retire().then((done) => {
19783
+ if (done && this.triggerRetirementTimer === timer) this.cancelTriggerCaptureRetirement();
19784
+ }).catch((error) => this.debugLog("[CDC] Retiring the capture triggers failed; trying again later", error)).finally(() => {
19785
+ running = false;
19786
+ });
19787
+ }, intervalMs);
19788
+ unref(timer);
19789
+ this.triggerRetirementTimer = timer;
19790
+ }
19791
+ cancelTriggerCaptureRetirement() {
19792
+ if (this.triggerRetirementTimer) clearInterval(this.triggerRetirementTimer);
19793
+ this.triggerRetirementTimer = void 0;
19794
+ }
19376
19795
  /** Stop the CDC listener and clear its state. */
19377
19796
  async stopCdc() {
19797
+ this.cancelTriggerCaptureRetirement();
19378
19798
  this.cdcActive = false;
19379
19799
  if (this.cdcListener) {
19380
19800
  await this.cdcListener.stop();
@@ -19457,7 +19877,42 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19457
19877
  const path = served.slug;
19458
19878
  const id = event.op === "TRUNCATE" ? ANY_ROW : this.extractIdFromCdcRow(served, event.row);
19459
19879
  const row = event.op === "DELETE" || event.op === "TRUNCATE" ? null : { _rebase_invalidated: true };
19460
- await this.notifyUpdate(path, id, row, void 0, false, "cdc");
19880
+ await this.notifyUpdate(path, id, row, void 0, false, "cdc", this.cdcChangeImage(served, event));
19881
+ }
19882
+ /**
19883
+ * What a captured change says about the row's two versions, by column
19884
+ * key — which list groups it can reach, never what they receive.
19885
+ *
19886
+ * From the WAL, the values it streamed (`CdcChangeEvent.values`). From the
19887
+ * capture trigger, the key alone, and only where the op pins the other
19888
+ * version: an insert had no row before, a delete has none after. A
19889
+ * trigger's update names the new key only — the old one may differ — and
19890
+ * a key too large to send names nothing: both are unknown.
19891
+ */
19892
+ cdcChangeImage(served, event) {
19893
+ if (event.op === "TRUNCATE") return void 0;
19894
+ const byKey = (values) => {
19895
+ if (values === null || values === void 0) return values;
19896
+ const keyed = {};
19897
+ for (const [columnName, value] of Object.entries(values)) {
19898
+ const column = served.columnsBySqlName.get(columnName);
19899
+ if (column) keyed[column.key] = value;
19900
+ }
19901
+ return keyed;
19902
+ };
19903
+ if (event.values) return {
19904
+ before: byKey(event.values.before),
19905
+ after: byKey(event.values.after)
19906
+ };
19907
+ if (event.truncated || Object.keys(event.row).length === 0) return void 0;
19908
+ if (event.op === "INSERT") return {
19909
+ before: null,
19910
+ after: byKey(event.row)
19911
+ };
19912
+ if (event.op === "DELETE") return {
19913
+ before: byKey(event.row),
19914
+ after: null
19915
+ };
19461
19916
  }
19462
19917
  /**
19463
19918
  * Deliver a change on a many-to-many junction table as a change to the child
@@ -19592,7 +20047,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
19592
20047
  onPayload: (payload) => this.handleCrossInstanceNotification(payload),
19593
20048
  onReconnect: () => this.resyncSubscriptions(),
19594
20049
  retryInitialConnect: true,
19595
- applicationName: this.listenerApplicationName
20050
+ applicationName: realtimeListenerApplicationName(this.listenerInstanceName, "entity")
19596
20051
  });
19597
20052
  await this.crossInstanceListener.start();
19598
20053
  logger.info(`📡 [RealtimeService] Cross-instance realtime enabled (instanceId: ${this.instanceId})`);
@@ -23135,6 +23590,10 @@ function diagnoseConnectFailure(err, connectionString) {
23135
23590
  logger.error(diagnoseDbError(err, url) ?? `❌ Database "${closed}" at ${hostInfo} is closed to new connections`);
23136
23591
  return new Error(`Database "${closed}" at ${hostInfo} is closed to new connections: ${reason}${detail}. Open it again with \`rebase db branch list\`.`, { cause: err });
23137
23592
  }
23593
+ if (isUntrustedServerCertificate(err)) {
23594
+ logger.error(diagnoseDbError(err, url) ?? `❌ The certificate of the PostgreSQL server at ${hostInfo} is not trusted`);
23595
+ return new Error(`The certificate of the PostgreSQL server at ${hostInfo} is not trusted: ${reason}${detail}. Use sslmode=no-verify to encrypt without verifying, or sslmode=verify-full with sslrootcert.`, { cause: err });
23596
+ }
23138
23597
  if (code === "53300") {
23139
23598
  const remedy = extractPgError(err)?.hint ?? "Close another client, cap this process's pool with REBASE_DB_POOL_MAX, or raise the server's max_connections.";
23140
23599
  logger.error(`
@@ -23594,27 +24053,52 @@ async function openPostgresDriver(pgConfig, config) {
23594
24053
  });
23595
24054
  }
23596
24055
  let walActive = false;
23597
- if (cdcMode === "wal") try {
24056
+ if (cdcMode === "wal" || cdcMode === "auto") try {
23598
24057
  const blocker = await walCaptureBlocker(cdcRunSql);
23599
24058
  if (blocker) throw new Error(blocker);
23600
24059
  if (realtimeProvisions) reportUnpublishedTables(await provisionWalPublication(cdcRunSql, cdcTables));
23601
24060
  if (realtimeSubscribes) await realtimeService.enableWalCdc(directUrl, cdcTables);
23602
24061
  walActive = true;
23603
24062
  } catch (err) {
23604
- logger.warn("⚠️ [CDC] REALTIME_CDC=wal, but changes cannot be streamed from the WAL — using trigger-based capture instead.", { detail: err instanceof Error ? err.message : String(err) });
24063
+ const notice = walFallbackNotice(cdcMode);
24064
+ logger[notice.level](notice.message, { detail: err instanceof Error ? err.message : String(err) });
23605
24065
  }
23606
24066
  if (walActive) {
23607
24067
  cdcEnabled = true;
23608
24068
  if (realtimeProvisions && realtimeSubscribes) {
24069
+ const ownName = realtimeService.listenerInstanceName;
24070
+ let triggersKept = false;
23609
24071
  try {
23610
- const removed = await removeTriggerCdc(cdcRunSql);
23611
- cdcFunctionCurrent = true;
23612
- if (removed > 0) logger.info(`ℹ️ [CDC] Removed ${removed} change-capture trigger(s): this process streams changes from the WAL instead.`);
24072
+ const retirement = await retireTriggerCaptureIfUnused(cdcRunSql, ownName);
24073
+ if ("removed" in retirement) {
24074
+ cdcFunctionCurrent = true;
24075
+ if (retirement.removed > 0) logger.info(`ℹ️ [CDC] Removed ${retirement.removed} change-capture trigger(s): this process streams changes from the WAL instead.`);
24076
+ } else {
24077
+ triggersKept = true;
24078
+ logger.info("ℹ️ [CDC] Keeping the change-capture triggers: " + (retirement.consumers === void 0 ? "could not tell whether another instance still listens on them." : `${retirement.consumers} other realtime connection(s) may still listen on them.`) + " They come off once none does.");
24079
+ }
23613
24080
  } catch (err) {
23614
- logger.warn("⚠️ [CDC] Could not remove the change-capture triggers, so every write still runs one and a NOTIFY. The next boot tries again.", { detail: err instanceof Error ? err.message : String(err) });
24081
+ triggersKept = true;
24082
+ logger.warn("⚠️ [CDC] Could not remove the change-capture triggers, so every write still runs one and a NOTIFY. This process tries again.", { detail: err instanceof Error ? err.message : String(err) });
24083
+ }
24084
+ if (triggersKept) {
24085
+ try {
24086
+ await provisionTriggerCdc(cdcRunSql, cdcTables);
24087
+ cdcFunctionCurrent = true;
24088
+ } catch (err) {
24089
+ logger.warn("⚠️ [CDC] Could not bring the kept change-capture triggers up to date.", { detail: err instanceof Error ? err.message : String(err) });
24090
+ }
24091
+ realtimeService.scheduleTriggerCaptureRetirement(async () => {
24092
+ const retirement = await retireTriggerCaptureIfUnused(cdcRunSql, ownName);
24093
+ if (!("removed" in retirement)) return false;
24094
+ triggersKept = false;
24095
+ if (retirement.removed > 0) logger.info(`ℹ️ [CDC] Removed ${retirement.removed} change-capture trigger(s): no other instance listens on them any more.`);
24096
+ return true;
24097
+ }, TRIGGER_RETIREMENT_INTERVAL_MS);
23615
24098
  }
23616
24099
  provisionCdcForTables = async (tables) => {
23617
24100
  reportUnpublishedTables(await provisionWalPublication(cdcRunSql, tables));
24101
+ if (triggersKept) await provisionTriggerCdc(cdcRunSql, tables);
23618
24102
  };
23619
24103
  } else if (realtimeProvisions) {
23620
24104
  try {
@@ -23630,11 +24114,22 @@ async function openPostgresDriver(pgConfig, config) {
23630
24114
  }
23631
24115
  logger.info("📡 [CDC] Realtime source = database-level change capture (mode: wal). All writes now emit realtime events regardless of origin." + (realtimeSubscribes ? "" : " This process sets up the capture but does not consume it."));
23632
24116
  } else try {
24117
+ let listenError;
24118
+ if (realtimeSubscribes) try {
24119
+ await realtimeService.enableCdc(directUrl);
24120
+ } catch (err) {
24121
+ listenError = err;
24122
+ }
23633
24123
  if (realtimeProvisions) {
23634
- await provisionTriggerCdc(cdcRunSql, cdcTables);
24124
+ try {
24125
+ await provisionTriggerCdc(cdcRunSql, cdcTables);
24126
+ } catch (err) {
24127
+ if (realtimeSubscribes && listenError === void 0) await realtimeService.stopCdc().catch(() => void 0);
24128
+ throw err;
24129
+ }
23635
24130
  cdcFunctionCurrent = true;
23636
24131
  }
23637
- if (realtimeSubscribes) await realtimeService.enableCdc(directUrl);
24132
+ if (listenError !== void 0) throw listenError;
23638
24133
  cdcEnabled = true;
23639
24134
  if (realtimeProvisions) provisionCdcForTables = async (tables) => {
23640
24135
  await provisionTriggerCdc(cdcRunSql, tables);
@@ -23887,7 +24382,7 @@ function createPostgresBootstrapper(pgConfig) {
23887
24382
  const openIndexBuildSession = (driverResult) => async () => {
23888
24383
  const db = requireProvisioningDb(driverResult);
23889
24384
  const pool = "$client" in db ? db.$client : void 0;
23890
- const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-CcSDA7wE.js").then((n) => n.r);
24385
+ const { clientIndexBuildSession, isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-88bWtYgx.js").then((n) => n.r);
23891
24386
  const config = effectiveConfig();
23892
24387
  if (isPooledPool(pool) || config.pooled) {
23893
24388
  if (!config.directConnectionString) throw pooledWithoutDirectUrlError(DEFAULT_DATA_SOURCE_KEY);
@@ -24030,11 +24525,11 @@ function createPostgresBootstrapper(pgConfig) {
24030
24525
  unavailable: historyUnavailableReason(state, { requireTransaction: false })
24031
24526
  }) };
24032
24527
  }
24033
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-5H2bL_80.js").then((n) => n.i);
24528
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-Bu6gAY-2.js").then((n) => n.i);
24034
24529
  const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
24035
24530
  const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
24036
24531
  if (historyIndexes.length > 0) {
24037
- const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-CcSDA7wE.js").then((n) => n.r);
24532
+ const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-88bWtYgx.js").then((n) => n.r);
24038
24533
  const indexOptions = {
24039
24534
  log: (message) => logger.info(`[history] ${message}`),
24040
24535
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
@@ -24090,9 +24585,9 @@ function createPostgresBootstrapper(pgConfig) {
24090
24585
  * proved it can bootstrap with.
24091
24586
  */
24092
24587
  async ensureTableSchema(tables, driverResult, log) {
24093
- const { ensureTables } = await import("./ensure-tables-Bvm-F2wW.js").then((n) => n.n);
24588
+ const { ensureTables } = await import("./ensure-tables-Lm-77eM5.js").then((n) => n.n);
24094
24589
  const queryable = provisioningQueryable(driverResult);
24095
- const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-5H2bL_80.js").then((n) => n.i);
24590
+ const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-Bu6gAY-2.js").then((n) => n.i);
24096
24591
  const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
24097
24592
  const plan = await ensureTables(queryable, tables, log, {
24098
24593
  lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
@@ -24104,7 +24599,7 @@ function createPostgresBootstrapper(pgConfig) {
24104
24599
  pendingIndexBuild?.cancel();
24105
24600
  pendingIndexBuild = void 0;
24106
24601
  if (!provisionOnly && plan.deferredIndexes.length > 0) {
24107
- const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-CcSDA7wE.js").then((n) => n.r);
24602
+ const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-88bWtYgx.js").then((n) => n.r);
24108
24603
  logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
24109
24604
  pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
24110
24605
  log: (message) => logger.info(`[schema] ${message}`),
@@ -24144,7 +24639,7 @@ function createPostgresBootstrapper(pgConfig) {
24144
24639
  await provisionRlsRuntime(driverResult);
24145
24640
  },
24146
24641
  async ensureTablePolicies(tables, driverResult, log) {
24147
- const { ensureTablePolicies, describeRulesDropped } = await import("./ensure-policies-rRmXb5bt.js");
24642
+ const { ensureTablePolicies, describeRulesDropped } = await import("./ensure-policies-nIITKxud.js");
24148
24643
  const queryable = provisioningQueryable(driverResult);
24149
24644
  const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
24150
24645
  if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
@@ -24280,7 +24775,7 @@ function createPostgresBootstrapper(pgConfig) {
24280
24775
  return driverResult.internals.driver.admin;
24281
24776
  },
24282
24777
  async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
24283
- const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-BevXvwfo.js").then((n) => n.c);
24778
+ const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-kZixcOXt.js").then((n) => n.c);
24284
24779
  if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
24285
24780
  const realtimeConfig = effectiveConfig().realtime;
24286
24781
  const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
@@ -24441,4 +24936,4 @@ async function openRebase(options) {
24441
24936
  //#endregion
24442
24937
  export { PostgresBackendDriver as $, reapSilentSockets as A, passwordResetTokens as B, PostgresChannelBus as C, frameByteLength as D, MemoryChannelBus as E, magicLinkTokensRelations as F, refreshTokensRelations as G, recoveryCodes as H, mfaChallenges as I, users as J, userIdentities as K, mfaChallengesRelations as L, appConfig as M, createAuthSchema as N, isChannelBusInstance$1 as O, magicLinkTokens as P, CONNECTION_OWNER as Q, mfaFactors as R, PG_NOTIFY_MAX_PAYLOAD_BYTES as S, parseChannelBusPayload as T, recoveryCodesRelations as U, passwordResetTokensRelations as V, refreshTokens as W, usersSchema as X, usersRelations as Y, AuthenticatedPostgresBackendDriver as Z, refetchConcurrencyFor as _, openPostgresDriver as a, SQL_RESULT_BYTE_BUDGET as at, CHANNEL_BUS_NOTIFY_CHANNEL as b, PostgresTableRegistry as c, resolveNestedPath as ct, PostgresRealtimeProvider as d, PostgresConditionBuilder as dt, RoleSwitchUnavailableError as et, RealtimeService as f, configureUnknownFilterFields as ft, parseRealtimeTuning as g, listedColumnKeys as gt, parseMaxSubscriptionsPerSocket as h, joinColumn as ht, isScaffoldedLocalDatabase as i, sqlRoleRanAs as it, terminateIfBacklogged as j, budgetSendBuffers as k, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as l, assertReadRequestReadable as lt, parseMaxSocketsPerUser as m, getUnknownFilterFieldsMode as mt, createPostgresBootstrapper as n, effectiveSqlRole as nt, postgresDriverConfigFromEnv as o, SqlResultTooLargeError as ot, packEntityChanges as p, escapeLikePattern as pt, userIdentitiesRelations as q, describeSchemaDriftCause as r, isRoleSwitchingOptedOut as rt, resolveSourceUrls as s, isNestedPath as st, openRebase as t, branchParentDatabase as tt, DEFAULT_RECOUNT_MIN_ROWS as u, DrizzleConditionBuilder as ut, createChannelBus as v, parseChannelBusFrame as w, DEFAULT_BATCH_WINDOW_MS as x, resolveChannelBusSetting as y, mfaFactorsRelations as z };
24443
24938
 
24444
- //# sourceMappingURL=open-rebase-4kisUF_k.js.map
24939
+ //# sourceMappingURL=open-rebase-OB4hhQuk.js.map