@terreno/api 0.30.0 → 56.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) 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 +100 -1
  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 +35 -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 +73 -21
  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 +40 -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 +903 -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/actions.openApi.test.ts +7 -10
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -295
  68. package/src/auth.test.ts +128 -176
  69. package/src/auth.ts +109 -0
  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/docLoader.ts +3 -1
  74. package/src/errors.ts +33 -0
  75. package/src/expressServer.test.ts +7 -1
  76. package/src/index.ts +42 -0
  77. package/src/middleware.test.ts +40 -1
  78. package/src/middleware.ts +15 -0
  79. package/src/openApiCompat.ts +99 -45
  80. package/src/permissions.test.ts +75 -1
  81. package/src/permissions.ts +49 -0
  82. package/src/plugins.test.ts +54 -0
  83. package/src/plugins.ts +43 -0
  84. package/src/realtime/changeStreamWatcher.ts +552 -114
  85. package/src/realtime/realtime.test.ts +157 -0
  86. package/src/realtime/realtimeApp.ts +75 -11
  87. package/src/realtime/sessionRevalidation.test.ts +423 -0
  88. package/src/realtime/sessionRevalidation.ts +273 -0
  89. package/src/realtime/socketAuth.test.ts +355 -0
  90. package/src/realtime/socketAuth.ts +228 -0
  91. package/src/realtime/socketUser.ts +69 -0
  92. package/src/realtime/types.ts +40 -0
  93. package/src/secretProviders.test.ts +7 -1
  94. package/src/secretProviders.ts +15 -3
  95. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  96. package/src/sync/executors.test.ts +882 -0
  97. package/src/sync/executors.ts +703 -0
  98. package/src/sync/integration.test.ts +1160 -0
  99. package/src/sync/loadHarness.ts +618 -0
  100. package/src/sync/models.ts +640 -0
  101. package/src/sync/mutationHandler.test.ts +1252 -0
  102. package/src/sync/mutationHandler.ts +850 -0
  103. package/src/sync/registry.ts +232 -0
  104. package/src/sync/routes.ts +812 -0
  105. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  106. package/src/sync/scripts/compactTombstones.ts +145 -0
  107. package/src/sync/serialize.ts +48 -0
  108. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  109. package/src/sync/socketHandlers.ts +320 -0
  110. package/src/sync/streams.ts +188 -0
  111. package/src/sync/sync.test.ts +582 -0
  112. package/src/sync/syncApp.ts +44 -0
  113. package/src/sync/syncBatch.ts +219 -0
  114. package/src/sync/syncFrontier.test.ts +494 -0
  115. package/src/sync/syncPhaseC.test.ts +718 -0
  116. package/src/sync/syncRoutes.test.ts +865 -0
  117. package/src/sync/syncSeqPlugin.ts +738 -0
  118. package/src/sync/syncSocket.test.ts +1440 -0
  119. package/src/sync/types.ts +270 -0
  120. package/src/terrenoApp.ts +37 -17
  121. package/src/tests/bunSetup.ts +8 -0
  122. package/tsconfig.json +4 -4
  123. package/tsconfig.typedoc.json +7 -1
  124. package/dist/__tests__/openApiCompat.test.js +0 -317
  125. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  126. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  127. package/dist/actions.openApi.test.d.ts +0 -1
  128. package/dist/actions.openApi.test.js +0 -255
  129. package/dist/actions.test.d.ts +0 -1
  130. package/dist/actions.test.js +0 -1089
  131. package/dist/api.arrayOperations.test.d.ts +0 -1
  132. package/dist/api.arrayOperations.test.js +0 -878
  133. package/dist/api.asyncHandler.test.d.ts +0 -1
  134. package/dist/api.asyncHandler.test.js +0 -236
  135. package/dist/api.coverage.test.d.ts +0 -1
  136. package/dist/api.coverage.test.js +0 -194
  137. package/dist/api.errorPaths.test.d.ts +0 -1
  138. package/dist/api.errorPaths.test.js +0 -801
  139. package/dist/api.errors.test.d.ts +0 -1
  140. package/dist/api.errors.test.js +0 -185
  141. package/dist/api.hooks.test.d.ts +0 -1
  142. package/dist/api.hooks.test.js +0 -950
  143. package/dist/api.query.test.d.ts +0 -1
  144. package/dist/api.query.test.js +0 -948
  145. package/dist/api.test.d.ts +0 -1
  146. package/dist/api.test.js +0 -2820
  147. package/dist/auth.compile.test.d.ts +0 -1
  148. package/dist/auth.compile.test.js +0 -201
  149. package/dist/auth.coverage.test.d.ts +0 -1
  150. package/dist/auth.coverage.test.js +0 -202
  151. package/dist/auth.test.d.ts +0 -1
  152. package/dist/auth.test.js +0 -2286
  153. package/dist/betterAuth.test.d.ts +0 -1
  154. package/dist/betterAuth.test.js +0 -181
  155. package/dist/betterAuthApp.test.d.ts +0 -1
  156. package/dist/betterAuthApp.test.js +0 -242
  157. package/dist/betterAuthSetup.test.d.ts +0 -1
  158. package/dist/betterAuthSetup.test.js +0 -762
  159. package/dist/config.test.d.ts +0 -1
  160. package/dist/config.test.js +0 -353
  161. package/dist/configuration.test.d.ts +0 -1
  162. package/dist/configuration.test.js +0 -980
  163. package/dist/configurationPlugin.test.d.ts +0 -1
  164. package/dist/configurationPlugin.test.js +0 -827
  165. package/dist/consentApp.test.d.ts +0 -1
  166. package/dist/consentApp.test.js +0 -1415
  167. package/dist/docLoader.test.d.ts +0 -1
  168. package/dist/docLoader.test.js +0 -137
  169. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  170. package/dist/envConfigurationPlugin.test.js +0 -369
  171. package/dist/errors.test.d.ts +0 -1
  172. package/dist/errors.test.js +0 -607
  173. package/dist/expressServer.test.d.ts +0 -1
  174. package/dist/expressServer.test.js +0 -1249
  175. package/dist/githubAuth.test.d.ts +0 -1
  176. package/dist/githubAuth.test.js +0 -1142
  177. package/dist/httpClient.test.d.ts +0 -1
  178. package/dist/httpClient.test.js +0 -1471
  179. package/dist/logger.test.d.ts +0 -1
  180. package/dist/logger.test.js +0 -685
  181. package/dist/middleware.test.d.ts +0 -1
  182. package/dist/middleware.test.js +0 -241
  183. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  184. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  185. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  186. package/dist/notifiers/slackNotifier.test.js +0 -297
  187. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/zoomNotifier.test.js +0 -373
  189. package/dist/openApi.test.d.ts +0 -1
  190. package/dist/openApi.test.js +0 -620
  191. package/dist/openApiBuilder.test.d.ts +0 -1
  192. package/dist/openApiBuilder.test.js +0 -601
  193. package/dist/openApiEtag.test.d.ts +0 -1
  194. package/dist/openApiEtag.test.js +0 -86
  195. package/dist/openApiValidator.test.d.ts +0 -1
  196. package/dist/openApiValidator.test.js +0 -761
  197. package/dist/permissions.middleware.test.d.ts +0 -1
  198. package/dist/permissions.middleware.test.js +0 -308
  199. package/dist/permissions.test.d.ts +0 -1
  200. package/dist/permissions.test.js +0 -439
  201. package/dist/plugins.test.d.ts +0 -1
  202. package/dist/plugins.test.js +0 -890
  203. package/dist/populate.test.d.ts +0 -1
  204. package/dist/populate.test.js +0 -373
  205. package/dist/realtime/realtime.test.d.ts +0 -10
  206. package/dist/realtime/realtime.test.js +0 -3982
  207. package/dist/requestContext.test.d.ts +0 -1
  208. package/dist/requestContext.test.js +0 -412
  209. package/dist/scriptRunner.test.d.ts +0 -1
  210. package/dist/scriptRunner.test.js +0 -386
  211. package/dist/secretProviders.test.d.ts +0 -1
  212. package/dist/secretProviders.test.js +0 -726
  213. package/dist/syncConsents.test.d.ts +0 -1
  214. package/dist/syncConsents.test.js +0 -522
  215. package/dist/terrenoApp.test.d.ts +0 -1
  216. package/dist/terrenoApp.test.js +0 -489
  217. package/dist/tests/bunSetup.d.ts +0 -1
  218. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  219. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  220. package/dist/tests/testEnv.d.ts +0 -0
  221. package/dist/tests/testEnv.js +0 -6
  222. package/dist/transformers.test.d.ts +0 -1
  223. package/dist/transformers.test.js +0 -423
  224. package/dist/utils.test.d.ts +0 -1
  225. package/dist/utils.test.js +0 -242
  226. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
