@terreno/api 0.31.0 → 56.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/dist/api.d.ts +10 -0
  2. package/dist/api.js +110 -361
  3. package/dist/auth.d.ts +26 -0
  4. package/dist/auth.js +121 -26
  5. package/dist/betterAuth.d.ts +5 -0
  6. package/dist/betterAuthSetup.js +23 -4
  7. package/dist/docLoader.js +12 -9
  8. package/dist/errors.d.ts +13 -0
  9. package/dist/errors.js +29 -1
  10. package/dist/index.d.ts +17 -1
  11. package/dist/index.js +29 -1
  12. package/dist/middleware.d.ts +7 -0
  13. package/dist/middleware.js +16 -1
  14. package/dist/openApiCompat.d.ts +10 -1
  15. package/dist/openApiCompat.js +115 -47
  16. package/dist/permissions.d.ts +27 -0
  17. package/dist/permissions.js +42 -1
  18. package/dist/plugins.d.ts +13 -0
  19. package/dist/plugins.js +47 -1
  20. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  21. package/dist/realtime/changeStreamWatcher.js +542 -137
  22. package/dist/realtime/realtimeApp.d.ts +2 -0
  23. package/dist/realtime/realtimeApp.js +83 -27
  24. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  25. package/dist/realtime/sessionRevalidation.js +438 -0
  26. package/dist/realtime/socketAuth.d.ts +97 -0
  27. package/dist/realtime/socketAuth.js +272 -0
  28. package/dist/realtime/socketUser.d.ts +54 -0
  29. package/dist/realtime/socketUser.js +75 -5
  30. package/dist/realtime/types.d.ts +54 -0
  31. package/dist/secretProviders.d.ts +23 -0
  32. package/dist/secretProviders.js +9 -3
  33. package/dist/sync/executors.d.ts +198 -0
  34. package/dist/sync/executors.js +670 -0
  35. package/dist/sync/loadHarness.js +807 -0
  36. package/dist/sync/models.d.ts +216 -0
  37. package/dist/sync/models.js +644 -0
  38. package/dist/sync/mutationHandler.d.ts +97 -0
  39. package/dist/sync/mutationHandler.js +886 -0
  40. package/dist/sync/registry.d.ts +73 -0
  41. package/dist/sync/registry.js +223 -0
  42. package/dist/sync/routes.d.ts +62 -0
  43. package/dist/sync/routes.js +936 -0
  44. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  45. package/dist/sync/scripts/compactTombstones.js +270 -0
  46. package/dist/sync/serialize.d.ts +20 -0
  47. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  48. package/dist/sync/socketHandlers.d.ts +54 -0
  49. package/dist/sync/socketHandlers.js +470 -0
  50. package/dist/sync/streams.d.ts +85 -0
  51. package/dist/sync/streams.js +221 -0
  52. package/dist/sync/syncApp.d.ts +29 -0
  53. package/dist/sync/syncApp.js +44 -0
  54. package/dist/sync/syncBatch.d.ts +71 -0
  55. package/dist/sync/syncBatch.js +252 -0
  56. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  57. package/dist/sync/syncSeqPlugin.js +899 -0
  58. package/dist/sync/types.d.ts +254 -0
  59. package/dist/sync/types.js +9 -0
  60. package/dist/terrenoApp.js +90 -27
  61. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  62. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  63. package/package.json +7 -6
  64. package/src/__tests__/openApiCompat.test.ts +20 -0
  65. package/src/api.errors.test.ts +32 -23
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -296
  68. package/src/auth.test.ts +202 -0
  69. package/src/auth.ts +134 -23
  70. package/src/betterAuth.ts +6 -0
  71. package/src/betterAuthSetup.test.ts +34 -0
  72. package/src/betterAuthSetup.ts +20 -1
  73. package/src/configuration.test.ts +59 -38
  74. package/src/configurationPlugin.test.ts +72 -42
  75. package/src/docLoader.ts +3 -1
  76. package/src/errors.ts +33 -0
  77. package/src/expressServer.test.ts +7 -1
  78. package/src/index.ts +42 -0
  79. package/src/middleware.test.ts +56 -1
  80. package/src/middleware.ts +15 -0
  81. package/src/openApiCompat.ts +99 -45
  82. package/src/permissions.test.ts +101 -17
  83. package/src/permissions.ts +49 -0
  84. package/src/plugins.test.ts +64 -0
  85. package/src/plugins.ts +56 -0
  86. package/src/realtime/changeStreamWatcher.ts +552 -114
  87. package/src/realtime/realtime.test.ts +157 -0
  88. package/src/realtime/realtimeApp.ts +82 -14
  89. package/src/realtime/realtimeAppSetup.test.ts +25 -27
  90. package/src/realtime/sessionRevalidation.test.ts +423 -0
  91. package/src/realtime/sessionRevalidation.ts +273 -0
  92. package/src/realtime/socketAuth.test.ts +355 -0
  93. package/src/realtime/socketAuth.ts +228 -0
  94. package/src/realtime/socketUser.ts +69 -0
  95. package/src/realtime/types.ts +54 -0
  96. package/src/secretProviders.test.ts +7 -1
  97. package/src/secretProviders.ts +15 -3
  98. package/src/secretProvidersGcpClient.test.ts +66 -0
  99. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  100. package/src/sync/executors.test.ts +882 -0
  101. package/src/sync/executors.ts +705 -0
  102. package/src/sync/integration.test.ts +1160 -0
  103. package/src/sync/loadHarness.ts +618 -0
  104. package/src/sync/models.ts +641 -0
  105. package/src/sync/mutationHandler.test.ts +1252 -0
  106. package/src/sync/mutationHandler.ts +850 -0
  107. package/src/sync/registry.ts +232 -0
  108. package/src/sync/routes.ts +812 -0
  109. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  110. package/src/sync/scripts/compactTombstones.ts +145 -0
  111. package/src/sync/serialize.ts +48 -0
  112. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  113. package/src/sync/socketHandlers.ts +320 -0
  114. package/src/sync/streams.ts +188 -0
  115. package/src/sync/sync.test.ts +582 -0
  116. package/src/sync/syncApp.ts +44 -0
  117. package/src/sync/syncBatch.ts +219 -0
  118. package/src/sync/syncFrontier.test.ts +494 -0
  119. package/src/sync/syncPhaseC.test.ts +718 -0
  120. package/src/sync/syncRoutes.test.ts +865 -0
  121. package/src/sync/syncSeqPlugin.ts +730 -0
  122. package/src/sync/syncSocket.test.ts +1440 -0
  123. package/src/sync/types.ts +270 -0
  124. package/src/terrenoApp.ts +37 -17
  125. package/src/tests/bunSetup.ts +8 -0
  126. package/tsconfig.json +4 -4
  127. package/tsconfig.typedoc.json +7 -1
  128. package/dist/__tests__/openApiCompat.test.js +0 -317
  129. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  130. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  131. package/dist/actions.openApi.test.d.ts +0 -1
  132. package/dist/actions.openApi.test.js +0 -253
  133. package/dist/actions.test.d.ts +0 -1
  134. package/dist/actions.test.js +0 -1087
  135. package/dist/api.arrayOperations.test.d.ts +0 -1
  136. package/dist/api.arrayOperations.test.js +0 -878
  137. package/dist/api.asyncHandler.test.d.ts +0 -1
  138. package/dist/api.asyncHandler.test.js +0 -236
  139. package/dist/api.coverage.test.d.ts +0 -1
  140. package/dist/api.coverage.test.js +0 -192
  141. package/dist/api.errorPaths.test.d.ts +0 -1
  142. package/dist/api.errorPaths.test.js +0 -887
  143. package/dist/api.errors.test.d.ts +0 -1
  144. package/dist/api.errors.test.js +0 -185
  145. package/dist/api.hooks.test.d.ts +0 -1
  146. package/dist/api.hooks.test.js +0 -950
  147. package/dist/api.query.test.d.ts +0 -1
  148. package/dist/api.query.test.js +0 -948
  149. package/dist/api.test.d.ts +0 -1
  150. package/dist/api.test.js +0 -2820
  151. package/dist/auth.compile.test.d.ts +0 -1
  152. package/dist/auth.compile.test.js +0 -201
  153. package/dist/auth.coverage.test.d.ts +0 -1
  154. package/dist/auth.coverage.test.js +0 -202
  155. package/dist/auth.test.d.ts +0 -1
  156. package/dist/auth.test.js +0 -2286
  157. package/dist/betterAuth.test.d.ts +0 -1
  158. package/dist/betterAuth.test.js +0 -181
  159. package/dist/betterAuthApp.test.d.ts +0 -1
  160. package/dist/betterAuthApp.test.js +0 -242
  161. package/dist/betterAuthSetup.test.d.ts +0 -1
  162. package/dist/betterAuthSetup.test.js +0 -762
  163. package/dist/config.test.d.ts +0 -1
  164. package/dist/config.test.js +0 -353
  165. package/dist/configuration.test.d.ts +0 -1
  166. package/dist/configuration.test.js +0 -980
  167. package/dist/configurationPlugin.test.d.ts +0 -1
  168. package/dist/configurationPlugin.test.js +0 -827
  169. package/dist/consentApp.test.d.ts +0 -1
  170. package/dist/consentApp.test.js +0 -1411
  171. package/dist/docLoader.test.d.ts +0 -1
  172. package/dist/docLoader.test.js +0 -137
  173. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  174. package/dist/envConfigurationPlugin.test.js +0 -369
  175. package/dist/errors.test.d.ts +0 -1
  176. package/dist/errors.test.js +0 -607
  177. package/dist/expressServer.test.d.ts +0 -1
  178. package/dist/expressServer.test.js +0 -1249
  179. package/dist/githubAuth.test.d.ts +0 -1
  180. package/dist/githubAuth.test.js +0 -1142
  181. package/dist/httpClient.test.d.ts +0 -1
  182. package/dist/httpClient.test.js +0 -1471
  183. package/dist/logger.test.d.ts +0 -1
  184. package/dist/logger.test.js +0 -685
  185. package/dist/middleware.test.d.ts +0 -1
  186. package/dist/middleware.test.js +0 -241
  187. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  189. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  190. package/dist/notifiers/slackNotifier.test.js +0 -297
  191. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  192. package/dist/notifiers/zoomNotifier.test.js +0 -373
  193. package/dist/openApi.test.d.ts +0 -1
  194. package/dist/openApi.test.js +0 -620
  195. package/dist/openApiBuilder.test.d.ts +0 -1
  196. package/dist/openApiBuilder.test.js +0 -599
  197. package/dist/openApiEtag.test.d.ts +0 -1
  198. package/dist/openApiEtag.test.js +0 -86
  199. package/dist/openApiValidator.test.d.ts +0 -1
  200. package/dist/openApiValidator.test.js +0 -795
  201. package/dist/permissions.middleware.test.d.ts +0 -1
  202. package/dist/permissions.middleware.test.js +0 -308
  203. package/dist/permissions.test.d.ts +0 -1
  204. package/dist/permissions.test.js +0 -439
  205. package/dist/plugins.test.d.ts +0 -1
  206. package/dist/plugins.test.js +0 -902
  207. package/dist/populate.test.d.ts +0 -1
  208. package/dist/populate.test.js +0 -370
  209. package/dist/realtime/realtime.test.d.ts +0 -10
  210. package/dist/realtime/realtime.test.js +0 -4213
  211. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  212. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  213. package/dist/requestContext.test.d.ts +0 -1
  214. package/dist/requestContext.test.js +0 -412
  215. package/dist/scriptRunner.test.d.ts +0 -1
  216. package/dist/scriptRunner.test.js +0 -386
  217. package/dist/secretProviders.test.d.ts +0 -1
  218. package/dist/secretProviders.test.js +0 -726
  219. package/dist/syncConsents.test.d.ts +0 -1
  220. package/dist/syncConsents.test.js +0 -522
  221. package/dist/terrenoApp.test.d.ts +0 -1
  222. package/dist/terrenoApp.test.js +0 -489
  223. package/dist/tests/bunSetup.d.ts +0 -1
  224. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  225. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  226. package/dist/tests/testEnv.d.ts +0 -0
  227. package/dist/tests/testEnv.js +0 -6
  228. package/dist/transformers.test.d.ts +0 -1
  229. package/dist/transformers.test.js +0 -423
  230. package/dist/utils.test.d.ts +0 -1
  231. package/dist/utils.test.js +0 -242
  232. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -0,0 +1,705 @@
