@terreno/api 57.2.0 → 57.4.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 (472) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +23 -10
  2. package/README.md +23 -7
  3. package/dist/actions.js +19 -7
  4. package/dist/adminTypes.d.ts +7 -0
  5. package/dist/adminTypes.js +6 -1
  6. package/dist/api.d.ts +14 -0
  7. package/dist/api.js +111 -60
  8. package/dist/audit/auditApp.d.ts +30 -0
  9. package/dist/audit/auditApp.js +155 -0
  10. package/dist/audit/auditEventModel.d.ts +29 -0
  11. package/dist/audit/auditEventModel.js +102 -0
  12. package/dist/audit/cloudTasksEnqueue.d.ts +32 -0
  13. package/dist/audit/cloudTasksEnqueue.js +162 -0
  14. package/dist/audit/diff.d.ts +10 -0
  15. package/dist/audit/diff.js +230 -0
  16. package/dist/audit/processQueue.d.ts +6 -0
  17. package/dist/audit/processQueue.js +101 -0
  18. package/dist/audit/rbacSink.d.ts +2 -0
  19. package/dist/audit/rbacSink.js +82 -0
  20. package/dist/audit/record.d.ts +56 -0
  21. package/dist/audit/record.js +373 -0
  22. package/dist/auth.d.ts +23 -10
  23. package/dist/auth.js +97 -32
  24. package/dist/authRecovery.d.ts +5 -0
  25. package/dist/authRecovery.js +350 -0
  26. package/dist/authTokens.d.ts +8 -0
  27. package/dist/authTokens.js +162 -0
  28. package/dist/betterAuth.d.ts +39 -0
  29. package/dist/betterAuthApp.d.ts +4 -0
  30. package/dist/betterAuthApp.js +26 -8
  31. package/dist/betterAuthSetup.d.ts +44 -2
  32. package/dist/betterAuthSetup.js +288 -18
  33. package/dist/collectionRegistry.d.ts +40 -0
  34. package/dist/collectionRegistry.js +97 -0
  35. package/dist/configurationApp.d.ts +11 -2
  36. package/dist/configurationApp.js +2 -4
  37. package/dist/docLoader.js +35 -6
  38. package/dist/expressServer.d.ts +26 -3
  39. package/dist/expressServer.js +79 -11
  40. package/dist/index.d.ts +42 -1
  41. package/dist/index.js +84 -2
  42. package/dist/mcp/auth.d.ts +1 -0
  43. package/dist/mcp/auth.js +47 -25
  44. package/dist/mcp/handlers.d.ts +1 -1
  45. package/dist/mcp/handlers.js +67 -233
  46. package/dist/mcp/query.d.ts +2 -15
  47. package/dist/mcp/query.js +8 -8
  48. package/dist/mcp/registry.d.ts +1 -5
  49. package/dist/mcp/registry.js +31 -20
  50. package/dist/mcp/schemaGenerator.d.ts +2 -7
  51. package/dist/mcp/schemaGenerator.js +41 -116
  52. package/dist/mcp/server.d.ts +1 -0
  53. package/dist/mcp/server.js +1 -0
  54. package/dist/mcp/serviceTokens.d.ts +16 -0
  55. package/dist/mcp/serviceTokens.js +345 -0
  56. package/dist/mcp/types.d.ts +2 -2
  57. package/dist/migrations/fixtures/all-down/20260910120000-one.d.ts +4 -0
  58. package/dist/migrations/fixtures/all-down/20260910120000-one.js +49 -0
  59. package/dist/migrations/fixtures/all-down/20260910120001-two.d.ts +4 -0
  60. package/dist/migrations/fixtures/all-down/20260910120001-two.js +49 -0
  61. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.d.ts +3 -0
  62. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +45 -0
  63. package/dist/migrations/fixtures/bad-name/not-a-migration.d.ts +3 -0
  64. package/dist/migrations/fixtures/bad-name/not-a-migration.js +45 -0
  65. package/dist/migrations/fixtures/missing-up/20260910120000-noup.d.ts +2 -0
  66. package/dist/migrations/fixtures/missing-up/20260910120000-noup.js +5 -0
  67. package/dist/migrations/fixtures/valid/20260910120000-alpha.d.ts +3 -0
  68. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +45 -0
  69. package/dist/migrations/fixtures/valid/20260910120001-beta.d.ts +4 -0
  70. package/dist/migrations/fixtures/valid/20260910120001-beta.js +49 -0
  71. package/dist/migrations/generate.d.ts +17 -0
  72. package/dist/migrations/generate.js +277 -0
  73. package/dist/migrations/load.d.ts +20 -0
  74. package/dist/migrations/load.js +236 -0
  75. package/dist/migrations/lock.d.ts +13 -0
  76. package/dist/migrations/lock.js +145 -0
  77. package/dist/migrations/runner.d.ts +42 -0
  78. package/dist/migrations/runner.js +503 -0
  79. package/dist/migrations/schemaCatalog.d.ts +44 -0
  80. package/dist/migrations/schemaCatalog.js +326 -0
  81. package/dist/migrations/types.d.ts +87 -0
  82. package/dist/migrations/types.js +7 -0
  83. package/dist/models/mcpServiceToken.d.ts +3 -0
  84. package/dist/models/mcpServiceToken.js +208 -0
  85. package/dist/models/notification.d.ts +2 -0
  86. package/dist/models/notification.js +62 -0
  87. package/dist/models/notificationPreference.d.ts +2 -0
  88. package/dist/models/notificationPreference.js +49 -0
  89. package/dist/notifications/notificationService.d.ts +40 -0
  90. package/dist/notifications/notificationService.js +323 -0
  91. package/dist/notifications/notificationsApp.d.ts +18 -0
  92. package/dist/notifications/notificationsApp.js +250 -0
  93. package/dist/notifications/notificationsBeforeSend.d.ts +14 -0
  94. package/dist/notifications/notificationsBeforeSend.js +77 -0
  95. package/dist/openApi.d.ts +1 -7
  96. package/dist/openApi.js +7 -6
  97. package/dist/openApiBuilder.d.ts +19 -7
  98. package/dist/openApiBuilder.js +61 -8
  99. package/dist/openApiCompat.js +1 -1
  100. package/dist/openApiValidator.d.ts +13 -1
  101. package/dist/openApiValidator.js +200 -38
  102. package/dist/orgs/orgContext.d.ts +23 -0
  103. package/dist/orgs/orgContext.js +198 -0
  104. package/dist/orgs/orgPermissions.d.ts +4 -0
  105. package/dist/orgs/orgPermissions.js +77 -0
  106. package/dist/orgs/orgPlugin.d.ts +13 -0
  107. package/dist/orgs/orgPlugin.js +84 -0
  108. package/dist/orgs/organizationModel.d.ts +13 -0
  109. package/dist/orgs/organizationModel.js +301 -0
  110. package/dist/orgs/organizationSettings.d.ts +19 -0
  111. package/dist/orgs/organizationSettings.js +120 -0
  112. package/dist/orgs/orgsApp.d.ts +28 -0
  113. package/dist/orgs/orgsApp.js +678 -0
  114. package/dist/permissions.d.ts +7 -13
  115. package/dist/permissions.js +8 -31
  116. package/dist/plugins.d.ts +14 -1
  117. package/dist/plugins.js +17 -6
  118. package/dist/populate.d.ts +2 -2
  119. package/dist/populate.js +47 -42
  120. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  121. package/dist/rateLimit/applyTrustProxy.js +17 -0
  122. package/dist/rateLimit/createStore.d.ts +2 -0
  123. package/dist/rateLimit/createStore.js +28 -0
  124. package/dist/rateLimit/memoryStore.d.ts +2 -0
  125. package/dist/rateLimit/memoryStore.js +108 -0
  126. package/dist/rateLimit/middleware.d.ts +3 -0
  127. package/dist/rateLimit/middleware.js +109 -0
  128. package/dist/rateLimit/mongoStore.d.ts +4 -0
  129. package/dist/rateLimit/mongoStore.js +123 -0
  130. package/dist/rateLimit/policies.d.ts +10 -0
  131. package/dist/rateLimit/policies.js +149 -0
  132. package/dist/rateLimit/redisStore.d.ts +4 -0
  133. package/dist/rateLimit/redisStore.js +156 -0
  134. package/dist/rateLimit/types.d.ts +54 -0
  135. package/dist/rateLimit/types.js +9 -0
  136. package/dist/rbac/access.js +35 -14
  137. package/dist/rbac/assertAllowed.d.ts +9 -0
  138. package/dist/rbac/assertAllowed.js +182 -0
  139. package/dist/rbac/membershipOrgAdminSource.d.ts +6 -0
  140. package/dist/rbac/membershipOrgAdminSource.js +122 -0
  141. package/dist/rbac/modelRouterAccess.d.ts +4 -0
  142. package/dist/rbac/modelRouterAccess.js +11 -4
  143. package/dist/rbac/permissionUtils.js +3 -2
  144. package/dist/rbac/resolve.js +65 -35
  145. package/dist/rbac/roleModel.d.ts +2 -5
  146. package/dist/rbac/roleModel.js +18 -4
  147. package/dist/rbac/routes.js +15 -6
  148. package/dist/rbac/statements.d.ts +10 -1
  149. package/dist/rbac/statements.js +19 -2
  150. package/dist/rbac/types.d.ts +5 -0
  151. package/dist/realtime/changeStreamWatcher.d.ts +10 -4
  152. package/dist/realtime/changeStreamWatcher.js +110 -64
  153. package/dist/realtime/deprecation.d.ts +13 -0
  154. package/dist/realtime/deprecation.js +33 -0
  155. package/dist/realtime/realtimeApp.d.ts +2 -1
  156. package/dist/realtime/realtimeApp.js +11 -11
  157. package/dist/realtime/registry.d.ts +0 -31
  158. package/dist/realtime/registry.js +44 -31
  159. package/dist/realtime/socketAuth.d.ts +5 -5
  160. package/dist/realtime/socketAuth.js +11 -1
  161. package/dist/realtime/socketUser.d.ts +5 -1
  162. package/dist/realtime/types.d.ts +14 -4
  163. package/dist/schemaMetadata.d.ts +56 -0
  164. package/dist/schemaMetadata.js +524 -0
  165. package/dist/seedRunner.d.ts +88 -0
  166. package/dist/seedRunner.js +627 -0
  167. package/dist/sync/adminBroadcastScope.d.ts +40 -0
  168. package/dist/sync/adminBroadcastScope.js +194 -0
  169. package/dist/sync/adminWindowAccess.d.ts +13 -0
  170. package/dist/sync/adminWindowAccess.js +96 -0
  171. package/dist/sync/adminWindowMutation.d.ts +88 -0
  172. package/dist/sync/adminWindowMutation.js +247 -0
  173. package/dist/sync/executors.d.ts +19 -3
  174. package/dist/sync/executors.js +194 -165
  175. package/dist/sync/loadHarness.js +28 -19
  176. package/dist/sync/models.js +26 -24
  177. package/dist/sync/mutationHandler.d.ts +14 -2
  178. package/dist/sync/mutationHandler.js +201 -76
  179. package/dist/sync/registrationSideEffects.d.ts +35 -0
  180. package/dist/sync/registrationSideEffects.js +151 -0
  181. package/dist/sync/registry.d.ts +2 -52
  182. package/dist/sync/registry.js +42 -187
  183. package/dist/sync/routes.d.ts +13 -0
  184. package/dist/sync/routes.js +116 -58
  185. package/dist/sync/scripts/compactTombstones.js +0 -2
  186. package/dist/sync/socketHandlers.d.ts +8 -2
  187. package/dist/sync/socketHandlers.js +144 -50
  188. package/dist/sync/streams.d.ts +2 -0
  189. package/dist/sync/streams.js +7 -1
  190. package/dist/sync/syncApp.d.ts +4 -3
  191. package/dist/sync/syncApp.js +5 -4
  192. package/dist/sync/syncBatch.d.ts +5 -2
  193. package/dist/sync/syncBatch.js +7 -6
  194. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  195. package/dist/sync/syncSeqPlugin.js +20 -16
  196. package/dist/sync/types.d.ts +18 -0
  197. package/dist/terrenoApp.d.ts +48 -5
  198. package/dist/terrenoApp.js +157 -72
  199. package/dist/tests/createTestData.d.ts +1 -3
  200. package/dist/tests/createTestData.js +3 -5
  201. package/dist/tests/models.d.ts +3 -0
  202. package/dist/tests/models.js +15 -2
  203. package/dist/tests/testHelper.d.ts +0 -5
  204. package/dist/tests/testHelper.js +2 -9
  205. package/dist/types/authToken.d.ts +33 -0
  206. package/dist/types/authToken.js +2 -0
  207. package/dist/types/mcpServiceToken.d.ts +41 -0
  208. package/dist/types/mcpServiceToken.js +2 -0
  209. package/dist/types/membership.d.ts +23 -0
  210. package/dist/types/membership.js +2 -0
  211. package/dist/types/notification.d.ts +28 -0
  212. package/dist/types/notification.js +2 -0
  213. package/dist/types/notificationPreference.d.ts +20 -0
  214. package/dist/types/notificationPreference.js +2 -0
  215. package/dist/types/organization.d.ts +36 -0
  216. package/dist/types/organization.js +2 -0
  217. package/dist/webhooks/headerValue.d.ts +2 -0
  218. package/dist/webhooks/headerValue.js +14 -0
  219. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  220. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  221. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  222. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  223. package/dist/webhooks/idempotency/webhookReceipt.d.ts +17 -0
  224. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  225. package/dist/webhooks/rawBody.d.ts +15 -0
  226. package/dist/webhooks/rawBody.js +23 -0
  227. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  228. package/dist/webhooks/timingSafeEqual.js +17 -0
  229. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  230. package/dist/webhooks/verifiers/hmac.js +49 -0
  231. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  232. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  233. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  234. package/dist/webhooks/verifiers/stripe.js +99 -0
  235. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  236. package/dist/webhooks/verifiers/twilio.js +112 -0
  237. package/dist/webhooks/webhooksApp.d.ts +33 -0
  238. package/dist/webhooks/webhooksApp.js +195 -0
  239. package/package.json +32 -27
  240. package/src/__snapshots__/openApi.test.ts.snap +444 -36
  241. package/src/__snapshots__/openApiBuilder.test.ts.snap +24 -24
  242. package/src/__snapshots__/schemaMetadata.test.ts.snap +196 -0
  243. package/src/actions.ts +20 -13
  244. package/src/adminModelRouter.test.ts +133 -0
  245. package/src/adminTypes.ts +8 -0
  246. package/src/api.arrayOperations.test.ts +43 -31
  247. package/src/api.hooks.test.ts +38 -29
  248. package/src/api.query.test.ts +31 -31
  249. package/src/api.test.ts +133 -97
  250. package/src/api.ts +84 -27
  251. package/src/audit/auditApp.test.ts +243 -0
  252. package/src/audit/auditApp.ts +139 -0
  253. package/src/audit/auditEventModel.ts +156 -0
  254. package/src/audit/auditRouter.test.ts +456 -0
  255. package/src/audit/cloudTasksEnqueue.test.ts +124 -0
  256. package/src/audit/cloudTasksEnqueue.ts +104 -0
  257. package/src/audit/diff.ts +163 -0
  258. package/src/audit/processQueue.ts +69 -0
  259. package/src/audit/rbacSink.test.ts +86 -0
  260. package/src/audit/rbacSink.ts +42 -0
  261. package/src/audit/record.test.ts +402 -0
  262. package/src/audit/record.ts +328 -0
  263. package/src/auth.test.ts +108 -52
  264. package/src/auth.ts +98 -29
  265. package/src/authRecovery.test.ts +281 -0
  266. package/src/authRecovery.ts +279 -0
  267. package/src/authTokens.test.ts +94 -0
  268. package/src/authTokens.ts +118 -0
  269. package/src/authVerification.test.ts +293 -0
  270. package/src/betterAuth.ts +31 -0
  271. package/src/betterAuthApp.test.ts +1 -0
  272. package/src/betterAuthApp.ts +27 -9
  273. package/src/betterAuthSetup.test.ts +595 -38
  274. package/src/betterAuthSetup.ts +261 -5
  275. package/src/collectionRegistry.test.ts +164 -0
  276. package/src/collectionRegistry.ts +135 -0
  277. package/src/configurationApp.ts +13 -7
  278. package/src/docLoader.test.ts +45 -1
  279. package/src/docLoader.ts +37 -6
  280. package/src/express.d.ts +3 -0
  281. package/src/expressServer.test.ts +180 -68
  282. package/src/expressServer.ts +75 -19
  283. package/src/githubAuth.test.ts +60 -55
  284. package/src/index.ts +127 -0
  285. package/src/mcp/auth.test.ts +47 -0
  286. package/src/mcp/auth.ts +32 -11
  287. package/src/mcp/handlers.test.ts +275 -0
  288. package/src/mcp/handlers.ts +45 -172
  289. package/src/mcp/integration.test.ts +59 -9
  290. package/src/mcp/query.ts +5 -7
  291. package/src/mcp/registry.ts +29 -20
  292. package/src/mcp/schemaGenerator.test.ts +8 -0
  293. package/src/mcp/schemaGenerator.ts +49 -131
  294. package/src/mcp/server.ts +2 -0
  295. package/src/mcp/serviceTokens.test.ts +330 -0
  296. package/src/mcp/serviceTokens.ts +307 -0
  297. package/src/mcp/toolGenerator.test.ts +82 -1
  298. package/src/mcp/types.ts +2 -6
  299. package/src/migrations/cli.test.ts +376 -0
  300. package/src/migrations/cli.ts +283 -0
  301. package/src/migrations/fixtures/all-down/20260910120000-one.ts +6 -0
  302. package/src/migrations/fixtures/all-down/20260910120001-two.ts +6 -0
  303. package/src/migrations/fixtures/bad-id/20260910120000-mismatch.ts +4 -0
  304. package/src/migrations/fixtures/bad-name/not-a-migration.ts +4 -0
  305. package/src/migrations/fixtures/missing-up/20260910120000-noup.ts +2 -0
  306. package/src/migrations/fixtures/valid/20260910120000-alpha.ts +4 -0
  307. package/src/migrations/fixtures/valid/20260910120001-beta.ts +6 -0
  308. package/src/migrations/generate.test.ts +333 -0
  309. package/src/migrations/generate.ts +216 -0
  310. package/src/migrations/load.test.ts +103 -0
  311. package/src/migrations/load.ts +124 -0
  312. package/src/migrations/lock.test.ts +133 -0
  313. package/src/migrations/lock.ts +118 -0
  314. package/src/migrations/runner.test.ts +504 -0
  315. package/src/migrations/runner.ts +358 -0
  316. package/src/migrations/schemaCatalog.test.ts +159 -0
  317. package/src/migrations/schemaCatalog.ts +262 -0
  318. package/src/migrations/types.ts +94 -0
  319. package/src/models/mcpServiceToken.test.ts +129 -0
  320. package/src/models/mcpServiceToken.ts +158 -0
  321. package/src/models/notification.ts +68 -0
  322. package/src/models/notificationPreference.ts +62 -0
  323. package/src/notifications/notificationService.ts +254 -0
  324. package/src/notifications/notificationsApp.test.ts +505 -0
  325. package/src/notifications/notificationsApp.ts +200 -0
  326. package/src/notifications/notificationsBeforeSend.ts +51 -0
  327. package/src/openApi.test.ts +80 -65
  328. package/src/openApi.ts +2 -1
  329. package/src/openApiBuilder.test.ts +95 -7
  330. package/src/openApiBuilder.ts +60 -12
  331. package/src/openApiCompat.ts +1 -1
  332. package/src/openApiValidator.test.ts +270 -56
  333. package/src/openApiValidator.ts +219 -36
  334. package/src/orgs/orgAccessOptIn.test.ts +87 -0
  335. package/src/orgs/orgContext.test.ts +259 -0
  336. package/src/orgs/orgContext.ts +151 -0
  337. package/src/orgs/orgPermissions.test.ts +105 -0
  338. package/src/orgs/orgPermissions.ts +40 -0
  339. package/src/orgs/orgPlugin.test.ts +130 -0
  340. package/src/orgs/orgPlugin.ts +70 -0
  341. package/src/orgs/orgRbac.test.ts +267 -0
  342. package/src/orgs/orgSecurityDefects.test.ts +415 -0
  343. package/src/orgs/organizationModel.test.ts +205 -0
  344. package/src/orgs/organizationModel.ts +257 -0
  345. package/src/orgs/organizationSettings.test.ts +113 -0
  346. package/src/orgs/organizationSettings.ts +126 -0
  347. package/src/orgs/orgsApp.test.ts +382 -0
  348. package/src/orgs/orgsApp.ts +563 -0
  349. package/src/permissions.test.ts +62 -36
  350. package/src/permissions.ts +8 -30
  351. package/src/plugins.test.ts +14 -0
  352. package/src/plugins.ts +34 -9
  353. package/src/populate.test.ts +34 -0
  354. package/src/populate.ts +40 -29
  355. package/src/rateLimit/applyTrustProxy.ts +17 -0
  356. package/src/rateLimit/createStore.ts +25 -0
  357. package/src/rateLimit/memoryStore.ts +40 -0
  358. package/src/rateLimit/middleware.ts +79 -0
  359. package/src/rateLimit/mongoStore.test.ts +80 -0
  360. package/src/rateLimit/mongoStore.ts +77 -0
  361. package/src/rateLimit/policies.ts +130 -0
  362. package/src/rateLimit/rateLimit.test.ts +328 -0
  363. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  364. package/src/rateLimit/redisStore.test.ts +114 -0
  365. package/src/rateLimit/redisStore.ts +86 -0
  366. package/src/rateLimit/types.ts +64 -0
  367. package/src/rbac/access.ts +16 -4
  368. package/src/rbac/assertAllowed.test.ts +325 -0
  369. package/src/rbac/assertAllowed.ts +157 -0
  370. package/src/rbac/backfillAdmins.test.ts +124 -0
  371. package/src/rbac/fieldViews.test.ts +89 -0
  372. package/src/rbac/membershipOrgAdminSource.ts +59 -0
  373. package/src/rbac/modelRouterAccess.test.ts +126 -0
  374. package/src/rbac/modelRouterAccess.ts +8 -2
  375. package/src/rbac/permissionUtils.test.ts +26 -5
  376. package/src/rbac/permissionUtils.ts +3 -2
  377. package/src/rbac/realtimeAccess.test.ts +109 -1
  378. package/src/rbac/resolve.test.ts +34 -2
  379. package/src/rbac/resolve.ts +31 -11
  380. package/src/rbac/roleManager.test.ts +169 -0
  381. package/src/rbac/roleModel.test.ts +34 -1
  382. package/src/rbac/roleModel.ts +17 -1
  383. package/src/rbac/routes.test.ts +233 -0
  384. package/src/rbac/routes.ts +16 -6
  385. package/src/rbac/statements.test.ts +19 -0
  386. package/src/rbac/statements.ts +19 -1
  387. package/src/rbac/types.ts +5 -0
  388. package/src/realtime/changeStreamWatcher.ts +73 -33
  389. package/src/realtime/deprecation.test.ts +60 -0
  390. package/src/realtime/deprecation.ts +33 -0
  391. package/src/realtime/realtime.test.ts +365 -189
  392. package/src/realtime/realtimeApp.ts +11 -11
  393. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  394. package/src/realtime/registry.ts +48 -42
  395. package/src/realtime/sessionRevalidation.test.ts +57 -44
  396. package/src/realtime/socketAuth.test.ts +75 -23
  397. package/src/realtime/socketAuth.ts +17 -6
  398. package/src/realtime/socketUser.ts +5 -3
  399. package/src/realtime/types.ts +14 -4
  400. package/src/schemaMetadata.test.ts +419 -0
  401. package/src/schemaMetadata.ts +593 -0
  402. package/src/scrubAdminFields.test.ts +105 -0
  403. package/src/seedRunner.test.ts +591 -0
  404. package/src/seedRunner.ts +464 -0
  405. package/src/sync/adminBroadcastConfig.test.ts +96 -0
  406. package/src/sync/adminBroadcastScope.test.ts +155 -0
  407. package/src/sync/adminBroadcastScope.ts +123 -0
  408. package/src/sync/adminWindowAccess.test.ts +57 -0
  409. package/src/sync/adminWindowAccess.ts +32 -0
  410. package/src/sync/adminWindowMutation.test.ts +450 -0
  411. package/src/sync/adminWindowMutation.ts +283 -0
  412. package/src/sync/docMatchesMutationData.test.ts +16 -0
  413. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  414. package/src/sync/executors.test.ts +40 -0
  415. package/src/sync/executors.ts +57 -18
  416. package/src/sync/integration.test.ts +15 -7
  417. package/src/sync/loadHarness.ts +28 -19
  418. package/src/sync/models.ts +32 -18
  419. package/src/sync/mutationHandler.test.ts +293 -17
  420. package/src/sync/mutationHandler.ts +180 -36
  421. package/src/sync/registrationSideEffects.test.ts +126 -0
  422. package/src/sync/registrationSideEffects.ts +131 -0
  423. package/src/sync/registry.ts +49 -171
  424. package/src/sync/routes.ts +55 -10
  425. package/src/sync/scripts/compactTombstones.ts +0 -2
  426. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  427. package/src/sync/socketHandlers.ts +154 -58
  428. package/src/sync/streams.ts +6 -0
  429. package/src/sync/sync.test.ts +28 -25
  430. package/src/sync/syncApp.ts +5 -4
  431. package/src/sync/syncBatch.ts +10 -4
  432. package/src/sync/syncFrontier.test.ts +17 -15
  433. package/src/sync/syncPhaseC.test.ts +54 -43
  434. package/src/sync/syncRoutes.test.ts +347 -38
  435. package/src/sync/syncSeqPlugin.ts +66 -44
  436. package/src/sync/syncSocket.test.ts +341 -81
  437. package/src/sync/types.ts +20 -0
  438. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  439. package/src/terrenoApp.migrations.test.ts +114 -0
  440. package/src/terrenoApp.test.ts +41 -0
  441. package/src/terrenoApp.ts +181 -46
  442. package/src/tests/createTestData.ts +2 -2
  443. package/src/tests/models.ts +24 -3
  444. package/src/tests/testHelper.ts +1 -7
  445. package/src/types/authToken.ts +41 -0
  446. package/src/types/mcpServiceToken.ts +48 -0
  447. package/src/types/membership.ts +48 -0
  448. package/src/types/notification.ts +34 -0
  449. package/src/types/notificationPreference.ts +28 -0
  450. package/src/types/organization.ts +49 -0
  451. package/src/webhooks/headerValue.test.ts +22 -0
  452. package/src/webhooks/headerValue.ts +12 -0
  453. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  454. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  455. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  456. package/src/webhooks/idempotency/webhookReceipt.ts +67 -0
  457. package/src/webhooks/rawBody.test.ts +107 -0
  458. package/src/webhooks/rawBody.ts +24 -0
  459. package/src/webhooks/timingSafeEqual.ts +16 -0
  460. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  461. package/src/webhooks/verifiers/hmac.ts +54 -0
  462. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  463. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  464. package/src/webhooks/verifiers/stripe.ts +67 -0
  465. package/src/webhooks/verifiers/twilio.ts +69 -0
  466. package/src/webhooks/webhooksApp.test.ts +221 -0
  467. package/src/webhooks/webhooksApp.ts +144 -0
  468. package/tsconfig.json +1 -1
  469. package/tsconfig.typedoc.json +2 -1
  470. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.d.ts +0 -2
  471. package/dist/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
  472. package/src/vendor/wesleytodd-openapi/lib/convert-yaml.js +0 -13