package/dist/api.d.ts CHANGED
@@ -6,6 +6,7 @@ import { type ModelRouterValidationOptions } from "./openApiValidator";
6
6
  import { type RESTPermissions } from "./permissions";
7
7
  import type { PopulatePath } from "./populate";
8
8
  import type { RealtimeConfig } from "./realtime/types";
9
+ import type { SyncConfig } from "./sync/types";
9
10
  import { type TerrenoTransformer } from "./transformers";
10
11
  export type JSONPrimitive = string | number | boolean | null;
11
12
  export interface JSONArray extends Array<JSONValue> {
@@ -249,6 +250,15 @@ export interface ModelRouterOptions<T> {
249
250
  * Requires the RealtimeApp plugin to be registered with TerrenoApp.
250
251
  */
251
252
  realtime?: RealtimeConfig;
253
+ /**
254
+ * Enable local-first sync (@terreno/syncdb) for this model. Documents are scoped
255
+ * into streams (owner/tenant/broadcast/custom) with monotonic per-stream cursors.
256
+ *
257
+ * Requires the schema to use `isDeletedPlugin` (soft delete tombstones) and
258
+ * `syncPlugin` (per-stream `_syncSeq` stamping) — validated at registration.
259
+ * Only works with the three-argument form: modelRouter('/path', Model, options).
260
+ */
261
+ sync?: SyncConfig;
252
262
  }
253
263
  /**
254
264
  * Registration object returned by modelRouter when called with a path.
package/dist/api.js CHANGED
@@ -139,34 +139,10 @@ var openApi_1 = require("./openApi");
139
139
  var openApiValidator_1 = require("./openApiValidator");
140
140
  var permissions_1 = require("./permissions");
141
141
  var registry_1 = require("./realtime/registry");
142
+ var executors_1 = require("./sync/executors");
143
+ var registry_2 = require("./sync/registry");
142
144
  var transformers_1 = require("./transformers");
143
145
  var utils_1 = require("./utils");
144
- /**
145
- * Picks the error to throw for something caught in a hook, transformer, or Mongoose middleware.
146
- * An `APIError` is passed through untouched so its status, code, detail, and meta reach the client;
147
- * anything else is wrapped in the given framework error. `wrapper` may override any field,
148
- * including `detail`, which defaults to the caught error's text.
149
- */
150
- var passthroughOrWrap = function (error, wrapper) {
151
- if ((0, errors_1.isAPIError)(error)) {
152
- return error;
153
- }
154
- return new errors_1.APIError(__assign({ cause: error, detail: (0, errors_1.errorDetail)(error), disableExternalErrorTracking: (0, errors_1.getDisableExternalErrorTracking)(error) }, wrapper));
155
- };
156
- /**
157
- * `passthroughOrWrap` for write paths (`model.create`, `doc.save`). Mongoose validation and cast
158
- * errors are converted first so their per-field messages survive as `meta.fields` instead of being
159
- * flattened into the wrapper's `detail`.
160
- */
161
- var passthroughOrWrapWrite = function (error, wrapper) {
162
- if (!(0, errors_1.isAPIError)(error) && error instanceof Error) {
163
- var converted = (0, errors_1.mongooseErrorToAPIError)(error);
164
- if (converted) {
165
- return converted;
166
- }
167
- }
168
- return passthroughOrWrap(error, wrapper);
169
- };
170
146
  var addPopulateToQuery = function (
171
147
  // noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
172
148
  // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type parameters vary widely across populated/unpopulated documents — caller passes concrete types
@@ -433,6 +409,10 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
433
409
  routePath: path,
434
410
  });
