@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,85 +1,11 @@
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
- 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
- var __read = (this && this.__read) || function (o, n) {
61
- var m = typeof Symbol === "function" && o[Symbol.iterator];
62
- if (!m) return o;
63
- var i = m.call(o), r, ar = [], e;
64
- try {
65
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
66
- }
67
- catch (error) { e = { error: error }; }
68
- finally {
69
- try {
70
- if (r && !r.done && (m = i["return"])) m.call(i);
71
- }
72
- finally { if (e) throw e.error; }
73
- }
74
- return ar;
75
- };
76
2
  Object.defineProperty(exports, "__esModule", { value: true });
77
3
  exports.syncPlugin = exports.SCOPE_MOVE_MARKER_ATTEMPTS = void 0;
78
- var errors_1 = require("../errors");
79
- var logger_1 = require("../logger");
80
- var models_1 = require("./models");
81
- var registry_1 = require("./registry");
82
- var streams_1 = require("./streams");
4
+ const errors_1 = require("../errors");
5
+ const logger_1 = require("../logger");
6
+ const models_1 = require("./models");
7
+ const registry_1 = require("./registry");
8
+ const streams_1 = require("./streams");
83
9
  /**
84
10
  * Schema plugin for sync-enabled models. Stamps a monotonic per-stream `_syncSeq` on
85
11
  * every single-document write and records `_syncPrevStream` when a write moves the
@@ -131,38 +57,34 @@ var streams_1 = require("./streams");
131
57
  * - `upsert: true` is rejected on query-writes (m8/C6): an upsert can create a document
132
58
  * the pre-write lookup never saw, escaping seq stamping.
133
59
  */
134
- var INITIAL_STREAM_KEY = "_syncInitialStream";
60
+ const INITIAL_STREAM_KEY = "_syncInitialStream";
135
61
  /**
136
62
  * Resolve the stream for a plain object under an entry's scope. Total by design: this also
137
63
  * runs on documents already in the database (hydration, post-commit seq confirmation, and
138
64
  * the previous-stream lookup for a scope move), where a legacy row with no scope value
139
65
  * must still be nameable rather than unreadable.
140
66
  */
141
- var streamForObject = function (entry, obj) {
142
- return (0, streams_1.resolveStreamForDoc)({ collectionTag: entry.collectionTag, doc: obj, scope: entry.config.scope });
143
- };
67
+ const streamForObject = (entry, obj) => (0, streams_1.resolveStreamForDoc)({ collectionTag: entry.collectionTag, doc: obj, scope: entry.config.scope });
144
68
  /**
145
69
  * Same, for the document a write is about to persist: refuses a tenant-scoped write with
146
70
  * no scope value rather than filing it under an unsubscribable `tenant:undefined` stream
147
71
  * (Task 9.21). Only the seq-stamping write paths use this — reads stay total.
148
72
  */
