@terreno/api 57.4.0 → 57.6.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 (208) 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 +598 -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/audit/auditApp.test.ts +5 -5
  173. package/src/audit/auditEventModel.ts +7 -3
  174. package/src/audit/auditRouter.test.ts +5 -5
  175. package/src/audit/rbacSink.test.ts +2 -2
  176. package/src/audit/record.test.ts +2 -2
  177. package/src/audit/record.ts +3 -2
  178. package/src/auth.ts +1 -1
  179. package/src/authRecovery.test.ts +43 -0
  180. package/src/authRecovery.ts +16 -10
  181. package/src/authTokens.ts +6 -2
  182. package/src/authVerification.test.ts +22 -0
  183. package/src/browserLogsRoute.ts +110 -0
  184. package/src/configurationPlugin.test.ts +1 -11
  185. package/src/expressServer.ts +10 -0
  186. package/src/frameworkModelNames.test.ts +62 -0
  187. package/src/frameworkModelNames.ts +33 -0
  188. package/src/index.ts +7 -0
  189. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  190. package/src/mcp/auth.test.ts +34 -1
  191. package/src/migrations/cli.test.ts +0 -23
  192. package/src/models/mcpServiceToken.ts +4 -3
  193. package/src/models/notification.ts +3 -2
  194. package/src/models/notificationPreference.ts +1 -1
  195. package/src/notifications/notificationsApp.test.ts +24 -1
  196. package/src/notifiers/slackNotifier.test.ts +186 -1
  197. package/src/notifiers/slackNotifier.ts +167 -8
  198. package/src/orgs/orgPlugin.ts +1 -1
  199. package/src/orgs/organizationModel.ts +11 -6
  200. package/src/plugins.test.ts +5 -0
  201. package/src/plugins.ts +3 -0
  202. package/src/realtime/realtimeApp.ts +1 -1
  203. package/src/sync/integration.test.ts +2 -2
  204. package/src/terrenoApp.ts +3 -0
  205. package/src/types.d.ts +1 -0
  206. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  207. package/tsconfig.json +13 -54
  208. 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,58 +32,22 @@ 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
35
  Object.defineProperty(exports, "__esModule", { value: true });
83
36
  exports.RealtimeApp = exports.installRealtimeSocketHandlers = exports.redactCredentials = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = void 0;
84
- var Sentry = __importStar(require("@sentry/bun"));
85
- var socket_io_1 = require("socket.io");
86
- var errors_1 = require("../errors");
87
- var logger_1 = require("../logger");
88
- var realtimeAccess_1 = require("../rbac/realtimeAccess");
89
- var registry_1 = require("../sync/registry");
90
- var socketHandlers_1 = require("../sync/socketHandlers");
91
- var syncApp_1 = require("../sync/syncApp");
92
- var changeStreamWatcher_1 = require("./changeStreamWatcher");
93
- var queryStore_1 = require("./queryStore");
94
- var registry_2 = require("./registry");
95
- var sessionRevalidation_1 = require("./sessionRevalidation");
96
- var socketAuth_1 = require("./socketAuth");
97
- var socketUser_1 = require("./socketUser");
37
+ const Sentry = __importStar(require("@sentry/bun"));
38
+ const socket_io_1 = require("socket.io");
39
+ const errors_1 = require("../errors");
40
+ const logger_1 = require("../logger");
41
+ const realtimeAccess_1 = require("../rbac/realtimeAccess");
42
+ const registry_1 = require("../sync/registry");
43
+ const socketHandlers_1 = require("../sync/socketHandlers");
44
+ const syncApp_1 = require("../sync/syncApp");
45
+ const changeStreamWatcher_1 = require("./changeStreamWatcher");
46
+ const queryStore_1 = require("./queryStore");
47
+ const registry_2 = require("./registry");
48
+ const sessionRevalidation_1 = require("./sessionRevalidation");
49
+ const socketAuth_1 = require("./socketAuth");
50
+ const socketUser_1 = require("./socketUser");
98
51
  /**
99
52
  * Caps on per-socket subscriptions. Prevents a malicious or buggy client from
100
53
  * exhausting server memory by opening unbounded subscriptions.
@@ -110,58 +63,45 @@ exports.MAX_QUERY_SUBSCRIPTIONS = 100;
110
63
  * Exported for testing.
111
64
  */
112
65
  /** @internal */
