@terreno/api 57.4.0 → 57.6.1

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 (210) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +617 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/api.arrayOperations.test.ts +44 -0
  173. package/src/api.ts +64 -39
  174. package/src/audit/auditApp.test.ts +5 -5
  175. package/src/audit/auditEventModel.ts +7 -3
  176. package/src/audit/auditRouter.test.ts +5 -5
  177. package/src/audit/rbacSink.test.ts +2 -2
  178. package/src/audit/record.test.ts +2 -2
  179. package/src/audit/record.ts +3 -2
  180. package/src/auth.ts +1 -1
  181. package/src/authRecovery.test.ts +43 -0
  182. package/src/authRecovery.ts +16 -10
  183. package/src/authTokens.ts +6 -2
  184. package/src/authVerification.test.ts +22 -0
  185. package/src/browserLogsRoute.ts +110 -0
  186. package/src/configurationPlugin.test.ts +1 -11
  187. package/src/expressServer.ts +10 -0
  188. package/src/frameworkModelNames.test.ts +62 -0
  189. package/src/frameworkModelNames.ts +33 -0
  190. package/src/index.ts +7 -0
  191. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  192. package/src/mcp/auth.test.ts +34 -1
  193. package/src/migrations/cli.test.ts +0 -23
  194. package/src/models/mcpServiceToken.ts +4 -3
  195. package/src/models/notification.ts +3 -2
  196. package/src/models/notificationPreference.ts +1 -1
  197. package/src/notifications/notificationsApp.test.ts +24 -1
  198. package/src/notifiers/slackNotifier.test.ts +186 -1
  199. package/src/notifiers/slackNotifier.ts +167 -8
  200. package/src/orgs/orgPlugin.ts +1 -1
  201. package/src/orgs/organizationModel.ts +11 -6
  202. package/src/plugins.test.ts +5 -0
  203. package/src/plugins.ts +3 -0
  204. package/src/realtime/realtimeApp.ts +1 -1
  205. package/src/sync/integration.test.ts +2 -2
  206. package/src/terrenoApp.ts +3 -0
  207. package/src/types.d.ts +1 -0
  208. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  209. package/tsconfig.json +13 -54
  210. package/tsconfig.typedoc.json +2 -0
@@ -1,15 +1,4 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
3
  if (k2 === undefined) k2 = k;
15
4
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -43,100 +32,28 @@ var __importStar = (this && this.__importStar) || (function () {
43
32
  return result;
44
33
  };
45
34
  })();
46
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
47
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
48
- return new (P || (P = Promise))(function (resolve, reject) {
49
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
50
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
51
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
52
- step((generator = generator.apply(thisArg, _arguments || [])).next());
53
- });
54
- };
55
- var __generator = (this && this.__generator) || function (thisArg, body) {
56
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
57
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
58
- function verb(n) { return function (v) { return step([n, v]); }; }
59
- function step(op) {
60
- if (f) throw new TypeError("Generator is already executing.");
61
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
62
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
63
- if (y = 0, t) op = [op[0] & 2, t.value];
64
- switch (op[0]) {
65
- case 0: case 1: t = op; break;
66
- case 4: _.label++; return { value: op[1], done: false };
67
- case 5: _.label++; y = op[1]; op = [0]; continue;
68
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
69
- default:
70
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
71
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
72
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
73
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
74
- if (t[2]) _.ops.pop();
75
- _.trys.pop(); continue;
76
- }
77
- op = body.call(thisArg, _);
78
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
79
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
80
- }
81
- };
82
- var __values = (this && this.__values) || function(o) {
83
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
84
- if (m) return m.call(o);
85
- if (o && typeof o.length === "number") return {
86
- next: function () {
87
- if (o && i >= o.length) o = void 0;
88
- return { value: o && o[i++], done: !o };
89
- }
90
- };
91
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
92
- };
93
- var __read = (this && this.__read) || function (o, n) {
94
- var m = typeof Symbol === "function" && o[Symbol.iterator];
95
- if (!m) return o;
96
- var i = m.call(o), r, ar = [], e;
97
- try {
98
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
99
- }
100
- catch (error) { e = { error: error }; }
101
- finally {
102
- try {
103
- if (r && !r.done && (m = i["return"])) m.call(i);
104
- }
105
- finally { if (e) throw e.error; }
106
- }
107
- return ar;
108
- };
109
- var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
110
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
111
- if (ar || !(i in from)) {
112
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
113
- ar[i] = from[i];
114
- }
115
- }
116
- return to.concat(ar || Array.prototype.slice.call(from));
117
- };
118
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
119
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
120
37
  };
121
38
  Object.defineProperty(exports, "__esModule", { value: true });
122
39
  exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = exports.emitSyncDeltaForChange = exports.emitToDocumentAndQueryRooms = exports.emitToAuthorizedRoom = exports.emitPayloadToAuthorizedRoom = exports.serializeDoc = exports.ensureApiId = exports.resolveRooms = exports.mapOperationType = exports.DEFAULT_IGNORED_COLLECTIONS = exports.SYNC_RESYNC_EVENT = void 0;
123
- var Sentry = __importStar(require("@sentry/bun"));
124
- var luxon_1 = require("luxon");
125
- var mongoose_1 = __importDefault(require("mongoose"));
126
- var errors_1 = require("../errors");
127
- var logger_1 = require("../logger");
128
- var realtimeAccess_1 = require("../rbac/realtimeAccess");
129
- var adminBroadcastScope_1 = require("../sync/adminBroadcastScope");
130
- var models_1 = require("../sync/models");
131
- var registry_1 = require("../sync/registry");
132
- var serialize_1 = require("../sync/serialize");
133
- var socketHandlers_1 = require("../sync/socketHandlers");
134
- var streams_1 = require("../sync/streams");
135
- var queryMatcher_1 = require("./queryMatcher");
136
- var queryStore_1 = require("./queryStore");
137
- var registry_2 = require("./registry");
138
- var socketUser_1 = require("./socketUser");
139
- var changeWatcher = null;
40
+ const Sentry = __importStar(require("@sentry/bun"));
41
+ const luxon_1 = require("luxon");
42
+ const mongoose_1 = __importDefault(require("mongoose"));
43
+ const errors_1 = require("../errors");
44
+ const logger_1 = require("../logger");
45
+ const realtimeAccess_1 = require("../rbac/realtimeAccess");
46
+ const adminBroadcastScope_1 = require("../sync/adminBroadcastScope");
47
+ const models_1 = require("../sync/models");
48
+ const registry_1 = require("../sync/registry");
49
+ const serialize_1 = require("../sync/serialize");
50
+ const socketHandlers_1 = require("../sync/socketHandlers");
51
+ const streams_1 = require("../sync/streams");
52
+ const queryMatcher_1 = require("./queryMatcher");
53
+ const queryStore_1 = require("./queryStore");
54
+ const registry_2 = require("./registry");
55
+ const socketUser_1 = require("./socketUser");
56
+ let changeWatcher = null;
140
57
  /**
141
58
  * Task 9.16: restart state for the single process-wide watcher.
142
59
  *
@@ -147,18 +64,18 @@ var changeWatcher = null;
147
64
  * observed resume token so no events in the gap are missed.
148
65
  */
149
66
  /** Resume token of the last change seen, replayed via `resumeAfter` on restart. */
150
- var lastResumeToken;
67
+ let lastResumeToken;
151
68
  /** Bumped on every open/stop so callbacks from a replaced stream are ignored. */
152
- var watcherGeneration = 0;
69
+ let watcherGeneration = 0;
153
70
  /** True between `stopChangeStreamWatcher()` and the next `startChangeStreamWatcher()`. */
154
- var watcherStopped = true;
71
+ let watcherStopped = true;
155
72
  /** Consecutive failed opens, driving the backoff delay. Reset on a successful change. */
156
- var restartAttempts = 0;
157
- var restartTimer = null;
73
+ let restartAttempts = 0;
74
+ let restartTimer = null;
158
75
  /** First restart delay; doubles per consecutive attempt up to the max. */
159
- var CHANGE_STREAM_RESTART_BASE_DELAY_MS = 250;
76
+ const CHANGE_STREAM_RESTART_BASE_DELAY_MS = 250;
160
77
  /** Ceiling for the restart backoff — a long outage retries once every 30s, forever. */
161
- var CHANGE_STREAM_RESTART_MAX_DELAY_MS = 30000;
78
+ const CHANGE_STREAM_RESTART_MAX_DELAY_MS = 30_000;
162
79
  /**
163
80
  * Socket event telling clients their cached cursors may have gaps and they must
164
81
  * re-bootstrap. Emitted when the change stream's oplog history is gone
@@ -168,14 +85,14 @@ var CHANGE_STREAM_RESTART_MAX_DELAY_MS = 30000;
168
85
  /** @internal */
169
86
  exports.SYNC_RESYNC_EVENT = "sync:resync-required";
170
87
  /** MongoDB error code / codeName for an unresumable change stream (oplog rolled past). */
171
- var CHANGE_STREAM_HISTORY_LOST_CODE = 286;
88
+ const CHANGE_STREAM_HISTORY_LOST_CODE = 286;
172
89
  /** True when the error means the resume token can no longer be used. */
173
- var isHistoryLostError = function (error) {
174
- var _a = (error !== null && error !== void 0 ? error : {}), code = _a.code, codeName = _a.codeName, message = _a.message;
90
+ const isHistoryLostError = (error) => {
91
+ const { code, codeName, message } = (error ?? {});
175
92
  return (code === CHANGE_STREAM_HISTORY_LOST_CODE ||
176
93
  codeName === "ChangeStreamHistoryLost" ||
177
- Boolean(message === null || message === void 0 ? void 0 : message.includes("ChangeStreamHistoryLost")) ||
178
- Boolean(message === null || message === void 0 ? void 0 : message.includes("resume point may no longer be in the oplog")));
94
+ Boolean(message?.includes("ChangeStreamHistoryLost")) ||
95
+ Boolean(message?.includes("resume point may no longer be in the oplog")));
179
96
  };