149
- var writableStreamForObject = function (entry, obj) {
73
+ const writableStreamForObject = (entry, obj) => {
150
74
  (0, streams_1.assertWritableStream)({ collectionTag: entry.collectionTag, doc: obj, scope: entry.config.scope });
151
75
  return streamForObject(entry, obj);
152
76
  };
153
- var unsupportedWrite = function (modelName, operation) {
154
- return new Error("".concat(operation, " is not supported on sync-enabled model ").concat(modelName, ": per-document seq ") +
155
- "stamping requires single-document writes (and deletes must be soft). " +
156
- "Loop per document instead.");
157
- };
77
+ const unsupportedWrite = (modelName, operation) => new Error(`${operation} is not supported on sync-enabled model ${modelName}: per-document seq ` +
78
+ "stamping requires single-document writes (and deletes must be soft). " +
79
+ "Loop per document instead.");
158
80
  /**
159
81
  * m9: a query-write on a synced model must target exactly one document by `_id`, so the
160
82
  * pre-write lookup resolves the stream of the SAME document the update mutates. A non-`_id`
161
83
  * filter can match a different document and stamp the wrong stream's seq (duplicate seqs
162
84
  * within a stream). Accept `{_id: value}` and `{_id: {$eq: value}}`.
163
85
  */
164
- var filterTargetsSingleId = function (filter) {
165
- var idClause = filter._id;
86
+ const filterTargetsSingleId = (filter) => {
87
+ const idClause = filter._id;
166
88
  if (idClause === undefined || idClause === null) {
167
89
  return false;
168
90
  }
@@ -172,18 +94,14 @@ var filterTargetsSingleId = function (filter) {
172
94
  return true;
173
95
  }
174
96
  // A query-operator object is only single-document when it is exactly `{$eq: value}`.
175
- var keys = Object.keys(idClause);
97
+ const keys = Object.keys(idClause);
176
98
  return keys.length === 1 && keys[0] === "$eq";
177
99
  };
178
- var nonIdFilterError = function (modelName, operation) {
179
- return new Error("".concat(operation, " on sync-enabled model ").concat(modelName, " must target a single document by _id ") +
180
- "(use findByIdAndUpdate or loop per document): a non-_id filter can stamp the wrong " +
181
- "stream's seq.");
182
- };
183
- var upsertError = function (modelName, operation) {
184
- return new Error("".concat(operation, " with upsert:true is not supported on sync-enabled model ").concat(modelName, ": an ") +
185
- "upsert can create a document the pre-write lookup never saw, escaping seq stamping.");
186
- };
100
+ const nonIdFilterError = (modelName, operation) => new Error(`${operation} on sync-enabled model ${modelName} must target a single document by _id ` +
101
+ "(use findByIdAndUpdate or loop per document): a non-_id filter can stamp the wrong " +
102
+ "stream's seq.");
103
+ const upsertError = (modelName, operation) => new Error(`${operation} with upsert:true is not supported on sync-enabled model ${modelName}: an ` +
104
+ "upsert can create a document the pre-write lookup never saw, escaping seq stamping.");
187
105
  /**
188
106
  * C4: how many times a scope-move marker insert is attempted before giving up. Losing the
189
107
  * marker loses the old stream's tombstone forever (the exact race C4 exists to eliminate),
@@ -191,12 +109,10 @@ var upsertError = function (modelName, operation) {
191
109
  */
192
110
  exports.SCOPE_MOVE_MARKER_ATTEMPTS = 3;
193
111
  /** Backoff between marker-write attempts. */
194
- var SCOPE_MOVE_MARKER_RETRY_MS = 25;
195
- var delay = function (ms) {
196
- return new Promise(function (resolve) {
197
- setTimeout(resolve, ms);
198
- });
199
- };
112
+ const SCOPE_MOVE_MARKER_RETRY_MS = 25;
113
+ const delay = (ms) => new Promise((resolve) => {
114
+ setTimeout(resolve, ms);
115
+ });
200
116
  /**
201
117
  * C4: write the scope-move marker (claim a seq from the OLD stream so it orders in that
202
118
  * stream's frontier). Runs AFTER the move commits, so it never leaves a phantom tombstone
@@ -206,81 +122,62 @@ var delay = function (ms) {
206
122
  * Never throws: the owning write has already committed, so a marker failure is logged
207
123
  * rather than surfaced to the caller.
208
124
  */
209
- var writeScopeMoveMarker = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
210
- var claim, error_1, attempt, error_2, exhausted;
211
- var entry = _b.entry, entityId = _b.entityId, fromStream = _b.fromStream, toStream = _b.toStream, session = _b.session;
212
- return __generator(this, function (_c) {
213
- switch (_c.label) {
214
- case 0:
215
- _c.trys.push([0, 2, , 3]);
216
- return [4 /*yield*/, (0, models_1.claimSyncSeqs)({ session: session, stream: fromStream })];
217
- case 1:
218
- claim = _c.sent();
219
- return [3 /*break*/, 3];
220
- case 2:
221
- error_1 = _c.sent();
222
- logger_1.logger.error("[sync] Failed to claim scope-move marker seq", {
223
- entityId: entityId,
224
- error: String(error_1),
225
- fromStream: fromStream,
226
- });
227
- return [2 /*return*/];
228
- case 3:
229
- attempt = 1;
230
- _c.label = 4;
231
- case 4:
232
- if (!(attempt <= exports.SCOPE_MOVE_MARKER_ATTEMPTS)) return [3 /*break*/, 12];
233
- _c.label = 5;
234
- case 5:
235
- _c.trys.push([5, 9, , 11]);
236
- return [4 /*yield*/, models_1.SyncScopeMove.create([
237
- {
238
- collectionTag: entry.collectionTag,
239
- entityId: entityId,
240
- fromStream: fromStream,
241
- seq: claim.lastSeq,
242
- toStream: toStream,
243
- },
244
- ], session ? { session: session } : {})];
245
- case 6:
246
- _c.sent();
247
- if (!claim.registered) return [3 /*break*/, 8];
248
- return [4 /*yield*/, (0, models_1.confirmSyncSeqs)({ seqs: claim.seqs, stream: fromStream }).catch(function (error) {
249
- logger_1.logger.error("[sync] Failed to confirm scope-move marker seq", {
250
- error: String(error),
251
- stream: fromStream,
252
- });
253
- })];
254
- case 7:
255
- _c.sent();
256
- _c.label = 8;
257
- case 8: return [2 /*return*/];
258
- case 9:
259
- error_2 = _c.sent();
260
- exhausted = attempt === exports.SCOPE_MOVE_MARKER_ATTEMPTS;
261
- logger_1.logger.error("[sync] Failed to write scope-move marker", {
262
- attempt: attempt,
263
- entityId: entityId,
264
- error: String(error_2),
265
- exhausted: exhausted,
266
- fromStream: fromStream,
125
+ const writeScopeMoveMarker = async ({ entry, entityId, fromStream, toStream, session, }) => {
126
+ let claim;
127
+ try {
128
+ claim = await (0, models_1.claimSyncSeqs)({ session, stream: fromStream });
129
+ }
130
+ catch (error) {
131
+ logger_1.logger.error("[sync] Failed to claim scope-move marker seq", {
132
+ entityId,
133
+ error: String(error),
134
+ fromStream,
135
+ });
136
+ return;
137
+ }
138
+ // Retry the insert with the SAME claimed seq so a retry cannot mint a second marker
139
+ // ordered at a different point in the old stream.
140
+ for (let attempt = 1; attempt <= exports.SCOPE_MOVE_MARKER_ATTEMPTS; attempt++) {
141
+ try {
142
+ await models_1.SyncScopeMove.create([
143
+ {
144
+ collectionTag: entry.collectionTag,
145
+ entityId,
146
+ fromStream,
147
+ seq: claim.lastSeq,
148
+ toStream,
149
+ },
150
+ ], session ? { session } : {});
151
+ // The marker's own seq on the old stream is confirmed once the insert lands: that
152
+ // insert is the committing write for the claim.
153
+ if (claim.registered) {
154
+ await (0, models_1.confirmSyncSeqs)({ seqs: claim.seqs, stream: fromStream }).catch((error) => {
155
+ logger_1.logger.error("[sync] Failed to confirm scope-move marker seq", {
156
+ error: String(error),
157
+ stream: fromStream,
158
+ });
267
159
  });
268
- if (exhausted) {
269
- // The claim is left pending: the old stream's frontier holds below the missing
270
- // tombstone until the lease ages it out, rather than skipping it silently.
271
- return [2 /*return*/];
272
- }
273
- return [4 /*yield*/, delay(SCOPE_MOVE_MARKER_RETRY_MS)];
274
- case 10:
275
- _c.sent();
276
- return [3 /*break*/, 11];
277
- case 11:
278
- attempt++;
279
- return [3 /*break*/, 4];
280
- case 12: return [2 /*return*/];
160
+ }
161
+ return;
281
162
  }
282
- });
283
- }); };
163
+ catch (error) {
164
+ const exhausted = attempt === exports.SCOPE_MOVE_MARKER_ATTEMPTS;
165
+ logger_1.logger.error("[sync] Failed to write scope-move marker", {
166
+ attempt,
167
+ entityId,
168
+ error: String(error),
169
+ exhausted,
170
+ fromStream,
171
+ });
172
+ if (exhausted) {
173
+ // The claim is left pending: the old stream's frontier holds below the missing
174
+ // tombstone until the lease ages it out, rather than skipping it silently.
175
+ return;
176
+ }
177
+ await delay(SCOPE_MOVE_MARKER_RETRY_MS);
178
+ }
179
+ }
180
+ };
284
181
  /**
285
182
  * Task 9.17: the confirm found no pending entry, meaning this writer's claim was reaped as
286
183
  * abandoned (it stalled past {@link PENDING_CLAIM_LEASE_MS} without crashing) and the
@@ -292,60 +189,43 @@ var writeScopeMoveMarker = function (_a) { return __awaiter(void 0, [_a], void 0
292
189
  * Returns the new seq, or undefined when re-stamping failed (logged; the document stays
293
190
  * below the frontier and only a full re-bootstrap recovers it).
294
191
  */
295
- var restampReapedSeq = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
296
- var claim, result, confirmed, error_3;
297
- var _c;
298
- var model = _b.model, id = _b.id, stream = _b.stream, reapedSeq = _b.reapedSeq;
299
- return __generator(this, function (_d) {
300
- switch (_d.label) {
301
- case 0:
302
- logger_1.logger.error("[sync] Seq claim was reaped before its write committed; re-stamping the document above " +
303
- "the frontier", { entityId: String(id), model: model.modelName, reapedSeq: reapedSeq, stream: stream });
304
- _d.label = 1;
305
- case 1:
306
- _d.trys.push([1, 7, , 8]);
307
- return [4 /*yield*/, (0, models_1.claimSyncSeqs)({ stream: stream })];
308
- case 2:
309
- claim = _d.sent();
310
- return [4 /*yield*/, model.collection.updateOne({ _id: id }, { $set: { _syncSeq: claim.lastSeq } })];
311
- case 3:
312
- result = _d.sent();
313
- if (!(((_c = result.matchedCount) !== null && _c !== void 0 ? _c : 0) === 0)) return [3 /*break*/, 5];
314
- logger_1.logger.error("[sync] Re-stamp matched no document; releasing the re-stamp claim", {
315
- entityId: String(id),
316
- seq: claim.lastSeq,
317
- stream: stream,
318
- });
319
- return [4 /*yield*/, (0, models_1.releaseSyncSeqs)({ seqs: claim.seqs, stream: stream })];
320
- case 4:
321
- _d.sent();
322
- return [2 /*return*/, undefined];
323
- case 5: return [4 /*yield*/, (0, models_1.confirmSyncSeqs)({ seqs: claim.seqs, stream: stream })];
324
- case 6:
325
- confirmed = _d.sent();
326
- if (!confirmed.cleared) {
327
- // Two reaps in a row means the process is pathologically slow; stop recursing.
328
- logger_1.logger.error("[sync] Re-stamped seq was itself reaped; document remains below the frontier", {
329
- entityId: String(id),
330
- seq: claim.lastSeq,
331
- stream: stream,
332
- });
333
- }
334
- return [2 /*return*/, claim.lastSeq];
335
- case 7:
336
- error_3 = _d.sent();
337
- logger_1.logger.error("[sync] Failed to re-stamp a reaped seq", {
338
- entityId: String(id),
339
- error: String(error_3),
340
- reapedSeq: reapedSeq,
341
- stream: stream,
342
- });
343
- return [2 /*return*/, undefined];
344
- case 8: return [2 /*return*/];
192
+ const restampReapedSeq = async ({ model, id, stream, reapedSeq, }) => {
193
+ logger_1.logger.error("[sync] Seq claim was reaped before its write committed; re-stamping the document above " +
194
+ "the frontier", { entityId: String(id), model: model.modelName, reapedSeq, stream });
195
+ try {
196
+ const claim = await (0, models_1.claimSyncSeqs)({ stream });
197
+ const result = await model.collection.updateOne({ _id: id }, { $set: { _syncSeq: claim.lastSeq } });
198
+ if ((result.matchedCount ?? 0) === 0) {
199
+ logger_1.logger.error("[sync] Re-stamp matched no document; releasing the re-stamp claim", {
200
+ entityId: String(id),
201
+ seq: claim.lastSeq,
202
+ stream,
203
+ });
204
+ await (0, models_1.releaseSyncSeqs)({ seqs: claim.seqs, stream });
205
+ return undefined;
345
206
  }
346
- });
347
- }); };
348
- var syncPlugin = function (schema) {
207
+ const confirmed = await (0, models_1.confirmSyncSeqs)({ seqs: claim.seqs, stream });
208
+ if (!confirmed.cleared) {
209
+ // Two reaps in a row means the process is pathologically slow; stop recursing.
210
+ logger_1.logger.error("[sync] Re-stamped seq was itself reaped; document remains below the frontier", {
211
+ entityId: String(id),
212
+ seq: claim.lastSeq,
213
+ stream,
214
+ });
215
+ }
216
+ return claim.lastSeq;
217
+ }
218
+ catch (error) {
219
+ logger_1.logger.error("[sync] Failed to re-stamp a reaped seq", {
220
+ entityId: String(id),
221
+ error: String(error),
222
+ reapedSeq,
223
+ stream,
224
+ });
225
+ return undefined;
226
+ }
227
+ };
228
+ const syncPlugin = (schema) => {
349
229
  // Task 9.13: `doc.save()` must be conditional on the version the document was loaded at,
350
230
  // so the `baseVersion` comparison in executeUpdate cannot be defeated by a concurrent
351
231
  // save landing between the read and the write.
@@ -374,130 +254,108 @@ var syncPlugin = function (schema) {
374
254
  // Capture the stream the document belonged to when it was loaded, so scope moves can
375
255
  // be detected at save time without re-querying.
376
256
  schema.post("init", function () {
377
- var entry = (0, registry_1.findSyncEntryByModelName)(this.constructor.modelName);
257
+ const entry = (0, registry_1.findSyncEntryByModelName)(this.constructor.modelName);
378
258
  if (!entry) {
379
259
  return;
380
260
  }
381
261
  this.$locals[INITIAL_STREAM_KEY] = streamForObject(entry, this.toObject());
382
262
  });
383
- var PENDING_COMMIT_KEY = "_syncPendingCommit";
384
- schema.pre("save", function () {
385
- return __awaiter(this, void 0, void 0, function () {
386
- var entry, ignored_1, meaningful, session, currentStream, prevStream, initialStream, claim, pending;
387
- var _a;
388
- return __generator(this, function (_b) {
389
- switch (_b.label) {
390
- case 0:
391
- entry = (0, registry_1.findSyncEntryByModelName)(this.constructor.modelName);
392
- if (!entry) {
393
- return [2 /*return*/];
394
- }
395
- // A previous save on this instance that failed after this hook leaves its pending work
396
- // behind; drop it so this save's post hook never acts on the earlier attempt's claim.
397
- this.$locals[PENDING_COMMIT_KEY] = undefined;
398
- // m10: a save that changes nothing meaningful must not burn a seq or emit a delta.
399
- // Excluded from the "meaningful" set: the sync stamps this hook writes (`_syncSeq`,
400
- // `_syncPrevStream`) and auto-managed timestamp metadata (`updated`, which
401
- // createdUpdatedPlugin bumps on EVERY save — otherwise no save would ever be a
402
- // no-op). A save whose only modified paths are these is a no-op: skip the claim.
403
- if (!this.isNew) {
404
- ignored_1 = new Set(["_syncSeq", "_syncPrevStream", "updated"]);
405
- meaningful = this.modifiedPaths().filter(function (p) { return !ignored_1.has(p); });
406
- if (meaningful.length === 0) {
407
- return [2 /*return*/];
408
- }
409
- }
410
- session = (_a = this.$session()) !== null && _a !== void 0 ? _a : null;
411
- currentStream = writableStreamForObject(entry, this.toObject());
412
- prevStream = null;
413
- if (!this.isNew) {
414
- initialStream = this.$locals[INITIAL_STREAM_KEY];
415
- if (initialStream && initialStream !== currentStream) {
416
- prevStream = initialStream;
417
- }
418
- }
419
- return [4 /*yield*/, (0, models_1.claimSyncSeqs)({ session: session, stream: currentStream })];
420
- case 1:
421
- claim = _b.sent();
422
- this.set({ _syncPrevStream: prevStream, _syncSeq: claim.lastSeq });
423
- pending = {
424
- claim: claim,
425
- currentStream: currentStream,
426
- entityId: String(this._id),
427
- entry: entry,
428
- prevStream: prevStream,
429
- session: session,
430
- };
431
- this.$locals[PENDING_COMMIT_KEY] = pending;
432
- return [2 /*return*/];
433
- }
434
- });
435
- });
263
+ const PENDING_COMMIT_KEY = "_syncPendingCommit";
264
+ schema.pre("save", async function () {
265
+ const entry = (0, registry_1.findSyncEntryByModelName)(this.constructor.modelName);
266
+ if (!entry) {
267
+ return;
268
+ }
269
+ // A previous save on this instance that failed after this hook leaves its pending work
270
+ // behind; drop it so this save's post hook never acts on the earlier attempt's claim.
271
+ this.$locals[PENDING_COMMIT_KEY] = undefined;
272
+ // m10: a save that changes nothing meaningful must not burn a seq or emit a delta.
273
+ // Excluded from the "meaningful" set: the sync stamps this hook writes (`_syncSeq`,
274
+ // `_syncPrevStream`) and auto-managed timestamp metadata (`updated`, which
275
+ // createdUpdatedPlugin bumps on EVERY save — otherwise no save would ever be a
276
+ // no-op). A save whose only modified paths are these is a no-op: skip the claim.
277
+ if (!this.isNew) {
278
+ const ignored = new Set(["_syncSeq", "_syncPrevStream", "updated"]);
279
+ const meaningful = this.modifiedPaths().filter((p) => !ignored.has(p));
280
+ if (meaningful.length === 0) {
281
+ return;
282
+ }
283
+ }
284
+ const session = this.$session() ?? null;
285
+ const currentStream = writableStreamForObject(entry, this.toObject());
286
+ let prevStream = null;
287
+ if (!this.isNew) {
288
+ const initialStream = this.$locals[INITIAL_STREAM_KEY];
289
+ if (initialStream && initialStream !== currentStream) {
290
+ prevStream = initialStream;
291
+ }
292
+ }
293
+ const claim = await (0, models_1.claimSyncSeqs)({ session, stream: currentStream });
294
+ this.set({ _syncPrevStream: prevStream, _syncSeq: claim.lastSeq });
295
+ // Stash everything post-commit work needs: the seq confirm (C1) and the scope-move
296
+ // marker (C4). Both MUST wait for the commit — a save that fails after this hook
297
+ // (E11000, VersionError, a later user hook) must leave neither a confirmed seq nor a
298
+ // phantom tombstone that old-stream clients would apply to a still-live document.
299
+ const pending = {
300
+ claim,
301
+ currentStream,
302
+ entityId: String(this._id),
303
+ entry,
304
+ prevStream,
305
+ session,
306
+ };
307
+ this.$locals[PENDING_COMMIT_KEY] = pending;
436
308
  });
437
309
  // C1/C4: once the document write commits, confirm the claimed seq (so the stable
438
310
  // frontier can advance past it) and record the durable scope-move marker. Document
439
311
  // post('save') `this` is the saved document.
440
- schema.post("save", function () {
441
- return __awaiter(this, void 0, void 0, function () {
442
- var pending, confirmed, restamped;
443
- return __generator(this, function (_a) {
444
- switch (_a.label) {
445
- case 0:
446
- pending = this.$locals[PENDING_COMMIT_KEY];
447
- if (!pending) {
448
- return [2 /*return*/];
449
- }
450
- this.$locals[PENDING_COMMIT_KEY] = undefined;
451
- if (!pending.claim.registered) return [3 /*break*/, 3];
452
- return [4 /*yield*/, (0, models_1.confirmSyncSeqs)({
453
- seqs: pending.claim.seqs,
454
- stream: pending.currentStream,
455
- }).catch(function (error) {
456
- // Never fail the user write for a confirm error: the entry ages out via the lease.
457
- logger_1.logger.error("[sync] Failed to confirm seq after save", {
458
- error: String(error),
459
- stream: pending.currentStream,
460
- });
461
- return { cleared: true };
462
- })];
463
- case 1:
464
- confirmed = _a.sent();
465
- if (!!confirmed.cleared) return [3 /*break*/, 3];
466
- return [4 /*yield*/, restampReapedSeq({
467
- id: this._id,
468
- model: this.constructor,
469
- reapedSeq: pending.claim.seqs[pending.claim.seqs.length - 1],
470
- stream: pending.currentStream,
471
- })];
472
- case 2:
473
- restamped = _a.sent();
474
- if (restamped !== undefined) {
475
- // Reflect the durable seq on the in-memory document so the caller's ack (and
476
- // any serialization of this instance) reports the seq clients will actually see.
477
- this.$set("_syncSeq", restamped);
478
- this.unmarkModified("_syncSeq");
479
- }
480
- _a.label = 3;
481
- case 3:
482
- if (!pending.prevStream) return [3 /*break*/, 5];
483
- return [4 /*yield*/, writeScopeMoveMarker({
484
- entityId: pending.entityId,
485
- entry: pending.entry,
486
- fromStream: pending.prevStream,
487
- session: pending.session,
488
- toStream: pending.currentStream,
489
- })];
490
- case 4:
491
- _a.sent();
492
- _a.label = 5;
493
- case 5:
494
- // The committed stream becomes the baseline for the next save on this instance; a
495
- // FAILED save keeps the old baseline so a retry still detects the move.
496
- this.$locals[INITIAL_STREAM_KEY] = pending.currentStream;
497
- return [2 /*return*/];
312
+ schema.post("save", async function () {
313
+ const pending = this.$locals[PENDING_COMMIT_KEY];
314
+ if (!pending) {
315
+ return;
316
+ }
317
+ this.$locals[PENDING_COMMIT_KEY] = undefined;
318
+ if (pending.claim.registered) {
319
+ const confirmed = await (0, models_1.confirmSyncSeqs)({
320
+ seqs: pending.claim.seqs,
321
+ stream: pending.currentStream,
322
+ }).catch((error) => {
323
+ // Never fail the user write for a confirm error: the entry ages out via the lease.
324
+ logger_1.logger.error("[sync] Failed to confirm seq after save", {
325
+ error: String(error),
326
+ stream: pending.currentStream,
327
+ });
328
+ return { cleared: true };
329
+ });
330
+ if (!confirmed.cleared) {
331
+ // Task 9.17: this writer's claim was reaped as abandoned while it was still
332
+ // running, so the frontier already passed the seq we just committed.
333
+ const restamped = await restampReapedSeq({
334
+ id: this._id,
335
+ model: this.constructor,
336
+ reapedSeq: pending.claim.seqs[pending.claim.seqs.length - 1],
337
+ stream: pending.currentStream,
338
+ });
339
+ if (restamped !== undefined) {
340
+ // Reflect the durable seq on the in-memory document so the caller's ack (and
341
+ // any serialization of this instance) reports the seq clients will actually see.
342
+ this.$set("_syncSeq", restamped);
343
+ this.unmarkModified("_syncSeq");
498
344
  }
345
+ }
346
+ }
347
+ if (pending.prevStream) {
348
+ await writeScopeMoveMarker({
349
+ entityId: pending.entityId,
350
+ entry: pending.entry,
351
+ fromStream: pending.prevStream,
352
+ session: pending.session,
353
+ toStream: pending.currentStream,
499
354
  });
500
- });
355
+ }
356
+ // The committed stream becomes the baseline for the next save on this instance; a
357
+ // FAILED save keeps the old baseline so a retry still detects the move.
358
+ this.$locals[INITIAL_STREAM_KEY] = pending.currentStream;
501
359
  });
502
360
  // Any save that claimed a seq in pre('save') but then failed (VersionError, E11000,
503
361
  // simulated/hook failure, etc.) never stamped that seq. Release it so the stable
@@ -508,369 +366,241 @@ var syncPlugin = function (schema) {
508
366
  // leaves an orphaned rejection that Bun reports as an unhandled error between tests,
509
367
  // even when the caller correctly awaited `save().catch(...)`.
510
368
  // Keep arity ≥ 3 so Kareem still classifies this as error middleware.
511
- schema.post("save", function (error, doc, _next) {
512
- return __awaiter(this, void 0, void 0, function () {
513
- var locals, pending;
514
- var _a;
515
- return __generator(this, function (_b) {
516
- switch (_b.label) {
517
- case 0:
518
- locals = ((_a = this === null || this === void 0 ? void 0 : this.$locals) !== null && _a !== void 0 ? _a : doc === null || doc === void 0 ? void 0 : doc.$locals);
519
- pending = locals === null || locals === void 0 ? void 0 : locals[PENDING_COMMIT_KEY];
520
- if (locals) {
521
- locals[PENDING_COMMIT_KEY] = undefined;
522
- }
523
- if (!(pending === null || pending === void 0 ? void 0 : pending.claim.registered)) return [3 /*break*/, 2];
524
- return [4 /*yield*/, (0, models_1.releaseSyncSeqs)({ seqs: pending.claim.seqs, stream: pending.currentStream }).catch(function (releaseError) {
525
- logger_1.logger.error("[sync] Failed to release seq claim after failed save", {
526
- error: String(releaseError),
527
- stream: pending.currentStream,
528
- });
529
- })];
530
- case 1:
531
- _b.sent();
532
- _b.label = 2;
533
- case 2: throw error;
534
- }
369
+ schema.post("save", async function (error, doc, _next) {
370
+ const locals = (this?.$locals ??
371
+ doc?.$locals);
372
+ const pending = locals?.[PENDING_COMMIT_KEY];
373
+ if (locals) {
374
+ locals[PENDING_COMMIT_KEY] = undefined;
375
+ }
376
+ if (pending?.claim.registered) {
377
+ await (0, models_1.releaseSyncSeqs)({ seqs: pending.claim.seqs, stream: pending.currentStream }).catch((releaseError) => {
378
+ logger_1.logger.error("[sync] Failed to release seq claim after failed save", {
379
+ error: String(releaseError),
380
+ stream: pending.currentStream,
381
+ });
535
382
  });
536
- });
383
+ }
384
+ throw error;
537
385
  });
538
386
  // Mongoose 9 insertMany pre hooks are async (no `next` callback) and receive docs + options.
539
- schema.pre("insertMany", function (docs, options) {
540
- return __awaiter(this, void 0, void 0, function () {
541
- var docsArray, model, entry, session, byStream, docsArray_1, docsArray_1_1, doc, stream, group, _loop_1, byStream_1, byStream_1_1, _a, stream, group, e_1_1;
542
- var e_2, _b, e_1, _c;
543
- var _d, _e;
544
- return __generator(this, function (_f) {
545
- switch (_f.label) {
546
- case 0:
547
- docsArray = Array.isArray(docs)
548
- ? docs
549
- : [docs];
550
- model = this;
551
- entry = (0, registry_1.findSyncEntryByModelName)(model.modelName);
552
- if (!entry || docsArray.length === 0) {
553
- return [2 /*return*/];
554
- }
555
- session = (_d = options === null || options === void 0 ? void 0 : options.session) !== null && _d !== void 0 ? _d : null;
556
- byStream = new Map();
557
- try {
558
- for (docsArray_1 = __values(docsArray), docsArray_1_1 = docsArray_1.next(); !docsArray_1_1.done; docsArray_1_1 = docsArray_1.next()) {
559
- doc = docsArray_1_1.value;
560
- stream = writableStreamForObject(entry, doc);
561
- group = (_e = byStream.get(stream)) !== null && _e !== void 0 ? _e : [];
562
- group.push(doc);
563
- byStream.set(stream, group);
564
- }
565
- }
566
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
567
- finally {
568
- try {
569
- if (docsArray_1_1 && !docsArray_1_1.done && (_b = docsArray_1.return)) _b.call(docsArray_1);
570
- }
571
- finally { if (e_2) throw e_2.error; }
572
- }
573
- _loop_1 = function (stream, group) {
574
- var claim;
575
- return __generator(this, function (_g) {
576
- switch (_g.label) {
577
- case 0: return [4 /*yield*/, (0, models_1.claimSyncSeqs)({ count: group.length, session: session, stream: stream })];
578
- case 1:
579
- claim = _g.sent();
580
- group.forEach(function (doc, index) {
581
- doc._syncPrevStream = null;
582
- doc._syncSeq = claim.seqs[index];
583
- });
584
- return [2 /*return*/];
585
- }
586
- });
587
- };
588
- _f.label = 1;
589
- case 1:
590
- _f.trys.push([1, 6, 7, 8]);
591
- byStream_1 = __values(byStream), byStream_1_1 = byStream_1.next();
592
- _f.label = 2;
593
- case 2:
594
- if (!!byStream_1_1.done) return [3 /*break*/, 5];
595
- _a = __read(byStream_1_1.value, 2), stream = _a[0], group = _a[1];
596
- return [5 /*yield**/, _loop_1(stream, group)];
597
- case 3:
598
- _f.sent();
599
- _f.label = 4;
600
- case 4:
601
- byStream_1_1 = byStream_1.next();
602
- return [3 /*break*/, 2];
603
- case 5: return [3 /*break*/, 8];
604
- case 6:
605
- e_1_1 = _f.sent();
606
- e_1 = { error: e_1_1 };
607
- return [3 /*break*/, 8];
608
- case 7:
609
- try {
610
- if (byStream_1_1 && !byStream_1_1.done && (_c = byStream_1.return)) _c.call(byStream_1);
611
- }
612
- finally { if (e_1) throw e_1.error; }
613
- return [7 /*endfinally*/];
614
- case 8: return [2 /*return*/];
615
- }
387
+ schema.pre("insertMany", async function (docs, options) {
388
+ const docsArray = Array.isArray(docs)
389
+ ? docs
390
+ : [docs];
391
+ const model = this;
392
+ const entry = (0, registry_1.findSyncEntryByModelName)(model.modelName);
393
+ if (!entry || docsArray.length === 0) {
394
+ return;
395
+ }
396
+ const session = options?.session ?? null;
397
+ const byStream = new Map();
398
+ for (const doc of docsArray) {
399
+ const stream = writableStreamForObject(entry, doc);
400
+ const group = byStream.get(stream) ?? [];
401
+ group.push(doc);
402
+ byStream.set(stream, group);
403
+ }
404
+ for (const [stream, group] of byStream) {
405
+ // The claim joins the caller's session so a transactional insertMany gets true
406
+ // counter+write atomicity (and registers no pending entry to confirm).
407
+ const claim = await (0, models_1.claimSyncSeqs)({ count: group.length, session, stream });
408
+ group.forEach((doc, index) => {
409
+ doc._syncPrevStream = null;
410
+ doc._syncSeq = claim.seqs[index];
616
411
  });
617
- });
412
+ }
413
+ // C1: the confirm belongs in post('insertMany') — confirming here would let the
414
+ // stable frontier (and therefore a snapshot cursor) advance past seqs whose
415
+ // documents have not committed yet, stranding them below every catch-up cursor.
618
416
  });
619
417
  // C1: the batch has committed — confirm the claimed seqs so the frontier advances past
620
418
  // them. Post insertMany middleware receives the inserted (hydrated) documents, which
621
419
  // carry the seqs stamped in the pre hook.
622
- schema.post("insertMany", function (docs) {
623
- return __awaiter(this, void 0, void 0, function () {
624
- var modelName, entry, seqsByStream, _a, _b, doc, obj, seq, stream, seqs, _loop_2, seqsByStream_1, seqsByStream_1_1, _c, stream, seqs, e_3_1;
625
- var e_4, _d, e_3, _e;
626
- var _f, _g, _h, _j;
627
- return __generator(this, function (_k) {
628
- switch (_k.label) {
629
- case 0:
630
- if (!Array.isArray(docs) || docs.length === 0) {
631
- return [2 /*return*/];
632
- }
633
- modelName = ((_h = (_g = (_f = docs[0]) === null || _f === void 0 ? void 0 : _f.constructor) === null || _g === void 0 ? void 0 : _g.modelName) !== null && _h !== void 0 ? _h : this.modelName);
634
- entry = modelName ? (0, registry_1.findSyncEntryByModelName)(modelName) : undefined;
635
- if (!entry) {
636
- return [2 /*return*/];
637
- }
638
- seqsByStream = new Map();
639
- try {
640
- for (_a = __values(docs), _b = _a.next(); !_b.done; _b = _a.next()) {
641
- doc = _b.value;
642
- // A session-backed claim registered nothing to confirm, and a `$pull` issued outside
643
- // the caller's still-open transaction would conflict with its counter write.
644
- if (typeof (doc === null || doc === void 0 ? void 0 : doc.$session) === "function" && doc.$session()) {
645
- continue;
646
- }
647
- obj = typeof (doc === null || doc === void 0 ? void 0 : doc.toObject) === "function" ? doc.toObject() : doc;
648
- seq = obj._syncSeq;
649
- if (typeof seq !== "number") {
650
- continue;
651
- }
652
- stream = streamForObject(entry, obj);
653
- seqs = (_j = seqsByStream.get(stream)) !== null && _j !== void 0 ? _j : [];
654
- seqs.push(seq);
655
- seqsByStream.set(stream, seqs);
656
- }
657
- }
658
- catch (e_4_1) { e_4 = { error: e_4_1 }; }
659
- finally {
660
- try {
661
- if (_b && !_b.done && (_d = _a.return)) _d.call(_a);
662
- }
663
- finally { if (e_4) throw e_4.error; }
664
- }
665
- _loop_2 = function (stream, seqs) {
666
- return __generator(this, function (_l) {
667
- switch (_l.label) {
668
- case 0: return [4 /*yield*/, (0, models_1.confirmSyncSeqs)({ seqs: seqs, stream: stream }).catch(function (error) {
669
- // Never fail the user write for a confirm error: the entries age out via the lease.
670
- logger_1.logger.error("[sync] Failed to confirm insertMany seqs", {
671
- error: String(error),
672
- stream: stream,
673
- });
674
- })];
675
- case 1:
676
- _l.sent();
677
- return [2 /*return*/];
678
- }
679
- });
680
- };
681
- _k.label = 1;
682
- case 1:
683
- _k.trys.push([1, 6, 7, 8]);
684
- seqsByStream_1 = __values(seqsByStream), seqsByStream_1_1 = seqsByStream_1.next();
685
- _k.label = 2;
686
- case 2:
687
- if (!!seqsByStream_1_1.done) return [3 /*break*/, 5];
688
- _c = __read(seqsByStream_1_1.value, 2), stream = _c[0], seqs = _c[1];
689
- return [5 /*yield**/, _loop_2(stream, seqs)];
690
- case 3:
691
- _k.sent();
692
- _k.label = 4;
693
- case 4:
694
- seqsByStream_1_1 = seqsByStream_1.next();
695
- return [3 /*break*/, 2];
696
- case 5: return [3 /*break*/, 8];
697
- case 6:
698
- e_3_1 = _k.sent();
699
- e_3 = { error: e_3_1 };
700
- return [3 /*break*/, 8];
701
- case 7:
702
- try {
703
- if (seqsByStream_1_1 && !seqsByStream_1_1.done && (_e = seqsByStream_1.return)) _e.call(seqsByStream_1);
704
- }
705
- finally { if (e_3) throw e_3.error; }
706
- return [7 /*endfinally*/];
707
- case 8: return [2 /*return*/];
708
- }
420
+ schema.post("insertMany", async function (docs) {
421
+ if (!Array.isArray(docs) || docs.length === 0) {
422
+ return;
423
+ }
424
+ const modelName = (docs[0]?.constructor?.modelName ??
425
+ this.modelName);
426
+ const entry = modelName ? (0, registry_1.findSyncEntryByModelName)(modelName) : undefined;
427
+ if (!entry) {
428
+ return;
429
+ }
430
+ const seqsByStream = new Map();
431
+ for (const doc of docs) {
432
+ // A session-backed claim registered nothing to confirm, and a `$pull` issued outside
433
+ // the caller's still-open transaction would conflict with its counter write.
434
+ if (typeof doc?.$session === "function" && doc.$session()) {
435
+ continue;
436
+ }
437
+ const obj = typeof doc?.toObject === "function" ? doc.toObject() : doc;
438
+ const seq = obj._syncSeq;
439
+ if (typeof seq !== "number") {
440
+ continue;
441
+ }
442
+ const stream = streamForObject(entry, obj);
443
+ const seqs = seqsByStream.get(stream) ?? [];
444
+ seqs.push(seq);
445
+ seqsByStream.set(stream, seqs);
446
+ }
447
+ for (const [stream, seqs] of seqsByStream) {
448
+ await (0, models_1.confirmSyncSeqs)({ seqs, stream }).catch((error) => {
449
+ // Never fail the user write for a confirm error: the entries age out via the lease.
450
+ logger_1.logger.error("[sync] Failed to confirm insertMany seqs", {
451
+ error: String(error),
452
+ stream,
453
+ });
709
454
  });
710
- });
455
+ }
711
456
  });
712
- var preQueryWrite = function () {
713
- return __awaiter(this, void 0, void 0, function () {
714
- var model, entry, operation, rawFilter, session, filter, matches, target, targetObj, previousStream, rawUpdate, op, isTrueReplacement, hasOperators, setFields, scopeField, currentStream, effectiveDoc, unsetFields, newScopeValue, prevStream, claim;
715
- var _a;
716
- var _b, _c, _d, _e, _f, _g, _h;
717
- return __generator(this, function (_j) {
718
- switch (_j.label) {
719
- case 0:
720
- model = this.model;
721
- entry = (0, registry_1.findSyncEntryByModelName)(model.modelName);
722
- if (!entry) {
723
- return [2 /*return*/];
724
- }
725
- operation = (_b = this.op) !== null && _b !== void 0 ? _b : "query-write";
726
- // m8/C6: reject upserts — an upsert can create a doc the lookup never saw.
727
- if (this.getOptions().upsert) {
728
- throw upsertError(model.modelName, operation);
729
- }
730
- rawFilter = this.getFilter();
731
- // m9: refuse a non-single-_id filter — it could match a different doc than intended.
732
- if (!filterTargetsSingleId(rawFilter)) {
733
- throw nonIdFilterError(model.modelName, operation);
734
- }
735
- session = (_c = this.getOptions().session) !== null && _c !== void 0 ? _c : null;
736
- filter = __assign({}, rawFilter);
737
- if (filter.deleted === undefined) {
738
- filter.deleted = { $in: [true, false] };
739
- }
740
- return [4 /*yield*/, model
741
- .find(filter)
742
- .setOptions(session ? { session: session } : {})
743
- .limit(1)];
744
- case 1:
745
- matches = _j.sent();
746
- target = matches[0];
747
- if (!target) {
748
- // The update matches nothing; let it proceed as a no-op.
749
- return [2 /*return*/];
750
- }
751
- targetObj = target.toObject();
752
- previousStream = streamForObject(entry, targetObj);
753
- rawUpdate = ((_d = this.getUpdate()) !== null && _d !== void 0 ? _d : {});
754
- op = (_e = this.op) !== null && _e !== void 0 ? _e : "";
755
- isTrueReplacement = op === "replaceOne" || op === "findOneAndReplace";
756
- hasOperators = Object.keys(rawUpdate).some(function (key) { return key.startsWith("$"); });
757
- setFields = isTrueReplacement
758
- ? {}
759
- : hasOperators
760
- ? ((_f = rawUpdate.$set) !== null && _f !== void 0 ? _f : {})
761
- : rawUpdate;
762
- scopeField = (0, streams_1.getScopeField)(entry.config.scope);
763
- if (typeof entry.config.scope === "function") {
764
- effectiveDoc = isTrueReplacement ? rawUpdate : __assign(__assign({}, targetObj), setFields);
765
- currentStream = streamForObject(entry, effectiveDoc);
766
- }
767
- else if (scopeField) {
768
- unsetFields = hasOperators
769
- ? ((_g = rawUpdate.$unset) !== null && _g !== void 0 ? _g : {})
770
- : {};
771
- newScopeValue = void 0;
772
- if (isTrueReplacement) {
773
- newScopeValue = rawUpdate[scopeField];
774
- }
775
- else if (scopeField in unsetFields) {
776
- newScopeValue = undefined;
777
- }
778
- else if (scopeField in setFields) {
779
- newScopeValue = setFields[scopeField];
780
- }
781
- else {
782
- newScopeValue = targetObj[scopeField];
783
- }
784
- // A replacement, a `$set` to null, or an `$unset` can strip the tenant field off an
785
- // existing document, which would move it into an unsubscribable stream just as
786
- // surely as creating it without one.
787
- (0, streams_1.assertWritableStream)({
788
- collectionTag: entry.collectionTag,
789
- doc: (_a = {}, _a[scopeField] = newScopeValue, _a),
790
- scope: entry.config.scope,
791
- });
792
- currentStream = (0, streams_1.streamForScopeValue)({
793
- collectionTag: entry.collectionTag,
794
- scope: entry.config.scope,
795
- scopeValue: newScopeValue,
796
- });
797
- }
798
- else {
799
- currentStream = previousStream;
800
- }
801
- prevStream = previousStream !== currentStream ? previousStream : null;
802
- return [4 /*yield*/, (0, models_1.claimSyncSeqs)({ session: session, stream: currentStream })];
803
- case 2:
804
- claim = _j.sent();
805
- if (isTrueReplacement || !hasOperators) {
806
- // True replacements and implicit-$set plain objects both take plain keys.
807
- rawUpdate._syncPrevStream = prevStream;
808
- rawUpdate._syncSeq = claim.lastSeq;
809
- }
810
- else {
811
- rawUpdate.$set = __assign(__assign({}, ((_h = rawUpdate.$set) !== null && _h !== void 0 ? _h : {})), { _syncPrevStream: prevStream, _syncSeq: claim.lastSeq });
812
- }
813
- this.setUpdate(rawUpdate);
814
- // Stash the claim + move info so the query post hook confirms/records after commit.
815
- this._syncPendingConfirm = {
816
- claim: claim,
817
- currentStream: currentStream,
818
- entityId: String(target._id),
819
- entry: entry,
820
- prevStream: prevStream,
821
- session: session,
822
- };
823
- return [2 /*return*/];
824
- }
457
+ const preQueryWrite = async function () {
458
+ const model = this.model;
459
+ const entry = (0, registry_1.findSyncEntryByModelName)(model.modelName);
460
+ if (!entry) {
461
+ return;
462
+ }
463
+ const operation = this.op ?? "query-write";
464
+ // m8/C6: reject upserts — an upsert can create a doc the lookup never saw.
465
+ if (this.getOptions().upsert) {
466
+ throw upsertError(model.modelName, operation);
467
+ }
468
+ const rawFilter = this.getFilter();
469
+ // m9: refuse a non-single-_id filter — it could match a different doc than intended.
470
+ if (!filterTargetsSingleId(rawFilter)) {
471
+ throw nonIdFilterError(model.modelName, operation);
472
+ }
473
+ const session = this.getOptions().session ?? null;
474
+ // Mirror update semantics: query updates are NOT auto-filtered by isDeletedPlugin
475
+ // (it only hooks find/findOne), so the lookup must see tombstones too.
476
+ const filter = { ...rawFilter };
477
+ if (filter.deleted === undefined) {
478
+ filter.deleted = { $in: [true, false] };
479
+ }
480
+ const matches = await model
481
+ .find(filter)
482
+ .setOptions(session ? { session } : {})
483
+ .limit(1);
484
+ const target = matches[0];
485
+ if (!target) {
486
+ // The update matches nothing; let it proceed as a no-op.
487
+ return;
488
+ }
489
+ const targetObj = target.toObject();
490
+ const previousStream = streamForObject(entry, targetObj);
491
+ const rawUpdate = (this.getUpdate() ?? {});
492
+ // Only replaceOne/findOneAndReplace replace the document. A plain object passed to
493
+ // updateOne/findOneAndUpdate is an IMPLICIT $set in Mongoose — treating it as a
494
+ // replacement would resolve the scope value as undefined and claim the wrong stream.
495
+ const op = this.op ?? "";
496
+ const isTrueReplacement = op === "replaceOne" || op === "findOneAndReplace";
497
+ const hasOperators = Object.keys(rawUpdate).some((key) => key.startsWith("$"));
498
+ // The fields the update effectively $sets (empty for true replacements).
499
+ const setFields = isTrueReplacement
500
+ ? {}
501
+ : hasOperators
502
+ ? (rawUpdate.$set ?? {})
503
+ : rawUpdate;
504
+ const scopeField = (0, streams_1.getScopeField)(entry.config.scope);
505
+ let currentStream;
506
+ if (typeof entry.config.scope === "function") {
507
+ const effectiveDoc = isTrueReplacement ? rawUpdate : { ...targetObj, ...setFields };
508
+ currentStream = streamForObject(entry, effectiveDoc);
509
+ }
510
+ else if (scopeField) {
511
+ // Distinguish "the update clears the scope field" from "the update leaves it
512
+ // alone": `??` cannot, because it treats an explicit `$set: {field: null}` as
513
+ // absent and falls back to the document's current value — which both hides the
514
+ // clear from the guard below and stamps the OLD stream's seq onto a document that
515
+ // no longer belongs to it.
516
+ const unsetFields = hasOperators
517
+ ? (rawUpdate.$unset ?? {})
518
+ : {};
519
+ let newScopeValue;
520
+ if (isTrueReplacement) {
521
+ newScopeValue = rawUpdate[scopeField];
522
+ }
523
+ else if (scopeField in unsetFields) {
524
+ newScopeValue = undefined;
525
+ }
526
+ else if (scopeField in setFields) {
527
+ newScopeValue = setFields[scopeField];
528
+ }
529
+ else {
530
+ newScopeValue = targetObj[scopeField];
531
+ }
532
+ // A replacement, a `$set` to null, or an `$unset` can strip the tenant field off an
533
+ // existing document, which would move it into an unsubscribable stream just as
534
+ // surely as creating it without one.
535
+ (0, streams_1.assertWritableStream)({
536
+ collectionTag: entry.collectionTag,
537
+ doc: { [scopeField]: newScopeValue },
538
+ scope: entry.config.scope,
825
539
  });
826
- });
540
+ currentStream = (0, streams_1.streamForScopeValue)({
541
+ collectionTag: entry.collectionTag,
542
+ scope: entry.config.scope,
543
+ scopeValue: newScopeValue,
544
+ });
545
+ }
546
+ else {
547
+ currentStream = previousStream;
548
+ }
549
+ const prevStream = previousStream !== currentStream ? previousStream : null;
550
+ const claim = await (0, models_1.claimSyncSeqs)({ session, stream: currentStream });
551
+ if (isTrueReplacement || !hasOperators) {
552
+ // True replacements and implicit-$set plain objects both take plain keys.
553
+ rawUpdate._syncPrevStream = prevStream;
554
+ rawUpdate._syncSeq = claim.lastSeq;
555
+ }
556
+ else {
557
+ rawUpdate.$set = {
558
+ ...(rawUpdate.$set ?? {}),
559
+ _syncPrevStream: prevStream,
560
+ _syncSeq: claim.lastSeq,
561
+ };
562
+ }
563
+ this.setUpdate(rawUpdate);
564
+ // Stash the claim + move info so the query post hook confirms/records after commit.
565
+ this._syncPendingConfirm = {
566
+ claim,
567
+ currentStream,
568
+ entityId: String(target._id),
569
+ entry,
570
+ prevStream,
571
+ session,
572
+ };
827
573
  };
828
574
  // C1/C4: after the query write commits, confirm the claimed seq and record the
829
575
  // scope-move marker. Query post middleware `this` is the Query (not a document).
830
- var postQueryWrite = function () {
831
- return __awaiter(this, void 0, void 0, function () {
832
- var pending, claim, currentStream, entityId, entry, prevStream, session;
833
- return __generator(this, function (_a) {
834
- switch (_a.label) {
835
- case 0:
836
- pending = this
837
- ._syncPendingConfirm;
838
- if (!pending) {
839
- return [2 /*return*/];
840
- }
841
- this._syncPendingConfirm =
842
- undefined;
843
- claim = pending.claim, currentStream = pending.currentStream, entityId = pending.entityId, entry = pending.entry, prevStream = pending.prevStream, session = pending.session;
844
- if (!claim.registered) return [3 /*break*/, 2];
845
- return [4 /*yield*/, (0, models_1.confirmSyncSeqs)({ seqs: claim.seqs, stream: currentStream }).catch(function (error) {
846
- logger_1.logger.error("[sync] Failed to confirm seq after query write", {
847
- error: String(error),
848
- stream: currentStream,
849
- });
850
- })];
851
- case 1:
852
- _a.sent();
853
- _a.label = 2;
854
- case 2:
855
- if (!prevStream) return [3 /*break*/, 4];
856
- // Retries internally and never throws: the move already committed, so the marker
857
- // must not be dropped on the first transient failure nor fail the user's write.
858
- return [4 /*yield*/, writeScopeMoveMarker({
859
- entityId: entityId,
860
- entry: entry,
861
- fromStream: prevStream,
862
- session: session,
863
- toStream: currentStream,
864
- })];
865
- case 3:
866
- // Retries internally and never throws: the move already committed, so the marker
867
- // must not be dropped on the first transient failure nor fail the user's write.
868
- _a.sent();
869
- _a.label = 4;
870
- case 4: return [2 /*return*/];
871
- }
576
+ const postQueryWrite = async function () {
577
+ const pending = this
578
+ ._syncPendingConfirm;
579
+ if (!pending) {
580
+ return;
581
+ }
582
+ this._syncPendingConfirm =
583
+ undefined;
584
+ const { claim, currentStream, entityId, entry, prevStream, session } = pending;
585
+ if (claim.registered) {
586
+ await (0, models_1.confirmSyncSeqs)({ seqs: claim.seqs, stream: currentStream }).catch((error) => {
587
+ logger_1.logger.error("[sync] Failed to confirm seq after query write", {
588
+ error: String(error),
589
+ stream: currentStream,
590
+ });
872
591
  });
873
- });
592
+ }
593
+ if (prevStream) {
594
+ // Retries internally and never throws: the move already committed, so the marker
595
+ // must not be dropped on the first transient failure nor fail the user's write.
596
+ await writeScopeMoveMarker({
597
+ entityId,
598
+ entry,
599
+ fromStream: prevStream,
600
+ session,
601
+ toStream: currentStream,
602
+ });
603
+ }
874
604
  };
875
605
  schema.pre("updateOne", { document: false, query: true }, preQueryWrite);
876
606
  schema.pre("findOneAndUpdate", preQueryWrite);
@@ -881,20 +611,18 @@ var syncPlugin = function (schema) {
881
611
  schema.post("replaceOne", postQueryWrite);
882
612
  schema.post("findOneAndReplace", postQueryWrite);
883
613
  // Unsupported multi-document / hard-delete paths throw for registered models.
884
- var guardQuery = function (operation) {
885
- return function () {
886
- var model = this.model;
887
- if ((0, registry_1.findSyncEntryByModelName)(model.modelName)) {
888
- throw unsupportedWrite(model.modelName, operation);
889
- }
890
- };
614
+ const guardQuery = (operation) => function () {
615
+ const model = this.model;
616
+ if ((0, registry_1.findSyncEntryByModelName)(model.modelName)) {
617
+ throw unsupportedWrite(model.modelName, operation);
618
+ }
891
619
  };
892
620
  schema.pre("updateMany", guardQuery("updateMany"));
893
621
  schema.pre("deleteMany", guardQuery("deleteMany"));
894
622
  schema.pre("deleteOne", { document: false, query: true }, guardQuery("deleteOne"));
895
623
  schema.pre("findOneAndDelete", guardQuery("findOneAndDelete"));
896
624
  schema.pre("deleteOne", { document: true, query: false }, function () {
897
- var entry = (0, registry_1.findSyncEntryByModelName)(this.constructor.modelName);
625
+ const entry = (0, registry_1.findSyncEntryByModelName)(this.constructor.modelName);
898
626
  if (entry) {
899
627
  throw unsupportedWrite(entry.modelName, "document deleteOne (hard delete)");
900
628
  }