435
411
  }
412
+ // Register for local-first sync if configured (validates the schema contract)
413
+ if (options.sync) {
414
+ (0, registry_2.registerSync)({ config: options.sync, model: model, options: options, routePath: path });
415
+ }
436
416
  return {
437
417
  __type: "modelRouter",
438
418
  _buildWithOpenApi: function (openApi) {
@@ -446,6 +426,10 @@ function modelRouter(pathOrModel, modelOrOptions, maybeOptions) {
446
426
  logger_1.logger.warn("modelRouter for ".concat(model.modelName, " has realtime config but was called without a path. ") +
447
427
  "Realtime sync only works with the three-argument form: modelRouter('/path', Model, options)");
448
428
  }
429
+ if (options.sync) {
430
+ logger_1.logger.warn("modelRouter for ".concat(model.modelName, " has sync config but was called without a path. ") +
431
+ "Local-first sync only works with the three-argument form: modelRouter('/path', Model, options)");
432
+ }
449
433
  return router;
450
434
  }
451
435
  var _buildModelRouter = function (model, options) {
@@ -468,120 +452,32 @@ var _buildModelRouter = function (model, options) {
468
452
  (0, permissions_1.permissionMiddleware)(model, options),
469
453
  createValidation,
470
454
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
471
- var body, error_1, data, error_2, populateQuery, error_3, error_4, serialized, error_5;
455
+ var doc, serialized, error_1;
472
456
  return __generator(this, function (_a) {
473
457
  switch (_a.label) {
474
- case 0:
475
- try {
476
- body = (0, transformers_1.transform)(options, req.body, "create", req.user);
477
- }
478
- catch (error) {
479
- throw passthroughOrWrap(error, {
480
- code: "transform-error",
481
- status: 400,
482
- title: "Transform error",
483
- });
484
- }
485
- if (!options.preCreate) return [3 /*break*/, 5];
486
- _a.label = 1;
458
+ case 0: return [4 /*yield*/, (0, executors_1.executeCreate)({
459
+ body: req.body,
460
+ model: model,
461
+ options: options,
462
+ req: req,
463
+ user: req.user,
464
+ })];
487
465
  case 1:
488
- _a.trys.push([1, 3, , 4]);
489
- return [4 /*yield*/, options.preCreate(body, req)];
466
+ doc = (_a.sent()).doc;
467
+ _a.label = 2;
490
468
  case 2:
491
- body = _a.sent();
492
- return [3 /*break*/, 4];
469
+ _a.trys.push([2, 4, , 5]);
470
+ return [4 /*yield*/, responseHandler(doc, "create", req, options)];
493
471
  case 3:
494
- error_1 = _a.sent();
495
- throw passthroughOrWrap(error_1, {
496
- code: "pre-create-hook-error",
497
- status: 400,
498
- title: "preCreate hook error",
499
- });
500
- case 4:
501
- if (body === undefined) {
502
- throw new errors_1.ForbiddenError({
503
- code: "create-not-allowed",
504
- detail: "A body must be returned from preCreate",
505
- title: "Create not allowed",
506
- });
507
- }
508
- if (body === null) {
509
- throw new errors_1.ForbiddenError({
510
- code: "create-not-allowed",
511
- detail: "preCreate hook returned null",
512
- title: "Create not allowed",
513
- });
514
- }
515
- _a.label = 5;
516
- case 5:
517
- if (body === undefined) {
518
- throw new errors_1.BadRequestError({
519
- code: "invalid-request-body",
520
- detail: "Body is undefined",
521
- title: "Invalid request body",
522
- });
523
- }
524
- _a.label = 6;
525
- case 6:
526
- _a.trys.push([6, 8, , 9]);
527
- return [4 /*yield*/, model.create(body)];
528
- case 7:
529
- data = (_a.sent());
530
- return [3 /*break*/, 9];
531
- case 8:
532
- error_2 = _a.sent();
533
- throw passthroughOrWrapWrite(error_2, {
534
- code: "create-error",
535
- status: 400,
536
- title: "Create error",
537
- });
538
- case 9:
539
- if (!options.populatePaths) return [3 /*break*/, 13];
540
- _a.label = 10;
541
- case 10:
542
- _a.trys.push([10, 12, , 13]);
543
- populateQuery = model.findById(data._id);
544
- populateQuery = (0, exports.addPopulateToQuery)(populateQuery, options.populatePaths);
545
- return [4 /*yield*/, populateQuery.exec()];
546
- case 11:
547
- data = _a.sent();
548
- return [3 /*break*/, 13];
549
- case 12:
550
- error_3 = _a.sent();
551
- throw passthroughOrWrap(error_3, {
552
- code: "populate-error",
553
- status: 400,
554
- title: "Populate error",
555
- });
556
- case 13:
557
- if (!options.postCreate) return [3 /*break*/, 17];
558
- _a.label = 14;
559
- case 14:
560
- _a.trys.push([14, 16, , 17]);
561
- return [4 /*yield*/, options.postCreate(data, req)];
562
- case 15:
563
- _a.sent();
564
- return [3 /*break*/, 17];
565
- case 16:
566
- error_4 = _a.sent();
567
- throw passthroughOrWrap(error_4, {
568
- code: "post-create-hook-error",
569
- status: 400,
570
- title: "postCreate hook error",
571
- });
572
- case 17:
573
- _a.trys.push([17, 19, , 20]);
574
- return [4 /*yield*/, responseHandler(data, "create", req, options)];
575
- case 18:
576
472
  serialized = _a.sent();
577
473
  return [2 /*return*/, res.status(201).json({ data: serialized })];
578
- case 19:
579
- error_5 = _a.sent();
580
- throw passthroughOrWrap(error_5, {
474
+ case 4:
475
+ error_1 = _a.sent();
476
+ throw (0, errors_1.passthroughOrWrap)(error_1, {
581
477
  code: "response-handler-error",
582
478
  title: "responseHandler error",
583
479
  });
584
- case 20: return [2 /*return*/];
480
+ case 5: return [2 /*return*/];
585
481
  }
586
482
  });
587
483
  }); }));