@@ -0,0 +1,51 @@
1
+ import {NotificationPreference} from "../models/notificationPreference";
2
+ import type {NotificationPreferenceChannel} from "../types/notificationPreference";
3
+
4
+ export type NotificationsBeforeSendChannel = "mail" | "push" | "sms" | "verification";
5
+
6
+ export interface NotificationsBeforeSendContext {
7
+ channel: NotificationsBeforeSendChannel;
8
+ userId?: string;
9
+ }
10
+
11
+ export interface NotificationsBeforeSendResult {
12
+ cancel?: boolean;
13
+ }
14
+
15
+ const PREFERENCE_FIELD_BY_CHANNEL: Partial<
16
+ Record<NotificationsBeforeSendChannel, NotificationPreferenceChannel>
17
+ > = {
18
+ mail: "mail",
19
+ push: "push",
20
+ sms: "sms",
21
+ };
22
+
23
+ /**
24
+ * Duck-typed CommsApp `beforeSend` hook that cancels outbound delivery when the user
25
+ * disabled that channel in NotificationPreference. Missing preference rows default to
26
+ * all channels on. The `verification` channel is never cancelled here.
27
+ */
28
+ export const notificationsBeforeSend = async ({
29
+ channel,
30
+ userId,
31
+ }: NotificationsBeforeSendContext): Promise<NotificationsBeforeSendResult | undefined> => {
32
+ if (channel === "verification" || !userId) {
33
+ return undefined;
34
+ }
35
+
36
+ const preferenceField = PREFERENCE_FIELD_BY_CHANNEL[channel];
37
+ if (!preferenceField) {
38
+ return undefined;
39
+ }
40
+
41
+ const preference = await NotificationPreference.findOneOrNone({ownerId: userId});
42
+ if (!preference) {
43
+ return undefined;
44
+ }
45
+
46
+ if (preference[preferenceField] === false) {
47
+ return {cancel: true};
48
+ }
49
+
50
+ return undefined;
51
+ };
@@ -1,12 +1,11 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {beforeEach, describe, expect, it} from "bun:test";
4
2
  import type express from "express";
