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