1
+ /**
2
+ * Transport-agnostic CRUD executors extracted from modelRouter's Express handlers.
3
+ *
4
+ * These run the full write pipeline — method-level and object-level permission checks,
5
+ * the deprecated `transformer.transform`, pre/post hooks, Mongoose validation, population,
6
+ * and soft-delete semantics — without requiring an HTTP request/response. The REST handlers
7
+ * in `api.ts` are thin wrappers over these, and the sync mutation channel
8
+ * (`applySyncMutation`) calls them directly.
9
+ *
10
+ * Hook compatibility: ModelRouterOptions hooks receive an `express.Request`. When an
11
+ * executor is called without `req` (e.g. from the sync channel), a minimal stub object
12
+ * `{user}` is passed instead, cast to `express.Request`. Hooks that only read `req.user`
13
+ * keep working; hooks that read other request properties (headers, params, body) will see
14
+ * `undefined` for those. REST handlers always pass the real request through, so existing
15
+ * behavior over HTTP is unchanged.
16
+ */
17
+ import type express from "express";
18
+ import cloneDeep from "lodash/cloneDeep";
19
+ import {DateTime} from "luxon";
20
+ import type {Document, Model} from "mongoose";
21
+
22
+ import {addPopulateToQuery, type ModelRouterOptions} from "../api";
23
+ import type {User} from "../auth";
24
+ import {loadDocOr404} from "../docLoader";
25
+ import {
26
+ APIError,
27
+ type APIErrorConstructor,
28
+ BadRequestError,
29
+ errorMessage,
30
+ ForbiddenError,
31
+ isAPIError,
32
+ passthroughOrWrap,
33
+ passthroughOrWrapWrite,
34
+ } from "../errors";
35
+ import {checkPermissions} from "../permissions";
36
+ import {transform} from "../transformers";
37
+
38
+ /** A hydrated mongoose document joined with the router's base type. */
39
+ export type ExecutorDoc<T> = Document<unknown, unknown, unknown> & T;
40
+
41
+ /** Result of a successful executor run. */
42
+ export interface ExecutorResult<T> {
43
+ /**
44
+ * The document after the operation completed: the created doc, the saved update, or the
45
+ * deleted doc (tombstoned with `deleted: true` for soft-delete models). Populated per
46
+ * `options.populatePaths` for create/update, matching the REST handlers.
47
+ */
48
+ doc: ExecutorDoc<T>;
49
+ /**
50
+ * C5 (FIX 6): present only when `executeUpdate` was called with
51
+ * `skipPostHooks: true` — the cleaned/transformed update body, needed to
52
+ * run `postUpdate` later via `runPostUpdate`.
53
+ */
54
+ cleanedBody?: Partial<T>;
55
+ /**
56
+ * C5 (FIX 6): present only when `executeUpdate` was called with
57
+ * `skipPostHooks: true` — the pre-update document snapshot, needed to
58
+ * run `postUpdate` later via `runPostUpdate`.
59
+ */
60
+ prevDoc?: T;
61
+ }
62
+
63
+ /**
64
+ * Optimistic-concurrency check for executeUpdate.
65
+ *
66
+ * - `timestamp`: replicates the REST `If-Unmodified-Since` last-write-wins check. The update
67
+ * is rejected with an `ExecutorConflictError` (409) when `ifUnmodifiedSince` is older than
68
+ * the document's `updated` (falling back to `created`) timestamp. An invalid Date throws a
69
+ * 400 "Invalid conflict-detection timestamp" carrying `invalidTimestampDetail` so REST
70
+ * handlers can report which header/body field failed to parse.
71
+ * - `seq`: compares `baseSeq` against the document's `_syncSeq`; any mismatch throws an
72
+ * `ExecutorConflictError` (409) carrying the current server doc and seq.
73
+ *
74
+ * The check runs after `preUpdate` (same as the REST handler) so unauthorized mutations are
75
+ * rejected before document data can leak in a conflict response.
76
+ */
77
+ export type ExecutorConcurrencyCheck =
78
+ | {
79
+ type: "timestamp";
80
+ /** Reject the update if the doc was modified after this instant. */
81
+ ifUnmodifiedSince: Date;
82
+ /** Detail for the 400 error when `ifUnmodifiedSince` is an invalid Date. */
83
+ invalidTimestampDetail?: string;
84
+ }
85
+ | {
86
+ type: "seq";
87
+ /** The `_syncSeq` the client last saw; must match the doc's current `_syncSeq`. */
88
+ baseSeq: number;
89
+ };
90
+
91
+ interface ExecutorConflictErrorConstructor extends APIErrorConstructor {
92
+ conflictType: "timestamp" | "seq";
93
+ doc: unknown;
94
+ serverSeq?: number;
95
+ }
96
+
97
+ /**
98
+ * Thrown by executeUpdate when a concurrency check fails. Carries the current server document
99
+ * (canonical copy) so callers can serialize it into a conflict response: the REST handler
100
+ * turns timestamp conflicts into the legacy 409 `{data, error, message}` body, and the sync
101
+ * mutation channel returns the doc + seq in its conflict nack.
102
+ */
103
+ export class ExecutorConflictError extends APIError {
104
+ /** Which concurrency mode detected the conflict. */
105
+ conflictType: "timestamp" | "seq";
106
+
107
+ /** The current server document at conflict time. */
108
+ doc: unknown;
109
+
110
+ /** The doc's `_syncSeq` at conflict time (seq mode only). */
111
+ serverSeq?: number;
112
+
113
+ constructor({conflictType, doc, serverSeq, ...apiErrorData}: ExecutorConflictErrorConstructor) {
114
+ super(apiErrorData);
115
+ this.conflictType = conflictType;
116
+ this.doc = doc;
117
+ this.serverSeq = serverSeq;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Duck-typed guard for {@link ExecutorConflictError}. The package compiles to ES5, where
123
+ * TypeScript's emit for classes extending built-ins (Error) breaks the prototype chain, so
124
+ * `instanceof` returns false for consumers running the compiled dist (bun running the TS
125
+ * source directly is unaffected — which is why unit/integration tests never caught it).
126
+ * Always use this guard instead of `instanceof ExecutorConflictError`.
127
+ */
128
+ export const isExecutorConflictError = (error: unknown): error is ExecutorConflictError => {
129
+ if (error instanceof ExecutorConflictError) {
130
+ return true;
131
+ }
132
+ const candidate = error as {conflictType?: unknown; status?: unknown; doc?: unknown};
133
+ return (
134
+ !!candidate &&
135
+ typeof candidate === "object" &&
136
+ (candidate.conflictType === "timestamp" || candidate.conflictType === "seq") &&
137
+ candidate.status === 409
138
+ );
139
+ };
140
+
141
+ /**
142
+ * Minimal stand-in for an Express request when executors run outside HTTP. Only `user` is
143
+ * populated — see the module doc comment for the hook compatibility contract.
144
+ */
145
+ const stubRequest = (user?: User): express.Request => ({user}) as unknown as express.Request;
146
+
147
+ /**
148
+ * True for the Mongoose error thrown when an `optimisticConcurrency` save matched no
149
+ * document (its `__v` filter failed) — i.e. another write landed since the load.
150
+ * Name-checked rather than `instanceof` for the same ES5-dist reason as
151
+ * {@link isExecutorConflictError}.
152
+ */
153
+ export const isVersionError = (error: unknown): boolean =>
154
+ (error as {name?: string} | undefined)?.name === "VersionError";
155
+
156
+ /**
157
+ * Re-read the document a version-conflicted save lost to, so the conflict response carries
158
+ * the CURRENT server state (the in-memory instance still holds the caller's rejected
159
+ * edits). Includes tombstones: the winning write may have been a soft delete, and the
160
+ * client needs to learn that too. Returns undefined if the read fails — the caller falls
161
+ * back to its own instance rather than failing the request.
162
+ */
163
+ const reloadDocForConflict = async <T>(
164
+ model: Model<T>,
165
+ id: string
166
+ ): Promise<ExecutorDoc<T> | undefined> => {
167
+ try {
168
+ const found = await model.find({_id: id, deleted: {$in: [true, false]}} as never).limit(1);
169
+ return found[0] as ExecutorDoc<T> | undefined;
170
+ } catch {
171
+ return undefined;
172
+ }
173
+ };
174
+
175
+ /**
176
+ * Create a document through the same pipeline as `POST /`: method-level permissions,
177
+ * `transformer.transform`, `preCreate`, `Model.create` (Mongoose validation), population,
178
+ * and `postCreate`. Throws APIErrors with the same statuses/titles as the REST handler.
179
+ */
180
+ export const executeCreate = async <T>({
181
+ model,
182
+ options,
183
+ user,
184
+ body,
185
+ req,
186
+ skipPostHooks,
187
+ }: {
188
+ model: Model<T>;
189
+ options: ModelRouterOptions<T>;
190
+ user?: User;
191
+ body: unknown;
192
+ /** The real Express request when called over HTTP; hooks receive a `{user}` stub otherwise. */
193
+ req?: express.Request;
194
+ /**
195
+ * C5 (FIX 6): when true, skip the built-in `postCreate` call — the caller
196
+ * (the sync mutation handler) runs it manually AFTER finalizing the
197
+ * idempotency ledger `applied`, so a post-hook throw can never make a
198
+ * committed write look like a failure. REST handlers never set this.
199
+ */
200
+ skipPostHooks?: boolean;
201
+ }): Promise<ExecutorResult<T>> => {
202
+ const request = req ?? stubRequest(user);
203
+
204
+ if (!(await checkPermissions("create", options.permissions.create, user))) {
205
+ throw new APIError({
206
+ status: 405,
207
+ title: `Access to CREATE on ${model.modelName} denied for ${user?.id}`,
208
+ });
209
+ }
210
+
211
+ let cleanedBody: Partial<T> | (Partial<T> | undefined)[] | null | undefined;
212
+ try {
213
+ cleanedBody = transform<T>(options, body as Partial<T> | Partial<T>[], "create", user);
214
+ } catch (error: unknown) {
215
+ throw passthroughOrWrap(error, {
216
+ code: "transform-error",
217
+ status: 400,
218
+ title: "Transform error",
219
+ });
220
+ }
221
+ if (options.preCreate) {
222
+ try {
223
+ cleanedBody = await options.preCreate(cleanedBody, request);
224
+ } catch (error: unknown) {
225
+ throw passthroughOrWrap(error, {
226
+ code: "pre-create-hook-error",
227
+ status: 400,
228
+ title: "preCreate hook error",
229
+ });
230
+ }
231
+ if (cleanedBody === undefined) {
232
+ throw new ForbiddenError({
233
+ code: "create-not-allowed",
234
+ detail: "A body must be returned from preCreate",
235
+ title: "Create not allowed",
236
+ });
237
+ }
238
+ if (cleanedBody === null) {
239
+ throw new ForbiddenError({
240
+ code: "create-not-allowed",
241
+ detail: "preCreate hook returned null",
242
+ title: "Create not allowed",
243
+ });
244
+ }
245
+ }
246
+ if (cleanedBody === undefined) {
247
+ throw new BadRequestError({
248
+ code: "invalid-request-body",
249
+ detail: "Body is undefined",
250
+ title: "Invalid request body",
251
+ });
252
+ }
253
+ let data: ExecutorDoc<T>;
254
+ try {
255
+ data = (await model.create(cleanedBody as T)) as ExecutorDoc<T>;
256
+ } catch (error: unknown) {
257
+ throw passthroughOrWrapWrite(error, {
258
+ code: "create-error",
259
+ status: 400,
260
+ title: "Create error",
261
+ });
262
+ }
263
+
264
+ if (options.populatePaths) {
265
+ try {
266
+ // noExplicitAny: mongoose Query type varies based on populatePaths
267
+ // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
268
+ let populateQuery: any = model.findById(data._id);
269
+ populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
270
+ data = await populateQuery.exec();
271
+ } catch (error: unknown) {
272
+ throw passthroughOrWrap(error, {
273
+ code: "populate-error",
274
+ status: 400,
275
+ title: "Populate error",
276
+ });
277
+ }
278
+ }
279
+
280
+ if (options.postCreate && !skipPostHooks) {
281
+ try {
282
+ await options.postCreate(data, request);
283
+ } catch (error: unknown) {
284
+ throw passthroughOrWrap(error, {
285
+ code: "post-create-hook-error",
286
+ status: 400,
287
+ title: "postCreate hook error",
288
+ });
289
+ }
290
+ }
291
+ return {doc: data};
292
+ };
293
+
294
+ /**
295
+ * C5 (FIX 6): run `postCreate` outside the write transaction/ledger-finalize
296
+ * window. Errors are the caller's responsibility to catch — the sync mutation
297
+ * handler logs them and reports a warning, never converting them into a nack
298
+ * (the document write already committed and the ledger already finalized
299
+ * `applied`).
300
+ */
301
+ export const runPostCreate = async <T>({
302
+ doc,
303
+ options,
304
+ request,
305
+ }: {
306
+ doc: ExecutorDoc<T>;
307
+ options: ModelRouterOptions<T>;
308
+ request: express.Request;
309
+ }): Promise<void> => {
310
+ if (options.postCreate) {
311
+ await options.postCreate(doc, request);
312
+ }
313
+ };
314
+
315
+ /**
316
+ * Update a document through the same pipeline as `PATCH /:id`: method-level and object-level
317
+ * permissions, doc loading (404), `transformer.transform`, `_updatedAt` stripping,
318
+ * `preUpdate`, the optional concurrency check, `doc.set` + `doc.save` (Mongoose validation),
319
+ * population, and `postUpdate`. Throws APIErrors with the same statuses/titles as the REST
320
+ * handler; concurrency conflicts throw `ExecutorConflictError` (409) carrying the server doc.
321
+ */
322
+ export const executeUpdate = async <T>({
323
+ model,
324
+ options,
325
+ user,
326
+ id,
327
+ body,
328
+ concurrencyCheck,
329
+ existingDoc,
330
+ req,
331
+ skipPostHooks,
332
+ }: {
333
+ model: Model<T>;
334
+ options: ModelRouterOptions<T>;
335
+ user?: User;
336
+ id: string;
337
+ body: unknown;
338
+ concurrencyCheck?: ExecutorConcurrencyCheck;
339
+ /**
340
+ * Pre-loaded document, used by the REST handler where permissionMiddleware already loaded
341
+ * and authorized it (avoids a second fetch). Permission checks still run either way.
342
+ */
343
+ existingDoc?: ExecutorDoc<T>;
344
+ /** The real Express request when called over HTTP; hooks receive a `{user}` stub otherwise. */
345
+ req?: express.Request;
346
+ /** C5 (FIX 6): see `executeCreate`'s `skipPostHooks` doc comment. */
347
+ skipPostHooks?: boolean;
348
+ }): Promise<ExecutorResult<T>> => {
349
+ const request = req ?? stubRequest(user);
350
+
351
+ if (!(await checkPermissions("update", options.permissions.update, user))) {
352
+ throw new APIError({
353
+ status: 405,
354
+ title: `Access to UPDATE on ${model.modelName} denied for ${user?.id}`,
355
+ });
356
+ }
357
+
358
+ let doc =
359
+ existingDoc ?? ((await loadDocOr404<T>(model, id, options.populatePaths)) as ExecutorDoc<T>);
360
+
361
+ if (!(await checkPermissions("update", options.permissions.update, user, doc))) {
362
+ throw new APIError({
363
+ status: 403,
364
+ title: `Access to GET on ${model.modelName}:${id} denied for ${user?.id}`,
365
+ });
366
+ }
367
+
368
+ let cleanedBody: Partial<T> | T | null | undefined;
369
+ try {
370
+ cleanedBody = transform<T>(options, body as Partial<T>, "update", user) as Partial<T>;
371
+ } catch (error: unknown) {
372
+ throw passthroughOrWrap(error, {
373
+ code: "transform-error",
374
+ detail: `PATCH failed on ${id} for user ${user?.id}: ${errorMessage(error)}`,
375
+ status: 403,
376
+ title: "PATCH failed",
377
+ });
378
+ }
379
+
380
+ // `_updatedAt` is conflict-detection metadata, not a model field: strip it from both the
381
+ // raw and transformed bodies before preUpdate processes them (mirrors the REST handler).
382
+ if (body && typeof body === "object") {
383
+ delete (body as Record<string, unknown>)._updatedAt;
384
+ }
385
+ if (cleanedBody && typeof cleanedBody === "object") {
386
+ delete (cleanedBody as Record<string, unknown>)._updatedAt;
387
+ }
388
+
389
+ if (options.preUpdate) {
390
+ try {
391
+ cleanedBody = await options.preUpdate(cleanedBody as Partial<T>, request);
392
+ } catch (error: unknown) {
393
+ throw passthroughOrWrap(error, {
394
+ code: "pre-update-hook-error",
395
+ detail: `preUpdate hook error on ${id}: ${errorMessage(error)}`,
396
+ status: 400,
397
+ title: "preUpdate hook error",
398
+ });
399
+ }
400
+ if (cleanedBody === undefined) {
401
+ throw new ForbiddenError({
402
+ code: "update-not-allowed",
403
+ detail: "A body must be returned from preUpdate",
404
+ title: "Update not allowed",
405
+ });
406
+ }
407
+ if (cleanedBody === null) {
408
+ throw new ForbiddenError({
409
+ code: "update-not-allowed",
410
+ detail: `preUpdate hook on ${id} returned null`,
411
+ title: "Update not allowed",
412
+ });
413
+ }
414
+ }
415
+
416
+ // Conflict detection runs after preUpdate so that unauthorized mutations
417
+ // are rejected before we leak document data in a conflict response.
418
+ if (concurrencyCheck?.type === "timestamp") {
419
+ const clientTimestamp = DateTime.fromJSDate(concurrencyCheck.ifUnmodifiedSince);
420
+ if (!clientTimestamp.isValid) {
421
+ throw new APIError({
422
+ detail:
423
+ concurrencyCheck.invalidTimestampDetail ??
424
+ "Conflict-detection timestamp could not be parsed as a date",
425
+ status: 400,
426
+ title: "Invalid conflict-detection timestamp",
427
+ });
428
+ }
429
+
430
+ const docRecord = doc as {created?: Date | string; updated?: Date | string};
431
+ let serverTimestamp: DateTime | null = null;
432
+ const serverTimestampValue = docRecord.updated ?? docRecord.created;
433
+ if (serverTimestampValue instanceof Date) {
434
+ serverTimestamp = DateTime.fromJSDate(serverTimestampValue);
435
+ } else if (typeof serverTimestampValue === "string") {
436
+ serverTimestamp = DateTime.fromISO(serverTimestampValue);
437
+ }
438
+
439
+ if (serverTimestamp && !serverTimestamp.isValid) {
440
+ throw new APIError({
441
+ detail: "Document timestamp could not be parsed as a date",
442
+ status: 400,
443
+ title: "Invalid server timestamp",
444
+ });
445
+ }
446
+
447
+ if (serverTimestamp && clientTimestamp < serverTimestamp) {
448
+ throw new ExecutorConflictError({
449
+ conflictType: "timestamp",
450
+ detail: "Document was modified since your last read",
451
+ disableExternalErrorTracking: true,
452
+ doc,
453
+ status: 409,
454
+ title: "Conflict",
455
+ });
456
+ }
457
+ } else if (concurrencyCheck?.type === "seq") {
458
+ const serverSeq = (doc as {_syncSeq?: number})._syncSeq ?? 0;
459
+ if (concurrencyCheck.baseSeq !== serverSeq) {
460
+ throw new ExecutorConflictError({
461
+ conflictType: "seq",
462
+ detail: "Document was modified since your last read",
463
+ disableExternalErrorTracking: true,
464
+ doc,
465
+ serverSeq,
466
+ status: 409,
467
+ title: `Sync conflict on ${model.modelName}:${id}: baseSeq ${concurrencyCheck.baseSeq} does not match server seq ${serverSeq}`,
468
+ });
469
+ }
470
+ }
471
+
472
+ // Make a copy for passing pre-saved values to hooks.
473
+ const prevDoc = cloneDeep(doc);
474
+
475
+ // Using .save here runs the risk of a versioning error if you try to make two simultaneous
476
+ // updates. We won't wind up with corrupted data, just an API error.
477
+ try {
478
+ doc.set(cleanedBody);
479
+ await doc.save();
480
+ } catch (error: unknown) {
481
+ // Task 9.13: `syncPlugin` enables Mongoose `optimisticConcurrency` on synced schemas, so
482
+ // this save is conditional on the `__v` the document was loaded at. A concurrent write
483
+ // that landed between the seq check above and this save therefore throws a VersionError
484
+ // instead of silently overwriting it — the same lost update the seq check exists to
485
+ // prevent, just detected at write time. Report it as the conflict the seq check would
486
+ // have produced had the other write landed a moment earlier.
487
+ if (concurrencyCheck?.type === "seq" && isVersionError(error)) {
488
+ const current = await reloadDocForConflict(model, id);
489
+ const serverSeq = (current as {_syncSeq?: number} | undefined)?._syncSeq ?? 0;
490
+ throw new ExecutorConflictError({
491
+ conflictType: "seq",
492
+ detail: "Document was modified since your last read",
493
+ disableExternalErrorTracking: true,
494
+ doc: current ?? doc,
495
+ serverSeq,
496
+ status: 409,
497
+ title: `Sync conflict on ${model.modelName}:${id}: a concurrent write landed while this update was in flight (baseSeq ${concurrencyCheck.baseSeq})`,
498
+ });
499
+ }
500
+ throw passthroughOrWrapWrite(error, {
501
+ code: "update-save-error",
502
+ detail: `preUpdate hook save error on ${id}: ${errorMessage(error)}`,
503
+ status: 400,
504
+ title: "preUpdate hook save error",
505
+ });
506
+ }
507
+
508
+ if (options.populatePaths) {
509
+ // noExplicitAny: mongoose Query type varies based on populatePaths
510
+ // biome-ignore lint/suspicious/noExplicitAny: mongoose Query type varies based on populatePaths
511
+ let populateQuery: any = model.findById(doc._id);
512
+ populateQuery = addPopulateToQuery(populateQuery, options.populatePaths);
513
+ doc = await populateQuery.exec();
514
+ }
515
+
516
+ if (options.postUpdate && !skipPostHooks) {
517
+ try {
518
+ await options.postUpdate(doc, cleanedBody as Partial<T>, request, prevDoc as T);
519
+ } catch (error: unknown) {
520
+ throw passthroughOrWrap(error, {
521
+ code: "post-update-hook-error",
522
+ detail: `postUpdate hook error on ${id}: ${errorMessage(error)}`,
523
+ status: 400,
524
+ title: "postUpdate hook error",
525
+ });
526
+ }
527
+ }
528
+
529
+ return {cleanedBody: cleanedBody as Partial<T>, doc, prevDoc: prevDoc as T};
530
+ };
531
+
532
+ /** C5 (FIX 6): run `postUpdate` outside the write/ledger-finalize window — see `runPostCreate`. */
533
+ export const runPostUpdate = async <T>({
534
+ doc,
535
+ cleanedBody,
536
+ prevDoc,
537
+ options,
538
+ request,
539
+ }: {
540
+ doc: ExecutorDoc<T>;
541
+ cleanedBody: Partial<T>;
542
+ prevDoc: T;
543
+ options: ModelRouterOptions<T>;
544
+ request: express.Request;
545
+ }): Promise<void> => {
546
+ if (options.postUpdate) {
547
+ await options.postUpdate(doc, cleanedBody, request, prevDoc);
548
+ }
549
+ };
550
+
551
+ /**
552
+ * Delete a document through the same pipeline as `DELETE /:id`: method-level and object-level
553
+ * permissions, doc loading (404), `preDelete`, soft delete (`deleted = true` + save when the
554
+ * schema has a Boolean `deleted` path, else `doc.deleteOne()`), and `postDelete`. Throws
555
+ * APIErrors with the same statuses/titles as the REST handler.
556
+ */
557
+ export const executeDelete = async <T>({
558
+ model,
559
+ options,
560
+ user,
561
+ id,
562
+ existingDoc,
563
+ req,
564
+ skipPostHooks,
565
+ }: {
566
+ model: Model<T>;
567
+ options: ModelRouterOptions<T>;
568
+ user?: User;
569
+ id: string;
570
+ /**
571
+ * Pre-loaded document, used by the REST handler where permissionMiddleware already loaded
572
+ * and authorized it (avoids a second fetch). Permission checks still run either way.
573
+ */
574
+ existingDoc?: ExecutorDoc<T> & {deleted?: boolean};
575
+ /** The real Express request when called over HTTP; hooks receive a `{user}` stub otherwise. */
576
+ req?: express.Request;
577
+ /** C5 (FIX 6): see `executeCreate`'s `skipPostHooks` doc comment. */
578
+ skipPostHooks?: boolean;
579
+ }): Promise<ExecutorResult<T>> => {
580
+ const request = req ?? stubRequest(user);
581
+
582
+ if (!(await checkPermissions("delete", options.permissions.delete, user))) {
583
+ throw new APIError({
584
+ status: 405,
585
+ title: `Access to DELETE on ${model.modelName} denied for ${user?.id}`,
586
+ });
587
+ }
588
+
589
+ // C8: delete of an already-deleted doc is idempotent — loadDocOr404 auto-filters
590
+ // soft-deleted docs and would 404 (a `validation` nack over sync). Load the tombstone
591
+ // directly and return it as an idempotent success (its existing seq) instead.
592
+ let doc = existingDoc;
593
+ if (!doc) {
594
+ try {
595
+ doc = (await loadDocOr404<T>(model, id, options.populatePaths)) as ExecutorDoc<T> & {
596
+ deleted?: boolean;
597
+ };
598
+ } catch (error: unknown) {
599
+ const alreadyDeleted =
600
+ isAPIError(error) &&
601
+ error.status === 404 &&
602
+ (error.meta as {deleted?: string} | undefined)?.deleted === "true";
603
+ if (alreadyDeleted) {
604
+ // Hydrate the tombstone bypassing the isDeletedPlugin find filter.
605
+ const tombstone = await model.find({_id: id, deleted: {$in: [true, false]}}).limit(1);
606
+ const resolved = tombstone[0] as ExecutorDoc<T> & {deleted?: boolean};
607
+ if (!resolved) {
608
+ throw error;
609
+ }
610
+ if (!(await checkPermissions("delete", options.permissions.delete, user, resolved))) {
611
+ throw new APIError({
612
+ status: 403,
613
+ title: `Access to GET on ${model.modelName}:${id} denied for ${user?.id}`,
614
+ });
615
+ }
616
+ return {doc: resolved};
617
+ }
618
+ throw error;
619
+ }
620
+ }
621
+
622
+ if (!(await checkPermissions("delete", options.permissions.delete, user, doc))) {
623
+ throw new APIError({
624
+ status: 403,
625
+ title: `Access to GET on ${model.modelName}:${id} denied for ${user?.id}`,
626
+ });
627
+ }
628
+
629
+ if (options.preDelete) {
630
+ let body: T | null | undefined;
631
+ try {
632
+ body = await options.preDelete(doc, request);
633
+ } catch (error: unknown) {
634
+ throw passthroughOrWrap(error, {
635
+ code: "pre-delete-hook-error",
636
+ detail: `preDelete hook error on ${id}: ${errorMessage(error)}`,
637
+ status: 403,
638
+ title: "preDelete hook error",
639
+ });
640
+ }
641
+ if (body === undefined) {
642
+ throw new ForbiddenError({
643
+ code: "delete-not-allowed",
644
+ detail: "A body must be returned from preDelete",
645
+ title: "Delete not allowed",
646
+ });
647
+ }
648
+ if (body === null) {
649
+ throw new ForbiddenError({
650
+ code: "delete-not-allowed",
651
+ detail: `preDelete hook for ${id} returned null`,
652
+ title: "Delete not allowed",
653
+ });
654
+ }
655
+ }
656
+
657
+ // Support .deleted from isDeleted plugin
658
+ if (
659
+ Object.keys(model.schema.paths).includes("deleted") &&
660
+ model.schema.paths.deleted.instance === "Boolean"
661
+ ) {
662
+ doc.deleted = true;
663
+ await doc.save();
664
+ } else {
665
+ // For models without the isDeleted plugin
666
+ try {
667
+ await doc.deleteOne();
668
+ } catch (error: unknown) {
669
+ throw passthroughOrWrap(error, {
670
+ code: "delete-error",
671
+ status: 400,
672
+ title: "Delete error",
673
+ });
674
+ }
675
+ }
676
+
677
+ if (options.postDelete && !skipPostHooks) {
678
+ try {
679
+ await options.postDelete(request, doc);
680
+ } catch (error: unknown) {
681
+ throw passthroughOrWrap(error, {
682
+ code: "post-delete-hook-error",
683
+ status: 400,
684
+ title: "postDelete hook error",
685
+ });
686
+ }
687
+ }
688
+
689
+ return {doc};
690
+ };
691
+
692
+ /** C5 (FIX 6): run `postDelete` outside the write/ledger-finalize window — see `runPostCreate`. */
693
+ export const runPostDelete = async <T>({
694
+ doc,
695
+ options,
696
+ request,
697
+ }: {
698
+ doc: ExecutorDoc<T>;
699
+ options: ModelRouterOptions<T>;
700
+ request: express.Request;
701
+ }): Promise<void> => {
702
+ if (options.postDelete) {
703
+ await options.postDelete(request, doc);
704
+ }
705
+ };