5
3
  import type {Router} from "express";
6
4
  import supertest from "supertest";
7
5
  import type TestAgent from "supertest/lib/agent";
8
6
 
9
- import {type ModelRouterOptions, modelRouter} from "./api";
7
+ import {type ModelRouterOptions, modelRouter, type OpenApiMiddleware} from "./api";
8
+ import type {UserModel as AuthUserModel} from "./auth";
10
9
  import {
11
10
  createOpenApiMiddleware,
12
11
  deleteOpenApiMiddleware,
@@ -17,9 +16,30 @@ import {
17
16
  } from "./openApi";
18
17
  import {Permissions} from "./permissions";
19
18
  import {TerrenoApp} from "./terrenoApp";
20
- import {FoodModel, setupDb, UserModel} from "./tests";
21
-
22
- function getMessageSummaryOpenApiMiddleware(options: Partial<ModelRouterOptions<any>>): any {
19
+ import {type Food, FoodModel, setupDb, UserModel} from "./tests";
20
+
21
+ const createPassThroughMiddleware = (): express.RequestHandler => (_req, _res, next) => next();
22
+
23
+ const createOpenApiStub = (
24
+ path: OpenApiMiddleware["path"] = () => createPassThroughMiddleware()
25
+ ): OpenApiMiddleware => {
26
+ return Object.assign(createPassThroughMiddleware(), {
27
+ component: () => undefined,
28
+ document: {},
29
+ path,
30
+ schema: () => undefined,
31
+ });
32
+ };
33
+
34
+ const asFoodOptions = (
35
+ options?: Partial<ModelRouterOptions<unknown>>
36
+ ): Partial<ModelRouterOptions<Food>> => {
37
+ return options as unknown as Partial<ModelRouterOptions<Food>>;
38
+ };
39
+
40
+ function getMessageSummaryOpenApiMiddleware(
41
+ options: Partial<ModelRouterOptions<unknown>>
42
+ ): express.RequestHandler {
23
43
  if (!options.openApi) {
24
44
  throw new Error("Expected openApi to be configured for test routes");
25
45
  }
@@ -55,11 +75,11 @@ function getMessageSummaryOpenApiMiddleware(options: Partial<ModelRouterOptions<
55
75
  });
56
76
  }
57
77
 
58
- function addRoutes(router: Router, options?: Partial<ModelRouterOptions<any>>): void {
78
+ function addRoutes(router: Router, options?: Partial<ModelRouterOptions<unknown>>): void {
59
79
  router.use(
60
80
  "/food",
61
- modelRouter(FoodModel as any, {
62
- ...options,
81
+ modelRouter(FoodModel, {
82
+ ...asFoodOptions(options),
63
83
  allowAnonymous: true,
64
84
  openApiExtraModelProperties: {
65
85
  foo: {
@@ -93,7 +113,7 @@ describe("openApi", () => {
93
113
  app = new TerrenoApp({
94
114
  configureApp: addRoutes,
95
115
  skipListen: true,
96
- userModel: UserModel as any,
116
+ userModel: UserModel as unknown as AuthUserModel,
97
117
  }).build();
98
118
  });
99
119
 
@@ -187,11 +207,14 @@ describe("openApi", () => {
187
207
  });
188
208
  });
189
209
 
190
- function addRoutesStringQuery(router: Router, options?: Partial<ModelRouterOptions<any>>): void {
210
+ function addRoutesStringQuery(
211
+ router: Router,
212
+ options?: Partial<ModelRouterOptions<unknown>>
213
+ ): void {
191
214
  router.use(
192
215
  "/food",
193
- modelRouter(FoodModel as any, {
194
- ...options,
216
+ modelRouter(FoodModel, {
217
+ ...asFoodOptions(options),
195
218
  allowAnonymous: true,
196
219
  permissions: {
197
220
  create: [Permissions.IsAny],
@@ -216,7 +239,7 @@ describe("openApi string query fields", () => {
216
239
  app = new TerrenoApp({
217
240
  configureApp: addRoutesStringQuery,
218
241
  skipListen: true,
219
- userModel: UserModel as any,
242
+ userModel: UserModel as unknown as AuthUserModel,
220
243
  }).build();
221
244
  });
222
245
 
@@ -240,7 +263,7 @@ describe("openApi string query fields", () => {
240
263
  });
241
264
  });
242
265
 
243
- function addRoutesPopulate(router: Router, options?: Partial<ModelRouterOptions<any>>): void {
266
+ function addRoutesPopulate(router: Router, options?: Partial<ModelRouterOptions<unknown>>): void {
244
267
  options?.openApi?.component("schemas", "LimitedUser", {
245
268
  properties: {
246
269
  email: {
@@ -257,8 +280,8 @@ function addRoutesPopulate(router: Router, options?: Partial<ModelRouterOptions<
257
280
 
258
281
  router.use(
259
282
  "/food",
260
- modelRouter(FoodModel as any, {
261
- ...options,
283
+ modelRouter(FoodModel, {
284
+ ...asFoodOptions(options),
262
285
  allowAnonymous: true,
263
286
  openApiExtraModelProperties: {
264
287
  foo: {
@@ -300,7 +323,7 @@ describe("openApi without swagger", () => {
300
323
  app = new TerrenoApp({
301
324
  configureApp: addRoutes,
302
325
  skipListen: true,
303
- userModel: UserModel as any,
326
+ userModel: UserModel as unknown as AuthUserModel,
304
327
  }).build();
305
328
  });
306
329
 
@@ -320,7 +343,7 @@ describe("openApi populate", () => {
320
343
  app = new TerrenoApp({
321
344
  configureApp: addRoutesPopulate,
322
345
  skipListen: true,
323
- userModel: UserModel as any,
346
+ userModel: UserModel as unknown as AuthUserModel,
324
347
  }).build();
325
348
  });
326
349
 
@@ -368,7 +391,6 @@ describe("openApi populate", () => {
368
391
  $ref: "#/components/schemas/LimitedUser",
369
392
  },
370
393
  },
371
- required: [],
372
394
  type: "object",
373
395
  },
374
396
  type: "array",
@@ -395,14 +417,14 @@ describe("openApi populate", () => {
395
417
 
396
418
  describe("openApi middleware no-op paths", () => {
397
419
  it("getOpenApiMiddleware returns noop when openApi not configured", () => {
398
- const mw = getOpenApiMiddleware(FoodModel as any, {});
420
+ const mw = getOpenApiMiddleware(FoodModel, {});
399
421
  expect(typeof mw).toBe("function");
400
422
  expect(mw.length).toBe(3);
401
423
  });
402
424
 
403
425
  it("getOpenApiMiddleware returns noop when read permissions are empty", () => {
404
- const mw = getOpenApiMiddleware(FoodModel as any, {
405
- openApi: {component: () => {}, path: () => (() => {}) as any} as any,
426
+ const mw = getOpenApiMiddleware(FoodModel, {
427
+ openApi: createOpenApiStub(),
406
428
  permissions: {
407
429
  create: [],
408
430
  delete: [],
@@ -416,13 +438,13 @@ describe("openApi middleware no-op paths", () => {
416
438
  });
417
439
 
418
440
  it("listOpenApiMiddleware returns noop when openApi not configured", () => {
419
- const mw = listOpenApiMiddleware(FoodModel as any, {});
441
+ const mw = listOpenApiMiddleware(FoodModel, {});
420
442
  expect(mw.length).toBe(3);
421
443
  });
422
444
 
423
445
  it("listOpenApiMiddleware returns noop when list permissions are empty", () => {
424
- const mw = listOpenApiMiddleware(FoodModel as any, {
425
- openApi: {path: () => (() => {}) as any} as any,
446
+ const mw = listOpenApiMiddleware(FoodModel, {
447
+ openApi: createOpenApiStub(),
426
448
  permissions: {
427
449
  create: [],
428
450
  delete: [],
@@ -437,14 +459,12 @@ describe("openApi middleware no-op paths", () => {
437
459
  it("listOpenApiMiddleware emits x-terreno-sync when sync is configured", () => {
438
460
  let captured: Record<string, unknown> | undefined;
439
461
  listOpenApiMiddleware(
440
- FoodModel as any,
462
+ FoodModel,
441
463
  {
442
- openApi: {
443
- path: (spec: Record<string, unknown>) => {
444
- captured = spec;
445
- return (() => {}) as express.RequestHandler;
446
- },
447
- } as any,
464
+ openApi: createOpenApiStub((spec: Record<string, unknown>) => {
465
+ captured = spec;
466
+ return createPassThroughMiddleware();
467
+ }),
448
468
  permissions: {
449
469
  create: [Permissions.IsAny],
450
470
  delete: [Permissions.IsAny],
@@ -461,13 +481,11 @@ describe("openApi middleware no-op paths", () => {
461
481
 
462
482
  it("listOpenApiMiddleware omits x-terreno-sync when sync is not configured", () => {
463
483
  let captured: Record<string, unknown> | undefined;
464
- listOpenApiMiddleware(FoodModel as any, {
465
- openApi: {
466
- path: (spec: Record<string, unknown>) => {
467
- captured = spec;
468
- return (() => {}) as express.RequestHandler;
469
- },
470
- } as any,
484
+ listOpenApiMiddleware(FoodModel, {
485
+ openApi: createOpenApiStub((spec: Record<string, unknown>) => {
486
+ captured = spec;
487
+ return createPassThroughMiddleware();
488
+ }),
471
489
  permissions: {
472
490
  create: [Permissions.IsAny],
473
491
  delete: [Permissions.IsAny],
@@ -481,13 +499,11 @@ describe("openApi middleware no-op paths", () => {
481
499
 
482
500
  it("listOpenApiMiddleware falls back to the model collection name without routePath", () => {
483
501
  let captured: Record<string, unknown> | undefined;
484
- listOpenApiMiddleware(FoodModel as any, {
485
- openApi: {
486
- path: (spec: Record<string, unknown>) => {
487
- captured = spec;
488
- return (() => {}) as express.RequestHandler;
489
- },
490
- } as any,
502
+ listOpenApiMiddleware(FoodModel, {
503
+ openApi: createOpenApiStub((spec: Record<string, unknown>) => {
504
+ captured = spec;
505
+ return createPassThroughMiddleware();
506
+ }),
491
507
  permissions: {
492
508
  create: [Permissions.IsAny],
493
509
  delete: [Permissions.IsAny],
@@ -507,10 +523,10 @@ describe("openApi middleware no-op paths", () => {
507
523
  let captured: Record<string, unknown> | undefined;
508
524
  const capturePath = (spec: Record<string, unknown>): express.RequestHandler => {
509
525
  captured = spec;
510
- return (() => {}) as express.RequestHandler;
526
+ return createPassThroughMiddleware();
511
527
  };
512
- const baseOptions = {
513
- openApi: {path: capturePath} as any,
528
+ const baseOptions: Partial<ModelRouterOptions<Food>> = {
529
+ openApi: createOpenApiStub(capturePath),
514
530
  permissions: {
515
531
  create: [Permissions.IsAny],
516
532
  delete: [Permissions.IsAny],
@@ -521,7 +537,7 @@ describe("openApi middleware no-op paths", () => {
521
537
  };
522
538
 
523
539
  listOpenApiMiddleware(
524
- FoodModel as any,
540
+ FoodModel,
525
541
  {
526
542
  ...baseOptions,
527
543
  sync: {scope: {field: "organizationId", type: "tenant"}},
@@ -531,7 +547,7 @@ describe("openApi middleware no-op paths", () => {
531
547
  expect(captured?.["x-terreno-sync"]).toEqual({collection: "projects", scope: "tenant"});
532
548
 
533
549
  listOpenApiMiddleware(
534
- FoodModel as any,
550
+ FoodModel,
535
551
  {
536
552
  ...baseOptions,
537
553
  sync: {scope: () => "workspace"},
@@ -542,13 +558,13 @@ describe("openApi middleware no-op paths", () => {
542
558
  });
543
559
 
544
560
  it("createOpenApiMiddleware returns noop when openApi not configured", () => {
545
- const mw = createOpenApiMiddleware(FoodModel as any, {});
561
+ const mw = createOpenApiMiddleware(FoodModel, {});
546
562
  expect(mw.length).toBe(3);
547
563
  });
548
564
 
549
565
  it("createOpenApiMiddleware returns noop when create permissions are empty", () => {
550
- const mw = createOpenApiMiddleware(FoodModel as any, {
551
- openApi: {path: () => (() => {}) as any} as any,
566
+ const mw = createOpenApiMiddleware(FoodModel, {
567
+ openApi: createOpenApiStub(),
552
568
  permissions: {
553
569
  create: [],
554
570
  delete: [],
@@ -561,13 +577,13 @@ describe("openApi middleware no-op paths", () => {
561
577
  });
562
578
 
563
579
  it("patchOpenApiMiddleware returns noop when openApi not configured", () => {
564
- const mw = patchOpenApiMiddleware(FoodModel as any, {});
580
+ const mw = patchOpenApiMiddleware(FoodModel, {});
565
581
  expect(mw.length).toBe(3);
566
582
  });
567
583
 
568
584
  it("patchOpenApiMiddleware returns noop when update permissions are empty", () => {
569
- const mw = patchOpenApiMiddleware(FoodModel as any, {
570
- openApi: {path: () => (() => {}) as any} as any,
585
+ const mw = patchOpenApiMiddleware(FoodModel, {
586
+ openApi: createOpenApiStub(),
571
587
  permissions: {
572
588
  create: [],
573
589
  delete: [],
@@ -580,13 +596,13 @@ describe("openApi middleware no-op paths", () => {
580
596
  });
581
597
 
582
598
  it("deleteOpenApiMiddleware returns noop when openApi not configured", () => {
583
- const mw = deleteOpenApiMiddleware(FoodModel as any, {});
599
+ const mw = deleteOpenApiMiddleware(FoodModel, {});
584
600
  expect(mw.length).toBe(3);
585
601
  });
586
602
 
587
603
  it("deleteOpenApiMiddleware returns noop when delete permissions are empty", () => {
588
- const mw = deleteOpenApiMiddleware(FoodModel as any, {
589
- openApi: {path: () => (() => {}) as any} as any,
604
+ const mw = deleteOpenApiMiddleware(FoodModel, {
605
+ openApi: createOpenApiStub(),
590
606
  permissions: {
591
607
  create: [],
592
608
  delete: [],
@@ -606,7 +622,7 @@ describe("openApi middleware no-op paths", () => {
606
622
  it("readOpenApiMiddleware returns noop when read permissions are empty", () => {
607
623
  const mw = readOpenApiMiddleware(
608
624
  {
609
- openApi: {path: () => (() => {}) as any} as any,
625
+ openApi: createOpenApiStub(),
610
626
  permissions: {
611
627
  create: [],
612
628
  delete: [],
@@ -623,11 +639,10 @@ describe("openApi middleware no-op paths", () => {
623
639
  });
624
640
 
625
641
  it("readOpenApiMiddleware returns middleware when configured with permissions", () => {
626
- // Use a simple path stub that returns a middleware function
627
- const pathFn = () => ((_req: any, _res: any, next: any) => next()) as any;
642
+ const pathFn: OpenApiMiddleware["path"] = () => createPassThroughMiddleware();
628
643
  const mw = readOpenApiMiddleware(
629
644
  {
630
- openApi: {path: pathFn} as any,
645
+ openApi: createOpenApiStub(pathFn),
631
646
  permissions: {
632
647
  create: [],
633
648
  delete: [],
package/src/openApi.ts CHANGED
@@ -15,7 +15,7 @@ const m2sOptions = {
15
15
  props: ["readOnly", "required", "enum", "default"],
16
16
  };
17
17
 
18
- export const apiErrorContent = {
18
+ const apiErrorContent = {
19
19
  "application/json": {
20
20
  schema: {$ref: "#/components/schemas/APIError"},
21
21
  },
@@ -491,6 +491,7 @@ export const deleteOpenApiMiddleware = <T>(
491
491
 
492
492
  // This is a generic OpenAPI wrapper for a read that returns any object described by `properties`.
493
493
  // Useful for endpoints that don't directly map to a model.
494
+ /** @internal */
494
495
  export const readOpenApiMiddleware = <T>(
495
496
  options: Partial<ModelRouterOptions<T>>,
496
497
  properties: Record<string, unknown>,
@@ -1,4 +1,4 @@
1
- import {beforeEach, describe, expect, it} from "bun:test";
1
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
2
2
  import type express from "express";
3
3
  import type {Router} from "express";
4
4
  import supertest from "supertest";
@@ -378,7 +378,7 @@ describe("OpenApiMiddlewareBuilder without OpenAPI", () => {
378
378
  .withTags(["test"])
379
379
  .withSummary("Test")
380
380
  .withResponse(200, {id: {type: "string"}})
381
- .build() as express.RequestHandler;
381
+ .build();
382
382
 
383
383
  // Middleware should be a function
384
384
  expect(typeof middleware).toBe("function");
@@ -392,7 +392,7 @@ describe("OpenApiMiddlewareBuilder without OpenAPI", () => {
392
392
  });
393
393
 
394
394
  it("build returns noop middleware when options is empty", () => {
395
- const middleware = createOpenApiBuilder({}).build() as express.RequestHandler;
395
+ const middleware = createOpenApiBuilder({}).build();
396
396
 
397
397
  let nextCalled = false;
398
398
  middleware({} as express.Request, {} as express.Response, () => {
@@ -476,9 +476,17 @@ describe("OpenApiMiddlewareBuilder configuration", () => {
476
476
  });
477
477
 
478
478
  describe("OpenApiMiddlewareBuilder withValidation / buildWithSchemas", () => {
479
- beforeEach(() => {
479
+ const resetValidatorConfig = (): void => {
480
480
  const {resetOpenApiValidatorConfig} = require("./openApiValidator");
481
481
  resetOpenApiValidatorConfig();
482
+ };
483
+
484
+ beforeEach(() => {
485
+ resetValidatorConfig();
486
+ });
487
+
488
+ afterEach(() => {
489
+ resetValidatorConfig();
482
490
  });
483
491
 
484
492
  it("buildWithSchemas returns bodySchema and querySchema", () => {
@@ -519,15 +527,15 @@ describe("OpenApiMiddlewareBuilder withValidation / buildWithSchemas", () => {
519
527
  expect(result.validationEnabled).toBe(false);
520
528
  });
521
529
 
522
- it("build() returns an array when validation is enabled with body and query", () => {
530
+ it("build() returns a single composed middleware when validation is enabled with body and query", () => {
523
531
  const result = createOpenApiBuilder({})
524
532
  .withRequestBody({name: {required: true, type: "string"}})
525
533
  .withQueryParameter("page", {type: "number"})
526
534
  .withValidation()
527
535
  .build();
528
536
 
529
- expect(Array.isArray(result)).toBe(true);
530
- expect(result).toHaveLength(3);
537
+ expect(typeof result).toBe("function");
538
+ expect(Array.isArray(result)).toBe(false);
531
539
  });
532
540
 
533
541
  it("build() returns a single middleware when validation is disabled", () => {
@@ -554,4 +562,84 @@ describe("OpenApiMiddlewareBuilder withValidation / buildWithSchemas", () => {
554
562
  // No body/query validation = just the openApi middleware (single fn)
555
563
  expect(typeof result).toBe("function");
556
564
  });
565
+
566
+ // The composed handler must still run every validator in order and surface a
567
+ // validator's synchronous throw, which routes previously got from Express
568
+ // spreading an array of middleware.
569
+ describe("composed validation middleware", () => {
570
+ const buildTestApp = (): express.Express => {
571
+ const {configureOpenApiValidator} = require("./openApiValidator");
572
+ configureOpenApiValidator({logValidationErrors: false});
573
+
574
+ const {apiErrorMiddleware} = require("./errors");
575
+ const expressLib = require("express") as typeof import("express");
576
+
577
+ const app = expressLib();
578
+ app.use(expressLib.json());
579
+ app.post(
580
+ "/widgets",
581
+ createOpenApiBuilder({})
582
+ .withRequestBody({name: {required: true, type: "string"}})
583
+ .withQueryParameter("page", {type: "number"})
584
+ .withValidation()
585
+ .build(),
586
+ (req, res) => {
587
+ res.json({name: (req.body as {name: string}).name});
588
+ }
589
+ );
590
+ app.use(apiErrorMiddleware);
591
+ return app;
592
+ };
593
+
594
+ it("passes a valid request through to the route handler", async () => {
595
+ const response = await supertest(buildTestApp())
596
+ .post("/widgets?page=2")
597
+ .send({name: "valid"});
598
+
599
+ expect(response.status).toBe(200);
600
+ expect(response.body.name).toBe("valid");
601
+ });
602
+
603
+ it("rejects a body missing a required field with a 400", async () => {
604
+ const response = await supertest(buildTestApp()).post("/widgets").send({});
605
+
606
+ expect(response.status).toBe(400);
607
+ });
608
+
609
+ it("keeps the documented path in /openapi.json when validation is composed", async () => {
610
+ process.env.REFRESH_TOKEN_SECRET = "testsecret1234";
611
+ process.env.ENABLE_SWAGGER = "true";
612
+
613
+ const {configureOpenApiValidator} = require("./openApiValidator");
614
+ configureOpenApiValidator({logValidationErrors: false});
615
+
616
+ const addValidatedWidgetRoute = (
617
+ router: express.Router,
618
+ options?: Partial<ModelRouterOptions<unknown>>
619
+ ): void => {
620
+ const middleware = createOpenApiBuilder(options ?? {})
621
+ .withTags(["Widgets"])
622
+ .withSummary("Create a widget")
623
+ .withRequestBody({name: {required: true, type: "string"}})
624
+ .withQueryParameter("page", {type: "number"})
625
+ .withValidation()
626
+ .build();
627
+ router.post("/widgets", middleware, (_req, res) => {
628
+ res.json({ok: true});
629
+ });
630
+ };
631
+
632
+ const documentedApp = new TerrenoApp({
633
+ configureApp: addValidatedWidgetRoute,
634
+ skipListen: true,
635
+ userModel: UserModel as unknown as AuthUserModel,
636
+ }).build();
637
+
638
+ const spec = await supertest(documentedApp).get("/openapi.json").expect(200);
639
+ expect(spec.body.paths["/widgets"]).toBeDefined();
640
+ expect(spec.body.paths["/widgets"].post).toBeDefined();
641
+ expect(spec.body.paths["/widgets"].post.summary).toBe("Create a widget");
642
+ expect(spec.body.paths["/widgets"].post.requestBody).toBeDefined();
643
+ });
644
+ });
557
645
  });
@@ -41,6 +41,46 @@ import {
41
41
  validateQueryParams,
42
42
  validateRequestBody,
43
43
  } from "./openApiValidator";
44
+ import {
45
+ get as getOpenApiLayerSchema,
46
+ set as setOpenApiLayerSchema,
47
+ } from "./vendor/wesleytodd-openapi/lib/layer-schema";
48
+
49
+ /**
50
+ * Run handlers in order as one Express middleware function.
51
+ *
52
+ * `@wesleytodd/openapi` stores path schemas on a Map keyed by the function
53
+ * Express registers. Copying the schema from the documentation handler onto
54
+ * the composed function keeps `/openapi.json` generation working.
55
+ */
56
+ const composeRequestHandlers = (handlers: express.RequestHandler[]): express.RequestHandler => {
57
+ const composed: express.RequestHandler = (req, res, next): void => {
58
+ const run = (index: number): void => {
59
+ if (index >= handlers.length) {
60
+ next();
61
+ return;
62
+ }
63
+ handlers[index](req, res, (error?: unknown): void => {
64
+ if (error) {
65
+ next(error);
66
+ return;
67
+ }
68
+ run(index + 1);
69
+ });
70
+ };
71
+ run(0);
72
+ };
73
+
74
+ for (const handler of handlers) {
75
+ const schema = getOpenApiLayerSchema(handler);
76
+ if (schema) {
77
+ setOpenApiLayerSchema(composed, schema);
78
+ break;
79
+ }
80
+ }
81
+
82
+ return composed;
83
+ };
44
84
 
45
85
  /**
46
86
  * Defines a property within an OpenAPI schema.
@@ -78,19 +118,30 @@ import {
78
118
  */
79
119
  export interface OpenApiSchemaProperty {
80
120
  /** The JSON Schema type (e.g., "string", "number", "boolean", "object", "array") */
81
- type: string;
121
+ type?: string;
122
+ /** JSON Schema oneOf for query operators (scalar or Mongo-style object). */
123
+ oneOf?: OpenApiSchemaProperty[];
82
124
  /** Human-readable description of the property */
83
125
  description?: string;
126
+ /** Allowed values for string/number enums in query validation. */
127
+ enum?: string[];
84
128
  /** Format hint for the type (e.g., "date-time", "email", "uri", "uuid") */
85
129
  format?: string;
86
130
  /** Schema for array items when type is "array" */
87
131
  items?: OpenApiSchemaProperty;
132
+ /** Minimum array length when type is "array". */
133
+ minItems?: number;
88
134
  /** Nested properties when type is "object" */
89
135
  properties?: Record<string, OpenApiSchemaProperty>;
90
136
  /** Schema for additional properties or boolean to allow/disallow them */
91
137
  additionalProperties?: OpenApiSchemaProperty | boolean;
92
- /** Whether this property is required in the parent object */
93
- required?: boolean;
138
+ /**
139
+ * Property-level required flag, or object-schema required key list for nested
140
+ * operator shapes (`{$in: ...}`, `{$regex: ...}`).
141
+ */
142
+ required?: boolean | string[];
143
+ /** When true, string values must be escaped regex literals (query `$regex` operator). */
144
+ escapedRegexLiteral?: boolean;
94
145
  }
95
146
 
96
147
  /**
@@ -741,13 +792,14 @@ export class OpenApiMiddlewareBuilder {
741
792
  * that integrates with the OpenAPI documentation system. If no OpenAPI
742
793
  * path is configured in options, returns a no-op middleware.
743
794
  *
744
- * If validation was enabled via `withValidation()`, returns an array
745
- * of middleware: [openApiDocMiddleware, validationMiddleware].
795
+ * If validation was enabled via `withValidation()`, body and query
796
+ * validators are composed into the same RequestHandler (they still run
797
+ * in order: OpenAPI docs, then body, then query).
746
798
  *
747
799
  * Default error responses (400, 401, 403, 404, 405) are automatically
748
800
  * merged with the configured responses.
749
801
  *
750
- * @returns Express middleware function(s) for OpenAPI documentation and optional validation
802
+ * @returns Express middleware for OpenAPI documentation and optional validation
751
803
  *
752
804
  * @example
753
805
  * ```typescript
@@ -759,9 +811,7 @@ export class OpenApiMiddlewareBuilder {
759
811
  * router.get("/users/:id", middleware, getUserHandler);
760
812
  * ```
761
813
  */
762
- // noExplicitAny: returns either a single RequestHandler or an array depending on validation config — callers spread or invoke
763
- // biome-ignore lint/suspicious/noExplicitAny: returns either a single RequestHandler or an array depending on validation config
764
- build(): any {
814
+ build(): express.RequestHandler {
765
815
  const noop: express.RequestHandler = (_a, _b, next) => next();
766
816
 
767
817
  // Build the OpenAPI documentation middleware
@@ -808,13 +858,11 @@ export class OpenApiMiddlewareBuilder {
808
858
  validators.push(validateQueryParams(this.queryParamSchemas, {enabled: true}));
809
859
  }
810
860
 
811
- // If only one middleware (the openApi one), return it directly
812
861
  if (validators.length === 1) {
813
862
  return openApiMiddleware;
814
863
  }
815
864
 
816
- // Return array of middleware to be spread in route definition
817
- return validators;
865
+ return composeRequestHandlers(validators);
818
866
  }
819
867
  }
820
868
 
@@ -175,7 +175,7 @@ export const patchExpressRouterUse = (): void => {
175
175
  ) => unknown;
176
176
  Object.defineProperty(routerPrototype, "use", {
177
177
  ...useDescriptor,
178
- value: function patchedRouterUse(this: {stack?: PatchedLayer[]}, ...args: unknown[]): unknown {
178
+ value(this: {stack?: PatchedLayer[]}, ...args: unknown[]): unknown {
179
179
  const stackBefore = this.stack?.length ?? 0;
180
180
  const result = originalUse.apply(this, args);
181
181
  annotateMountLayers(this.stack, stackBefore, args);