@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
@@ -1,4 +1,15 @@
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
+ };
2
13
  var __values = (this && this.__values) || function(o) {
3
14
  var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
4
15
  if (m) return m.call(o);
@@ -35,9 +46,24 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
35
46
  }
36
47
  return to.concat(ar || Array.prototype.slice.call(from));
37
48
  };
49
+ var __importDefault = (this && this.__importDefault) || function (mod) {
50
+ return (mod && mod.__esModule) ? mod : { "default": mod };
51
+ };
38
52
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.openApiCompatMiddleware = exports.patchAppUse = void 0;
53
+ exports.openApiCompatMiddleware = exports.patchAppUse = exports.patchExpressRouterUse = void 0;
54
+ /**
55
+ * Patches the Express router stack to add `.regexp` on layers for
56
+ * compatibility with @wesleytodd/openapi, which expects Express 4-style
57
+ * layers with `.regexp.fast_slash`.
58
+ *
59
+ * In Express 5 (router@2.x), layers use `.slash` (boolean) and `.matchers`
60
+ * (array of functions) instead of `.regexp`.
61
+ *
62
+ * @see https://github.com/wesleytodd/express-openapi/issues/70
63
+ */
64
+ var express_1 = __importDefault(require("express"));
40
65
  var MOUNT_PATH_KEY = "__openApiMountPath";