113
- var redactCredentials = function (url) {
66
+ const redactCredentials = (url) => {
114
67
  try {
115
- var parsed = new URL(url);
68
+ const parsed = new URL(url);
116
69
  if (parsed.username || parsed.password) {
117
70
  parsed.username = "";
118
71
  parsed.password = "";
119
72
  // URL serialization drops the empty userinfo; reinsert a sentinel so logs make it
120
73
  // obvious credentials were stripped rather than silently absent from the source URL.
121
- return parsed.toString().replace("".concat(parsed.protocol, "//"), "".concat(parsed.protocol, "//***@"));
74
+ return parsed.toString().replace(`${parsed.protocol}//`, `${parsed.protocol}//***@`);
122
75
  }
123
76
  return parsed.toString();
124
77
  }
125
- catch (_a) {
78
+ catch {
126
79
  return url.replace(/^(\w+):\/\/[^@/]*@/, "$1://***@");
127
80
  }
128
81
  };
129
82
  exports.redactCredentials = redactCredentials;
130
- var canSubscribe = function (entry, method, user) { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
131
- return [2 /*return*/, (0, realtimeAccess_1.canSubscribeRealtime)(entry, method, user)];
132
- }); }); };
133
- var getAuthorizedQuery = function (entry, query, user) { return __awaiter(void 0, void 0, void 0, function () {
134
- var filteredQuery, error_1;
135
- return __generator(this, function (_a) {
136
- switch (_a.label) {
137
- case 0: return [4 /*yield*/, canSubscribe(entry, "list", user)];
138
- case 1:
139
- if (!(_a.sent())) {
140
- return [2 /*return*/, null];
141
- }
142
- if (!entry.options.queryFilter) {
143
- return [2 /*return*/, query];
144
- }
145
- _a.label = 2;
146
- case 2:
147
- _a.trys.push([2, 4, , 5]);
148
- return [4 /*yield*/, entry.options.queryFilter(user, query)];
149
- case 3:
150
- filteredQuery = _a.sent();
151
- return [3 /*break*/, 5];
152
- case 4:
153
- error_1 = _a.sent();
154
- logger_1.logger.error("[realtime] queryFilter threw for ".concat(entry.modelName, "/list: ").concat(error_1, ". Denying query subscription."));
155
- Sentry.captureException(error_1);
156
- return [2 /*return*/, null];
157
- case 5:
158
- if (filteredQuery === null) {
159
- return [2 /*return*/, null];
160
- }
161
- return [2 /*return*/, __assign(__assign({}, query), filteredQuery)];
162
- }
163
- });
164
- }); };
83
+ const canSubscribe = async (entry, method, user) => (0, realtimeAccess_1.canSubscribeRealtime)(entry, method, user);
84
+ const getAuthorizedQuery = async (entry, query, user) => {
85
+ if (!(await canSubscribe(entry, "list", user))) {
86
+ return null;
87
+ }
88
+ if (!entry.options.queryFilter) {
89
+ return query;
90
+ }
91
+ let filteredQuery;
92
+ try {
93
+ filteredQuery = await entry.options.queryFilter(user, query);
94
+ }
95
+ catch (error) {
96
+ logger_1.logger.error(`[realtime] queryFilter threw for ${entry.modelName}/list: ${error}. Denying query subscription.`);
97
+ Sentry.captureException(error);
98
+ return null;
99
+ }
100
+ if (filteredQuery === null) {
101
+ return null;
102
+ }
103
+ return { ...query, ...filteredQuery };
104
+ };
165
105
  /**
166
106
  * Install the realtime subscription handlers on a single socket. Extracted from the
167
107
  * RealtimeApp connection handler so this logic can be unit-tested with a mock socket
@@ -173,228 +113,155 @@ var getAuthorizedQuery = function (entry, query, user) { return __awaiter(void 0
173
113
  * - owner-strategy isolation (non-admin users cannot subscribe to other users' rooms)
174
114
  * - server-side queryId computation (clients can't hijack queries by colliding ids)
175
115
  */