@@ -592,7 +488,7 @@ var _buildModelRouter = function (model, options) {
592
488
  (0, openApi_1.listOpenApiMiddleware)(model, options),
593
489
  queryValidation,
594
490
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
595
- var query, _a, _b, queryParam, _c, _d, queryParam, queryFilter, error_6, limit, builtQuery, total, populatedQuery, data, error_7, serialized, error_8, more, msg;
491
+ var query, _a, _b, queryParam, _c, _d, queryParam, queryFilter, error_2, limit, builtQuery, total, populatedQuery, data, error_3, serialized, error_4, more, msg;
596
492
  var e_6, _e, e_7, _f;
597
493
  var _g, _h, _j, _k, _l, _m;
598
494
  return __generator(this, function (_o) {
@@ -656,8 +552,8 @@ var _buildModelRouter = function (model, options) {
656
552
  queryFilter = _o.sent();
657
553
  return [3 /*break*/, 4];
658
554
  case 3:
659
- error_6 = _o.sent();
660
- throw passthroughOrWrap(error_6, {
555
+ error_2 = _o.sent();
556
+ throw (0, errors_1.passthroughOrWrap)(error_2, {
661
557
  code: "query-filter-error",
662
558
  status: 400,
663
559
  title: "Query filter error",
@@ -711,8 +607,8 @@ var _buildModelRouter = function (model, options) {
711
607
  data = (_o.sent());
712
608
  return [3 /*break*/, 10];
713
609
  case 9:
714
- error_7 = _o.sent();
715
- throw passthroughOrWrap(error_7, {
610
+ error_3 = _o.sent();
611
+ throw (0, errors_1.passthroughOrWrap)(error_3, {
716
612
  code: "list-error",
717
613
  title: "List error",
718
614
  });
@@ -723,8 +619,8 @@ var _buildModelRouter = function (model, options) {
723
619
  serialized = _o.sent();
724
620
  return [3 /*break*/, 13];
725
621
  case 12:
726
- error_8 = _o.sent();
727
- throw passthroughOrWrap(error_8, {
622
+ error_4 = _o.sent();
623
+ throw (0, errors_1.passthroughOrWrap)(error_4, {
728
624
  code: "response-handler-error",
729
625
  title: "responseHandler error",
730
626
  });
@@ -757,7 +653,7 @@ var _buildModelRouter = function (model, options) {
757
653
  return [2 /*return*/, res.json({ data: serialized })];
758
654
  }
759
655
  catch (error) {
760
- throw passthroughOrWrap(error, {
656
+ throw (0, errors_1.passthroughOrWrap)(error, {
761
657
  code: "serialization-error",
762
658
  title: "Serialization error",
763
659
  });
@@ -771,7 +667,7 @@ var _buildModelRouter = function (model, options) {
771
667
  (0, openApi_1.getOpenApiMiddleware)(model, options),
772
668
  (0, permissions_1.permissionMiddleware)(model, options),
773
669
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
774
- var data, serialized, error_9;
670
+ var data, serialized, error_5;
775
671
  return __generator(this, function (_a) {
776
672
  switch (_a.label) {
777
673
  case 0:
@@ -784,8 +680,8 @@ var _buildModelRouter = function (model, options) {
784
680
  serialized = _a.sent();
785
681
  return [2 /*return*/, res.json({ data: serialized })];
786
682
  case 3:
787
- error_9 = _a.sent();
788
- throw passthroughOrWrap(error_9, {
683
+ error_5 = _a.sent();
684
+ throw (0, errors_1.passthroughOrWrap)(error_5, {
789
685
  code: "response-handler-error",
790
686
  title: "responseHandler error",
791
687
  });
@@ -809,61 +705,13 @@ var _buildModelRouter = function (model, options) {
809
705
  (0, permissions_1.permissionMiddleware)(model, options),
810
706
  updateValidation,
811
707
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
812
- var doc, body, bodyUpdatedAt, error_10, preciseUnmodifiedSince, httpUnmodifiedSince, timestampValue, httpTimestampValue, usingPreciseHeader, usingHttpHeader, clientTimestamp, docRecord, serverTimestamp, serverTimestampValue, serialized, prevDoc, error_11, populateQuery, error_12, serialized, error_13;
813
- var _a, _b;
814
- return __generator(this, function (_c) {
815
- switch (_c.label) {
708
+ var existingDoc, bodyUpdatedAt, preciseUnmodifiedSince, httpUnmodifiedSince, timestampValue, httpTimestampValue, concurrencyCheck, usingPreciseHeader, usingHttpHeader, clientTimestamp, doc, error_6, serialized, serialized, error_7;
709
+ return __generator(this, function (_a) {
710
+ switch (_a.label) {
816
711
  case 0:
817
- doc = req.obj;
818
- try {
819
- body = (0, transformers_1.transform)(options, req.body, "update", req.user);
820
- }
821
- catch (error) {
822
- throw passthroughOrWrap(error, {
823
- code: "transform-error",
824
- detail: "PATCH failed on ".concat(req.params.id, " for user ").concat((_a = req.user) === null || _a === void 0 ? void 0 : _a.id, ": ").concat((0, errors_1.errorDetail)(error)),
825
- status: 403,
826
- title: "PATCH failed",
827
- });
828
- }
712
+ existingDoc = req
713
+ .obj;
829
714
  bodyUpdatedAt = req.body._updatedAt;
830
- delete req.body._updatedAt;
831
- if (body && typeof body === "object") {
832
- delete body._updatedAt;
833
- }
834
- if (!options.preUpdate) return [3 /*break*/, 5];
835
- _c.label = 1;
836
- case 1:
837
- _c.trys.push([1, 3, , 4]);
838
- return [4 /*yield*/, options.preUpdate(body, req)];
839
- case 2:
840
- body = _c.sent();
841
- return [3 /*break*/, 4];
842
- case 3:
843
- error_10 = _c.sent();
844
- throw passthroughOrWrap(error_10, {
845
- code: "pre-update-hook-error",
846
- detail: "preUpdate hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_10)),
847
- status: 400,
848
- title: "preUpdate hook error",
849
- });
850
- case 4:
851
- if (body === undefined) {
852
- throw new errors_1.ForbiddenError({
853
- code: "update-not-allowed",
854
- detail: "A body must be returned from preUpdate",
855
- title: "Update not allowed",
856
- });
857
- }
858
- if (body === null) {
859
- throw new errors_1.ForbiddenError({
860
- code: "update-not-allowed",
861
- detail: "preUpdate hook on ".concat(req.params.id, " returned null"),
862
- title: "Update not allowed",
863
- });
864
- }
865
- _c.label = 5;
866
- case 5:
867
715
  preciseUnmodifiedSince = req.headers["x-unmodified-since-iso"];
868
716
  httpUnmodifiedSince = req.headers["if-unmodified-since"];
869
717
  timestampValue = Array.isArray(preciseUnmodifiedSince)
@@ -872,106 +720,67 @@ var _buildModelRouter = function (model, options) {
872
720
  httpTimestampValue = Array.isArray(httpUnmodifiedSince)
873
721
  ? httpUnmodifiedSince[0]
874
722
  : httpUnmodifiedSince;
875
- if (!(timestampValue || httpTimestampValue || bodyUpdatedAt)) return [3 /*break*/, 7];
876
- usingPreciseHeader = Boolean(timestampValue);
877
- usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
878
- clientTimestamp = timestampValue
879
- ? luxon_1.DateTime.fromISO(timestampValue)
880
- : httpTimestampValue
881
- ? luxon_1.DateTime.fromHTTP(httpTimestampValue)
882
- : luxon_1.DateTime.fromISO(bodyUpdatedAt);
883
- if (!clientTimestamp.isValid) {
884
- throw new errors_1.BadRequestError({
885
- code: "invalid-conflict-detection-timestamp",
886
- detail: usingPreciseHeader
723
+ if (timestampValue || httpTimestampValue || bodyUpdatedAt) {
724
+ usingPreciseHeader = Boolean(timestampValue);
725
+ usingHttpHeader = !usingPreciseHeader && Boolean(httpTimestampValue);
726
+ clientTimestamp = timestampValue
727
+ ? luxon_1.DateTime.fromISO(timestampValue)
728
+ : httpTimestampValue
729
+ ? luxon_1.DateTime.fromHTTP(httpTimestampValue)
730
+ : luxon_1.DateTime.fromISO(bodyUpdatedAt);
731
+ concurrencyCheck = {
732
+ // An unparseable value round-trips as an invalid Date; the executor turns it into
733
+ // the 400 "Invalid conflict-detection timestamp" error after preUpdate has run.
734
+ ifUnmodifiedSince: clientTimestamp.toJSDate(),
735
+ invalidTimestampDetail: usingPreciseHeader
887
736
  ? "X-Unmodified-Since-ISO header could not be parsed as an ISO date"
888
737
  : usingHttpHeader
889
738
  ? "If-Unmodified-Since header could not be parsed as an HTTP date"
890
739
  : "_updatedAt body field could not be parsed as an ISO date",
891
- title: "Invalid conflict-detection timestamp",
892
- });
740
+ type: "timestamp",
741
+ };
893
742
  }
894
- docRecord = doc;
895
- serverTimestamp = null;
896
- serverTimestampValue = (_b = docRecord.updated) !== null && _b !== void 0 ? _b : docRecord.created;
897
- if (serverTimestampValue instanceof Date) {
898
- serverTimestamp = luxon_1.DateTime.fromJSDate(serverTimestampValue);
899
- }
900
- else if (typeof serverTimestampValue === "string") {
901
- serverTimestamp = luxon_1.DateTime.fromISO(serverTimestampValue);
902
- }
903
- if (serverTimestamp && !serverTimestamp.isValid) {
904
- throw new errors_1.BadRequestError({
905
- code: "invalid-server-timestamp",
906
- detail: "Document timestamp could not be parsed as a date",
907
- title: "Invalid server timestamp",
908
- });
909
- }
910
- if (!(serverTimestamp && clientTimestamp < serverTimestamp)) return [3 /*break*/, 7];
911
- return [4 /*yield*/, responseHandler(doc, "update", req, options)];
912
- case 6:
913
- serialized = _c.sent();
743
+ _a.label = 1;
744
+ case 1:
745
+ _a.trys.push([1, 3, , 6]);
746
+ return [4 /*yield*/, (0, executors_1.executeUpdate)({
747
+ body: req.body,
748
+ concurrencyCheck: concurrencyCheck,
749
+ existingDoc: existingDoc,
750
+ id: req.params.id,
751
+ model: model,
752
+ options: options,
753
+ req: req,
754
+ user: req.user,
755
+ })];
756
+ case 2:
757
+ (doc = (_a.sent()).doc);
758
+ return [3 /*break*/, 6];
759
+ case 3:
760
+ error_6 = _a.sent();
761
+ if (!(0, executors_1.isExecutorConflictError)(error_6)) return [3 /*break*/, 5];
762
+ return [4 /*yield*/, responseHandler(error_6.doc, "update", req, options)];
763
+ case 4:
764
+ serialized = _a.sent();
914
765
  return [2 /*return*/, res.status(409).json({
915
766
  data: serialized,
916
767
  error: "Conflict",
917
768
  message: "Document was modified since your last read",
918
769
  })];
919
- case 7:
920
- prevDoc = (0, cloneDeep_1.default)(doc);
921
- _c.label = 8;
922
- case 8:
923
- _c.trys.push([8, 10, , 11]);
924
- doc.set(body);
925
- return [4 /*yield*/, doc.save()];
926
- case 9:
927
- _c.sent();
928
- return [3 /*break*/, 11];
929
- case 10:
930
- error_11 = _c.sent();
931
- throw passthroughOrWrapWrite(error_11, {
932
- code: "update-save-error",
933
- detail: "preUpdate hook save error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_11)),
934
- status: 400,
935
- title: "preUpdate hook save error",
936
- });
937
- case 11:
938
- if (!options.populatePaths) return [3 /*break*/, 13];
939
- populateQuery = model.findById(doc._id);
940
- populateQuery = (0, exports.addPopulateToQuery)(populateQuery, options.populatePaths);
941
- return [4 /*yield*/, populateQuery.exec()];
942
- case 12:
943
- doc = _c.sent();
944
- _c.label = 13;
945
- case 13:
946
- if (!options.postUpdate) return [3 /*break*/, 17];
947
- _c.label = 14;
948
- case 14:
949
- _c.trys.push([14, 16, , 17]);
950
- return [4 /*yield*/, options.postUpdate(doc, body, req, prevDoc)];
951
- case 15:
952
- _c.sent();
953
- return [3 /*break*/, 17];
954
- case 16:
955
- error_12 = _c.sent();
956
- throw passthroughOrWrap(error_12, {
957
- code: "post-update-hook-error",
958
- detail: "postUpdate hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_12)),
959
- status: 400,
960
- title: "postUpdate hook error",
961
- });
962
- case 17:
963
- _c.trys.push([17, 19, , 20]);
770
+ case 5: throw error_6;
771
+ case 6:
772
+ _a.trys.push([6, 8, , 9]);
964
773
  return [4 /*yield*/, responseHandler(doc, "update", req, options)];
965
- case 18:
966
- serialized = _c.sent();
774
+ case 7:
775
+ serialized = _a.sent();
967
776
  return [2 /*return*/, res.json({ data: serialized })];
968
- case 19:
969
- error_13 = _c.sent();
970
- throw passthroughOrWrap(error_13, {
777
+ case 8:
778
+ error_7 = _a.sent();
779
+ throw (0, errors_1.passthroughOrWrap)(error_7, {
971
780
  code: "response-handler-error",
972
781
  title: "responseHandler error",
973
782
  });
974
- case 20: return [2 /*return*/];
783
+ case 9: return [2 /*return*/];
975
784
  }
976
785
  });
977
786
  }); }));
@@ -980,87 +789,27 @@ var _buildModelRouter = function (model, options) {
980
789
  (0, openApi_1.deleteOpenApiMiddleware)(model, options),
981
790
  (0, permissions_1.permissionMiddleware)(model, options),
982
791
  ], (0, exports.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
983
- var doc, body, error_14, error_15, error_16;
792
+ var existingDoc;
984
793
  return __generator(this, function (_a) {
985
794
  switch (_a.label) {
986
795
  case 0:
987
- doc = req.obj;
988
- if (!options.preDelete) return [3 /*break*/, 5];
989
- body = void 0;
990
- _a.label = 1;
796
+ existingDoc = req.obj;
797
+ return [4 /*yield*/, (0, executors_1.executeDelete)({
798
+ existingDoc: existingDoc,
799
+ id: req.params.id,
800
+ model: model,
801
+ options: options,
802
+ req: req,
803
+ user: req.user,
804
+ })];
991
805
  case 1:
992
- _a.trys.push([1, 3, , 4]);
993
- return [4 /*yield*/, options.preDelete(doc, req)];
994
- case 2:
995
- body = _a.sent();
996
- return [3 /*break*/, 4];
997
- case 3:
998
- error_14 = _a.sent();
999
- throw passthroughOrWrap(error_14, {
1000
- code: "pre-delete-hook-error",
1001
- detail: "preDelete hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_14)),
1002
- status: 403,
1003
- title: "preDelete hook error",
1004
- });
1005
- case 4:
1006
- if (body === undefined) {
1007
- throw new errors_1.ForbiddenError({
1008
- code: "delete-not-allowed",
1009
- detail: "A body must be returned from preDelete",
1010
- title: "Delete not allowed",
1011
- });
1012
- }
1013
- if (body === null) {
1014
- throw new errors_1.ForbiddenError({
1015
- code: "delete-not-allowed",
1016
- detail: "preDelete hook for ".concat(req.params.id, " returned null"),
1017
- title: "Delete not allowed",
1018
- });
1019
- }
1020
- _a.label = 5;
1021
- case 5:
1022
- if (!(Object.keys(model.schema.paths).includes("deleted") &&
1023
- model.schema.paths.deleted.instance === "Boolean")) return [3 /*break*/, 7];
1024
- doc.deleted = true;
1025
- return [4 /*yield*/, doc.save()];
1026
- case 6:
1027
806
  _a.sent();
1028
- return [3 /*break*/, 10];
1029
- case 7:
1030
- _a.trys.push([7, 9, , 10]);
1031
- return [4 /*yield*/, doc.deleteOne()];
1032
- case 8:
1033
- _a.sent();
1034
- return [3 /*break*/, 10];
1035
- case 9:
1036
- error_15 = _a.sent();
1037
- throw passthroughOrWrap(error_15, {
1038
- code: "delete-error",
1039
- status: 400,
1040
- title: "Delete error",
1041
- });
1042
- case 10:
1043
- if (!options.postDelete) return [3 /*break*/, 14];
1044
- _a.label = 11;
1045
- case 11:
1046
- _a.trys.push([11, 13, , 14]);
1047
- return [4 /*yield*/, options.postDelete(req, doc)];
1048
- case 12:
1049
- _a.sent();
1050
- return [3 /*break*/, 14];
1051
- case 13:
1052
- error_16 = _a.sent();
1053
- throw passthroughOrWrap(error_16, {
1054
- code: "post-delete-hook-error",
1055
- status: 400,
1056
- title: "postDelete hook error",
1057
- });
1058
- case 14: return [2 /*return*/, res.status(204).json({})];
807
+ return [2 /*return*/, res.status(204).json({})];
1059
808
  }
1060
809
  });
1061
810
  }); }));
1062
811
  var arrayOperation = function (req, res, operation) { return __awaiter(void 0, void 0, void 0, function () {
1063
- var doc, prevDoc, field, itemId, array, index, body, error_17, error_18, error_19;
812
+ var doc, prevDoc, field, itemId, array, index, body, error_8, error_9, error_10;
1064
813
  var _a;
1065
814
  var _b, _c;
1066
815
  return __generator(this, function (_d) {
@@ -1157,7 +906,7 @@ var _buildModelRouter = function (model, options) {
1157
906
  body = (0, transformers_1.transform)(options, body, "update", req.user);
1158
907
  }
1159
908
  catch (error) {
1160
- throw passthroughOrWrap(error, {
909
+ throw (0, errors_1.passthroughOrWrap)(error, {
1161
910
  code: "transform-error",
1162
911
  status: 403,
1163
912
  title: "Transform error",
@@ -1172,10 +921,10 @@ var _buildModelRouter = function (model, options) {
1172
921
  body = _d.sent();
1173
922
  return [3 /*break*/, 7];
1174
923
  case 6:
1175
- error_17 = _d.sent();
1176
- throw passthroughOrWrap(error_17, {
924
+ error_8 = _d.sent();
925
+ throw (0, errors_1.passthroughOrWrap)(error_8, {
1177
926
  code: "pre-update-hook-error",
1178
- detail: "preUpdate hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_17)),
927
+ detail: "preUpdate hook error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_8)),
1179
928
  status: 400,
1180
929
  title: "preUpdate hook error",
1181
930
  });
@@ -1203,10 +952,10 @@ var _buildModelRouter = function (model, options) {
1203
952
  _d.sent();
1204
953
  return [3 /*break*/, 11];
1205
954
  case 10:
1206
- error_18 = _d.sent();
1207
- throw passthroughOrWrapWrite(error_18, {
955
+ error_9 = _d.sent();
956
+ throw (0, errors_1.passthroughOrWrapWrite)(error_9, {
1208
957
  code: "update-save-error",
1209
- detail: "PATCH Pre Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_18)),
958
+ detail: "PATCH Pre Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_9)),
1210
959
  status: 400,
1211
960
  title: "PATCH Pre Update error",
1212
961
  });
@@ -1220,10 +969,10 @@ var _buildModelRouter = function (model, options) {
1220
969
  _d.sent();
1221
970
  return [3 /*break*/, 15];
1222
971
  case 14:
1223
- error_19 = _d.sent();
1224
- throw passthroughOrWrap(error_19, {
972
+ error_10 = _d.sent();
973
+ throw (0, errors_1.passthroughOrWrap)(error_10, {
1225
974
  code: "post-update-hook-error",
1226
- detail: "PATCH Post Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_19)),
975
+ detail: "PATCH Post Update error on ".concat(req.params.id, ": ").concat((0, errors_1.errorDetail)(error_10)),
1227
976
  status: 400,
1228
977
  title: "PATCH Post Update error",
1229
978
  });