66
+ var isExpressRouterUsePatched = false;
41
67
  /**
42
68
  * Extract Express 4-style keys from a path string.
43
69
  * Parses `:paramName` and `*paramName` segments into `{name, optional}` objects
@@ -77,52 +103,64 @@ var buildRegexpForPath = function (pathStr, isMount) {
77
103
  }
78
104
  return new RegExp("^".concat(pattern, "\\/?$"));
79
105
  };
106
+ var annotateMountLayers = function (stack, stackBefore, args) {
107
+ if (!stack) {
108
+ return;
109
+ }
110
+ var mountPath = typeof args[0] === "string" ? args[0] : undefined;
111
+ if (!mountPath || mountPath === "/") {
112
+ return;
113
+ }
114
+ var normalizedMountPath = mountPath.replace(/\/+$/, "");
115
+ for (var i = stackBefore; i < stack.length; i++) {
116
+ stack[i][MOUNT_PATH_KEY] = normalizedMountPath;
117
+ }
118
+ };
80
119
  var patchRouterStack = function (stack) {
81
120
  var e_1, _a;
82
121
  var _b, _c, _d, _e;
83
122
  try {
84
123
  for (var stack_1 = __values(stack), stack_1_1 = stack_1.next(); !stack_1_1.done; stack_1_1 = stack_1.next()) {
85
124
  var layer = stack_1_1.value;
86
- if (layer.regexp !== undefined) {
87
- continue;
88
- }
89
- // Determine the path string for this layer
90
- var pathStr = void 0;
91
- var isMount = layer.name === "router" || !!((_b = layer.handle) === null || _b === void 0 ? void 0 : _b.stack);
92
- if (layer.slash) {
93
- // Express 5 layers use .slash instead of .regexp.fast_slash
94
- layer.regexp = { fast_slash: true };
95
- }
96
- else if (layer[MOUNT_PATH_KEY]) {
97
- pathStr = layer[MOUNT_PATH_KEY];
98
- layer.regexp = buildRegexpForPath(pathStr, isMount);
99
- }
100
- else if (layer.path && typeof layer.path === "string") {
101
- pathStr = layer.path;
102
- layer.regexp = buildRegexpForPath(pathStr, false);
103
- }
104
- else if (((_c = layer.route) === null || _c === void 0 ? void 0 : _c.path) && typeof layer.route.path === "string") {
105
- pathStr = layer.route.path;
106
- layer.regexp = buildRegexpForPath(pathStr, false);
107
- }
108
- else {
109
- layer.regexp = /^\/?$/;
110
- }
111
- // Populate keys in Express 4 format: [{name, optional}]
112
- // @wesleytodd/openapi reads layer.keys[i].name for path parameters
113
- if (!layer.keys || (Array.isArray(layer.keys) && layer.keys.length === 0)) {
114
- if (pathStr) {
115
- layer.keys = extractKeysFromPath(pathStr);
125
+ if (layer.regexp === undefined) {
126
+ // Determine the path string for this layer
127
+ var pathStr = void 0;
128
+ var isMount = layer.name === "router" || !!((_b = layer.handle) === null || _b === void 0 ? void 0 : _b.stack);
129
+ if (layer.slash) {
130
+ // Express 5 layers use .slash instead of .regexp.fast_slash
131
+ layer.regexp = { fast_slash: true };
132
+ }
133
+ else if (layer[MOUNT_PATH_KEY]) {
134
+ pathStr = layer[MOUNT_PATH_KEY];
135
+ layer.regexp = buildRegexpForPath(pathStr, isMount);
136
+ }
137
+ else if (layer.path && typeof layer.path === "string") {
138
+ pathStr = layer.path;
139
+ layer.regexp = buildRegexpForPath(pathStr, false);
140
+ }
141
+ else if (((_c = layer.route) === null || _c === void 0 ? void 0 : _c.path) && typeof layer.route.path === "string") {
142
+ pathStr = layer.route.path;
143
+ layer.regexp = buildRegexpForPath(pathStr, false);
116
144
  }
117
145
  else {
118
- layer.keys = [];
146
+ layer.regexp = /^\/?$/;
147
+ }
148
+ // Populate keys in Express 4 format: [{name, optional}]
149
+ // @wesleytodd/openapi reads layer.keys[i].name for path parameters
150
+ if (!layer.keys || (Array.isArray(layer.keys) && layer.keys.length === 0)) {
151
+ if (pathStr) {
152
+ layer.keys = extractKeysFromPath(pathStr);
153
+ }
154
+ else {
155
+ layer.keys = [];
156
+ }
157
+ }
158
+ else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
159
+ // Express 5 stores keys as plain strings after match() — convert to objects
160
+ layer.keys = layer.keys.map(function (k) { return ({ name: k, optional: false }); });
119
161
  }
120
162
  }
121
- else if (Array.isArray(layer.keys) && typeof layer.keys[0] === "string") {
122
- // Express 5 stores keys as plain strings after match() — convert to objects
123
- layer.keys = layer.keys.map(function (k) { return ({ name: k, optional: false }); });
124
- }
125
- // Recursively patch nested stacks
163
+ // Recursively patch nested stacks even when this layer already had a regexp.
126
164
  if ((_d = layer.handle) === null || _d === void 0 ? void 0 : _d.stack) {
127
165
  patchRouterStack(layer.handle.stack);
128
166
  }
@@ -139,6 +177,44 @@ var patchRouterStack = function (stack) {
139
177
  finally { if (e_1) throw e_1.error; }
140
178
  }
141
179
  };
180
+ /**
181
+ * Patches `express.Router().use` so nested mounts (e.g. `router.use("/gpt/histories", ...)`)
182
+ * record `__openApiMountPath` the same way `app.use` does. Without this, nested
183
+ * modelRouter OpenAPI paths are omitted from `/openapi.json`.
184
+ *
185
+ * Express 5's Router puts `use` a few prototypes up from the instance, so we walk
186
+ * the chain until we find the own `use` descriptor.
187
+ */
188
+ var patchExpressRouterUse = function () {
189
+ if (isExpressRouterUsePatched) {
190
+ return;
191
+ }
192
+ isExpressRouterUsePatched = true;
193
+ var routerPrototype = Object.getPrototypeOf(express_1.default.Router());
194
+ while (routerPrototype && !Object.getOwnPropertyDescriptor(routerPrototype, "use")) {
195
+ routerPrototype = Object.getPrototypeOf(routerPrototype);
196
+ }
197
+ if (!routerPrototype) {
198
+ return;
199
+ }
200
+ var useDescriptor = Object.getOwnPropertyDescriptor(routerPrototype, "use");
201
+ if (!(useDescriptor === null || useDescriptor === void 0 ? void 0 : useDescriptor.value)) {
202
+ return;
203
+ }
204
+ var originalUse = useDescriptor.value;
205
+ Object.defineProperty(routerPrototype, "use", __assign(__assign({}, useDescriptor), { value: function patchedRouterUse() {
206
+ var _a, _b;
207
+ var args = [];
208
+ for (var _i = 0; _i < arguments.length; _i++) {
209
+ args[_i] = arguments[_i];
210
+ }
211
+ var stackBefore = (_b = (_a = this.stack) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
212
+ var result = originalUse.apply(this, args);
213
+ annotateMountLayers(this.stack, stackBefore, args);
214
+ return result;
215
+ } }));
216
+ };
217
+ exports.patchExpressRouterUse = patchExpressRouterUse;
142
218
  /**
143
219
  * Wraps an Express app's `use` method to record the mount path on each
144
220
  * layer added to the router stack. This runs at setup time so that
@@ -147,6 +223,7 @@ var patchRouterStack = function (stack) {
147
223
  * Must be called before any routes are registered.
148
224
  */
149
225
  var patchAppUse = function (app) {
226
+ (0, exports.patchExpressRouterUse)();
150
227
  var internal = app;
151
228
  var originalUse = app.use.bind(app);
152
229
  var patchedUse = function () {
@@ -161,16 +238,7 @@ var patchAppUse = function (app) {
161
238
  var result = originalUse.apply(void 0, __spreadArray([], __read(args), false));
162
239
  // After use(), check if new layers were added and annotate them
163
240
  var routerAfter = (_d = internal._router) !== null && _d !== void 0 ? _d : internal.router;
164
- if (routerAfter === null || routerAfter === void 0 ? void 0 : routerAfter.stack) {
165
- var stackAfter = routerAfter.stack.length;
166
- // The first arg is the mount path if it's a string
167
- var mountPath = typeof args[0] === "string" ? args[0] : undefined;
168
- if (mountPath && mountPath !== "/") {
169
- for (var i = stackBefore; i < stackAfter; i++) {
170
- routerAfter.stack[i][MOUNT_PATH_KEY] = mountPath.replace(/\/+$/, "");
171
- }
172
- }
173
- }
241
+ annotateMountLayers(routerAfter === null || routerAfter === void 0 ? void 0 : routerAfter.stack, stackBefore, args);
174
242
  return result;
175
243
  };
176
244
  app.use = patchedUse;
@@ -14,11 +14,38 @@ export interface RESTPermissions<T> {
14
14
  export declare const OwnerQueryFilter: (user?: User) => {
15
15
  ownerId: string;
16
16
  } | null;
17
+ /**
18
+ * A user that may belong to one or more organizations (tenants). Backends that use tenant-scoped
19
+ * models add an `organizationIds` array to their user model; this interface lets the shared
20
+ * permission/query-filter helpers read it without every consumer casting by hand.
21
+ */
22
+ export interface OrganizationScopedUser extends User {
23
+ organizationIds?: string[];
24
+ }
25
+ /** Reads the caller's organization ids, tolerating users without the `organizationIds` field. */
26
+ export declare const getUserOrganizationIds: (user?: User) => string[];
27
+ /**
28
+ * Restricts list queries to documents belonging to one of the caller's organizations. This is the
29
+ * tenant-scoped analog of {@link OwnerQueryFilter}: it filters on the document's `organizationId`
30
+ * field using the user's `organizationIds`. Returns `null` for anonymous callers (no user).
31
+ */
32
+ export declare const OrganizationQueryFilter: (user?: User) => {
33
+ organizationId: {
34
+ $in: string[];
35
+ };
36
+ } | null;
17
37
  export declare const Permissions: {
18
38
  IsAdmin: (_method: RESTMethod, user?: User) => boolean;
19
39
  IsAny: () => boolean;
20
40
  IsAuthenticated: (_method: RESTMethod, user?: User) => boolean;
21
41
  IsAuthenticatedOrReadOnly: (method: RESTMethod, user?: User) => boolean;
42
+ /**
43
+ * Object-level permission for tenant-scoped documents: the caller must belong to the document's
44
+ * organization (admins always pass). With no object (list/create checks) it returns true and
45
+ * defers to the {@link OrganizationQueryFilter} / a `preCreate` hook to scope access. Expects the
46
+ * document to expose an `organizationId` and the user an `organizationIds` array.
47
+ */
48
+ IsOrganizationMember: (_method: RESTMethod, user?: User, obj?: unknown) => boolean;
22
49
  IsOwner: (_method: RESTMethod, user?: User, obj?: unknown) => boolean;
23
50
  IsOwnerOrReadOnly: (method: RESTMethod, user?: User, obj?: unknown) => boolean;
24
51
  };
@@ -47,7 +47,7 @@ var __values = (this && this.__values) || function(o) {
47
47
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
48
  };
49
49
  Object.defineProperty(exports, "__esModule", { value: true });
50
- exports.permissionMiddleware = exports.checkPermissions = exports.Permissions = exports.OwnerQueryFilter = void 0;
50
+ exports.permissionMiddleware = exports.checkPermissions = exports.Permissions = exports.OrganizationQueryFilter = exports.getUserOrganizationIds = exports.OwnerQueryFilter = void 0;
51
51
  var docLoader_1 = require("./docLoader");
52
52
  var errors_1 = require("./errors");
53
53
  var OwnerQueryFilter = function (user) {
@@ -57,6 +57,24 @@ var OwnerQueryFilter = function (user) {
57
57
  return null;
58
58
  };
59
59
  exports.OwnerQueryFilter = OwnerQueryFilter;
60
+ /** Reads the caller's organization ids, tolerating users without the `organizationIds` field. */
61
+ var getUserOrganizationIds = function (user) {
62
+ var _a;
63
+ return (_a = user === null || user === void 0 ? void 0 : user.organizationIds) !== null && _a !== void 0 ? _a : [];
64
+ };
65
+ exports.getUserOrganizationIds = getUserOrganizationIds;
66
+ /**
67
+ * Restricts list queries to documents belonging to one of the caller's organizations. This is the
68
+ * tenant-scoped analog of {@link OwnerQueryFilter}: it filters on the document's `organizationId`
69
+ * field using the user's `organizationIds`. Returns `null` for anonymous callers (no user).
70
+ */
71
+ var OrganizationQueryFilter = function (user) {
72
+ if (!user) {
73
+ return null;
74
+ }
75
+ return { organizationId: { $in: (0, exports.getUserOrganizationIds)(user) } };
76
+ };
77
+ exports.OrganizationQueryFilter = OrganizationQueryFilter;
60
78
  exports.Permissions = {
61
79
  IsAdmin: function (_method, user) {
62
80
  return Boolean(user === null || user === void 0 ? void 0 : user.admin);
@@ -76,6 +94,29 @@ exports.Permissions = {
76
94
  }
77
95
  return method === "list" || method === "read";
78
96
  },
97
+ /**
98
+ * Object-level permission for tenant-scoped documents: the caller must belong to the document's
99
+ * organization (admins always pass). With no object (list/create checks) it returns true and
100
+ * defers to the {@link OrganizationQueryFilter} / a `preCreate` hook to scope access. Expects the
101
+ * document to expose an `organizationId` and the user an `organizationIds` array.
102
+ */
103
+ IsOrganizationMember: function (_method, user, obj) {
104
+ // When checking if we can possibly perform the action, return true.
105
+ if (!obj) {
106
+ return true;
107
+ }
108
+ if (!user) {
109
+ return false;
110
+ }
111
+ if (user === null || user === void 0 ? void 0 : user.admin) {
112
+ return true;
113
+ }
114
+ var organizationId = obj.organizationId;
115
+ if (!organizationId) {
116
+ return false;
117
+ }
118
+ return (0, exports.getUserOrganizationIds)(user).includes(organizationId);
119
+ },
79
120
  IsOwner: function (_method, user, obj) {
80
121
  var _a;
81
122
  // When checking if we can possibly perform the action, return true.
package/dist/plugins.d.ts CHANGED
@@ -63,6 +63,19 @@ export declare const upsertPlugin: <T>(schema: Schema<any, any, any, any>) => vo
63
63
  export interface HasUpsert<T> {
64
64
  upsert(conditions: Record<string, unknown>, update: Record<string, unknown>): Promise<T>;
65
65
  }
66
+ /** For models with the excludeArchivedPlugin, extend this interface to add the archived field. */
67
+ export interface IsArchived {
68
+ archived: boolean;
69
+ }
70
+ /**
71
+ * Adds an `archived` boolean field and excludes archived documents from `find()` / `findOne()`
72
+ * queries by default. Pass `{archived: true}` explicitly to include them. This is a soft-archive
73
+ * analog to {@link isDeletedPlugin}: use it when documents should be hidden from normal listings
74
+ * but kept (and still directly queryable) rather than treated as deleted.
75
+ * @param schema Mongoose Schema
76
+ * @param defaultValue Default value for the `archived` field (defaults to `false`)
77
+ */
78
+ export declare const excludeArchivedPlugin: (schema: Schema<any, any, any, any>, defaultValue?: boolean) => void;
66
79
  export interface FindOneOrNonePlugin<T> {
67
80
  findOneOrNone(query: Record<string, unknown>, errorArgs?: Partial<APIErrorOptions>): Promise<(Document & T) | null>;
68
81
  }
package/dist/plugins.js CHANGED
@@ -95,7 +95,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
95
95
  }
96
96
  };
97
97
  Object.defineProperty(exports, "__esModule", { value: true });
98
- exports.DateOnly = exports.upsertPlugin = exports.findExactlyOne = exports.findOneOrNoneFor = exports.findOneOrNone = exports.firebaseJWTPlugin = exports.createdUpdatedPlugin = exports.isDisabledPlugin = exports.isDeletedPlugin = exports.baseUserPlugin = void 0;
98
+ exports.DateOnly = exports.excludeArchivedPlugin = exports.upsertPlugin = exports.findExactlyOne = exports.findOneOrNoneFor = exports.findOneOrNone = exports.firebaseJWTPlugin = exports.createdUpdatedPlugin = exports.isDisabledPlugin = exports.isDeletedPlugin = exports.baseUserPlugin = void 0;
99
99
  var luxon_1 = require("luxon");
100
100
  var mongoose_1 = __importStar(require("mongoose"));
101
101
  var errors_1 = require("./errors");
@@ -354,6 +354,52 @@ var upsertPlugin = function (schema) {
354
354
  };
355
355
  };
356
356
  exports.upsertPlugin = upsertPlugin;
357
+ /**
358
+ * Adds an `archived` boolean field and excludes archived documents from `find()` / `findOne()`
359
+ * queries by default. Pass `{archived: true}` explicitly to include them. This is a soft-archive
360
+ * analog to {@link isDeletedPlugin}: use it when documents should be hidden from normal listings
361
+ * but kept (and still directly queryable) rather than treated as deleted.
362
+ * @param schema Mongoose Schema
363
+ * @param defaultValue Default value for the `archived` field (defaults to `false`)
364
+ */
365
+ var excludeArchivedPlugin = function (
366
+ // noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
367
+ // biome-ignore lint/suspicious/noExplicitAny: Schema generics must be loose to accept arbitrary consumer schemas
368
+ schema, defaultValue) {
369
+ if (defaultValue === void 0) { defaultValue = false; }
370
+ schema.add({
371
+ archived: {
372
+ default: defaultValue,
373
+ description: "Archived objects are not returned in any find() by default. " +
374
+ "Add {archived: true} to find them.",
375
+ index: true,
376
+ type: Boolean,
377
+ },
378
+ });
379
+ // Mirror isDeletedPlugin: filter both find and findOne so findExactlyOne / findOneOrNone
380
+ // also exclude archived documents unless the query sets `archived` explicitly.
381
+ // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
382
+ // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
383
+ var applyArchiveFilter = function (query) {
384
+ var conditions = query.getFilter();
385
+ // Only apply the default filter when the query does not mention `archived` at all, so an
386
+ // explicit `{archived: true}` (or `false`) is always respected.
387
+ if (conditions.archived === undefined) {
388
+ query.setQuery(__assign(__assign({}, conditions), { archived: { $ne: true } }));
389
+ }
390
+ };
391
+ // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
392
+ // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
393
+ schema.pre("find", function () {
394
+ applyArchiveFilter(this);
395
+ });
396
+ // noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
397
+ // biome-ignore lint/suspicious/noExplicitAny: Query<any, any> must be loose to accept arbitrary consumer queries
398
+ schema.pre("findOne", function () {
399
+ applyArchiveFilter(this);
400
+ });
401
+ };
402
+ exports.excludeArchivedPlugin = excludeArchivedPlugin;
357
403
  var DateOnly = /** @class */ (function (_super) {
358
404
  __extends(DateOnly, _super);
359
405
  function DateOnly(key, options) {
@@ -1,9 +1,35 @@
1
- import mongoose from "mongoose";
1
+ import type { ChangeStreamDocument } from "mongodb";
2
2
  import type { Server } from "socket.io";
3
- type ChangeStreamDocument = mongoose.mongo.ChangeStreamDocument;
4
3
  import type { User } from "../auth";
4
+ import { type PermissionMethod } from "../permissions";
5
+ import { type SyncRegistryEntry } from "../sync/registry";
5
6
  import { type RealtimeRegistryEntry } from "./registry";
6
7
  import type { ChangeStreamConfig, RealtimeEvent } from "./types";
8
+ /**
9
+ * The subset of ChangeStreamDocument variants this watcher actually processes.
10
+ * The pipeline filters for ["insert", "update", "replace", "delete"], so we never
11
+ * see drop / rename / invalidate / index events at runtime.
12
+ */
13
+ type WatchedChange = Extract<ChangeStreamDocument, {
14
+ operationType: "insert" | "update" | "replace" | "delete";
15
+ }>;
16
+ /** First restart delay; doubles per consecutive attempt up to the max. */
17
+ export declare const CHANGE_STREAM_RESTART_BASE_DELAY_MS = 250;
18
+ /** Ceiling for the restart backoff — a long outage retries once every 30s, forever. */
19
+ export declare const CHANGE_STREAM_RESTART_MAX_DELAY_MS = 30000;
20
+ /**
21
+ * Socket event telling clients their cached cursors may have gaps and they must
22
+ * re-bootstrap. Emitted when the change stream's oplog history is gone
23
+ * (`ChangeStreamHistoryLost`), which is the one failure a resume token cannot repair.
24
+ * Payload: {@link SyncResyncHint}.
25
+ */
26
+ export declare const SYNC_RESYNC_EVENT = "sync:resync-required";
27
+ /**
28
+ * C7: the sync bookkeeping collections must never drive fan-out — their own change
29
+ * events are internal (counters/ledger/markers/keys), and processing them would emit
30
+ * spurious deltas or reprocess scope-move markers. Exported for testing.
31
+ */
32
+ export declare const DEFAULT_IGNORED_COLLECTIONS: string[];
7
33
  /**
8
34
  * Map MongoDB change stream operation types to our method names.
9
35
  *
@@ -17,6 +43,18 @@ import type { ChangeStreamConfig, RealtimeEvent } from "./types";
17
43
  * Exported for testing.
18
44
  */
19
45
  export declare const mapOperationType: (operationType: string, change: ChangeStreamDocument, enabledMethods?: ReadonlyArray<"create" | "update" | "delete">) => "create" | "update" | "delete" | null;
46
+ /**
47
+ * The minimal registry-entry shape the authorized-room emitters need. Both
48
+ * `RealtimeRegistryEntry` and `SyncRegistryEntry` satisfy it structurally.
49
+ */
50
+ export interface AuthorizedEmitEntry {
51
+ modelName: string;
52
+ options: {
53
+ permissions: {
54
+ read: PermissionMethod<any>[];
55
+ };
56
+ };
57
+ }
20
58
  /**
21
59
  * Determine which Socket.io rooms to emit to based on the room strategy.
22
60
  * Exported for testing.
@@ -44,6 +82,24 @@ export declare const ensureApiId: (data: unknown) => unknown;
44
82
  * was supposed to strip.
45
83
  */
46
84
  export declare const serializeDoc: (entry: RealtimeRegistryEntry, doc: Record<string, unknown>, method: "create" | "update" | "delete", user?: User) => Promise<unknown>;
85
+ /**
86
+ * Generalized authorized-room emitter: iterates the sockets in `room`, runs the per-socket
87
+ * read-permission check against `fullDocument`, builds the payload per socket (so
88
+ * responseHandlers can tailor output to the receiving user), and emits `eventName`.
89
+ *
90
+ * `emitToAuthorizedRoom` (legacy "sync" events) and the sync layer's `sync:delta`
91
+ * emission both delegate here.
92
+ */
93
+ export declare const emitPayloadToAuthorizedRoom: ({ io, room, eventName, entry, fullDocument, buildPayload, logDebug, }: {
94
+ io: Server;
95
+ room: string;
96
+ eventName: string;
97
+ entry: AuthorizedEmitEntry;
98
+ fullDocument: Record<string, unknown> | undefined;
99
+ /** Build the per-socket payload; a throw drops the emission for that socket only. */
100
+ buildPayload: (user: User | undefined) => Promise<unknown> | unknown;
101
+ logDebug: (msg: string) => void;
102
+ }) => Promise<void>;
47
103
  export declare const emitToAuthorizedRoom: (io: Server, room: string, event: RealtimeEvent, entry: RealtimeRegistryEntry, fullDocument: Record<string, unknown> | undefined, logDebug: (msg: string) => void) => Promise<void>;
48
104
  /**
49
105
  * Emit a sync event to document-specific and query rooms.
@@ -62,12 +118,53 @@ export declare const emitToAuthorizedRoom: (io: Server, room: string, event: Rea
62
118
  * Exported for testing.
63
119
  */
64
120
  export declare const emitToDocumentAndQueryRooms: (io: Server, collection: string, event: RealtimeEvent, fullDocument: Record<string, unknown> | undefined, logDebug: (msg: string) => void, entry?: RealtimeRegistryEntry) => Promise<void>;
121
+ /**
122
+ * Emit `sync:delta` events for a change on a sync-registered collection.
123
+ *
124
+ * Deltas fan out to the dedicated `sync:{stream}` rooms joined via `sync:subscribe`
125
+ * (independent of the legacy realtime rooms), with the same per-socket read-permission
126
+ * checks as legacy events. `seq` and `stream` come from the post-image: the `syncPlugin`
127
+ * stamps `_syncSeq` on every synced write and the watcher runs `updateLookup`.
128
+ *
129
+ * Soft deletes (an update setting `deleted: true`, reclassified by `mapOperationType`)
130
+ * produce a `method: "delete"` delta with `deleted: true` and the tombstone data intact.
131
+ *
132
+ * Scope moves (C4): the old-stream tombstone is derived from durable `SyncScopeMove`
133
+ * markers (written by `syncPlugin` in the same op-scope as the move), NOT from the racy
134
+ * `_syncPrevStream` post-image — a second write racing this event's processing can reset
135
+ * `_syncPrevStream`, but it cannot erase the durable marker. For each marker on this
136
+ * document, a data-less tombstone is emitted to the marker's `fromStream` (carrying the
137
+ * marker's old-stream seq), and the new-stream delta is reported as `method: "create"`.
138
+ * Client tombstone application is idempotent by seq, so re-emitting a marker on a later
139
+ * change of the same doc is harmless.
140
+ *
141
+ * Every emitted delta carries `frontierSeq` (the emitting stream's stable frontier at
142
+ * emit time, C1); the client advances its cursor to `min(delta.seq, delta.frontierSeq)`
143
+ * so a delta observed out of commit order never advances a cursor past an uncommitted hole.
144
+ *
145
+ * A model with both `realtime` and `sync` configs emits both the legacy "sync" event and
146
+ * "sync:delta" — distinct event names, no interference (documented as transitional).
147
+ *
148
+ * Exported for testing.
149
+ */
150
+ export declare const emitSyncDeltaForChange: ({ io, entry, change, docId, logDebug, }: {
151
+ io: Server;
152
+ entry: SyncRegistryEntry;
153
+ change: WatchedChange;
154
+ docId: string;
155
+ logDebug: (msg: string) => void;
156
+ }) => Promise<void>;
65
157
  /**
66
158
  * Start watching MongoDB change streams and emitting real-time events.
159
+ *
160
+ * Task 9.16: the stream is supervised — an `error`/`close`/`end` schedules a re-open with
161
+ * exponential backoff, resuming from the last seen token. Call
162
+ * {@link stopChangeStreamWatcher} to end supervision.
67
163
  */
68
164
  export declare const startChangeStreamWatcher: (io: Server, config?: ChangeStreamConfig, debug?: boolean) => void;
69
165
  /**
70
- * Stop the change stream watcher.
166
+ * Stop the change stream watcher and end Task 9.16's restart supervision (a pending
167
+ * reopen is cancelled, and terminal events from the closing stream are ignored).
71
168
  */
72
169
  export declare const stopChangeStreamWatcher: () => Promise<void>;
73
170
  export {};