176
- var installRealtimeSocketHandlers = function (socket, options) {
177
- var _a, _b, _c;
178
- if (options === void 0) { options = {}; }
179
- var logInfo = (_a = options.logInfo) !== null && _a !== void 0 ? _a : (function () { });
180
- var userId = (_b = socket.decodedToken) === null || _b === void 0 ? void 0 : _b.id;
181
- var isAdmin = ((_c = socket.decodedToken) === null || _c === void 0 ? void 0 : _c.admin) === true;
116
+ const installRealtimeSocketHandlers = (socket, options = {}) => {
117
+ const logInfo = options.logInfo ?? (() => { });
118
+ const userId = socket.decodedToken?.id;
119
+ const isAdmin = socket.decodedToken?.admin === true;
182
120
  // D2: re-derive per event rather than capturing once at install time, so a
183
121
  // handshake-time-loaded full user (or one refreshed by D1's sweep) is always used.
184
- var currentUser = function () { return (0, socketUser_1.getSocketUser)(socket); };
185
- var counts = { document: 0, model: 0, query: 0 };
186
- var joinUserRooms = function () { return __awaiter(void 0, void 0, void 0, function () {
187
- return __generator(this, function (_a) {
188
- switch (_a.label) {
189
- case 0:
190
- if (!userId) return [3 /*break*/, 3];
191
- return [4 /*yield*/, socket.join("user:".concat(userId))];
192
- case 1:
193
- _a.sent();
194
- return [4 /*yield*/, socket.join("authenticated")];
195
- case 2:
196
- _a.sent();
197
- logInfo("[realtime] User ".concat(userId, " connected"));
198
- _a.label = 3;
199
- case 3:
200
- if (!isAdmin) return [3 /*break*/, 5];
201
- return [4 /*yield*/, socket.join("admin")];
202
- case 4:
203
- _a.sent();
204
- logInfo("[realtime] Admin user ".concat(userId, " joined admin room"));
205
- _a.label = 5;
206
- case 5: return [2 /*return*/];
207
- }
208
- });
209
- }); };
122
+ const currentUser = () => (0, socketUser_1.getSocketUser)(socket);
123
+ const counts = { document: 0, model: 0, query: 0 };
124
+ const joinUserRooms = async () => {
125
+ if (userId) {
126
+ await socket.join(`user:${userId}`);
127
+ await socket.join("authenticated");
128
+ logInfo(`[realtime] User ${userId} connected`);
129
+ }
130
+ if (isAdmin) {
131
+ await socket.join("admin");
132
+ logInfo(`[realtime] Admin user ${userId} joined admin room`);
133
+ }
134
+ };
210
135
  // Fire-and-forget — there is nothing useful for the caller to await.
211
136
  void joinUserRooms();
212
- socket.on("subscribe:model", function (modelName) { return __awaiter(void 0, void 0, void 0, function () {
213
- var entry;
214
- return __generator(this, function (_a) {
215
- switch (_a.label) {
216
- case 0:
217
- if (typeof modelName !== "string" || modelName.length === 0) {
218
- return [2 /*return*/];
219
- }
220
- if (counts.model >= exports.MAX_MODEL_SUBSCRIPTIONS) {
221
- logInfo("[realtime] User ".concat(userId, " hit model subscription limit"));
222
- return [2 /*return*/];
223
- }
224
- entry = (0, registry_2.findRegistryEntryByRoutePath)(modelName);
225
- if (!entry) {
226
- logInfo("[realtime] User ".concat(userId, " denied model subscription: collection \"").concat(modelName, "\" not registered"));
227
- return [2 /*return*/];
228
- }
229
- // Owner-strategy models fan out via user:{ownerId} — there is no shared model room
230
- // that should be open to all users. Owners receive events through their user room
231
- // automatically; admins can use the admin room to see everything.
232
- if (entry.config.roomStrategy === "owner" && !isAdmin) {
233
- logInfo("[realtime] User ".concat(userId, " denied model subscription for ").concat(modelName, ": ") +
234
- "owner strategy restricts model room to admins");
235
- return [2 /*return*/];
236
- }
237
- return [4 /*yield*/, canSubscribe(entry, "list", currentUser())];
238
- case 1:
239
- if (!(_a.sent())) {
240
- logInfo("[realtime] User ".concat(userId, " denied model subscription for ").concat(modelName, ": list permission denied"));
241
- return [2 /*return*/];
242
- }
243
- counts.model += 1;
244
- return [4 /*yield*/, socket.join("model:".concat(modelName))];
245
- case 2:
246
- _a.sent();
247
- logInfo("[realtime] User ".concat(userId, " subscribed to model:").concat(modelName));
248
- return [2 /*return*/];
249
- }
250
- });
251
- }); });
252
- socket.on("unsubscribe:model", function (modelName) { return __awaiter(void 0, void 0, void 0, function () {
253
- return __generator(this, function (_a) {
254
- switch (_a.label) {
255
- case 0:
256
- if (!(typeof modelName === "string" && modelName.length > 0)) return [3 /*break*/, 2];
257
- return [4 /*yield*/, socket.leave("model:".concat(modelName))];
258
- case 1:
259
- _a.sent();
260
- counts.model = Math.max(0, counts.model - 1);
261
- logInfo("[realtime] User ".concat(userId, " unsubscribed from model:").concat(modelName));
262
- _a.label = 2;
263
- case 2: return [2 /*return*/];
264
- }
265
- });
266
- }); });
267
- socket.on("subscribe:document", function (payload) { return __awaiter(void 0, void 0, void 0, function () {
268
- var entry, room;
269
- return __generator(this, function (_a) {
270
- switch (_a.label) {
271
- case 0:
272
- if (!(payload === null || payload === void 0 ? void 0 : payload.collection) ||
273
- !(payload === null || payload === void 0 ? void 0 : payload.id) ||
274
- typeof payload.collection !== "string" ||
275
- typeof payload.id !== "string") {
276
- return [2 /*return*/];
277
- }
278
- if (counts.document >= exports.MAX_DOCUMENT_SUBSCRIPTIONS) {
279
- logInfo("[realtime] User ".concat(userId, " hit document subscription limit"));
280
- return [2 /*return*/];
281
- }
282
- entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
283
- if (!entry) {
284
- logInfo("[realtime] User ".concat(userId, " denied document subscription: ") +
285
- "collection \"".concat(payload.collection, "\" not registered"));
286
- return [2 /*return*/];
287
- }
288
- return [4 /*yield*/, canSubscribe(entry, "read", currentUser())];
289
- case 1:
290
- if (!(_a.sent())) {
291
- logInfo("[realtime] User ".concat(userId, " denied document subscription for ") +
292
- "".concat(payload.collection, "/").concat(payload.id, ": read permission denied"));
293
- return [2 /*return*/];
294
- }
295
- if (entry.config.roomStrategy === "owner" && !isAdmin) {
296
- logInfo("[realtime] User ".concat(userId, " denied document subscription for ") +
297
- "".concat(payload.collection, "/").concat(payload.id, ": owner strategy requires admin"));
298
- return [2 /*return*/];
299
- }
300
- counts.document += 1;
301
- room = "document:".concat(payload.collection, ":").concat(payload.id);
302
- return [4 /*yield*/, socket.join(room)];
303
- case 2:
304
- _a.sent();
305
- logInfo("[realtime] User ".concat(userId, " subscribed to ").concat(room));
306
- return [2 /*return*/];
307
- }
308
- });
309
- }); });
310
- socket.on("unsubscribe:document", function (payload) { return __awaiter(void 0, void 0, void 0, function () {
311
- var room;
312
- return __generator(this, function (_a) {
313
- switch (_a.label) {
314
- case 0:
315
- if (!((payload === null || payload === void 0 ? void 0 : payload.collection) && (payload === null || payload === void 0 ? void 0 : payload.id))) return [3 /*break*/, 2];
316
- room = "document:".concat(payload.collection, ":").concat(payload.id);
317
- return [4 /*yield*/, socket.leave(room)];
318
- case 1:
319
- _a.sent();
320
- counts.document = Math.max(0, counts.document - 1);
321
- logInfo("[realtime] User ".concat(userId, " unsubscribed from ").concat(room));
322
- _a.label = 2;
323
- case 2: return [2 /*return*/];
324
- }
325
- });
326
- }); });
327
- socket.on("subscribe:query", function (payload) { return __awaiter(void 0, void 0, void 0, function () {
328
- var entry, query, queryId;
329
- return __generator(this, function (_a) {
330
- switch (_a.label) {
331
- case 0:
332
- if (!(payload === null || payload === void 0 ? void 0 : payload.collection) ||
333
- !(payload === null || payload === void 0 ? void 0 : payload.query) ||
334
- typeof payload.collection !== "string" ||
335
- typeof payload.query !== "object" ||
336
- Array.isArray(payload.query)) {
337
- return [2 /*return*/];
338
- }
339
- if (counts.query >= exports.MAX_QUERY_SUBSCRIPTIONS) {
340
- logInfo("[realtime] User ".concat(userId, " hit query subscription limit"));
341
- return [2 /*return*/];
342
- }
343
- entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
344
- if (!entry) {
345
- logInfo("[realtime] User ".concat(userId, " denied query subscription: ") +
346
- "collection \"".concat(payload.collection, "\" not registered"));
347
- return [2 /*return*/];
348
- }
349
- return [4 /*yield*/, getAuthorizedQuery(entry, __assign({}, payload.query), currentUser())];
350
- case 1:
351
- query = _a.sent();
352
- if (!query) {
353
- logInfo("[realtime] User ".concat(userId, " denied query subscription for ").concat(payload.collection, ": ") +
354
- "list permission or query filter denied");
355
- return [2 /*return*/];
356
- }
357
- if (entry.config.roomStrategy === "owner" && !isAdmin) {
358
- if (!userId) {
359
- return [2 /*return*/];
360
- }
361
- query = __assign(__assign({}, query), { ownerId: userId });
362
- }
363
- queryId = (0, queryStore_1.computeQueryId)(payload.collection, query);
364
- (0, queryStore_1.addQuerySubscription)(socket.id, payload.collection, query, queryId);
365
- counts.query += 1;
366
- return [4 /*yield*/, socket.join("query:".concat(queryId))];
367
- case 2:
368
- _a.sent();
369
- socket.emit("query:subscribed", {
370
- clientQueryId: payload.queryId,
371
- collection: payload.collection,
372
- queryId: queryId,
373
- });
374
- logInfo("[realtime] User ".concat(userId, " subscribed to query:").concat(queryId, " on ").concat(payload.collection));
375
- return [2 /*return*/];
376
- }
377
- });
378
- }); });
379
- socket.on("unsubscribe:query", function (payload) { return __awaiter(void 0, void 0, void 0, function () {
380
- return __generator(this, function (_a) {
381
- switch (_a.label) {
382
- case 0:
383
- if (!(payload === null || payload === void 0 ? void 0 : payload.queryId)) return [3 /*break*/, 2];
384
- (0, queryStore_1.removeQuerySubscription)(socket.id, payload.queryId);
385
- return [4 /*yield*/, socket.leave("query:".concat(payload.queryId))];
386
- case 1:
387
- _a.sent();
388
- counts.query = Math.max(0, counts.query - 1);
389
- logInfo("[realtime] User ".concat(userId, " unsubscribed from query:").concat(payload.queryId));
390
- _a.label = 2;
391
- case 2: return [2 /*return*/];
137
+ socket.on("subscribe:model", async (modelName) => {
138
+ if (typeof modelName !== "string" || modelName.length === 0) {
139
+ return;
140
+ }
141
+ if (counts.model >= exports.MAX_MODEL_SUBSCRIPTIONS) {
142
+ logInfo(`[realtime] User ${userId} hit model subscription limit`);
143
+ return;
144
+ }
145
+ const entry = (0, registry_2.findRegistryEntryByRoutePath)(modelName);
146
+ if (!entry) {
147
+ logInfo(`[realtime] User ${userId} denied model subscription: collection "${modelName}" not registered`);
148
+ return;
149
+ }
150
+ // Owner-strategy models fan out via user:{ownerId} — there is no shared model room
151
+ // that should be open to all users. Owners receive events through their user room
152
+ // automatically; admins can use the admin room to see everything.
153
+ if (entry.config.roomStrategy === "owner" && !isAdmin) {
154
+ logInfo(`[realtime] User ${userId} denied model subscription for ${modelName}: ` +
155
+ "owner strategy restricts model room to admins");
156
+ return;
157
+ }
158
+ if (!(await canSubscribe(entry, "list", currentUser()))) {
159
+ logInfo(`[realtime] User ${userId} denied model subscription for ${modelName}: list permission denied`);
160
+ return;
161
+ }
162
+ counts.model += 1;
163
+ await socket.join(`model:${modelName}`);
164
+ logInfo(`[realtime] User ${userId} subscribed to model:${modelName}`);
165
+ });
166
+ socket.on("unsubscribe:model", async (modelName) => {
167
+ if (typeof modelName === "string" && modelName.length > 0) {
168
+ await socket.leave(`model:${modelName}`);
169
+ counts.model = Math.max(0, counts.model - 1);
170
+ logInfo(`[realtime] User ${userId} unsubscribed from model:${modelName}`);
171
+ }
172
+ });
173
+ socket.on("subscribe:document", async (payload) => {
174
+ if (!payload?.collection ||
175
+ !payload?.id ||
176
+ typeof payload.collection !== "string" ||
177
+ typeof payload.id !== "string") {
178
+ return;
179
+ }
180
+ if (counts.document >= exports.MAX_DOCUMENT_SUBSCRIPTIONS) {
181
+ logInfo(`[realtime] User ${userId} hit document subscription limit`);
182
+ return;
183
+ }
184
+ const entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
185
+ if (!entry) {
186
+ logInfo(`[realtime] User ${userId} denied document subscription: ` +
187
+ `collection "${payload.collection}" not registered`);
188
+ return;
189
+ }
190
+ if (!(await canSubscribe(entry, "read", currentUser()))) {
191
+ logInfo(`[realtime] User ${userId} denied document subscription for ` +
192
+ `${payload.collection}/${payload.id}: read permission denied`);
193
+ return;
194
+ }
195
+ if (entry.config.roomStrategy === "owner" && !isAdmin) {
196
+ logInfo(`[realtime] User ${userId} denied document subscription for ` +
197
+ `${payload.collection}/${payload.id}: owner strategy requires admin`);
198
+ return;
199
+ }
200
+ counts.document += 1;
201
+ const room = `document:${payload.collection}:${payload.id}`;
202
+ await socket.join(room);
203
+ logInfo(`[realtime] User ${userId} subscribed to ${room}`);
204
+ });
205
+ socket.on("unsubscribe:document", async (payload) => {
206
+ if (payload?.collection && payload?.id) {
207
+ const room = `document:${payload.collection}:${payload.id}`;
208
+ await socket.leave(room);
209
+ counts.document = Math.max(0, counts.document - 1);
210
+ logInfo(`[realtime] User ${userId} unsubscribed from ${room}`);
211
+ }
212
+ });
213
+ socket.on("subscribe:query", async (payload) => {
214
+ if (!payload?.collection ||
215
+ !payload?.query ||
216
+ typeof payload.collection !== "string" ||
217
+ typeof payload.query !== "object" ||
218
+ Array.isArray(payload.query)) {
219
+ return;
220
+ }
221
+ if (counts.query >= exports.MAX_QUERY_SUBSCRIPTIONS) {
222
+ logInfo(`[realtime] User ${userId} hit query subscription limit`);
223
+ return;
224
+ }
225
+ const entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
226
+ if (!entry) {
227
+ logInfo(`[realtime] User ${userId} denied query subscription: ` +
228
+ `collection "${payload.collection}" not registered`);
229
+ return;
230
+ }
231
+ let query = await getAuthorizedQuery(entry, { ...payload.query }, currentUser());
232
+ if (!query) {
233
+ logInfo(`[realtime] User ${userId} denied query subscription for ${payload.collection}: ` +
234
+ "list permission or query filter denied");
235
+ return;
236
+ }
237
+ if (entry.config.roomStrategy === "owner" && !isAdmin) {
238
+ if (!userId) {
239
+ return;
392
240
  }
241
+ query = { ...query, ownerId: userId };
242
+ }
243
+ const queryId = (0, queryStore_1.computeQueryId)(payload.collection, query);
244
+ (0, queryStore_1.addQuerySubscription)(socket.id, payload.collection, query, queryId);
245
+ counts.query += 1;
246
+ await socket.join(`query:${queryId}`);
247
+ socket.emit("query:subscribed", {
248
+ clientQueryId: payload.queryId,
249
+ collection: payload.collection,
250
+ queryId,
393
251
  });
394
- }); });
395
- socket.on("disconnect", function () {
252
+ logInfo(`[realtime] User ${userId} subscribed to query:${queryId} on ${payload.collection}`);
253
+ });
254
+ socket.on("unsubscribe:query", async (payload) => {
255
+ if (payload?.queryId) {
256
+ (0, queryStore_1.removeQuerySubscription)(socket.id, payload.queryId);
257
+ await socket.leave(`query:${payload.queryId}`);
258
+ counts.query = Math.max(0, counts.query - 1);
259
+ logInfo(`[realtime] User ${userId} unsubscribed from query:${payload.queryId}`);
260
+ }
261
+ });
262
+ socket.on("disconnect", () => {
396
263
  (0, queryStore_1.removeAllSocketQueries)(socket.id);
397
- logInfo("[realtime] User ".concat(userId, " disconnected"));
264
+ logInfo(`[realtime] User ${userId} disconnected`);
398
265
  });
399
266
  };
400
267
  exports.installRealtimeSocketHandlers = installRealtimeSocketHandlers;
@@ -422,39 +289,35 @@ exports.installRealtimeSocketHandlers = installRealtimeSocketHandlers;
422
289
  * .start();
423
290
  * ```
424
291
  */
425
- var RealtimeApp = /** @class */ (function () {
426
- function RealtimeApp(config) {
427
- if (config === void 0) { config = {}; }
428
- this.app = null;
429
- this.io = null;
430
- this.sessionRevalidation = null;
292
+ class RealtimeApp {
293
+ app = null;
294
+ io = null;
295
+ config;
296
+ sessionRevalidation = null;
297
+ constructor(config = {}) {
431
298
  this.config = config;
432
299
  }
433
300
  /**
434
301
  * Register routes and middleware. Adds a /realtime/health endpoint.
435
302
  */
436
- RealtimeApp.prototype.register = function (app) {
437
- var _this = this;
303
+ register(app) {
438
304
  this.app = app;
439
- app.get("/realtime/health", function (_req, res) {
440
- var _a, _b, _c, _d;
441
- var connected = (_c = (_b = (_a = _this.io) === null || _a === void 0 ? void 0 : _a.engine) === null || _b === void 0 ? void 0 : _b.clientsCount) !== null && _c !== void 0 ? _c : 0;
305
+ app.get("/realtime/health", (_req, res) => {
306
+ const connected = this.io?.engine?.clientsCount ?? 0;
442
307
  res.json({
443
308
  clients: connected,
444
- debug: (_d = _this.config.debug) !== null && _d !== void 0 ? _d : false,
445
- status: _this.io ? "running" : "not_started",
309
+ debug: this.config.debug ?? false,
310
+ status: this.io ? "running" : "not_started",
446
311
  });
447
312
  });
448
- };
313
+ }
449
314
  /**
450
315
  * Called after the HTTP server is created. Sets up Socket.io, auth, rooms,
451
316
  * and starts the change stream watcher.
452
317
  */
453
- RealtimeApp.prototype.onServerCreated = function (server) {
454
- var _this = this;
455
- var _a, _b, _c, _d, _e;
456
- var debug = (_a = this.config.debug) !== null && _a !== void 0 ? _a : false;
457
- var logInfo = function (message) {
318
+ onServerCreated(server) {
319
+ const debug = this.config.debug ?? false;
320
+ const logInfo = (message) => {
458
321
  if (debug) {
459
322
  logger_1.logger.info(message);
460
323
  }
@@ -463,15 +326,15 @@ var RealtimeApp = /** @class */ (function () {
463
326
  logInfo("[realtime] Setting up Socket.io server...");
464
327
  // Prefer an injected Server constructor in tests so callers never need
465
328
  // process-wide `mock.module("socket.io")` (which poisons later files).
466
- var SocketServerCtor = (_b = this.config.SocketServer) !== null && _b !== void 0 ? _b : socket_io_1.Server;
329
+ const SocketServerCtor = this.config.SocketServer ?? socket_io_1.Server;
467
330
  this.io = new SocketServerCtor(server, {
468
- cors: (_c = this.config.cors) !== null && _c !== void 0 ? _c : {
331
+ cors: this.config.cors ?? {
469
332
  methods: ["GET", "POST"],
470
333
  origin: "*",
471
334
  },
472
335
  });
473
336
  // Authentication middleware: legacy JWT first when configured, optionally Better Auth sessions.
474
- var tokenSecret = (_d = this.config.tokenSecret) !== null && _d !== void 0 ? _d : process.env.TOKEN_SECRET;
337
+ const tokenSecret = this.config.tokenSecret ?? process.env.TOKEN_SECRET;
475
338
  if (!tokenSecret && !this.config.betterAuth) {
476
339
  throw new errors_1.APIError({
477
340
  status: 500,
@@ -485,12 +348,16 @@ var RealtimeApp = /** @class */ (function () {
485
348
  // thunk (not a value captured once here) so a later change to
486
349
  // process.env.TOKEN_ISSUER — or to an explicitly configured tokenIssuer — is
487
350
  // honored on every handshake, matching the HTTP path's per-request env read.
488
- var resolveTokenIssuer = function () { var _a; return (_a = _this.config.tokenIssuer) !== null && _a !== void 0 ? _a : process.env.TOKEN_ISSUER; };
489
- this.io.use((0, socketAuth_1.createSocketAuthMiddleware)(__assign({ betterAuth: this.config.betterAuth, issuer: resolveTokenIssuer }, (tokenSecret ? { tokenSecret: tokenSecret } : {}))));
490
- var authKinds = [tokenSecret ? "JWT" : null, this.config.betterAuth ? "Better Auth" : null]
351
+ const resolveTokenIssuer = () => this.config.tokenIssuer ?? process.env.TOKEN_ISSUER;
352
+ this.io.use((0, socketAuth_1.createSocketAuthMiddleware)({
353
+ betterAuth: this.config.betterAuth,
354
+ issuer: resolveTokenIssuer,
355
+ tokenSecret,
356
+ }));
357
+ const authKinds = [tokenSecret ? "JWT" : null, this.config.betterAuth ? "Better Auth" : null]
491
358
  .filter(Boolean)
492
359
  .join(" + ");
493
- logInfo("[realtime] Socket auth middleware added (".concat(authKinds, ")"));
360
+ logInfo(`[realtime] Socket auth middleware added (${authKinds})`);
494
361
  // Task 9.21: tenant/custom sync scopes can only be resolved from the full user
495
362
  // document, so warn loudly here (once, at startup) rather than silently serving
496
363
  // empty tenant streams for the life of the process.
@@ -498,106 +365,86 @@ var RealtimeApp = /** @class */ (function () {
498
365
  // Configure adapter for multi-instance deployments
499
366
  this.setupAdapter(logInfo);
500
367
  // Connection handling
501
- this.io.on("connection", function (socket) {
502
- var _a, _b;
368
+ this.io.on("connection", (socket) => {
503
369
  try {
504
370
  // D2: load the full user document once at handshake (by the decoded
505
371
  // token's id) and cache it on socket.data.fullUser — getSocketUser prefers
506
372
  // it over the synthetic {_id, admin, id} shape for every authorization
507
373
  // check below. Fire-and-forget: handlers install synchronously and fall
508
374
  // back to the synthetic shape until this resolves.
509
- void (0, sessionRevalidation_1.loadFullUserForSocket)(socket, _this.config.userModel);
375
+ void (0, sessionRevalidation_1.loadFullUserForSocket)(socket, this.config.userModel);
510
376
  // The auth middleware adds `decodedToken` at runtime; cast through
511
377
  // RealtimeSocketLike (a structural subset) to keep socket handler logic testable.
512
- (0, exports.installRealtimeSocketHandlers)(socket, { logInfo: logInfo });
378
+ (0, exports.installRealtimeSocketHandlers)(socket, { logInfo });
513
379
  // Sync protocol handlers (sync:subscribe / sync:mutate). Options come from the
514
380
  // SyncApp registered on this Express app or an explicit `sync` override here;
515
381
  // with neither, the handlers still install and reject unknown collections.
516
- (0, socketHandlers_1.installSyncSocketHandlers)(_this.io, socket, (_b = (_a = _this.config.sync) !== null && _a !== void 0 ? _a : (_this.app ? (0, syncApp_1.getSyncAppOptions)(_this.app) : undefined)) !== null && _b !== void 0 ? _b : {}, { logInfo: logInfo });
382
+ (0, socketHandlers_1.installSyncSocketHandlers)(this.io, socket, this.config.sync ?? (this.app ? (0, syncApp_1.getSyncAppOptions)(this.app) : undefined) ?? {}, { logInfo });
517
383
  }
518
384
  catch (error) {
519
- logger_1.logger.error("[realtime] Error handling connection: ".concat(error));
385
+ logger_1.logger.error(`[realtime] Error handling connection: ${error}`);
520
386
  Sentry.captureException(error);
521
387
  }
522
388
  });
523
- this.io.on("connect_error", function (error) {
524
- logger_1.logger.error("[realtime] Connection error: ".concat(error.message));
389
+ this.io.on("connect_error", (error) => {
390
+ logger_1.logger.error(`[realtime] Connection error: ${error.message}`);
525
391
  Sentry.captureException(error);
526
392
  });
527
393
  // Start the change stream watcher (injectable for unit tests — see SocketServer).
528
- var startWatcher = (_e = this.config.startChangeStreamWatcher) !== null && _e !== void 0 ? _e : changeStreamWatcher_1.startChangeStreamWatcher;
394
+ const startWatcher = this.config.startChangeStreamWatcher ?? changeStreamWatcher_1.startChangeStreamWatcher;
529
395
  startWatcher(this.io, this.config.changeStream, debug);
530
396
  // D1: periodic session re-validation sweep — disconnects sockets whose JWT has
531
397
  // expired, whose Better Auth session is no longer valid, or whose user has
532
398
  // since been disabled; also refreshes socket.data.fullUser (D2) and
533
399
  // re-resolves sync room membership (D4) for sockets that remain valid.
534
400
  // A thunk (not a snapshot) reads this app's SyncApp options fresh on every sweep.
535
- this.sessionRevalidation = (0, sessionRevalidation_1.startSessionRevalidationSweep)(this.io, function () {
536
- var _a;
537
- return ({
538
- betterAuth: _this.config.betterAuth,
539
- intervalMs: _this.config.sessionRevalidationIntervalMs,
540
- logInfo: logInfo,
541
- sync: (_a = _this.config.sync) !== null && _a !== void 0 ? _a : (_this.app ? (0, syncApp_1.getSyncAppOptions)(_this.app) : undefined),
542
- userModel: _this.config.userModel,
543
- });
544
- });
401
+ this.sessionRevalidation = (0, sessionRevalidation_1.startSessionRevalidationSweep)(this.io, () => ({
402
+ betterAuth: this.config.betterAuth,
403
+ intervalMs: this.config.sessionRevalidationIntervalMs,
404
+ logInfo,
405
+ sync: this.config.sync ?? (this.app ? (0, syncApp_1.getSyncAppOptions)(this.app) : undefined),
406
+ userModel: this.config.userModel,
407
+ }));
545
408
  logInfo("[realtime] Socket.io server setup complete");
546
409
  }
547
410
  catch (error) {
548
- logger_1.logger.error("[realtime] Failed to set up Socket.io: ".concat(error));
411
+ logger_1.logger.error(`[realtime] Failed to set up Socket.io: ${error}`);
549
412
  Sentry.captureException(error);
550
413
  throw error;
551
414
  }
552
- };
415
+ }
553
416
  /**
554
417
  * Get the Socket.io server instance.
555
418
  */
556
- RealtimeApp.prototype.getIo = function () {
419
+ getIo() {
557
420
  return this.io;
558
- };
421
+ }
559
422
  /**
560
423
  * Gracefully shut down the real-time server.
561
424
  */
562
- RealtimeApp.prototype.close = function () {
563
- return __awaiter(this, void 0, void 0, function () {
564
- var error_2;
565
- var _a;
566
- return __generator(this, function (_b) {
567
- switch (_b.label) {
568
- case 0:
569
- _b.trys.push([0, 4, , 5]);
570
- (_a = this.sessionRevalidation) === null || _a === void 0 ? void 0 : _a.stop();
571
- this.sessionRevalidation = null;
572
- return [4 /*yield*/, (0, changeStreamWatcher_1.stopChangeStreamWatcher)()];
573
- case 1:
574
- _b.sent();
575
- if (!this.io) return [3 /*break*/, 3];
576
- return [4 /*yield*/, this.io.close()];
577
- case 2:
578
- _b.sent();
579
- this.io = null;
580
- _b.label = 3;
581
- case 3: return [3 /*break*/, 5];
582
- case 4:
583
- error_2 = _b.sent();
584
- logger_1.logger.error("[realtime] Error closing: ".concat(error_2));
585
- return [3 /*break*/, 5];
586
- case 5: return [2 /*return*/];
587
- }
588
- });
589
- });
590
- };
591
- RealtimeApp.prototype.setupAdapter = function (logInfo) {
592
- var _a, _b, _c;
425
+ async close() {
426
+ try {
427
+ this.sessionRevalidation?.stop();
428
+ this.sessionRevalidation = null;
429
+ await (0, changeStreamWatcher_1.stopChangeStreamWatcher)();
430
+ if (this.io) {
431
+ await this.io.close();
432
+ this.io = null;
433
+ }
434
+ }
435
+ catch (error) {
436
+ logger_1.logger.error(`[realtime] Error closing: ${error}`);
437
+ }
438
+ }
439
+ setupAdapter(logInfo) {
593
440
  if (!this.io) {
594
441
  return;
595
442
  }
596
- var adapter = (_a = this.config.adapter) !== null && _a !== void 0 ? _a : "none";
443
+ const adapter = this.config.adapter ?? "none";
597
444
  if (adapter === "redis") {
598
- var redisUrl = (_c = (_b = this.config.redisUrl) !== null && _b !== void 0 ? _b : process.env.VALKEY_URL) !== null && _c !== void 0 ? _c : process.env.REDIS_URL;
445
+ const redisUrl = this.config.redisUrl ?? process.env.VALKEY_URL ?? process.env.REDIS_URL;
599
446
  if (redisUrl) {
600
- logInfo("[realtime] Redis adapter configured with URL: ".concat((0, exports.redactCredentials)(redisUrl)));
447
+ logInfo(`[realtime] Redis adapter configured with URL: ${(0, exports.redactCredentials)(redisUrl)}`);
601
448
  // Redis adapter must be configured externally by the consuming app
602
449
  // since @socket.io/redis-adapter and ioredis are optional peer dependencies.
603
450
  // Use realtimeApp.getIo() to access the Socket.io instance and call
@@ -610,7 +457,6 @@ var RealtimeApp = /** @class */ (function () {
610
457
  }
611
458
  }
612
459
  // 'none' — no adapter, single instance mode
613
- };
614
- return RealtimeApp;
615
- }());
460
+ }
461
+ }
616
462
  exports.RealtimeApp = RealtimeApp;