180
97
  /**
181
98
  * C8: per-entity serialized dispatch. The change-stream `"change"` handler is async and
@@ -185,13 +102,12 @@ var isHistoryLostError = function (error) {
185
102
  * (`{collection}:{docId}`) so same-entity deltas dispatch strictly in change-stream
186
103
  * order, while different entities still run concurrently. Chains self-clean when idle.
187
104
  */
188
- var entityDispatchChains = new Map();
189
- var serializePerEntity = function (key, task) {
190
- var _a;
191
- var prior = (_a = entityDispatchChains.get(key)) !== null && _a !== void 0 ? _a : Promise.resolve();
192
- var next = prior.then(task, task);
105
+ const entityDispatchChains = new Map();
106
+ const serializePerEntity = (key, task) => {
107
+ const prior = entityDispatchChains.get(key) ?? Promise.resolve();
108
+ const next = prior.then(task, task);
193
109
  entityDispatchChains.set(key, next);
194
- void next.finally(function () {
110
+ void next.finally(() => {
195
111
  // Drop the chain once this was the last queued task, so the map does not grow.
196
112
  if (entityDispatchChains.get(key) === next) {
197
113
  entityDispatchChains.delete(key);
@@ -225,9 +141,7 @@ exports.DEFAULT_IGNORED_COLLECTIONS = [
225
141
  * Exported for testing.
226
142
  */
227
143
  /** @internal */
228
- var mapOperationType = function (operationType, change, enabledMethods) {
229
- var _a, _b;
230
- if (enabledMethods === void 0) { enabledMethods = ["create", "update", "delete"]; }
144
+ const mapOperationType = (operationType, change, enabledMethods = ["create", "update", "delete"]) => {
231
145
  if (operationType === "insert") {
232
146
  return "create";
233
147
  }
@@ -235,8 +149,8 @@ var mapOperationType = function (operationType, change, enabledMethods) {
235
149
  // Soft delete on an update event: the document was patched with deleted=true.
236
150
  // `change` is typed as the full union (without operationType narrowing) because
237
151
  // callers/tests pass change objects without setting `operationType` on the change.
238
- var updateChange = change;
239
- var isSoftDelete = operationType === "update" && ((_b = (_a = updateChange.updateDescription) === null || _a === void 0 ? void 0 : _a.updatedFields) === null || _b === void 0 ? void 0 : _b.deleted) === true;
152
+ const updateChange = change;
153
+ const isSoftDelete = operationType === "update" && updateChange.updateDescription?.updatedFields?.deleted === true;
240
154
  if (isSoftDelete && enabledMethods.includes("delete")) {
241
155
  return "delete";
242
156
  }
@@ -252,45 +166,32 @@ exports.mapOperationType = mapOperationType;
252
166
  * Get the collection tag from a route path (strips leading "/").
253
167
  * E.g. "/todos" -> "todos"
254
168
  */
255
- var getCollectionTag = function (routePath) { return routePath.replace(/^\//, ""); };
256
- var getSocketsInRoom = function (io, room) {
257
- var e_1, _a;
258
- var socketIds = io.sockets.adapter.rooms.get(room);
169
+ const getCollectionTag = (routePath) => routePath.replace(/^\//, "");
170
+ const getSocketsInRoom = (io, room) => {
171
+ const socketIds = io.sockets.adapter.rooms.get(room);
259
172
  if (!socketIds) {
260
173
  return [];
261
174
  }
262
- var sockets = [];
263
- try {
264
- for (var socketIds_1 = __values(socketIds), socketIds_1_1 = socketIds_1.next(); !socketIds_1_1.done; socketIds_1_1 = socketIds_1.next()) {
265
- var socketId = socketIds_1_1.value;
266
- var socket = io.sockets.sockets.get(socketId);
267
- if (socket) {
268
- sockets.push(socket);
269
- }
270
- }
271
- }
272
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
273
- finally {
274
- try {
275
- if (socketIds_1_1 && !socketIds_1_1.done && (_a = socketIds_1.return)) _a.call(socketIds_1);
175
+ const sockets = [];
176
+ for (const socketId of socketIds) {
177
+ const socket = io.sockets.sockets.get(socketId);
178
+ if (socket) {
179
+ sockets.push(socket);
276
180
  }
277
- finally { if (e_1) throw e_1.error; }
278
181
  }
279
182
  return sockets;
280
183
  };
281
- var emitCollectionTag = function (entry) { var _a; return (_a = entry.collectionTag) !== null && _a !== void 0 ? _a : (entry.routePath ? getCollectionTag(entry.routePath) : undefined); };
282
- var canReadDocument = function (entry, user, doc) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
283
- return [2 /*return*/, (0, realtimeAccess_1.canReadDocumentRealtime)(entry, user, doc)];
284
- }); }); };
184
+ const emitCollectionTag = (entry) => entry.collectionTag ?? (entry.routePath ? getCollectionTag(entry.routePath) : undefined);
185
+ const canReadDocument = async (entry, user, doc) => (0, realtimeAccess_1.canReadDocumentRealtime)(entry, user, doc);
285
186
  /**
286
187
  * Determine which Socket.io rooms to emit to based on the room strategy.
287
188
  * Exported for testing.
288
189
  */
289
190
  /** @internal */
290
- var resolveRooms = function (entry, doc, method) {
291
- var roomStrategy = entry.config.roomStrategy;
191
+ const resolveRooms = (entry, doc, method) => {
192
+ const { roomStrategy } = entry.config;
292
193
  // Use the collection tag (e.g. "todos") for model rooms, matching what the frontend subscribes to
293
- var collectionTag = getCollectionTag(entry.routePath);
194
+ const collectionTag = getCollectionTag(entry.routePath);
294
195
  if (typeof roomStrategy === "function") {
295
196
  // Custom room resolver — pass a minimal pseudo-request. The strategy only inspects
296
197
  // doc/method; we never read fields off req here, so an empty cast is safe.
@@ -298,19 +199,19 @@ var resolveRooms = function (entry, doc, method) {
298
199
  }
299
200
  switch (roomStrategy) {
300
201
  case "owner": {
301
- var ownerId = (doc === null || doc === void 0 ? void 0 : doc.ownerId) != null ? String(doc.ownerId) : undefined;
202
+ const ownerId = doc?.ownerId != null ? String(doc.ownerId) : undefined;
302
203
  if (ownerId) {
303
- return ["user:".concat(ownerId)];
204
+ return [`user:${ownerId}`];
304
205
  }
305
206
  // If no ownerId, fall back to model room
306
- return ["model:".concat(collectionTag)];
207
+ return [`model:${collectionTag}`];
307
208
  }
308
209
  case "model":
309
- return ["model:".concat(collectionTag)];
210
+ return [`model:${collectionTag}`];
310
211
  case "broadcast":
311
212
  return ["authenticated"];
312
213
  default:
313
- return ["model:".concat(collectionTag)];
214
+ return [`model:${collectionTag}`];
314
215
  }
315
216
  };
316
217
  exports.resolveRooms = resolveRooms;
@@ -319,13 +220,13 @@ exports.resolveRooms = resolveRooms;
319
220
  * Change stream fullDocument payloads are raw BSON objects with `_id` only.
320
221
  */
321
222
  /** @internal */
322
- var ensureApiId = function (data) {
223
+ const ensureApiId = (data) => {
323
224
  if (data == null || typeof data !== "object" || Array.isArray(data)) {
324
225
  return data;
325
226
  }
326
- var serialized = data;
227
+ const serialized = data;
327
228
  if (serialized._id != null && serialized.id == null) {
328
- return __assign(__assign({}, serialized), { id: serialized._id });
229
+ return { ...serialized, id: serialized._id };
329
230
  }
330
231
  return data;
331
232
  };
@@ -347,53 +248,39 @@ exports.ensureApiId = ensureApiId;
347
248
  * was supposed to strip.
348
249
  */
349
250
  /** @internal */
350
- var serializeDoc = function (entry, doc, method, user) { return __awaiter(void 0, void 0, void 0, function () {
351
- var _a, error_1, responseHandler, restMethod, syntheticReq, serialized, masked, error_2, fallback, maskedFallback;
352
- var _b;
353
- return __generator(this, function (_c) {
354
- switch (_c.label) {
355
- case 0:
356
- if (!entry.config.realtimeResponseHandler) return [3 /*break*/, 4];
357
- _c.label = 1;
358
- case 1:
359
- _c.trys.push([1, 3, , 4]);
360
- _a = exports.ensureApiId;
361
- return [4 /*yield*/, entry.config.realtimeResponseHandler(doc, method)];
362
- case 2: return [2 /*return*/, _a.apply(void 0, [_c.sent()])];
363
- case 3:
364
- error_1 = _c.sent();
365
- logger_1.logger.error("[realtime] realtimeResponseHandler threw for ".concat(entry.modelName, "/").concat(method, ": ").concat(error_1, ". ") +
366
- "Dropping event to avoid leaking unsanitized data.");
367
- throw error_1;
368
- case 4:
369
- responseHandler = (_b = entry.options) === null || _b === void 0 ? void 0 : _b.responseHandler;
370
- if (!responseHandler) return [3 /*break*/, 9];
371
- _c.label = 5;
372
- case 5:
373
- _c.trys.push([5, 8, , 9]);
374
- restMethod = method === "delete" ? "read" : method;
375
- syntheticReq = { params: {}, query: {}, user: user };
376
- return [4 /*yield*/, responseHandler(doc, restMethod, syntheticReq, entry.options)];
377
- case 6:
378
- serialized = _c.sent();
379
- return [4 /*yield*/, (0, realtimeAccess_1.maskRealtimeDocument)(entry, user, serialized, restMethod)];
380
- case 7:
381
- masked = _c.sent();
382
- return [2 /*return*/, (0, exports.ensureApiId)(masked)];
383
- case 8:
384
- error_2 = _c.sent();
385
- logger_1.logger.error("[realtime] modelRouter responseHandler threw during realtime serialization for " +
386
- "".concat(entry.modelName, "/").concat(method, ": ").concat(error_2, ". Dropping event to avoid leaking unsanitized data."));
387
- throw error_2;
388
- case 9:
389
- fallback = typeof doc.toJSON === "function" ? doc.toJSON() : doc;
390
- return [4 /*yield*/, (0, realtimeAccess_1.maskRealtimeDocument)(entry, user, fallback, method === "delete" ? "read" : method)];
391
- case 10:
392
- maskedFallback = _c.sent();
393
- return [2 /*return*/, (0, exports.ensureApiId)(maskedFallback)];
251
+ const serializeDoc = async (entry, doc, method, user) => {
252
+ if (entry.config.realtimeResponseHandler) {
253
+ try {
254
+ return (0, exports.ensureApiId)(await entry.config.realtimeResponseHandler(doc, method));
394
255
  }
395
- });
396
- }); };
256
+ catch (error) {
257
+ logger_1.logger.error(`[realtime] realtimeResponseHandler threw for ${entry.modelName}/${method}: ${error}. ` +
258
+ "Dropping event to avoid leaking unsanitized data.");
259
+ throw error;
260
+ }
261
+ }
262
+ const responseHandler = entry.options?.responseHandler;
263
+ if (responseHandler) {
264
+ try {
265
+ // The REST responseHandler signature expects a "list" | "create" | "read" | "update" method.
266
+ // Map "delete" → "read" so handlers that branch on method receive a sane value.
267
+ const restMethod = method === "delete" ? "read" : method;
268
+ // Synthesize the minimal request shape responseHandlers commonly inspect.
269
+ const syntheticReq = { params: {}, query: {}, user };
270
+ const serialized = await responseHandler(doc, restMethod, syntheticReq, entry.options);
271
+ const masked = await (0, realtimeAccess_1.maskRealtimeDocument)(entry, user, serialized, restMethod);
272
+ return (0, exports.ensureApiId)(masked);
273
+ }
274
+ catch (error) {
275
+ logger_1.logger.error(`[realtime] modelRouter responseHandler threw during realtime serialization for ` +
276
+ `${entry.modelName}/${method}: ${error}. Dropping event to avoid leaking unsanitized data.`);
277
+ throw error;
278
+ }
279
+ }
280
+ const fallback = typeof doc.toJSON === "function" ? doc.toJSON() : doc;
281
+ const maskedFallback = await (0, realtimeAccess_1.maskRealtimeDocument)(entry, user, fallback, method === "delete" ? "read" : method);
282
+ return (0, exports.ensureApiId)(maskedFallback);
283
+ };
397
284
  exports.serializeDoc = serializeDoc;
398
285
  /**
399
286
  * Generalized authorized-room emitter: iterates the sockets in `room`, runs the per-socket
@@ -403,114 +290,60 @@ exports.serializeDoc = serializeDoc;
403
290
  * `emitToAuthorizedRoom` (legacy "sync" events) and the sync layer's `sync:delta`
404
291
  * emission both delegate here.
405
292
  */
406
- var emitPayloadToAuthorizedRoom = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
407
- var sockets, sockets_1, sockets_1_1, socket, user, permissionDocument, collectionTag, adminDecision, _c, _d, _e, canRead, _f, _g, _h, error_3, e_2_1;
408
- var e_2, _j;
409
- var io = _b.io, room = _b.room, eventName = _b.eventName, entry = _b.entry, fullDocument = _b.fullDocument, buildPayload = _b.buildPayload, logDebug = _b.logDebug;
410
- return __generator(this, function (_k) {
411
- switch (_k.label) {
412
- case 0:
413
- sockets = getSocketsInRoom(io, room);
414
- _k.label = 1;
415
- case 1:
416
- _k.trys.push([1, 13, 14, 15]);
417
- sockets_1 = __values(sockets), sockets_1_1 = sockets_1.next();
418
- _k.label = 2;
419
- case 2:
420
- if (!!sockets_1_1.done) return [3 /*break*/, 12];
421
- socket = sockets_1_1.value;
422
- return [4 /*yield*/, (0, socketUser_1.awaitSocketFullUser)(socket)];
423
- case 3:
424
- user = _k.sent();
425
- _k.label = 4;
426
- case 4:
427
- _k.trys.push([4, 10, , 11]);
428
- permissionDocument = fullDocument !== null && fullDocument !== void 0 ? fullDocument : {};
429
- collectionTag = emitCollectionTag(entry);
430
- if (!(collectionTag && (0, adminBroadcastScope_1.isAdminBroadcastSocketRoom)(room, collectionTag))) return [3 /*break*/, 7];
431
- return [4 /*yield*/, (0, adminBroadcastScope_1.authorizeAdminBroadcastDocument)({
432
- doc: fullDocument,
433
- modelName: entry.modelName,
434
- user: user,
435
- })];
436
- case 5:
437
- adminDecision = _k.sent();
293
+ const emitPayloadToAuthorizedRoom = async ({ io, room, eventName, entry, fullDocument, buildPayload, logDebug, }) => {
294
+ const sockets = getSocketsInRoom(io, room);
295
+ for (const socket of sockets) {
296
+ const user = await (0, socketUser_1.awaitSocketFullUser)(socket);
297
+ try {
298
+ // Hard deletes have no document context; use an empty object so object-scoped
299
+ // permission helpers fail closed instead of treating the check as preflight.
300
+ const permissionDocument = fullDocument ?? {};
301
+ const collectionTag = emitCollectionTag(entry);
302
+ if (collectionTag && (0, adminBroadcastScope_1.isAdminBroadcastSocketRoom)(room, collectionTag)) {
303
+ const adminDecision = await (0, adminBroadcastScope_1.authorizeAdminBroadcastDocument)({
304
+ doc: fullDocument,
305
+ modelName: entry.modelName,
306
+ user,
307
+ });
438
308
  if (adminDecision === "deny") {
439
- logDebug("[realtime] Skipped ".concat(room, " for ").concat(socket.id, ": admin broadcast scope denied"));
440
- return [3 /*break*/, 11];
441
- }
442
- if (!(adminDecision === "allow")) return [3 /*break*/, 7];
443
- _d = (_c = socket).emit;
444
- _e = [eventName];
445
- return [4 /*yield*/, buildPayload(user)];
446
- case 6:
447
- _d.apply(_c, _e.concat([_k.sent()]));
448
- return [3 /*break*/, 11];
449
- case 7: return [4 /*yield*/, canReadDocument(entry, user, permissionDocument)];
450
- case 8:
451
- canRead = _k.sent();
452
- if (!canRead) {
453
- logDebug("[realtime] Skipped ".concat(room, " for ").concat(socket.id, ": read permission denied"));
454
- return [3 /*break*/, 11];
309
+ logDebug(`[realtime] Skipped ${room} for ${socket.id}: admin broadcast scope denied`);
310
+ continue;
455
311
  }
456
- _g = (_f = socket).emit;
457
- _h = [eventName];
458
- return [4 /*yield*/, buildPayload(user)];
459
- case 9:
460
- _g.apply(_f, _h.concat([_k.sent()]));
461
- return [3 /*break*/, 11];
462
- case 10:
463
- error_3 = _k.sent();
464
- logger_1.logger.error("[realtime] Failed to emit ".concat(eventName, " for ").concat(entry.modelName, " to socket ").concat(socket.id, ": ").concat(error_3));
465
- Sentry.captureException(error_3);
466
- return [3 /*break*/, 11];
467
- case 11:
468
- sockets_1_1 = sockets_1.next();
469
- return [3 /*break*/, 2];
470
- case 12: return [3 /*break*/, 15];
471
- case 13:
472
- e_2_1 = _k.sent();
473
- e_2 = { error: e_2_1 };
474
- return [3 /*break*/, 15];
475
- case 14:
476
- try {
477
- if (sockets_1_1 && !sockets_1_1.done && (_j = sockets_1.return)) _j.call(sockets_1);
312
+ if (adminDecision === "allow") {
313
+ socket.emit(eventName, await buildPayload(user));
314
+ continue;
478
315
  }
479
- finally { if (e_2) throw e_2.error; }
480
- return [7 /*endfinally*/];
481
- case 15: return [2 /*return*/];
316
+ }
317
+ const canRead = await canReadDocument(entry, user, permissionDocument);
318
+ if (!canRead) {
319
+ logDebug(`[realtime] Skipped ${room} for ${socket.id}: read permission denied`);
320
+ continue;
321
+ }
322
+ socket.emit(eventName, await buildPayload(user));
482
323
  }
483
- });
484
- }); };
324
+ catch (error) {
325
+ logger_1.logger.error(`[realtime] Failed to emit ${eventName} for ${entry.modelName} to socket ${socket.id}: ${error}`);
326
+ Sentry.captureException(error);
327
+ }
328
+ }
329
+ };
485
330
  exports.emitPayloadToAuthorizedRoom = emitPayloadToAuthorizedRoom;
486
331
  /** @internal */
487
- var emitToAuthorizedRoom = function (io, room, event, entry, fullDocument, logDebug) { return __awaiter(void 0, void 0, void 0, function () {
488
- return __generator(this, function (_a) {
489
- return [2 /*return*/, (0, exports.emitPayloadToAuthorizedRoom)({
490
- buildPayload: function (user) { return __awaiter(void 0, void 0, void 0, function () {
491
- var data;
492
- return __generator(this, function (_a) {
493
- switch (_a.label) {
494
- case 0:
495
- if (!fullDocument) {
496
- return [2 /*return*/, event];
497
- }
498
- return [4 /*yield*/, (0, exports.serializeDoc)(entry, fullDocument, event.method, user)];
499
- case 1:
500
- data = _a.sent();
501
- return [2 /*return*/, __assign(__assign({}, event), { data: data })];
502
- }
503
- });
504
- }); },
505
- entry: entry,
506
- eventName: "sync",
507
- fullDocument: fullDocument,
508
- io: io,
509
- logDebug: logDebug,
510
- room: room,
511
- })];
512
- });
513
- }); };
332
+ const emitToAuthorizedRoom = async (io, room, event, entry, fullDocument, logDebug) => (0, exports.emitPayloadToAuthorizedRoom)({
333
+ buildPayload: async (user) => {
334
+ if (!fullDocument) {
335
+ return event;
336
+ }
337
+ const data = await (0, exports.serializeDoc)(entry, fullDocument, event.method, user);
338
+ return { ...event, data };
339
+ },
340
+ entry,
341
+ eventName: "sync",
342
+ fullDocument,
343
+ io,
344
+ logDebug,
345
+ room,
346
+ });
514
347
  exports.emitToAuthorizedRoom = emitToAuthorizedRoom;
515
348
  /**
516
349
  * Emit a sync event to document-specific and query rooms.
@@ -529,226 +362,169 @@ exports.emitToAuthorizedRoom = emitToAuthorizedRoom;
529
362
  * Exported for testing.
530
363
  */
531
364
  /** @internal */
532
- var emitToDocumentAndQueryRooms = function (io, collection, event, fullDocument, logDebug, entry) { return __awaiter(void 0, void 0, void 0, function () {
533
- var docRoom, isOwnerStrategy, querySubscriptions, querySubscriptions_1, querySubscriptions_1_1, _a, queryId, query, queryRoom, docMatches, removeEvent, e_3_1;
534
- var e_3, _b;
535
- return __generator(this, function (_c) {
536
- switch (_c.label) {
537
- case 0:
538
- docRoom = "document:".concat(collection, ":").concat(event.id);
539
- if (!entry) return [3 /*break*/, 2];
540
- return [4 /*yield*/, (0, exports.emitToAuthorizedRoom)(io, docRoom, event, entry, fullDocument, logDebug)];
541
- case 1:
542
- _c.sent();
543
- return [3 /*break*/, 3];
544
- case 2:
545
- io.to(docRoom).emit("sync", event);
546
- _c.label = 3;
547
- case 3:
548
- logDebug("[realtime] Emitted ".concat(event.method, " to ").concat(docRoom));
549
- isOwnerStrategy = (entry === null || entry === void 0 ? void 0 : entry.config.roomStrategy) === "owner";
550
- querySubscriptions = (0, queryStore_1.getQuerySubscriptionsForCollection)(collection);
551
- _c.label = 4;
552
- case 4:
553
- _c.trys.push([4, 28, 29, 30]);
554
- querySubscriptions_1 = __values(querySubscriptions), querySubscriptions_1_1 = querySubscriptions_1.next();
555
- _c.label = 5;
556
- case 5:
557
- if (!!querySubscriptions_1_1.done) return [3 /*break*/, 27];
558
- _a = querySubscriptions_1_1.value, queryId = _a.queryId, query = _a.query;
559
- queryRoom = "query:".concat(queryId);
560
- if (!(event.method === "delete")) return [3 /*break*/, 14];
561
- if (!!fullDocument) return [3 /*break*/, 9];
365
+ const emitToDocumentAndQueryRooms = async (io, collection, event, fullDocument, logDebug, entry) => {
366
+ // Emit to document-specific room
367
+ const docRoom = `document:${collection}:${event.id}`;
368
+ if (entry) {
369
+ await (0, exports.emitToAuthorizedRoom)(io, docRoom, event, entry, fullDocument, logDebug);
370
+ }
371
+ else {
372
+ io.to(docRoom).emit("sync", event);
373
+ }
374
+ logDebug(`[realtime] Emitted ${event.method} to ${docRoom}`);
375
+ const isOwnerStrategy = entry?.config.roomStrategy === "owner";
376
+ // Evaluate query subscriptions
377
+ const querySubscriptions = (0, queryStore_1.getQuerySubscriptionsForCollection)(collection);
378
+ for (const { queryId, query } of querySubscriptions) {
379
+ const queryRoom = `query:${queryId}`;
380
+ if (event.method === "delete") {
381
+ if (!fullDocument) {
562
382
  // Hard delete with no document context. For owner-strategy collections we can't
563
383
  // tell which query rooms belong to the owner without leaking activity to others,
564
384
  // so skip query fanout entirely — subscribers will reconcile on next fetch.
565
385
  if (isOwnerStrategy) {
566
- logDebug("[realtime] Skipping hard delete fanout to ".concat(queryRoom, " (owner strategy, no fullDocument)"));
567
- return [3 /*break*/, 26];
386
+ logDebug(`[realtime] Skipping hard delete fanout to ${queryRoom} (owner strategy, no fullDocument)`);
387
+ continue;
568
388
  }
569
- if (!entry) return [3 /*break*/, 7];
570
- return [4 /*yield*/, (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug)];
571
- case 6:
572
- _c.sent();
573
- return [3 /*break*/, 8];
574
- case 7:
575
- io.to(queryRoom).emit("sync", event);
576
- _c.label = 8;
577
- case 8:
578
- logDebug("[realtime] Emitted hard delete to ".concat(queryRoom));
579
- return [3 /*break*/, 26];
580
- case 9:
581
- if (!(0, queryMatcher_1.matchesQuery)(fullDocument, query)) return [3 /*break*/, 13];
582
- if (!entry) return [3 /*break*/, 11];
583
- return [4 /*yield*/, (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug)];
584
- case 10:
585
- _c.sent();
586
- return [3 /*break*/, 12];
587
- case 11:
588
- io.to(queryRoom).emit("sync", event);
589
- _c.label = 12;
590
- case 12:
591
- logDebug("[realtime] Emitted soft delete to ".concat(queryRoom, " (query matched)"));
592
- _c.label = 13;
593
- case 13: return [3 /*break*/, 26];
594
- case 14:
595
- if (!fullDocument) {
596
- return [3 /*break*/, 26];
389
+ if (entry) {
390
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
597
391
  }
598
- docMatches = (0, queryMatcher_1.matchesQuery)(fullDocument, query);
599
- if (!(event.method === "create" && docMatches)) return [3 /*break*/, 18];
600
- if (!entry) return [3 /*break*/, 16];
601
- return [4 /*yield*/, (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug)];
602
- case 15:
603
- _c.sent();
604
- return [3 /*break*/, 17];
605
- case 16:
606
- io.to(queryRoom).emit("sync", event);
607
- _c.label = 17;
608
- case 17:
609
- logDebug("[realtime] Emitted create to ".concat(queryRoom, " (query matched)"));
610
- return [3 /*break*/, 26];
611
- case 18:
612
- if (!(event.method === "update")) return [3 /*break*/, 26];
613
- if (!docMatches) return [3 /*break*/, 22];
614
- if (!entry) return [3 /*break*/, 20];
615
- return [4 /*yield*/, (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug)];
616
- case 19:
617
- _c.sent();
618
- return [3 /*break*/, 21];
619
- case 20:
392
+ else {
393
+ io.to(queryRoom).emit("sync", event);
394
+ }
395
+ logDebug(`[realtime] Emitted hard delete to ${queryRoom}`);
396
+ continue;
397
+ }
398
+ // Soft delete: only forward to query rooms whose filter the document satisfies.
399
+ if ((0, queryMatcher_1.matchesQuery)(fullDocument, query)) {
400
+ if (entry) {
401
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
402
+ }
403
+ else {
404
+ io.to(queryRoom).emit("sync", event);
405
+ }
406
+ logDebug(`[realtime] Emitted soft delete to ${queryRoom} (query matched)`);
407
+ }
408
+ continue;
409
+ }
410
+ if (!fullDocument) {
411
+ continue;
412
+ }
413
+ const docMatches = (0, queryMatcher_1.matchesQuery)(fullDocument, query);
414
+ if (event.method === "create" && docMatches) {
415
+ // New document matches the query — send create event
416
+ if (entry) {
417
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
418
+ }
419
+ else {
620
420
  io.to(queryRoom).emit("sync", event);
621
- _c.label = 21;
622
- case 21:
623
- logDebug("[realtime] Emitted update to ".concat(queryRoom, " (query matched)"));
624
- return [3 /*break*/, 26];
625
- case 22:
626
- removeEvent = __assign(__assign({}, event), { method: "delete" });
627
- if (!entry) return [3 /*break*/, 24];
628
- return [4 /*yield*/, (0, exports.emitToAuthorizedRoom)(io, queryRoom, removeEvent, entry, fullDocument, logDebug)];
629
- case 23:
630
- _c.sent();
631
- return [3 /*break*/, 25];
632
- case 24:
633
- io.to(queryRoom).emit("sync", removeEvent);
634
- _c.label = 25;
635
- case 25:
636
- logDebug("[realtime] Emitted delete to ".concat(queryRoom, " (query no longer matched)"));
637
- _c.label = 26;
638
- case 26:
639
- querySubscriptions_1_1 = querySubscriptions_1.next();
640
- return [3 /*break*/, 5];
641
- case 27: return [3 /*break*/, 30];
642
- case 28:
643
- e_3_1 = _c.sent();
644
- e_3 = { error: e_3_1 };
645
- return [3 /*break*/, 30];
646
- case 29:
647
- try {
648
- if (querySubscriptions_1_1 && !querySubscriptions_1_1.done && (_b = querySubscriptions_1.return)) _b.call(querySubscriptions_1);
421
+ }
422
+ logDebug(`[realtime] Emitted create to ${queryRoom} (query matched)`);
423
+ }
424
+ else if (event.method === "update") {
425
+ if (docMatches) {
426
+ // Document still matches (or newly matches) — send update event
427
+ if (entry) {
428
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, event, entry, fullDocument, logDebug);
429
+ }
430
+ else {
431
+ io.to(queryRoom).emit("sync", event);
649
432
  }
650
- finally { if (e_3) throw e_3.error; }
651
- return [7 /*endfinally*/];
652
- case 30: return [2 /*return*/];
433
+ logDebug(`[realtime] Emitted update to ${queryRoom} (query matched)`);
434
+ }
435
+ else {
436
+ // Document no longer matches the query — send delete event so client removes it
437
+ const removeEvent = {
438
+ ...event,
439
+ method: "delete",
440
+ };
441
+ if (entry) {
442
+ await (0, exports.emitToAuthorizedRoom)(io, queryRoom, removeEvent, entry, fullDocument, logDebug);
443
+ }
444
+ else {
445
+ io.to(queryRoom).emit("sync", removeEvent);
446
+ }
447
+ logDebug(`[realtime] Emitted delete to ${queryRoom} (query no longer matched)`);
448
+ }
653
449
  }
654
- });
655
- }); };
450
+ }
451
+ };
656
452
  exports.emitToDocumentAndQueryRooms = emitToDocumentAndQueryRooms;
657
453
  /**
658
454
  * Emit legacy realtime "sync" events for a change on a realtime-registered collection.
659
455
  * Extracted verbatim from the change handler so sync-delta emission (which is keyed off
660
456
  * the independent sync registry) runs even when the realtime path skips the change.
661
457
  */
662
- var processRealtimeChange = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
663
- var method, fullDocument, isHardDelete, rooms, collectionTag, collection, event, rooms_1, rooms_1_1, room, e_4_1, metadata;
664
- var e_4, _c;
665
- var _d;
666
- var io = _b.io, entry = _b.entry, change = _b.change, docId = _b.docId, logDebug = _b.logDebug, logInfo = _b.logInfo;
667
- return __generator(this, function (_e) {
668
- switch (_e.label) {
669
- case 0:
670
- method = (0, exports.mapOperationType)(change.operationType, change, entry.config.methods);
671
- if (!method) {
672
- return [2 /*return*/];
673
- }
674
- // Check if this method is enabled for this model
675
- if (!entry.config.methods.includes(method)) {
676
- logDebug("[realtime] Method ".concat(method, " not enabled for ").concat(entry.modelName));
677
- return [2 /*return*/];
678
- }
679
- fullDocument = change.operationType === "delete" ? undefined : change.fullDocument;
680
- isHardDelete = method === "delete" && !fullDocument;
681
- if (isHardDelete) {
682
- // Hard delete: no fullDocument, so we can't resolve owner/custom rooms.
683
- // For owner strategy we cannot safely fan out to a model room without
684
- // leaking deletes across users — admins still receive the event via the
685
- // admin room and any document-specific subscribers via document rooms.
686
- if (entry.config.roomStrategy === "owner") {
687
- rooms = ["admin"];
688
- }
689
- else if (entry.config.roomStrategy === "broadcast") {
690
- rooms = ["authenticated"];
691
- }
692
- else {
693
- collectionTag = getCollectionTag(entry.routePath);
694
- rooms = ["model:".concat(collectionTag)];
695
- }
696
- }
697
- else {
698
- rooms = (0, exports.resolveRooms)(entry, fullDocument !== null && fullDocument !== void 0 ? fullDocument : {}, method);
699
- }
700
- collection = getCollectionTag(entry.routePath);
701
- event = __assign({ collection: collection, id: docId, method: method, model: entry.modelName, timestamp: luxon_1.DateTime.now().toMillis() }, (change.operationType === "update" && ((_d = change.updateDescription) === null || _d === void 0 ? void 0 : _d.updatedFields)
702
- ? { updatedFields: Object.keys(change.updateDescription.updatedFields) }
703
- : {}));
704
- _e.label = 1;
705
- case 1:
706
- _e.trys.push([1, 6, 7, 8]);
707
- rooms_1 = __values(rooms), rooms_1_1 = rooms_1.next();
708
- _e.label = 2;
709
- case 2:
710
- if (!!rooms_1_1.done) return [3 /*break*/, 5];
711
- room = rooms_1_1.value;
712
- return [4 /*yield*/, (0, exports.emitToAuthorizedRoom)(io, room, event, entry, fullDocument, logDebug)];
713
- case 3:
714
- _e.sent();
715
- _e.label = 4;
716
- case 4:
717
- rooms_1_1 = rooms_1.next();
718
- return [3 /*break*/, 2];
719
- case 5: return [3 /*break*/, 8];
720
- case 6:
721
- e_4_1 = _e.sent();
722
- e_4 = { error: e_4_1 };
723
- return [3 /*break*/, 8];
724
- case 7:
725
- try {
726
- if (rooms_1_1 && !rooms_1_1.done && (_c = rooms_1.return)) _c.call(rooms_1);
727
- }
728
- finally { if (e_4) throw e_4.error; }
729
- return [7 /*endfinally*/];
730
- case 8:
731
- // Emit to document-specific and query rooms
732
- return [4 /*yield*/, (0, exports.emitToDocumentAndQueryRooms)(io, collection, event, fullDocument, logDebug, entry)];
733
- case 9:
734
- // Emit to document-specific and query rooms
735
- _e.sent();
736
- logDebug("[realtime] Emitted ".concat(method, " for ").concat(entry.modelName, "/").concat(docId, " to rooms: ").concat(rooms.join(", ")));
737
- metadata = {
738
- collection: event.collection,
739
- id: event.id,
740
- method: event.method,
741
- model: event.model,
742
- timestamp: event.timestamp,
743
- };
744
- if (event.updatedFields) {
745
- metadata.updatedFields = event.updatedFields;
746
- }
747
- logInfo("[realtime] sync event: ".concat(JSON.stringify(metadata)));
748
- return [2 /*return*/];
458
+ const processRealtimeChange = async ({ io, entry, change, docId, logDebug, logInfo, }) => {
459
+ // Map to our method type. Pass enabledMethods so soft deletes only
460
+ // remap to "delete" when the model actually subscribes to deletes —
461
+ // otherwise the change is kept as "update" so update subscribers
462
+ // still receive it.
463
+ const method = (0, exports.mapOperationType)(change.operationType, change, entry.config.methods);
464
+ if (!method) {
465
+ return;
466
+ }
467
+ // Check if this method is enabled for this model
468
+ if (!entry.config.methods.includes(method)) {
469
+ logDebug(`[realtime] Method ${method} not enabled for ${entry.modelName}`);
470
+ return;
471
+ }
472
+ // fullDocument is present on insert/update/replace; absent on delete.
473
+ const fullDocument = change.operationType === "delete" ? undefined : change.fullDocument;
474
+ // For hard deletes, we don't have the full document
475
+ const isHardDelete = method === "delete" && !fullDocument;
476
+ // Determine target rooms
477
+ let rooms;
478
+ if (isHardDelete) {
479
+ // Hard delete: no fullDocument, so we can't resolve owner/custom rooms.
480
+ // For owner strategy we cannot safely fan out to a model room without
481
+ // leaking deletes across users — admins still receive the event via the
482
+ // admin room and any document-specific subscribers via document rooms.
483
+ if (entry.config.roomStrategy === "owner") {
484
+ rooms = ["admin"];
749
485
  }
750
- });
751
- }); };
486
+ else if (entry.config.roomStrategy === "broadcast") {
487
+ rooms = ["authenticated"];
488
+ }
489
+ else {
490
+ const collectionTag = getCollectionTag(entry.routePath);
491
+ rooms = [`model:${collectionTag}`];
492
+ }
493
+ }
494
+ else {
495
+ rooms = (0, exports.resolveRooms)(entry, fullDocument ?? {}, method);
496
+ }
497
+ const collection = getCollectionTag(entry.routePath);
498
+ const event = {
499
+ collection,
500
+ id: docId,
501
+ method,
502
+ model: entry.modelName,
503
+ timestamp: luxon_1.DateTime.now().toMillis(),
504
+ ...(change.operationType === "update" && change.updateDescription?.updatedFields
505
+ ? { updatedFields: Object.keys(change.updateDescription.updatedFields) }
506
+ : {}),
507
+ };
508
+ // Emit to strategy-based rooms (model/owner/broadcast)
509
+ for (const room of rooms) {
510
+ await (0, exports.emitToAuthorizedRoom)(io, room, event, entry, fullDocument, logDebug);
511
+ }
512
+ // Emit to document-specific and query rooms
513
+ await (0, exports.emitToDocumentAndQueryRooms)(io, collection, event, fullDocument, logDebug, entry);
514
+ logDebug(`[realtime] Emitted ${method} for ${entry.modelName}/${docId} to rooms: ${rooms.join(", ")}`);
515
+ // Log only metadata — never the document payload, which may contain sensitive fields.
516
+ const metadata = {
517
+ collection: event.collection,
518
+ id: event.id,
519
+ method: event.method,
520
+ model: event.model,
521
+ timestamp: event.timestamp,
522
+ };
523
+ if (event.updatedFields) {
524
+ metadata.updatedFields = event.updatedFields;
525
+ }
526
+ logInfo(`[realtime] sync event: ${JSON.stringify(metadata)}`);
527
+ };
752
528
  /**
753
529
  * Emit `sync:delta` events for a change on a sync-registered collection.
754
530
  *
@@ -778,166 +554,103 @@ var processRealtimeChange = function (_a) { return __awaiter(void 0, [_a], void
778
554
  *
779
555
  * Exported for testing.
780
556
  */
781
- var emitSyncDeltaForChange = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
782
- var fullDocument, mapped, method, deleted, seq, stream, markers, movedAway, _loop_1, markers_1, markers_1_1, marker, e_5_1, emitLiveDelta;
783
- var e_5, _c;
784
- var io = _b.io, entry = _b.entry, change = _b.change, docId = _b.docId, logDebug = _b.logDebug;
785
- return __generator(this, function (_d) {
786
- switch (_d.label) {
787
- case 0:
788
- if (change.operationType === "delete") {
789
- // Hard deletes are blocked on synced models by syncPlugin; a direct collection-level
790
- // delete has no post-image, so neither stream nor seq can be resolved. Clients
791
- // reconcile via snapshot instead.
792
- logDebug("[sync] Skipping hard delete for synced collection ".concat(entry.collectionTag, "/").concat(docId, ": ") +
793
- "no post-image to resolve stream/seq");
794
- return [2 /*return*/];
795
- }
796
- fullDocument = change.fullDocument;
797
- if (!fullDocument) {
798
- logDebug("[sync] Skipping ".concat(entry.collectionTag, "/").concat(docId, ": change has no fullDocument"));
799
- return [2 /*return*/];
800
- }
801
- mapped = (0, exports.mapOperationType)(change.operationType, change);
802
- if (!mapped) {
803
- return [2 /*return*/];
804
- }
805
- method = mapped;
806
- deleted = fullDocument.deleted === true;
807
- seq = typeof fullDocument._syncSeq === "number" ? fullDocument._syncSeq : 0;
808
- stream = (0, streams_1.resolveStreamForDoc)({
809
- collectionTag: entry.collectionTag,
810
- doc: fullDocument,
811
- scope: entry.config.scope,
812
- });
813
- return [4 /*yield*/, models_1.SyncScopeMove.find({
814
- collectionTag: entry.collectionTag,
815
- entityId: docId,
816
- }).lean()];
817
- case 1:
818
- markers = _d.sent();
819
- movedAway = false;
820
- _loop_1 = function (marker) {
821
- var markerFrontier, tombstone;
822
- return __generator(this, function (_e) {
823
- switch (_e.label) {
824
- case 0:
825
- if (marker.fromStream === stream) {
826
- return [2 /*return*/, "continue"];
827
- }
828
- movedAway = true;
829
- return [4 /*yield*/, (0, models_1.computeStableFrontier)({ stream: marker.fromStream })];
830
- case 1:
831
- markerFrontier = _e.sent();
832
- tombstone = {
833
- collection: entry.collectionTag,
834
- deleted: true,
835
- frontierSeq: markerFrontier,
836
- id: docId,
837
- method: "delete",
838
- seq: marker.seq,
839
- stream: marker.fromStream,
840
- };
841
- return [4 /*yield*/, (0, exports.emitPayloadToAuthorizedRoom)({
842
- buildPayload: function () { return tombstone; },
843
- entry: entry,
844
- eventName: "sync:delta",
845
- fullDocument: fullDocument,
846
- io: io,
847
- logDebug: logDebug,
848
- room: (0, socketHandlers_1.syncRoomForStream)(marker.fromStream),
849
- })];
850
- case 2:
851
- _e.sent();
852
- logDebug("[sync] Emitted scope-move tombstone for ".concat(entry.collectionTag, "/").concat(docId, " to ").concat(marker.fromStream, " seq=").concat(marker.seq));
853
- return [2 /*return*/];
854
- }
855
- });
856
- };
857
- _d.label = 2;
858
- case 2:
859
- _d.trys.push([2, 7, 8, 9]);
860
- markers_1 = __values(markers), markers_1_1 = markers_1.next();
861
- _d.label = 3;
862
- case 3:
863
- if (!!markers_1_1.done) return [3 /*break*/, 6];
864
- marker = markers_1_1.value;
865
- return [5 /*yield**/, _loop_1(marker)];
866
- case 4:
867
- _d.sent();
868
- _d.label = 5;
869
- case 5:
870
- markers_1_1 = markers_1.next();
871
- return [3 /*break*/, 3];
872
- case 6: return [3 /*break*/, 9];
873
- case 7:
874
- e_5_1 = _d.sent();
875
- e_5 = { error: e_5_1 };
876
- return [3 /*break*/, 9];
877
- case 8:
878
- try {
879
- if (markers_1_1 && !markers_1_1.done && (_c = markers_1.return)) _c.call(markers_1);
880
- }
881
- finally { if (e_5) throw e_5.error; }
882
- return [7 /*endfinally*/];
883
- case 9:
884
- // The new stream sees a moved-away doc for the first time: report it as a create
885
- // (unless the same write also soft-deleted the doc, in which case the tombstone wins).
886
- if (movedAway && method !== "delete") {
887
- method = "create";
888
- }
889
- emitLiveDelta = function (targetStream) { return __awaiter(void 0, void 0, void 0, function () {
890
- var frontierSeq, liveDelta;
891
- return __generator(this, function (_a) {
892
- switch (_a.label) {
893
- case 0: return [4 /*yield*/, (0, models_1.computeStableFrontier)({ stream: targetStream })];
894
- case 1:
895
- frontierSeq = _a.sent();
896
- liveDelta = __assign({ collection: entry.collectionTag, frontierSeq: frontierSeq, id: docId, method: method, seq: seq, stream: targetStream }, (deleted ? { deleted: true } : {}));
897
- return [4 /*yield*/, (0, exports.emitPayloadToAuthorizedRoom)({
898
- // C7: tombstone deltas carry no data (only id/seq/deleted); live deltas serialize.
899
- buildPayload: deleted
900
- ? function () { return liveDelta; }
901
- : function (user) { return __awaiter(void 0, void 0, void 0, function () {
902
- var syntheticReq, data, _a;
903
- return __generator(this, function (_b) {
904
- switch (_b.label) {
905
- case 0:
906
- syntheticReq = { params: {}, query: {}, user: user };
907
- _a = exports.ensureApiId;
908
- return [4 /*yield*/, (0, serialize_1.serializeSyncPayload)({ doc: fullDocument, entry: entry, method: method, req: syntheticReq })];
909
- case 1:
910
- data = _a.apply(void 0, [_b.sent()]);
911
- return [2 /*return*/, __assign(__assign({}, liveDelta), { data: data })];
912
- }
913
- });
914
- }); },
915
- entry: entry,
916
- eventName: "sync:delta",
917
- fullDocument: fullDocument,
918
- io: io,
919
- logDebug: logDebug,
920
- room: (0, socketHandlers_1.syncRoomForStream)(targetStream),
921
- })];
922
- case 2:
923
- _a.sent();
924
- logDebug("[sync] Emitted sync:delta ".concat(method, " for ").concat(entry.collectionTag, "/").concat(docId, " seq=").concat(seq, " stream=").concat(targetStream, " frontier=").concat(frontierSeq));
925
- return [2 /*return*/];
926
- }
927
- });
928
- }); };
929
- return [4 /*yield*/, emitLiveDelta(stream)];
930
- case 10:
931
- _d.sent();
932
- if (!(entry.config.adminBroadcast === true)) return [3 /*break*/, 12];
933
- return [4 /*yield*/, emitLiveDelta((0, streams_1.adminBroadcastStream)(entry.collectionTag))];
934
- case 11:
935
- _d.sent();
936
- _d.label = 12;
937
- case 12: return [2 /*return*/];
938
- }
557
+ const emitSyncDeltaForChange = async ({ io, entry, change, docId, logDebug, }) => {
558
+ if (change.operationType === "delete") {
559
+ // Hard deletes are blocked on synced models by syncPlugin; a direct collection-level
560
+ // delete has no post-image, so neither stream nor seq can be resolved. Clients
561
+ // reconcile via snapshot instead.
562
+ logDebug(`[sync] Skipping hard delete for synced collection ${entry.collectionTag}/${docId}: ` +
563
+ "no post-image to resolve stream/seq");
564
+ return;
565
+ }
566
+ const fullDocument = change.fullDocument;
567
+ if (!fullDocument) {
568
+ logDebug(`[sync] Skipping ${entry.collectionTag}/${docId}: change has no fullDocument`);
569
+ return;
570
+ }
571
+ const mapped = (0, exports.mapOperationType)(change.operationType, change);
572
+ if (!mapped) {
573
+ return;
574
+ }
575
+ let method = mapped;
576
+ const deleted = fullDocument.deleted === true;
577
+ const seq = typeof fullDocument._syncSeq === "number" ? fullDocument._syncSeq : 0;
578
+ const stream = (0, streams_1.resolveStreamForDoc)({
579
+ collectionTag: entry.collectionTag,
580
+ doc: fullDocument,
581
+ scope: entry.config.scope,
939
582
  });
940
- }); };
583
+ // C4: emit old-stream tombstones from durable markers, not the racy _syncPrevStream.
584
+ const markers = await models_1.SyncScopeMove.find({
585
+ collectionTag: entry.collectionTag,
586
+ entityId: docId,
587
+ }).lean();
588
+ let movedAway = false;
589
+ for (const marker of markers) {
590
+ if (marker.fromStream === stream) {
591
+ continue;
592
+ }
593
+ movedAway = true;
594
+ const markerFrontier = await (0, models_1.computeStableFrontier)({ stream: marker.fromStream });
595
+ const tombstone = {
596
+ collection: entry.collectionTag,
597
+ deleted: true,
598
+ frontierSeq: markerFrontier,
599
+ id: docId,
600
+ method: "delete",
601
+ seq: marker.seq,
602
+ stream: marker.fromStream,
603
+ };
604
+ await (0, exports.emitPayloadToAuthorizedRoom)({
605
+ buildPayload: () => tombstone,
606
+ entry,
607
+ eventName: "sync:delta",
608
+ fullDocument,
609
+ io,
610
+ logDebug,
611
+ room: (0, socketHandlers_1.syncRoomForStream)(marker.fromStream),
612
+ });
613
+ logDebug(`[sync] Emitted scope-move tombstone for ${entry.collectionTag}/${docId} to ${marker.fromStream} seq=${marker.seq}`);
614
+ }
615
+ // The new stream sees a moved-away doc for the first time: report it as a create
616
+ // (unless the same write also soft-deleted the doc, in which case the tombstone wins).
617
+ if (movedAway && method !== "delete") {
618
+ method = "create";
619
+ }
620
+ const emitLiveDelta = async (targetStream) => {
621
+ const frontierSeq = await (0, models_1.computeStableFrontier)({ stream: targetStream });
622
+ const liveDelta = {
623
+ collection: entry.collectionTag,
624
+ frontierSeq,
625
+ id: docId,
626
+ method,
627
+ seq,
628
+ stream: targetStream,
629
+ ...(deleted ? { deleted: true } : {}),
630
+ };
631
+ await (0, exports.emitPayloadToAuthorizedRoom)({
632
+ // C7: tombstone deltas carry no data (only id/seq/deleted); live deltas serialize.
633
+ buildPayload: deleted
634
+ ? () => liveDelta
635
+ : async (user) => {
636
+ const syntheticReq = { params: {}, query: {}, user };
637
+ const data = (0, exports.ensureApiId)(await (0, serialize_1.serializeSyncPayload)({ doc: fullDocument, entry, method, req: syntheticReq }));
638
+ return { ...liveDelta, data };
639
+ },
640
+ entry,
641
+ eventName: "sync:delta",
642
+ fullDocument,
643
+ io,
644
+ logDebug,
645
+ room: (0, socketHandlers_1.syncRoomForStream)(targetStream),
646
+ });
647
+ logDebug(`[sync] Emitted sync:delta ${method} for ${entry.collectionTag}/${docId} seq=${seq} stream=${targetStream} frontier=${frontierSeq}`);
648
+ };
649
+ await emitLiveDelta(stream);
650
+ if (entry.config.adminBroadcast === true) {
651
+ await emitLiveDelta((0, streams_1.adminBroadcastStream)(entry.collectionTag));
652
+ }
653
+ };
941
654
  exports.emitSyncDeltaForChange = emitSyncDeltaForChange;
942
655
  /**
943
656
  * Start watching MongoDB change streams and emitting real-time events.
@@ -946,13 +659,11 @@ exports.emitSyncDeltaForChange = emitSyncDeltaForChange;
946
659
  * exponential backoff, resuming from the last seen token. Call
947
660
  * {@link stopChangeStreamWatcher} to end supervision.
948
661
  */
949
- var startChangeStreamWatcher = function (io, config, debug) {
950
- if (config === void 0) { config = {}; }
951
- if (debug === void 0) { debug = false; }
662
+ const startChangeStreamWatcher = (io, config = {}, debug = false) => {
952
663
  watcherStopped = false;
953
664
  restartAttempts = 0;
954
665
  lastResumeToken = undefined;
955
- openChangeStream({ config: config, debug: debug, io: io });
666
+ openChangeStream({ config, debug, io });
956
667
  };
957
668
  exports.startChangeStreamWatcher = startChangeStreamWatcher;
958
669
  /**
@@ -960,50 +671,46 @@ exports.startChangeStreamWatcher = startChangeStreamWatcher;
960
671
  * was stopped, when a newer stream is already running (a failing stream can fire several
961
672
  * terminal events), or when a restart is already pending.
962
673
  */
963
- var scheduleChangeStreamRestart = function (_a) {
964
- var _b;
965
- var config = _a.config, debug = _a.debug, generation = _a.generation, io = _a.io, reason = _a.reason;
674
+ const scheduleChangeStreamRestart = ({ config, debug, generation, io, reason, }) => {
966
675
  if (watcherStopped || generation !== watcherGeneration || restartTimer) {
967
676
  return;
968
677
  }
969
678
  restartAttempts += 1;
970
- var delayMs = Math.min(CHANGE_STREAM_RESTART_BASE_DELAY_MS * Math.pow(2, (restartAttempts - 1)), CHANGE_STREAM_RESTART_MAX_DELAY_MS);
971
- logger_1.logger.warn("[realtime] Change stream ".concat(reason, "; reopening in ").concat(delayMs, "ms (attempt ").concat(restartAttempts, ")"), { resumable: lastResumeToken !== undefined });
972
- restartTimer = setTimeout(function () {
679
+ const delayMs = Math.min(CHANGE_STREAM_RESTART_BASE_DELAY_MS * 2 ** (restartAttempts - 1), CHANGE_STREAM_RESTART_MAX_DELAY_MS);
680
+ logger_1.logger.warn(`[realtime] Change stream ${reason}; reopening in ${delayMs}ms (attempt ${restartAttempts})`, { resumable: lastResumeToken !== undefined });
681
+ restartTimer = setTimeout(() => {
973
682
  restartTimer = null;
974
683
  if (watcherStopped) {
975
684
  return;
976
685
  }
977
- openChangeStream({ config: config, debug: debug, io: io, isReopen: true });
686
+ openChangeStream({ config, debug, io, isReopen: true });
978
687
  }, delayMs);
979
688
  // Never hold the process open just to retry a watcher.
980
- (_b = restartTimer.unref) === null || _b === void 0 ? void 0 : _b.call(restartTimer);
689
+ restartTimer.unref?.();
981
690
  };
982
691
  /**
983
692
  * Open (or re-open) the change stream and wire its listeners. Throws only for a
984
693
  * configuration-level failure on the FIRST open (no connection, `watch` returned nothing),
985
694
  * which must fail startup loudly; a failure while reopening is retried with backoff.
986
695
  */
987
- var openChangeStream = function (_a) {
988
- var _b, _c, _d, _e;
989
- var config = _a.config, debug = _a.debug, io = _a.io, _f = _a.isReopen, isReopen = _f === void 0 ? false : _f;
990
- var logInfo = function (message) {
696
+ const openChangeStream = ({ config, debug, io, isReopen = false, }) => {
697
+ const logInfo = (message) => {
991
698
  if (debug) {
992
699
  logger_1.logger.info(message);
993
700
  }
994
701
  };
995
- var logDebug = function (message) {
702
+ const logDebug = (message) => {
996
703
  if (debug) {
997
704
  logger_1.logger.debug(message);
998
705
  }
999
706
  };
1000
- var generation = ++watcherGeneration;
707
+ const generation = ++watcherGeneration;
1001
708
  try {
1002
709
  logInfo("[realtime] Initializing change stream watcher...");
1003
- var ignored = new Set(__spreadArray(__spreadArray([], __read(exports.DEFAULT_IGNORED_COLLECTIONS), false), __read(((_b = config.ignoredCollections) !== null && _b !== void 0 ? _b : [])), false));
1004
- var ignoredOps_1 = new Set((_c = config.ignoredOperations) !== null && _c !== void 0 ? _c : []);
710
+ const ignored = new Set([...exports.DEFAULT_IGNORED_COLLECTIONS, ...(config.ignoredCollections ?? [])]);
711
+ const ignoredOps = new Set(config.ignoredOperations ?? []);
1005
712
  // Build the change stream pipeline
1006
- var pipeline = [
713
+ const pipeline = [
1007
714
  {
1008
715
  $match: {
1009
716
  "ns.coll": { $nin: Array.from(ignored) },
@@ -1020,104 +727,94 @@ var openChangeStream = function (_a) {
1020
727
  },
1021
728
  },
1022
729
  ];
1023
- var nativeDb = mongoose_1.default.connection.db;
730
+ const nativeDb = mongoose_1.default.connection.db;
1024
731
  if (!nativeDb) {
1025
732
  throw new errors_1.APIError({
1026
733
  status: 500,
1027
734
  title: "MongoDB connection not available for change stream",
1028
735
  });
1029
736
  }
1030
- var options = __assign({ batchSize: (_d = config.batchSize) !== null && _d !== void 0 ? _d : 50, fullDocument: (_e = config.fullDocument) !== null && _e !== void 0 ? _e : "updateLookup", fullDocumentBeforeChange: "off",
737
+ const options = {
738
+ batchSize: config.batchSize ?? 50,
739
+ fullDocument: config.fullDocument ?? "updateLookup",
740
+ fullDocumentBeforeChange: "off",
1031
741
  // How long the cursor waits for new events before yielding control.
1032
742
  // Lower values give more responsive updates at the cost of more frequent driver round-trips.
1033
- maxAwaitTimeMS: 1000 }, (lastResumeToken !== undefined ? { resumeAfter: lastResumeToken } : {}));
1034
- var stream = nativeDb.watch(pipeline, options);
743
+ maxAwaitTimeMS: 1000,
744
+ // Task 9.16: resume where the previous stream died so events during the outage are
745
+ // delivered rather than lost. Absent on a first open and after history loss.
746
+ ...(lastResumeToken !== undefined ? { resumeAfter: lastResumeToken } : {}),
747
+ };
748
+ const stream = nativeDb.watch(pipeline, options);
1035
749
  if (!stream) {
1036
750
  throw new errors_1.APIError({ status: 500, title: "Failed to create change stream watcher" });
1037
751
  }
1038
752
  changeWatcher = stream;
1039
- stream.on("change", function (rawChange) { return __awaiter(void 0, void 0, void 0, function () {
1040
- var token, change_1, collectionName, docId_1, entry, syncEntry_1, error_4;
1041
- var _a, _b, _c;
1042
- return __generator(this, function (_d) {
1043
- switch (_d.label) {
1044
- case 0:
1045
- _d.trys.push([0, 3, , 4]);
1046
- token = rawChange._id;
1047
- if (token !== undefined) {
1048
- lastResumeToken = token;
1049
- }
1050
- // A stream that is delivering events has recovered; drop the accumulated backoff so
1051
- // the next unrelated failure retries promptly instead of at the previous ceiling.
1052
- restartAttempts = 0;
1053
- // The pipeline restricts operationType to a subset that always has ns/documentKey;
1054
- // narrow once here so downstream code doesn't need repeated casts.
1055
- if (rawChange.operationType !== "insert" &&
1056
- rawChange.operationType !== "update" &&
1057
- rawChange.operationType !== "replace" &&
1058
- rawChange.operationType !== "delete") {
1059
- return [2 /*return*/];
1060
- }
1061
- change_1 = rawChange;
1062
- collectionName = (_a = change_1.ns) === null || _a === void 0 ? void 0 : _a.coll;
1063
- docId_1 = (_c = (_b = change_1.documentKey) === null || _b === void 0 ? void 0 : _b._id) === null || _c === void 0 ? void 0 : _c.toString();
1064
- if (!collectionName || !docId_1) {
1065
- return [2 /*return*/];
1066
- }
1067
- // Check if this operation type is ignored
1068
- if (ignoredOps_1.has(change_1.operationType)) {
1069
- return [2 /*return*/];
1070
- }
1071
- entry = (0, registry_2.findRegistryEntryByCollection)(collectionName);
1072
- syncEntry_1 = (0, registry_1.findSyncEntryByCollectionName)(collectionName);
1073
- if (!entry && !syncEntry_1) {
1074
- // Not a registered realtime or sync model — skip
1075
- logDebug("[realtime] No registry entry for collection: ".concat(collectionName));
1076
- return [2 /*return*/];
753
+ stream.on("change", async (rawChange) => {
754
+ try {
755
+ // Task 9.16: record the resume token FIRST, for every change — including ones this
756
+ // watcher ignores. A token only from processed events would rewind the stream to an
757
+ // old position after a restart and re-deliver everything since.
758
+ const token = rawChange._id;
759
+ if (token !== undefined) {
760
+ lastResumeToken = token;
761
+ }
762
+ // A stream that is delivering events has recovered; drop the accumulated backoff so
763
+ // the next unrelated failure retries promptly instead of at the previous ceiling.
764
+ restartAttempts = 0;
765
+ // The pipeline restricts operationType to a subset that always has ns/documentKey;
766
+ // narrow once here so downstream code doesn't need repeated casts.
767
+ if (rawChange.operationType !== "insert" &&
768
+ rawChange.operationType !== "update" &&
769
+ rawChange.operationType !== "replace" &&
770
+ rawChange.operationType !== "delete") {
771
+ return;
772
+ }
773
+ const change = rawChange;
774
+ const collectionName = change.ns?.coll;
775
+ const docId = change.documentKey?._id?.toString();
776
+ if (!collectionName || !docId) {
777
+ return;
778
+ }
779
+ // Check if this operation type is ignored
780
+ if (ignoredOps.has(change.operationType)) {
781
+ return;
782
+ }
783
+ // Realtime and sync registries are independent: a model may be in either or both.
784
+ // A model with both configs emits both the legacy "sync" event and "sync:delta".
785
+ const entry = (0, registry_2.findRegistryEntryByCollection)(collectionName);
786
+ const syncEntry = (0, registry_1.findSyncEntryByCollectionName)(collectionName);
787
+ if (!entry && !syncEntry) {
788
+ // Not a registered realtime or sync model — skip
789
+ logDebug(`[realtime] No registry entry for collection: ${collectionName}`);
790
+ return;
791
+ }
792
+ if (entry) {
793
+ await processRealtimeChange({ change, docId, entry, io, logDebug, logInfo });
794
+ }
795
+ if (syncEntry) {
796
+ // C8: serialize per entity so same-doc deltas emit in change-stream order;
797
+ // different docs still dispatch concurrently. See serializePerEntity + the
798
+ // per-entity LWW-by-seq contract documented in sync/types.ts (SyncDelta).
799
+ serializePerEntity(`${collectionName}:${docId}`, async () => {
800
+ try {
801
+ await (0, exports.emitSyncDeltaForChange)({ change, docId, entry: syncEntry, io, logDebug });
1077
802
  }
1078
- if (!entry) return [3 /*break*/, 2];
1079
- return [4 /*yield*/, processRealtimeChange({ change: change_1, docId: docId_1, entry: entry, io: io, logDebug: logDebug, logInfo: logInfo })];
1080
- case 1:
1081
- _d.sent();
1082
- _d.label = 2;
1083
- case 2:
1084
- if (syncEntry_1) {
1085
- // C8: serialize per entity so same-doc deltas emit in change-stream order;
1086
- // different docs still dispatch concurrently. See serializePerEntity + the
1087
- // per-entity LWW-by-seq contract documented in sync/types.ts (SyncDelta).
1088
- serializePerEntity("".concat(collectionName, ":").concat(docId_1), function () { return __awaiter(void 0, void 0, void 0, function () {
1089
- var error_5;
1090
- return __generator(this, function (_a) {
1091
- switch (_a.label) {
1092
- case 0:
1093
- _a.trys.push([0, 2, , 3]);
1094
- return [4 /*yield*/, (0, exports.emitSyncDeltaForChange)({ change: change_1, docId: docId_1, entry: syncEntry_1, io: io, logDebug: logDebug })];
1095
- case 1:
1096
- _a.sent();
1097
- return [3 /*break*/, 3];
1098
- case 2:
1099
- error_5 = _a.sent();
1100
- logger_1.logger.error("[sync] Error emitting sync delta: ".concat(error_5));
1101
- Sentry.captureException(error_5);
1102
- return [3 /*break*/, 3];
1103
- case 3: return [2 /*return*/];
1104
- }
1105
- });
1106
- }); });
803
+ catch (error) {
804
+ logger_1.logger.error(`[sync] Error emitting sync delta: ${error}`);
805
+ Sentry.captureException(error);
1107
806
  }
1108
- return [3 /*break*/, 4];
1109
- case 3:
1110
- error_4 = _d.sent();
1111
- logger_1.logger.error("[realtime] Error processing change event: ".concat(error_4));
1112
- Sentry.captureException(error_4);
1113
- return [3 /*break*/, 4];
1114
- case 4: return [2 /*return*/];
807
+ });
1115
808
  }
1116
- });
1117
- }); });
1118
- stream.on("error", function (err) {
809
+ }
810
+ catch (error) {
811
+ logger_1.logger.error(`[realtime] Error processing change event: ${error}`);
812
+ Sentry.captureException(error);
813
+ }
814
+ });
815
+ stream.on("error", (err) => {
1119
816
  Sentry.captureException(err);
1120
- logger_1.logger.error("[realtime] Change stream error: ".concat((err === null || err === void 0 ? void 0 : err.message) || err));
817
+ logger_1.logger.error(`[realtime] Change stream error: ${err?.message || err}`);
1121
818
  if (isHistoryLostError(err)) {
1122
819
  // The oplog no longer contains the resume point, so the gap can never be replayed.
1123
820
  // Reopen from NOW and tell clients to re-bootstrap: their cursors may sit below
@@ -1125,28 +822,28 @@ var openChangeStream = function (_a) {
1125
822
  lastResumeToken = undefined;
1126
823
  logger_1.logger.error("[sync] Change stream history lost; reopening without a resume token and asking " +
1127
824
  "clients to resync");
1128
- var hint = { reason: "history_lost" };
825
+ const hint = { reason: "history_lost" };
1129
826
  io.emit(exports.SYNC_RESYNC_EVENT, hint);
1130
827
  }
1131
- scheduleChangeStreamRestart({ config: config, debug: debug, generation: generation, io: io, reason: "errored" });
828
+ scheduleChangeStreamRestart({ config, debug, generation, io, reason: "errored" });
1132
829
  });
1133
- stream.on("close", function () {
830
+ stream.on("close", () => {
1134
831
  logger_1.logger.warn("[realtime] Change stream closed");
1135
- scheduleChangeStreamRestart({ config: config, debug: debug, generation: generation, io: io, reason: "closed" });
832
+ scheduleChangeStreamRestart({ config, debug, generation, io, reason: "closed" });
1136
833
  });
1137
- stream.on("end", function () {
834
+ stream.on("end", () => {
1138
835
  logger_1.logger.warn("[realtime] Change stream ended");
1139
- scheduleChangeStreamRestart({ config: config, debug: debug, generation: generation, io: io, reason: "ended" });
836
+ scheduleChangeStreamRestart({ config, debug, generation, io, reason: "ended" });
1140
837
  });
1141
838
  logInfo("[realtime] Change stream watcher initialized successfully");
1142
839
  }
1143
840
  catch (error) {
1144
- logger_1.logger.error("[realtime] Failed to initialize change stream watcher: ".concat(error));
841
+ logger_1.logger.error(`[realtime] Failed to initialize change stream watcher: ${error}`);
1145
842
  Sentry.captureException(error);
1146
843
  // A first open must fail startup loudly; a failed REOPEN (the DB is down mid-flight)
1147
844
  // has no caller to throw to, so keep retrying with backoff instead.
1148
845
  if (isReopen && !watcherStopped) {
1149
- scheduleChangeStreamRestart({ config: config, debug: debug, generation: generation, io: io, reason: "failed to open" });
846
+ scheduleChangeStreamRestart({ config, debug, generation, io, reason: "failed to open" });
1150
847
  return;
1151
848
  }
1152
849
  throw error;
@@ -1156,25 +853,17 @@ var openChangeStream = function (_a) {
1156
853
  * Stop the change stream watcher and end Task 9.16's restart supervision (a pending
1157
854
  * reopen is cancelled, and terminal events from the closing stream are ignored).
1158
855
  */
1159
- var stopChangeStreamWatcher = function () { return __awaiter(void 0, void 0, void 0, function () {
1160
- return __generator(this, function (_a) {
1161
- switch (_a.label) {
1162
- case 0:
1163
- watcherStopped = true;
1164
- if (restartTimer) {
1165
- clearTimeout(restartTimer);
1166
- restartTimer = null;
1167
- }
1168
- restartAttempts = 0;
1169
- lastResumeToken = undefined;
1170
- if (!changeWatcher) return [3 /*break*/, 2];
1171
- return [4 /*yield*/, changeWatcher.close()];
1172
- case 1:
1173
- _a.sent();
1174
- changeWatcher = null;
1175
- _a.label = 2;
1176
- case 2: return [2 /*return*/];
1177
- }
1178
- });
1179
- }); };
856
+ const stopChangeStreamWatcher = async () => {
857
+ watcherStopped = true;
858
+ if (restartTimer) {
859
+ clearTimeout(restartTimer);
860
+ restartTimer = null;
861
+ }
862
+ restartAttempts = 0;
863
+ lastResumeToken = undefined;
864
+ if (changeWatcher) {
865
+ await changeWatcher.close();
866
+ changeWatcher = null;
867
+ }
868
+ };
1180
869
  exports.stopChangeStreamWatcher = stopChangeStreamWatcher;