@terreno/api 0.31.0 → 56.0.0-beta.2

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 (232) hide show
  1. package/dist/api.d.ts +10 -0
  2. package/dist/api.js +110 -361
  3. package/dist/auth.d.ts +26 -0
  4. package/dist/auth.js +121 -26
  5. package/dist/betterAuth.d.ts +5 -0
  6. package/dist/betterAuthSetup.js +23 -4
  7. package/dist/docLoader.js +12 -9
  8. package/dist/errors.d.ts +13 -0
  9. package/dist/errors.js +29 -1
  10. package/dist/index.d.ts +17 -1
  11. package/dist/index.js +29 -1
  12. package/dist/middleware.d.ts +7 -0
  13. package/dist/middleware.js +16 -1
  14. package/dist/openApiCompat.d.ts +10 -1
  15. package/dist/openApiCompat.js +115 -47
  16. package/dist/permissions.d.ts +27 -0
  17. package/dist/permissions.js +42 -1
  18. package/dist/plugins.d.ts +13 -0
  19. package/dist/plugins.js +47 -1
  20. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  21. package/dist/realtime/changeStreamWatcher.js +542 -137
  22. package/dist/realtime/realtimeApp.d.ts +2 -0
  23. package/dist/realtime/realtimeApp.js +83 -27
  24. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  25. package/dist/realtime/sessionRevalidation.js +438 -0
  26. package/dist/realtime/socketAuth.d.ts +97 -0
  27. package/dist/realtime/socketAuth.js +272 -0
  28. package/dist/realtime/socketUser.d.ts +54 -0
  29. package/dist/realtime/socketUser.js +75 -5
  30. package/dist/realtime/types.d.ts +54 -0
  31. package/dist/secretProviders.d.ts +23 -0
  32. package/dist/secretProviders.js +9 -3
  33. package/dist/sync/executors.d.ts +198 -0
  34. package/dist/sync/executors.js +670 -0
  35. package/dist/sync/loadHarness.js +807 -0
  36. package/dist/sync/models.d.ts +216 -0
  37. package/dist/sync/models.js +644 -0
  38. package/dist/sync/mutationHandler.d.ts +97 -0
  39. package/dist/sync/mutationHandler.js +886 -0
  40. package/dist/sync/registry.d.ts +73 -0
  41. package/dist/sync/registry.js +223 -0
  42. package/dist/sync/routes.d.ts +62 -0
  43. package/dist/sync/routes.js +936 -0
  44. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  45. package/dist/sync/scripts/compactTombstones.js +270 -0
  46. package/dist/sync/serialize.d.ts +20 -0
  47. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  48. package/dist/sync/socketHandlers.d.ts +54 -0
  49. package/dist/sync/socketHandlers.js +470 -0
  50. package/dist/sync/streams.d.ts +85 -0
  51. package/dist/sync/streams.js +221 -0
  52. package/dist/sync/syncApp.d.ts +29 -0
  53. package/dist/sync/syncApp.js +44 -0
  54. package/dist/sync/syncBatch.d.ts +71 -0
  55. package/dist/sync/syncBatch.js +252 -0
  56. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  57. package/dist/sync/syncSeqPlugin.js +899 -0
  58. package/dist/sync/types.d.ts +254 -0
  59. package/dist/sync/types.js +9 -0
  60. package/dist/terrenoApp.js +90 -27
  61. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  62. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  63. package/package.json +7 -6
  64. package/src/__tests__/openApiCompat.test.ts +20 -0
  65. package/src/api.errors.test.ts +32 -23
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -296
  68. package/src/auth.test.ts +202 -0
  69. package/src/auth.ts +134 -23
  70. package/src/betterAuth.ts +6 -0
  71. package/src/betterAuthSetup.test.ts +34 -0
  72. package/src/betterAuthSetup.ts +20 -1
  73. package/src/configuration.test.ts +59 -38
  74. package/src/configurationPlugin.test.ts +72 -42
  75. package/src/docLoader.ts +3 -1
  76. package/src/errors.ts +33 -0
  77. package/src/expressServer.test.ts +7 -1
  78. package/src/index.ts +42 -0
  79. package/src/middleware.test.ts +56 -1
  80. package/src/middleware.ts +15 -0
  81. package/src/openApiCompat.ts +99 -45
  82. package/src/permissions.test.ts +101 -17
  83. package/src/permissions.ts +49 -0
  84. package/src/plugins.test.ts +64 -0
  85. package/src/plugins.ts +56 -0
  86. package/src/realtime/changeStreamWatcher.ts +552 -114
  87. package/src/realtime/realtime.test.ts +157 -0
  88. package/src/realtime/realtimeApp.ts +82 -14
  89. package/src/realtime/realtimeAppSetup.test.ts +25 -27
  90. package/src/realtime/sessionRevalidation.test.ts +423 -0
  91. package/src/realtime/sessionRevalidation.ts +273 -0
  92. package/src/realtime/socketAuth.test.ts +355 -0
  93. package/src/realtime/socketAuth.ts +228 -0
  94. package/src/realtime/socketUser.ts +69 -0
  95. package/src/realtime/types.ts +54 -0
  96. package/src/secretProviders.test.ts +7 -1
  97. package/src/secretProviders.ts +15 -3
  98. package/src/secretProvidersGcpClient.test.ts +66 -0
  99. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  100. package/src/sync/executors.test.ts +882 -0
  101. package/src/sync/executors.ts +705 -0
  102. package/src/sync/integration.test.ts +1160 -0
  103. package/src/sync/loadHarness.ts +618 -0
  104. package/src/sync/models.ts +641 -0
  105. package/src/sync/mutationHandler.test.ts +1252 -0
  106. package/src/sync/mutationHandler.ts +850 -0
  107. package/src/sync/registry.ts +232 -0
  108. package/src/sync/routes.ts +812 -0
  109. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  110. package/src/sync/scripts/compactTombstones.ts +145 -0
  111. package/src/sync/serialize.ts +48 -0
  112. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  113. package/src/sync/socketHandlers.ts +320 -0
  114. package/src/sync/streams.ts +188 -0
  115. package/src/sync/sync.test.ts +582 -0
  116. package/src/sync/syncApp.ts +44 -0
  117. package/src/sync/syncBatch.ts +219 -0
  118. package/src/sync/syncFrontier.test.ts +494 -0
  119. package/src/sync/syncPhaseC.test.ts +718 -0
  120. package/src/sync/syncRoutes.test.ts +865 -0
  121. package/src/sync/syncSeqPlugin.ts +730 -0
  122. package/src/sync/syncSocket.test.ts +1440 -0
  123. package/src/sync/types.ts +270 -0
  124. package/src/terrenoApp.ts +37 -17
  125. package/src/tests/bunSetup.ts +8 -0
  126. package/tsconfig.json +4 -4
  127. package/tsconfig.typedoc.json +7 -1
  128. package/dist/__tests__/openApiCompat.test.js +0 -317
  129. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  130. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  131. package/dist/actions.openApi.test.d.ts +0 -1
  132. package/dist/actions.openApi.test.js +0 -253
  133. package/dist/actions.test.d.ts +0 -1
  134. package/dist/actions.test.js +0 -1087
  135. package/dist/api.arrayOperations.test.d.ts +0 -1
  136. package/dist/api.arrayOperations.test.js +0 -878
  137. package/dist/api.asyncHandler.test.d.ts +0 -1
  138. package/dist/api.asyncHandler.test.js +0 -236
  139. package/dist/api.coverage.test.d.ts +0 -1
  140. package/dist/api.coverage.test.js +0 -192
  141. package/dist/api.errorPaths.test.d.ts +0 -1
  142. package/dist/api.errorPaths.test.js +0 -887
  143. package/dist/api.errors.test.d.ts +0 -1
  144. package/dist/api.errors.test.js +0 -185
  145. package/dist/api.hooks.test.d.ts +0 -1
  146. package/dist/api.hooks.test.js +0 -950
  147. package/dist/api.query.test.d.ts +0 -1
  148. package/dist/api.query.test.js +0 -948
  149. package/dist/api.test.d.ts +0 -1
  150. package/dist/api.test.js +0 -2820
  151. package/dist/auth.compile.test.d.ts +0 -1
  152. package/dist/auth.compile.test.js +0 -201
  153. package/dist/auth.coverage.test.d.ts +0 -1
  154. package/dist/auth.coverage.test.js +0 -202
  155. package/dist/auth.test.d.ts +0 -1
  156. package/dist/auth.test.js +0 -2286
  157. package/dist/betterAuth.test.d.ts +0 -1
  158. package/dist/betterAuth.test.js +0 -181
  159. package/dist/betterAuthApp.test.d.ts +0 -1
  160. package/dist/betterAuthApp.test.js +0 -242
  161. package/dist/betterAuthSetup.test.d.ts +0 -1
  162. package/dist/betterAuthSetup.test.js +0 -762
  163. package/dist/config.test.d.ts +0 -1
  164. package/dist/config.test.js +0 -353
  165. package/dist/configuration.test.d.ts +0 -1
  166. package/dist/configuration.test.js +0 -980
  167. package/dist/configurationPlugin.test.d.ts +0 -1
  168. package/dist/configurationPlugin.test.js +0 -827
  169. package/dist/consentApp.test.d.ts +0 -1
  170. package/dist/consentApp.test.js +0 -1411
  171. package/dist/docLoader.test.d.ts +0 -1
  172. package/dist/docLoader.test.js +0 -137
  173. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  174. package/dist/envConfigurationPlugin.test.js +0 -369
  175. package/dist/errors.test.d.ts +0 -1
  176. package/dist/errors.test.js +0 -607
  177. package/dist/expressServer.test.d.ts +0 -1
  178. package/dist/expressServer.test.js +0 -1249
  179. package/dist/githubAuth.test.d.ts +0 -1
  180. package/dist/githubAuth.test.js +0 -1142
  181. package/dist/httpClient.test.d.ts +0 -1
  182. package/dist/httpClient.test.js +0 -1471
  183. package/dist/logger.test.d.ts +0 -1
  184. package/dist/logger.test.js +0 -685
  185. package/dist/middleware.test.d.ts +0 -1
  186. package/dist/middleware.test.js +0 -241
  187. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  189. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  190. package/dist/notifiers/slackNotifier.test.js +0 -297
  191. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  192. package/dist/notifiers/zoomNotifier.test.js +0 -373
  193. package/dist/openApi.test.d.ts +0 -1
  194. package/dist/openApi.test.js +0 -620
  195. package/dist/openApiBuilder.test.d.ts +0 -1
  196. package/dist/openApiBuilder.test.js +0 -599
  197. package/dist/openApiEtag.test.d.ts +0 -1
  198. package/dist/openApiEtag.test.js +0 -86
  199. package/dist/openApiValidator.test.d.ts +0 -1
  200. package/dist/openApiValidator.test.js +0 -795
  201. package/dist/permissions.middleware.test.d.ts +0 -1
  202. package/dist/permissions.middleware.test.js +0 -308
  203. package/dist/permissions.test.d.ts +0 -1
  204. package/dist/permissions.test.js +0 -439
  205. package/dist/plugins.test.d.ts +0 -1
  206. package/dist/plugins.test.js +0 -902
  207. package/dist/populate.test.d.ts +0 -1
  208. package/dist/populate.test.js +0 -370
  209. package/dist/realtime/realtime.test.d.ts +0 -10
  210. package/dist/realtime/realtime.test.js +0 -4213
  211. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  212. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  213. package/dist/requestContext.test.d.ts +0 -1
  214. package/dist/requestContext.test.js +0 -412
  215. package/dist/scriptRunner.test.d.ts +0 -1
  216. package/dist/scriptRunner.test.js +0 -386
  217. package/dist/secretProviders.test.d.ts +0 -1
  218. package/dist/secretProviders.test.js +0 -726
  219. package/dist/syncConsents.test.d.ts +0 -1
  220. package/dist/syncConsents.test.js +0 -522
  221. package/dist/terrenoApp.test.d.ts +0 -1
  222. package/dist/terrenoApp.test.js +0 -489
  223. package/dist/tests/bunSetup.d.ts +0 -1
  224. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  225. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  226. package/dist/tests/testEnv.d.ts +0 -0
  227. package/dist/tests/testEnv.js +0 -6
  228. package/dist/transformers.test.d.ts +0 -1
  229. package/dist/transformers.test.js +0 -423
  230. package/dist/utils.test.d.ts +0 -1
  231. package/dist/utils.test.js +0 -242
  232. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -0,0 +1,470 @@
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
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ 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);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ 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;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __values = (this && this.__values) || function(o) {
50
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
51
+ if (m) return m.call(o);
52
+ if (o && typeof o.length === "number") return {
53
+ next: function () {
54
+ if (o && i >= o.length) o = void 0;
55
+ return { value: o && o[i++], done: !o };
56
+ }
57
+ };
58
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
59
+ };
60
+ Object.defineProperty(exports, "__esModule", { value: true });
61
+ exports.installSyncSocketHandlers = exports.syncRoomForStream = exports.MAX_SYNC_SUBSCRIBE_ARRAY_LENGTH = exports.MAX_SYNC_COLLECTION_SUBSCRIPTIONS = void 0;
62
+ var logger_1 = require("../logger");
63
+ var permissions_1 = require("../permissions");
64
+ var socketUser_1 = require("../realtime/socketUser");
65
+ var registry_1 = require("./registry");
66
+ var streams_1 = require("./streams");
67
+ var syncBatch_1 = require("./syncBatch");
68
+ /**
69
+ * Socket handlers for the SyncDB local-first protocol:
70
+ *
71
+ * - `sync:subscribe {collections}` / `sync:unsubscribe {collections}` — resolves the
72
+ * caller's streams from the sync registry scope config and joins/leaves `sync:{stream}`
73
+ * rooms. Owner scopes always use the socket's own userId (never a client-supplied one);
74
+ * tenant and custom scopes resolve stream values via `SyncAppOptions.getUserScopes`.
75
+ * Sync deltas fan out through these dedicated `sync:{stream}` rooms rather than the
76
+ * legacy realtime rooms so the two event families never overlap.
77
+ * - `sync:mutate` — applies a mutation through `applySyncMutation` and replies with
78
+ * `sync:ack {mutationId, id, seq}` or `sync:nack {mutationId, code, ...}`; when the
79
+ * client supplied a Socket.io ack callback it also receives `{ack}` / `{nack}`.
80
+ * - `sync:error {collection, message}` — emitted for per-collection subscribe failures
81
+ * (unknown collection, permission denied, missing scope resolver, cap exceeded).
82
+ *
83
+ * ## Wiring
84
+ *
85
+ * `RealtimeApp` installs these handlers on every connection with the `SyncAppOptions`
86
+ * attached to the same Express application, so multiple app instances stay isolated.
87
+ */
88
+ /** Maximum distinct collection subscriptions per socket (DoS protection). */
89
+ exports.MAX_SYNC_COLLECTION_SUBSCRIPTIONS = 50;
90
+ /**
91
+ * C8: maximum entries accepted in a single `sync:subscribe`/`sync:unsubscribe`
92
+ * `collections` array — checked BEFORE iterating so an oversized array is rejected
93
+ * with no per-entry work.
94
+ */
95
+ exports.MAX_SYNC_SUBSCRIBE_ARRAY_LENGTH = 100;
96
+ /** The Socket.io room a sync stream fans out through. */
97
+ var syncRoomForStream = function (stream) { return "sync:".concat(stream); };
98
+ exports.syncRoomForStream = syncRoomForStream;
99
+ /**
100
+ * Resolve the streams a user may subscribe to for a collection. Returns null (after
101
+ * emitting `sync:error`) when the scope cannot be resolved for this user/server config.
102
+ */
103
+ var resolveUserStreams = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
104
+ var collection, emitError, error_1;
105
+ var entry = _b.entry, user = _b.user, options = _b.options, socket = _b.socket;
106
+ return __generator(this, function (_c) {
107
+ switch (_c.label) {
108
+ case 0:
109
+ collection = entry.collectionTag;
110
+ emitError = function (message) {
111
+ socket.emit("sync:error", { collection: collection, message: message });
112
+ };
113
+ _c.label = 1;
114
+ case 1:
115
+ _c.trys.push([1, 3, , 4]);
116
+ return [4 /*yield*/, (0, streams_1.resolveUserStreamsForEntry)({
117
+ entry: entry,
118
+ getUserScopes: options.getUserScopes,
119
+ user: user,
120
+ })];
121
+ case 2: return [2 /*return*/, _c.sent()];
122
+ case 3:
123
+ error_1 = _c.sent();
124
+ if (error_1 instanceof streams_1.MissingScopeResolverError) {
125
+ emitError(error_1.message);
126
+ return [2 /*return*/, null];
127
+ }
128
+ logger_1.logger.error("[sync] getUserScopes threw for ".concat(collection, ": ").concat(error_1));
129
+ emitError("Failed to resolve scopes for ".concat(collection));
130
+ return [2 /*return*/, null];
131
+ case 4: return [2 /*return*/];
132
+ }
133
+ });
134
+ }); };
135
+ /**
136
+ * Install the sync socket handlers on a single socket. Wired into RealtimeApp's
137
+ * connection handler alongside `installRealtimeSocketHandlers`.
138
+ *
139
+ * The `_io` server parameter is accepted for signature symmetry with future fan-out
140
+ * needs; the current handlers only act on the connecting socket.
141
+ */
142
+ var installSyncSocketHandlers = function (_io, socket, options, handlerOptions) {
143
+ var _a, _b, _c, _d;
144
+ if (options === void 0) { options = {}; }
145
+ if (handlerOptions === void 0) { handlerOptions = {}; }
146
+ var logInfo = (_a = handlerOptions.logInfo) !== null && _a !== void 0 ? _a : (function () { });
147
+ var userId = (_b = socket.decodedToken) === null || _b === void 0 ? void 0 : _b.id;
148
+ // D2: re-derive the authorizing user on every event rather than capturing it once
149
+ // at install time — `socket.data.fullUser` is loaded at handshake and refreshed by
150
+ // D1's sweep, so a mutation sent after a refresh (e.g. after `organizationIds`
151
+ // changed) sees the current full user, not a handshake-time snapshot.
152
+ //
153
+ // Task 9.21: awaits the handshake load when it is still in flight, closing the window
154
+ // where an event arriving first was authorized against the synthetic JWT-claim user
155
+ // (no membership fields — tenant scopes resolved to nothing).
156
+ var currentUser = function () { return (0, socketUser_1.awaitSocketFullUser)(socket); };
157
+ // collection tag -> joined sync rooms, for unsubscribe/disconnect cleanup and D4's
158
+ // sweep-time re-resolution. Exposed on socket.data (when present — real sockets
159
+ // always have it; minimal test doubles may not) so the sweep, which runs outside
160
+ // this closure, can read and mutate it directly.
161
+ var subscriptions = (_d = (_c = socket.data) === null || _c === void 0 ? void 0 : _c.syncSubscriptions) !== null && _d !== void 0 ? _d : new Map();
162
+ if (socket.data) {
163
+ socket.data.syncSubscriptions = subscriptions;
164
+ }
165
+ socket.on("sync:subscribe", function (payload) { return __awaiter(void 0, void 0, void 0, function () {
166
+ var collections, collections_1, collections_1_1, collection, entry, user, streams, rooms, rooms_1, rooms_1_1, room, e_1_1, e_2_1;
167
+ var e_2, _a, e_1, _b;
168
+ return __generator(this, function (_c) {
169
+ switch (_c.label) {
170
+ case 0:
171
+ collections = Array.isArray(payload === null || payload === void 0 ? void 0 : payload.collections) ? payload.collections : null;
172
+ if (!collections) {
173
+ return [2 /*return*/];
174
+ }
175
+ // C8: reject an oversized array up front (length check before iterating).
176
+ if (collections.length > exports.MAX_SYNC_SUBSCRIBE_ARRAY_LENGTH) {
177
+ logInfo("[sync] User ".concat(userId, " sent an oversized sync:subscribe array"));
178
+ socket.emit("sync:error", {
179
+ collection: "",
180
+ message: "sync:subscribe accepts at most ".concat(exports.MAX_SYNC_SUBSCRIBE_ARRAY_LENGTH, " collections"),
181
+ });
182
+ return [2 /*return*/];
183
+ }
184
+ _c.label = 1;
185
+ case 1:
186
+ _c.trys.push([1, 16, 17, 18]);
187
+ collections_1 = __values(collections), collections_1_1 = collections_1.next();
188
+ _c.label = 2;
189
+ case 2:
190
+ if (!!collections_1_1.done) return [3 /*break*/, 15];
191
+ collection = collections_1_1.value;
192
+ if (typeof collection !== "string" || collection.length === 0) {
193
+ return [3 /*break*/, 14];
194
+ }
195
+ if (subscriptions.has(collection)) {
196
+ // Already subscribed — idempotent.
197
+ return [3 /*break*/, 14];
198
+ }
199
+ if (subscriptions.size >= exports.MAX_SYNC_COLLECTION_SUBSCRIPTIONS) {
200
+ logInfo("[sync] User ".concat(userId, " hit sync collection subscription limit"));
201
+ socket.emit("sync:error", {
202
+ collection: collection,
203
+ message: "Sync subscription limit of ".concat(exports.MAX_SYNC_COLLECTION_SUBSCRIPTIONS, " collections reached"),
204
+ });
205
+ return [3 /*break*/, 14];
206
+ }
207
+ entry = (0, registry_1.findSyncEntryByCollectionTag)(collection);
208
+ if (!entry) {
209
+ socket.emit("sync:error", { collection: collection, message: "Unknown sync collection: ".concat(collection) });
210
+ return [3 /*break*/, 14];
211
+ }
212
+ return [4 /*yield*/, currentUser()];
213
+ case 3:
214
+ user = _c.sent();
215
+ if (!user) {
216
+ socket.emit("sync:error", { collection: collection, message: "Authentication required" });
217
+ return [3 /*break*/, 14];
218
+ }
219
+ return [4 /*yield*/, (0, permissions_1.checkPermissions)("list", entry.options.permissions.list, user)];
220
+ case 4:
221
+ if (!(_c.sent())) {
222
+ logInfo("[sync] User ".concat(userId, " denied sync subscription for ").concat(collection));
223
+ socket.emit("sync:error", {
224
+ collection: collection,
225
+ message: "Access to sync collection ".concat(collection, " denied"),
226
+ });
227
+ return [3 /*break*/, 14];
228
+ }
229
+ return [4 /*yield*/, resolveUserStreams({ entry: entry, options: options, socket: socket, user: user })];
230
+ case 5:
231
+ streams = _c.sent();
232
+ if (!streams) {
233
+ return [3 /*break*/, 14];
234
+ }
235
+ rooms = new Set(streams.map(exports.syncRoomForStream));
236
+ _c.label = 6;
237
+ case 6:
238
+ _c.trys.push([6, 11, 12, 13]);
239
+ rooms_1 = (e_1 = void 0, __values(rooms)), rooms_1_1 = rooms_1.next();
240
+ _c.label = 7;
241
+ case 7:
242
+ if (!!rooms_1_1.done) return [3 /*break*/, 10];
243
+ room = rooms_1_1.value;
244
+ return [4 /*yield*/, socket.join(room)];
245
+ case 8:
246
+ _c.sent();
247
+ _c.label = 9;
248
+ case 9:
249
+ rooms_1_1 = rooms_1.next();
250
+ return [3 /*break*/, 7];
251
+ case 10: return [3 /*break*/, 13];
252
+ case 11:
253
+ e_1_1 = _c.sent();
254
+ e_1 = { error: e_1_1 };
255
+ return [3 /*break*/, 13];
256
+ case 12:
257
+ try {
258
+ if (rooms_1_1 && !rooms_1_1.done && (_b = rooms_1.return)) _b.call(rooms_1);
259
+ }
260
+ finally { if (e_1) throw e_1.error; }
261
+ return [7 /*endfinally*/];
262
+ case 13:
263
+ subscriptions.set(collection, rooms);
264
+ socket.emit("sync:subscribed", { collection: collection, streams: streams });
265
+ logInfo("[sync] User ".concat(userId, " subscribed to ").concat(collection, ": ").concat(streams.join(", ")));
266
+ _c.label = 14;
267
+ case 14:
268
+ collections_1_1 = collections_1.next();
269
+ return [3 /*break*/, 2];
270
+ case 15: return [3 /*break*/, 18];
271
+ case 16:
272
+ e_2_1 = _c.sent();
273
+ e_2 = { error: e_2_1 };
274
+ return [3 /*break*/, 18];
275
+ case 17:
276
+ try {
277
+ if (collections_1_1 && !collections_1_1.done && (_a = collections_1.return)) _a.call(collections_1);
278
+ }
279
+ finally { if (e_2) throw e_2.error; }
280
+ return [7 /*endfinally*/];
281
+ case 18: return [2 /*return*/];
282
+ }
283
+ });
284
+ }); });
285
+ socket.on("sync:unsubscribe", function (payload) { return __awaiter(void 0, void 0, void 0, function () {
286
+ var collections, collections_2, collections_2_1, collection, rooms, rooms_2, rooms_2_1, room, e_3_1, e_4_1;
287
+ var e_4, _a, e_3, _b;
288
+ return __generator(this, function (_c) {
289
+ switch (_c.label) {
290
+ case 0:
291
+ collections = Array.isArray(payload === null || payload === void 0 ? void 0 : payload.collections) ? payload.collections : null;
292
+ if (!collections) {
293
+ return [2 /*return*/];
294
+ }
295
+ _c.label = 1;
296
+ case 1:
297
+ _c.trys.push([1, 13, 14, 15]);
298
+ collections_2 = __values(collections), collections_2_1 = collections_2.next();
299
+ _c.label = 2;
300
+ case 2:
301
+ if (!!collections_2_1.done) return [3 /*break*/, 12];
302
+ collection = collections_2_1.value;
303
+ if (typeof collection !== "string") {
304
+ return [3 /*break*/, 11];
305
+ }
306
+ rooms = subscriptions.get(collection);
307
+ if (!rooms) {
308
+ return [3 /*break*/, 11];
309
+ }
310
+ _c.label = 3;
311
+ case 3:
312
+ _c.trys.push([3, 8, 9, 10]);
313
+ rooms_2 = (e_3 = void 0, __values(rooms)), rooms_2_1 = rooms_2.next();
314
+ _c.label = 4;
315
+ case 4:
316
+ if (!!rooms_2_1.done) return [3 /*break*/, 7];
317
+ room = rooms_2_1.value;
318
+ return [4 /*yield*/, socket.leave(room)];
319
+ case 5:
320
+ _c.sent();
321
+ _c.label = 6;
322
+ case 6:
323
+ rooms_2_1 = rooms_2.next();
324
+ return [3 /*break*/, 4];
325
+ case 7: return [3 /*break*/, 10];
326
+ case 8:
327
+ e_3_1 = _c.sent();
328
+ e_3 = { error: e_3_1 };
329
+ return [3 /*break*/, 10];
330
+ case 9:
331
+ try {
332
+ if (rooms_2_1 && !rooms_2_1.done && (_b = rooms_2.return)) _b.call(rooms_2);
333
+ }
334
+ finally { if (e_3) throw e_3.error; }
335
+ return [7 /*endfinally*/];
336
+ case 10:
337
+ subscriptions.delete(collection);
338
+ logInfo("[sync] User ".concat(userId, " unsubscribed from ").concat(collection));
339
+ _c.label = 11;
340
+ case 11:
341
+ collections_2_1 = collections_2.next();
342
+ return [3 /*break*/, 2];
343
+ case 12: return [3 /*break*/, 15];
344
+ case 13:
345
+ e_4_1 = _c.sent();
346
+ e_4 = { error: e_4_1 };
347
+ return [3 /*break*/, 15];
348
+ case 14:
349
+ try {
350
+ if (collections_2_1 && !collections_2_1.done && (_a = collections_2.return)) _a.call(collections_2);
351
+ }
352
+ finally { if (e_4) throw e_4.error; }
353
+ return [7 /*endfinally*/];
354
+ case 15: return [2 /*return*/];
355
+ }
356
+ });
357
+ }); });
358
+ socket.on("sync:mutate", function (payload, ack) { return __awaiter(void 0, void 0, void 0, function () {
359
+ var respond, nack, user, _a, outcome, stage, error_2;
360
+ return __generator(this, function (_b) {
361
+ switch (_b.label) {
362
+ case 0:
363
+ respond = function (outcome) {
364
+ if (outcome.type === "ack") {
365
+ socket.emit("sync:ack", outcome.ack);
366
+ }
367
+ else {
368
+ socket.emit("sync:nack", outcome.nack);
369
+ }
370
+ if (typeof ack === "function") {
371
+ ack(outcome.type === "ack" ? { ack: outcome.ack } : { nack: outcome.nack });
372
+ }
373
+ };
374
+ nack = function (partial) {
375
+ respond({
376
+ nack: __assign({ mutationId: typeof (payload === null || payload === void 0 ? void 0 : payload.mutationId) === "string" ? payload.mutationId : "" }, partial),
377
+ type: "nack",
378
+ });
379
+ };
380
+ return [4 /*yield*/, currentUser()];
381
+ case 1:
382
+ user = _b.sent();
383
+ if (!user) {
384
+ nack({ code: "unauthorized", message: "Authentication required" });
385
+ return [2 /*return*/];
386
+ }
387
+ _b.label = 2;
388
+ case 2:
389
+ _b.trys.push([2, 4, , 5]);
390
+ return [4 /*yield*/, (0, syncBatch_1.runSyncMutation)({
391
+ mutation: payload,
392
+ scopeResolver: options.getUserScopes,
393
+ user: user,
394
+ })];
395
+ case 3:
396
+ _a = _b.sent(), outcome = _a.outcome, stage = _a.stage;
397
+ if (stage === "rate_limited") {
398
+ logInfo("[sync] User ".concat(userId, " hit the sync:mutate rate limit"));
399
+ }
400
+ respond(outcome);
401
+ return [3 /*break*/, 5];
402
+ case 4:
403
+ error_2 = _b.sent();
404
+ logger_1.logger.error("[sync] sync:mutate failed for socket ".concat(socket.id, ": ").concat(error_2));
405
+ nack({ code: "error", message: "Internal error applying mutation" });
406
+ return [3 /*break*/, 5];
407
+ case 5: return [2 /*return*/];
408
+ }
409
+ });
410
+ }); });
411
+ socket.on("sync:mutateBatch", function (payload, ack) { return __awaiter(void 0, void 0, void 0, function () {
412
+ var respondBatch, singleNackBatch, mutations, user, _a, response, stage, error_3;
413
+ return __generator(this, function (_b) {
414
+ switch (_b.label) {
415
+ case 0:
416
+ // FIX 5: emit the receipt IMMEDIATELY, before any processing (including
417
+ // rate-limit/auth checks) — this is what lets the client distinguish
418
+ // "no sync:mutateBatch handler at all" (silence past the grace period)
419
+ // from "the server is just slow finishing this batch" (a receipt
420
+ // arrived; the client then waits the full batch timeout instead of
421
+ // falling back to single sends and possibly double-processing).
422
+ if (typeof (payload === null || payload === void 0 ? void 0 : payload.batchId) === "string" && payload.batchId.length > 0) {
423
+ socket.emit("sync:batchReceived", { batchId: payload.batchId });
424
+ }
425
+ respondBatch = function (response) {
426
+ if (typeof ack === "function") {
427
+ ack(response);
428
+ }
429
+ };
430
+ singleNackBatch = function (partial, mutationId) {
431
+ if (mutationId === void 0) { mutationId = ""; }
432
+ respondBatch({ results: [{ nack: __assign({ mutationId: mutationId }, partial), type: "nack" }] });
433
+ };
434
+ mutations = Array.isArray(payload === null || payload === void 0 ? void 0 : payload.mutations) ? payload.mutations : [];
435
+ return [4 /*yield*/, currentUser()];
436
+ case 1:
437
+ user = _b.sent();
438
+ if (!user) {
439
+ singleNackBatch({ code: "unauthorized", message: "Authentication required" });
440
+ return [2 /*return*/];
441
+ }
442
+ _b.label = 2;
443
+ case 2:
444
+ _b.trys.push([2, 4, , 5]);
445
+ return [4 /*yield*/, (0, syncBatch_1.runSyncBatch)({
446
+ mutations: mutations,
447
+ scopeResolver: options.getUserScopes,
448
+ user: user,
449
+ })];
450
+ case 3:
451
+ _a = _b.sent(), response = _a.response, stage = _a.stage;
452
+ if (stage === "rate_limited") {
453
+ logInfo("[sync] User ".concat(userId, " hit the sync:mutateBatch rate limit"));
454
+ }
455
+ respondBatch(response);
456
+ return [3 /*break*/, 5];
457
+ case 4:
458
+ error_3 = _b.sent();
459
+ logger_1.logger.error("[sync] sync:mutateBatch failed for socket ".concat(socket.id, ": ").concat(error_3));
460
+ singleNackBatch({ code: "error", message: "Internal error applying batch" });
461
+ return [3 /*break*/, 5];
462
+ case 5: return [2 /*return*/];
463
+ }
464
+ });
465
+ }); });
466
+ socket.on("disconnect", function () {
467
+ subscriptions.clear();
468
+ });
469
+ };
470
+ exports.installSyncSocketHandlers = installSyncSocketHandlers;
@@ -0,0 +1,85 @@
1
+ import type { User } from "../auth";
2
+ import type { SyncRegistryEntry } from "./registry";
3
+ import type { SyncScope } from "./types";
4
+ /**
5
+ * Stream key resolution for SyncDB.
6
+ *
7
+ * A stream is the unit of ordered delivery and cursor resumption:
8
+ * `{collectionTag}|owner:{ownerId}`, `{collectionTag}|tenant:{tenantId}`,
9
+ * `{collectionTag}|all` (broadcast), or `{collectionTag}|custom:{value}`.
10
+ */
11
+ /** The document field a scope reads, or null for broadcast/custom scopes. */
12
+ export declare const getScopeField: (scope: SyncScope) => string | null;
13
+ /** Build a stream key from a collection tag and a raw scope value. */
14
+ export declare const streamForScopeValue: ({ collectionTag, scope, scopeValue, }: {
15
+ collectionTag: string;
16
+ scope: SyncScope;
17
+ scopeValue: unknown;
18
+ }) => string;
19
+ /**
20
+ * Parse a stream key into its collection tag and scope value. The value is everything
21
+ * after the first `:` following the `|`-delimited collection tag, so custom values
22
+ * containing `:` survive intact. Broadcast streams (`{tag}|all`) yield `scopeValue: null`.
23
+ * Returns null when the key is not a valid stream key.
24
+ */
25
+ export declare const parseStreamKey: (stream: string) => {
26
+ collectionTag: string;
27
+ scopeKind: string;
28
+ scopeValue: string | null;
29
+ } | null;
30
+ /**
31
+ * Resolve the stream a document belongs to under the given scope.
32
+ *
33
+ * Deliberately total: readers (the change-stream watcher, the tombstone compactor) must
34
+ * be able to name a stream for any document already in the database, including legacy
35
+ * rows written before a scope field existed. Rejecting an unroutable document is the
36
+ * write path's job — see {@link assertWritableStream}.
37
+ */
38
+ export declare const resolveStreamForDoc: ({ collectionTag, scope, doc, }: {
39
+ collectionTag: string;
40
+ scope: SyncScope;
41
+ doc: Record<string, unknown>;
42
+ }) => string;
43
+ /**
44
+ * Write-path guard: refuse to file a tenant-scoped document under `tenant:undefined`, a
45
+ * stream no client can ever subscribe to, which would leave the document written,
46
+ * invisible, and never synced (Task 9.21).
47
+ *
48
+ * Called from the `_syncSeq` plugin's write hooks, so it sees the EFFECTIVE scope value —
49
+ * after any `preCreate` has injected it and before the write commits — on every write
50
+ * path, sync mutations and plain REST/model writes alike. That is why the sync mutation
51
+ * handler does not try to infer the same thing from the raw request body: a create may
52
+ * legitimately omit the field for `preCreate` to supply.
53
+ *
54
+ * Owner scopes are intentionally not guarded: `ownerId` is conventionally stamped by
55
+ * `preCreate`/`IsOwner` plumbing, and an unowned document is still admin-reachable, so
56
+ * tightening that is a separate behavioral change.
57
+ */
58
+ export declare const assertWritableStream: ({ collectionTag, scope, doc, }: {
59
+ collectionTag: string;
60
+ scope: SyncScope;
61
+ doc: Record<string, unknown>;
62
+ }) => void;
63
+ /**
64
+ * Resolve the streams a user currently belongs to for one registered entry — the
65
+ * authoritative membership set, shared by the socket `sync:subscribe` handler,
66
+ * `GET /sync/streams`, and the snapshot stream-membership check.
67
+ *
68
+ * - broadcast → the single `{collection}|all` stream.
69
+ * - owner → the single stream keyed by the authenticated user's own id (a client-supplied
70
+ * id must never select the stream).
71
+ * - tenant / custom → one stream per value from `getUserScopes`. Requires the resolver;
72
+ * throws {@link MissingScopeResolverError} when it is absent.
73
+ *
74
+ * Runs against the FULL user (D2) so tenant memberships resolve from current
75
+ * `organizationIds`.
76
+ */
77
+ export declare class MissingScopeResolverError extends Error {
78
+ collection: string;
79
+ constructor(collection: string);
80
+ }
81
+ export declare const resolveUserStreamsForEntry: ({ entry, user, getUserScopes, }: {
82
+ entry: SyncRegistryEntry;
83
+ user: User;
84
+ getUserScopes?: (user: User, entry: SyncRegistryEntry) => Promise<string[]> | string[];
85
+ }) => Promise<string[]>;