@pattern-stack/codegen 0.15.1 → 0.15.3

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 (527) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/dist/chunk-27ETSJ2X.js +84 -0
  3. package/dist/chunk-27ETSJ2X.js.map +1 -0
  4. package/dist/chunk-2E224ZSN.js +20 -0
  5. package/dist/chunk-2E224ZSN.js.map +1 -0
  6. package/dist/chunk-2FTZLDBP.js +179 -0
  7. package/dist/chunk-2FTZLDBP.js.map +1 -0
  8. package/dist/chunk-2N4UG4VD.js +20 -0
  9. package/dist/chunk-2N4UG4VD.js.map +1 -0
  10. package/dist/chunk-2TVVBC53.js +92 -0
  11. package/dist/chunk-2TVVBC53.js.map +1 -0
  12. package/dist/chunk-2VHZ7EKC.js +37 -0
  13. package/dist/chunk-2VHZ7EKC.js.map +1 -0
  14. package/dist/chunk-32BMMV4H.js +109 -0
  15. package/dist/chunk-32BMMV4H.js.map +1 -0
  16. package/dist/chunk-32DOFN3T.js +4042 -0
  17. package/dist/chunk-32DOFN3T.js.map +1 -0
  18. package/dist/chunk-36U5UGIO.js +107 -0
  19. package/dist/chunk-36U5UGIO.js.map +1 -0
  20. package/dist/chunk-3CJFPU6Q.js +14 -0
  21. package/dist/chunk-3CJFPU6Q.js.map +1 -0
  22. package/dist/chunk-3NMCDN7L.js +90 -0
  23. package/dist/chunk-3NMCDN7L.js.map +1 -0
  24. package/dist/chunk-3SZFUTXE.js +62 -0
  25. package/dist/chunk-3SZFUTXE.js.map +1 -0
  26. package/dist/chunk-4DOJBQTP.js +117 -0
  27. package/dist/chunk-4DOJBQTP.js.map +1 -0
  28. package/dist/chunk-4H3PETLM.js +290 -0
  29. package/dist/chunk-4H3PETLM.js.map +1 -0
  30. package/dist/chunk-4JLJYWJC.js +308 -0
  31. package/dist/chunk-4JLJYWJC.js.map +1 -0
  32. package/dist/chunk-4KNXX6TI.js +29 -0
  33. package/dist/chunk-4KNXX6TI.js.map +1 -0
  34. package/dist/chunk-4LH67P4U.js +17 -0
  35. package/dist/chunk-4LH67P4U.js.map +1 -0
  36. package/dist/chunk-4MF3HKJA.js +94 -0
  37. package/dist/chunk-4MF3HKJA.js.map +1 -0
  38. package/dist/chunk-4MVGAMUA.js +40 -0
  39. package/dist/chunk-4MVGAMUA.js.map +1 -0
  40. package/dist/chunk-4RFHUZXU.js +635 -0
  41. package/dist/chunk-4RFHUZXU.js.map +1 -0
  42. package/dist/chunk-5A432NZJ.js +7 -0
  43. package/dist/chunk-5A432NZJ.js.map +1 -0
  44. package/dist/chunk-5Y7W3XR6.js +356 -0
  45. package/dist/chunk-5Y7W3XR6.js.map +1 -0
  46. package/dist/chunk-6DWFJNIK.js +15 -0
  47. package/dist/chunk-6DWFJNIK.js.map +1 -0
  48. package/dist/chunk-6I7ULIN6.js +15 -0
  49. package/dist/chunk-6I7ULIN6.js.map +1 -0
  50. package/dist/chunk-6XY6ZMMD.js +25 -0
  51. package/dist/chunk-6XY6ZMMD.js.map +1 -0
  52. package/dist/chunk-7B3RYX45.js +63 -0
  53. package/dist/chunk-7B3RYX45.js.map +1 -0
  54. package/dist/chunk-7C3FOSDI.js +1 -0
  55. package/dist/chunk-7C3FOSDI.js.map +1 -0
  56. package/dist/chunk-7KOW6PU6.js +59 -0
  57. package/dist/chunk-7KOW6PU6.js.map +1 -0
  58. package/dist/chunk-7RELQJIN.js +22 -0
  59. package/dist/chunk-7RELQJIN.js.map +1 -0
  60. package/dist/chunk-7YGORYZD.js +112 -0
  61. package/dist/chunk-7YGORYZD.js.map +1 -0
  62. package/dist/chunk-AHV4GDYM.js +63 -0
  63. package/dist/chunk-AHV4GDYM.js.map +1 -0
  64. package/dist/chunk-AQFQ4BYM.js +81 -0
  65. package/dist/chunk-AQFQ4BYM.js.map +1 -0
  66. package/dist/chunk-AS3NAZB6.js +14 -0
  67. package/dist/chunk-AS3NAZB6.js.map +1 -0
  68. package/dist/chunk-BGULBWKJ.js +88 -0
  69. package/dist/chunk-BGULBWKJ.js.map +1 -0
  70. package/dist/chunk-BIO6F7YI.js +17 -0
  71. package/dist/chunk-BIO6F7YI.js.map +1 -0
  72. package/dist/chunk-BOPZWRJK.js +36 -0
  73. package/dist/chunk-BOPZWRJK.js.map +1 -0
  74. package/dist/chunk-BPARRK6F.js +14 -0
  75. package/dist/chunk-BPARRK6F.js.map +1 -0
  76. package/dist/chunk-CO6LUM72.js +59 -0
  77. package/dist/chunk-CO6LUM72.js.map +1 -0
  78. package/dist/chunk-DCCZB4UC.js +100 -0
  79. package/dist/chunk-DCCZB4UC.js.map +1 -0
  80. package/dist/chunk-DV4RV2DC.js +59 -0
  81. package/dist/chunk-DV4RV2DC.js.map +1 -0
  82. package/dist/chunk-EDKJU5BO.js +11 -0
  83. package/dist/chunk-EDKJU5BO.js.map +1 -0
  84. package/dist/chunk-EO2QPOKH.js +116 -0
  85. package/dist/chunk-EO2QPOKH.js.map +1 -0
  86. package/dist/chunk-EOLLMEAH.js +155 -0
  87. package/dist/chunk-EOLLMEAH.js.map +1 -0
  88. package/dist/chunk-EWYCWP4H.js +14 -0
  89. package/dist/chunk-EWYCWP4H.js.map +1 -0
  90. package/dist/chunk-EXVDJMIY.js +33 -0
  91. package/dist/chunk-EXVDJMIY.js.map +1 -0
  92. package/dist/chunk-FASRXRX5.js +19 -0
  93. package/dist/chunk-FASRXRX5.js.map +1 -0
  94. package/dist/chunk-FBGHYQIZ.js +201 -0
  95. package/dist/chunk-FBGHYQIZ.js.map +1 -0
  96. package/dist/chunk-FI34KYZ5.js +1 -0
  97. package/dist/chunk-FI34KYZ5.js.map +1 -0
  98. package/dist/chunk-FN2PYDPP.js +1 -0
  99. package/dist/chunk-FN2PYDPP.js.map +1 -0
  100. package/dist/chunk-GCYKMF22.js +81 -0
  101. package/dist/chunk-GCYKMF22.js.map +1 -0
  102. package/dist/chunk-GM3RMJIJ.js +92 -0
  103. package/dist/chunk-GM3RMJIJ.js.map +1 -0
  104. package/dist/chunk-GYGNEQSC.js +9 -0
  105. package/dist/chunk-GYGNEQSC.js.map +1 -0
  106. package/dist/chunk-H5NH7KPE.js +21 -0
  107. package/dist/chunk-H5NH7KPE.js.map +1 -0
  108. package/dist/chunk-HNWZFNKP.js +168 -0
  109. package/dist/chunk-HNWZFNKP.js.map +1 -0
  110. package/dist/chunk-HUH73XGI.js +1 -0
  111. package/dist/chunk-HUH73XGI.js.map +1 -0
  112. package/dist/chunk-I6MVCB5A.js +39 -0
  113. package/dist/chunk-I6MVCB5A.js.map +1 -0
  114. package/dist/chunk-IBGER4YK.js +12 -0
  115. package/dist/chunk-IBGER4YK.js.map +1 -0
  116. package/dist/chunk-IF5I3DAA.js +92 -0
  117. package/dist/chunk-IF5I3DAA.js.map +1 -0
  118. package/dist/chunk-IP4OO26U.js +54 -0
  119. package/dist/chunk-IP4OO26U.js.map +1 -0
  120. package/dist/chunk-IWAOY6KC.js +1 -0
  121. package/dist/chunk-IWAOY6KC.js.map +1 -0
  122. package/dist/chunk-IYNSRIGR.js +122 -0
  123. package/dist/chunk-IYNSRIGR.js.map +1 -0
  124. package/dist/chunk-J37YWU7Y.js +19 -0
  125. package/dist/chunk-J37YWU7Y.js.map +1 -0
  126. package/dist/chunk-J6KZS54B.js +269 -0
  127. package/dist/chunk-J6KZS54B.js.map +1 -0
  128. package/dist/chunk-J6MN42LG.js +19 -0
  129. package/dist/chunk-J6MN42LG.js.map +1 -0
  130. package/dist/chunk-J7JMVS2B.js +53 -0
  131. package/dist/chunk-J7JMVS2B.js.map +1 -0
  132. package/dist/chunk-JRQO2IOF.js +65 -0
  133. package/dist/chunk-JRQO2IOF.js.map +1 -0
  134. package/dist/chunk-JWNHNUYL.js +96 -0
  135. package/dist/chunk-JWNHNUYL.js.map +1 -0
  136. package/dist/chunk-K2I6XIK5.js +122 -0
  137. package/dist/chunk-K2I6XIK5.js.map +1 -0
  138. package/dist/chunk-KVOWSC5S.js +1 -0
  139. package/dist/chunk-KVOWSC5S.js.map +1 -0
  140. package/dist/chunk-KYR3B3OW.js +79 -0
  141. package/dist/chunk-KYR3B3OW.js.map +1 -0
  142. package/dist/chunk-L3LZWWSX.js +61 -0
  143. package/dist/chunk-L3LZWWSX.js.map +1 -0
  144. package/dist/chunk-L4SDDEEU.js +1 -0
  145. package/dist/chunk-L4SDDEEU.js.map +1 -0
  146. package/dist/chunk-L6FTY45T.js +13 -0
  147. package/dist/chunk-L6FTY45T.js.map +1 -0
  148. package/dist/chunk-L7BNNRGI.js +134 -0
  149. package/dist/chunk-L7BNNRGI.js.map +1 -0
  150. package/dist/chunk-LG57S2SC.js +150 -0
  151. package/dist/chunk-LG57S2SC.js.map +1 -0
  152. package/dist/chunk-M6QLSLPO.js +97 -0
  153. package/dist/chunk-M6QLSLPO.js.map +1 -0
  154. package/dist/chunk-MZ6GV4YF.js +21 -0
  155. package/dist/chunk-MZ6GV4YF.js.map +1 -0
  156. package/dist/chunk-N5OTOWTP.js +55 -0
  157. package/dist/chunk-N5OTOWTP.js.map +1 -0
  158. package/dist/chunk-NN7XZEGF.js +14 -0
  159. package/dist/chunk-NN7XZEGF.js.map +1 -0
  160. package/dist/chunk-NPFPZ2HO.js +13 -0
  161. package/dist/chunk-NPFPZ2HO.js.map +1 -0
  162. package/dist/chunk-NXXDZ6ZF.js +42 -0
  163. package/dist/chunk-NXXDZ6ZF.js.map +1 -0
  164. package/dist/chunk-NYBCQZC7.js +11 -0
  165. package/dist/chunk-NYBCQZC7.js.map +1 -0
  166. package/dist/chunk-O37C3YE6.js +111 -0
  167. package/dist/chunk-O37C3YE6.js.map +1 -0
  168. package/dist/chunk-OFRRBC7M.js +78 -0
  169. package/dist/chunk-OFRRBC7M.js.map +1 -0
  170. package/dist/chunk-OGIZXGPY.js +222 -0
  171. package/dist/chunk-OGIZXGPY.js.map +1 -0
  172. package/dist/chunk-OKXZ63IA.js +168 -0
  173. package/dist/chunk-OKXZ63IA.js.map +1 -0
  174. package/dist/chunk-OSQRXVG2.js +58 -0
  175. package/dist/chunk-OSQRXVG2.js.map +1 -0
  176. package/dist/chunk-OTDN3OUQ.js +215 -0
  177. package/dist/chunk-OTDN3OUQ.js.map +1 -0
  178. package/dist/chunk-PNZSGAB2.js +114 -0
  179. package/dist/chunk-PNZSGAB2.js.map +1 -0
  180. package/dist/chunk-PRWIX6UW.js +21 -0
  181. package/dist/chunk-PRWIX6UW.js.map +1 -0
  182. package/dist/chunk-PSXUNOVU.js +7 -0
  183. package/dist/chunk-PSXUNOVU.js.map +1 -0
  184. package/dist/chunk-QLTJSCE6.js +44 -0
  185. package/dist/chunk-QLTJSCE6.js.map +1 -0
  186. package/dist/chunk-RC23QROE.js +447 -0
  187. package/dist/chunk-RC23QROE.js.map +1 -0
  188. package/dist/chunk-RDVTWIYY.js +212 -0
  189. package/dist/chunk-RDVTWIYY.js.map +1 -0
  190. package/dist/chunk-RFH7N6EP.js +36 -0
  191. package/dist/chunk-RFH7N6EP.js.map +1 -0
  192. package/dist/chunk-RHVN6NA7.js +134 -0
  193. package/dist/chunk-RHVN6NA7.js.map +1 -0
  194. package/dist/chunk-S7C6TIIF.js +21 -0
  195. package/dist/chunk-S7C6TIIF.js.map +1 -0
  196. package/dist/chunk-SNQ3TOWP.js +20 -0
  197. package/dist/chunk-SNQ3TOWP.js.map +1 -0
  198. package/dist/chunk-SOVM2VEK.js +14 -0
  199. package/dist/chunk-SOVM2VEK.js.map +1 -0
  200. package/dist/chunk-SQDOBLBP.js +13 -0
  201. package/dist/chunk-SQDOBLBP.js.map +1 -0
  202. package/dist/chunk-SR7F3TJY.js +130 -0
  203. package/dist/chunk-SR7F3TJY.js.map +1 -0
  204. package/dist/chunk-SZVPIHWE.js +129 -0
  205. package/dist/chunk-SZVPIHWE.js.map +1 -0
  206. package/dist/chunk-T4BIIU5E.js +89 -0
  207. package/dist/chunk-T4BIIU5E.js.map +1 -0
  208. package/dist/chunk-T6SCOJF4.js +92 -0
  209. package/dist/chunk-T6SCOJF4.js.map +1 -0
  210. package/dist/chunk-TNXH7BJS.js +48 -0
  211. package/dist/chunk-TNXH7BJS.js.map +1 -0
  212. package/dist/chunk-U64T4YZE.js +9 -0
  213. package/dist/chunk-U64T4YZE.js.map +1 -0
  214. package/dist/chunk-UQ5EHOH2.js +39 -0
  215. package/dist/chunk-UQ5EHOH2.js.map +1 -0
  216. package/dist/chunk-UTN4GBPQ.js +1 -0
  217. package/dist/chunk-UTN4GBPQ.js.map +1 -0
  218. package/dist/chunk-V4AF6DI4.js +16 -0
  219. package/dist/chunk-V4AF6DI4.js.map +1 -0
  220. package/dist/chunk-W72PRNJY.js +126 -0
  221. package/dist/chunk-W72PRNJY.js.map +1 -0
  222. package/dist/chunk-WL67FZGF.js +21 -0
  223. package/dist/chunk-WL67FZGF.js.map +1 -0
  224. package/dist/chunk-WWGYCIJX.js +29 -0
  225. package/dist/chunk-WWGYCIJX.js.map +1 -0
  226. package/dist/chunk-X2GMTYPA.js +50 -0
  227. package/dist/chunk-X2GMTYPA.js.map +1 -0
  228. package/dist/chunk-XCEI7NUH.js +41 -0
  229. package/dist/chunk-XCEI7NUH.js.map +1 -0
  230. package/dist/chunk-Y7GDG744.js +88 -0
  231. package/dist/chunk-Y7GDG744.js.map +1 -0
  232. package/dist/chunk-Y7RRSEOC.js +9 -0
  233. package/dist/chunk-Y7RRSEOC.js.map +1 -0
  234. package/dist/chunk-YLPAPPLW.js +75 -0
  235. package/dist/chunk-YLPAPPLW.js.map +1 -0
  236. package/dist/chunk-YPWODKD5.js +184 -0
  237. package/dist/chunk-YPWODKD5.js.map +1 -0
  238. package/dist/chunk-YSLTTQLC.js +25 -0
  239. package/dist/chunk-YSLTTQLC.js.map +1 -0
  240. package/dist/chunk-YTN6BKWA.js +121 -0
  241. package/dist/chunk-YTN6BKWA.js.map +1 -0
  242. package/dist/chunk-Z7PQCAVK.js +200 -0
  243. package/dist/chunk-Z7PQCAVK.js.map +1 -0
  244. package/dist/chunk-ZUKFQL6E.js +47 -0
  245. package/dist/chunk-ZUKFQL6E.js.map +1 -0
  246. package/dist/chunk-ZUMULSEQ.js +1 -0
  247. package/dist/chunk-ZUMULSEQ.js.map +1 -0
  248. package/dist/runtime/analytics/index.js +8 -41
  249. package/dist/runtime/analytics/index.js.map +1 -1
  250. package/dist/runtime/analytics/types.js +8 -41
  251. package/dist/runtime/analytics/types.js.map +1 -1
  252. package/dist/runtime/base-classes/activity-entity-repository.js +6 -312
  253. package/dist/runtime/base-classes/activity-entity-repository.js.map +1 -1
  254. package/dist/runtime/base-classes/activity-entity-service.js +6 -212
  255. package/dist/runtime/base-classes/activity-entity-service.js.map +1 -1
  256. package/dist/runtime/base-classes/base-read-use-cases.js +5 -27
  257. package/dist/runtime/base-classes/base-read-use-cases.js.map +1 -1
  258. package/dist/runtime/base-classes/base-repository.js +5 -277
  259. package/dist/runtime/base-classes/base-repository.js.map +1 -1
  260. package/dist/runtime/base-classes/base-service.js +5 -184
  261. package/dist/runtime/base-classes/base-service.js.map +1 -1
  262. package/dist/runtime/base-classes/index.js +59 -1076
  263. package/dist/runtime/base-classes/index.js.map +1 -1
  264. package/dist/runtime/base-classes/integrated-entity-repository.js +6 -486
  265. package/dist/runtime/base-classes/integrated-entity-repository.js.map +1 -1
  266. package/dist/runtime/base-classes/integrated-entity-service.js +6 -213
  267. package/dist/runtime/base-classes/integrated-entity-service.js.map +1 -1
  268. package/dist/runtime/base-classes/junction-integration-repository.js +8 -448
  269. package/dist/runtime/base-classes/junction-integration-repository.js.map +1 -1
  270. package/dist/runtime/base-classes/knowledge-entity-repository.js +6 -283
  271. package/dist/runtime/base-classes/knowledge-entity-repository.js.map +1 -1
  272. package/dist/runtime/base-classes/knowledge-entity-service.js +6 -190
  273. package/dist/runtime/base-classes/knowledge-entity-service.js.map +1 -1
  274. package/dist/runtime/base-classes/lifecycle-events.js +8 -70
  275. package/dist/runtime/base-classes/lifecycle-events.js.map +1 -1
  276. package/dist/runtime/base-classes/metadata-entity-repository.js +6 -330
  277. package/dist/runtime/base-classes/metadata-entity-repository.js.map +1 -1
  278. package/dist/runtime/base-classes/metadata-entity-service.js +6 -212
  279. package/dist/runtime/base-classes/metadata-entity-service.js.map +1 -1
  280. package/dist/runtime/base-classes/tenant-context.js +10 -36
  281. package/dist/runtime/base-classes/tenant-context.js.map +1 -1
  282. package/dist/runtime/base-classes/with-analytics.js +4 -7
  283. package/dist/runtime/base-classes/with-analytics.js.map +1 -1
  284. package/dist/runtime/constants/tokens.js +5 -3
  285. package/dist/runtime/constants/tokens.js.map +1 -1
  286. package/dist/runtime/eav-helpers.js +2 -0
  287. package/dist/runtime/eav-helpers.js.map +1 -1
  288. package/dist/runtime/pipes/zod-validation.pipe.js +3 -10
  289. package/dist/runtime/pipes/zod-validation.pipe.js.map +1 -1
  290. package/dist/runtime/shared/openapi/error-response.dto.js +5 -8
  291. package/dist/runtime/shared/openapi/error-response.dto.js.map +1 -1
  292. package/dist/runtime/shared/openapi/errors.js +5 -19
  293. package/dist/runtime/shared/openapi/errors.js.map +1 -1
  294. package/dist/runtime/shared/openapi/index.js +15 -106
  295. package/dist/runtime/shared/openapi/index.js.map +1 -1
  296. package/dist/runtime/shared/openapi/registry.js +6 -103
  297. package/dist/runtime/shared/openapi/registry.js.map +1 -1
  298. package/dist/runtime/shared/openapi/registry.tokens.js +4 -2
  299. package/dist/runtime/shared/openapi/registry.tokens.js.map +1 -1
  300. package/dist/runtime/subsystems/analytics/analytics.module.js +8 -117
  301. package/dist/runtime/subsystems/analytics/analytics.module.js.map +1 -1
  302. package/dist/runtime/subsystems/analytics/analytics.tokens.js +7 -8
  303. package/dist/runtime/subsystems/analytics/analytics.tokens.js.map +1 -1
  304. package/dist/runtime/subsystems/analytics/cube-backend.js +6 -71
  305. package/dist/runtime/subsystems/analytics/cube-backend.js.map +1 -1
  306. package/dist/runtime/subsystems/analytics/index.js +16 -117
  307. package/dist/runtime/subsystems/analytics/index.js.map +1 -1
  308. package/dist/runtime/subsystems/analytics/noop-backend.js +4 -21
  309. package/dist/runtime/subsystems/analytics/noop-backend.js.map +1 -1
  310. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js +4 -8
  311. package/dist/runtime/subsystems/auth/auth-oauth-state.schema.js.map +1 -1
  312. package/dist/runtime/subsystems/auth/auth.module.js +12 -359
  313. package/dist/runtime/subsystems/auth/auth.module.js.map +1 -1
  314. package/dist/runtime/subsystems/auth/auth.tokens.js +12 -13
  315. package/dist/runtime/subsystems/auth/auth.tokens.js.map +1 -1
  316. package/dist/runtime/subsystems/auth/backends/encryption-key/env.js +4 -49
  317. package/dist/runtime/subsystems/auth/backends/encryption-key/env.js.map +1 -1
  318. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js +6 -64
  319. package/dist/runtime/subsystems/auth/backends/state-store.drizzle-backend.js.map +1 -1
  320. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js +5 -47
  321. package/dist/runtime/subsystems/auth/backends/state-store.memory-backend.js.map +1 -1
  322. package/dist/runtime/subsystems/auth/controllers/auth.controller.js +5 -139
  323. package/dist/runtime/subsystems/auth/controllers/auth.controller.js.map +1 -1
  324. package/dist/runtime/subsystems/auth/index.js +53 -542
  325. package/dist/runtime/subsystems/auth/index.js.map +1 -1
  326. package/dist/runtime/subsystems/auth/middleware/requester-context.js +9 -65
  327. package/dist/runtime/subsystems/auth/middleware/requester-context.js.map +1 -1
  328. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js +4 -9
  329. package/dist/runtime/subsystems/auth/protocols/oauth-state-store.js.map +1 -1
  330. package/dist/runtime/subsystems/auth/runtime/connection-broken.error.js +4 -15
  331. package/dist/runtime/subsystems/auth/runtime/connection-broken.error.js.map +1 -1
  332. package/dist/runtime/subsystems/auth/runtime/oauth2-refresh.strategy.js +5 -104
  333. package/dist/runtime/subsystems/auth/runtime/oauth2-refresh.strategy.js.map +1 -1
  334. package/dist/runtime/subsystems/auth/runtime/session-expired.error.js +5 -16
  335. package/dist/runtime/subsystems/auth/runtime/session-expired.error.js.map +1 -1
  336. package/dist/runtime/subsystems/auth/runtime/with-auth-retry.js +5 -29
  337. package/dist/runtime/subsystems/auth/runtime/with-auth-retry.js.map +1 -1
  338. package/dist/runtime/subsystems/bridge/assert-tenant-id.js +5 -18
  339. package/dist/runtime/subsystems/bridge/assert-tenant-id.js.map +1 -1
  340. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js +12 -184
  341. package/dist/runtime/subsystems/bridge/bridge-delivery-handler.js.map +1 -1
  342. package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.js +10 -448
  343. package/dist/runtime/subsystems/bridge/bridge-delivery.drizzle-backend.js.map +1 -1
  344. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js +5 -126
  345. package/dist/runtime/subsystems/bridge/bridge-delivery.memory-backend.js.map +1 -1
  346. package/dist/runtime/subsystems/bridge/bridge-delivery.schema.js +6 -308
  347. package/dist/runtime/subsystems/bridge/bridge-delivery.schema.js.map +1 -1
  348. package/dist/runtime/subsystems/bridge/bridge-errors.js +6 -35
  349. package/dist/runtime/subsystems/bridge/bridge-errors.js.map +1 -1
  350. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js +14 -606
  351. package/dist/runtime/subsystems/bridge/bridge-outbox-drain-hook.js.map +1 -1
  352. package/dist/runtime/subsystems/bridge/bridge.module.js +35 -3476
  353. package/dist/runtime/subsystems/bridge/bridge.module.js.map +1 -1
  354. package/dist/runtime/subsystems/bridge/bridge.tokens.js +9 -7
  355. package/dist/runtime/subsystems/bridge/bridge.tokens.js.map +1 -1
  356. package/dist/runtime/subsystems/bridge/event-flow.service.js +11 -137
  357. package/dist/runtime/subsystems/bridge/event-flow.service.js.map +1 -1
  358. package/dist/runtime/subsystems/bridge/generated/registry.js +4 -2
  359. package/dist/runtime/subsystems/bridge/generated/registry.js.map +1 -1
  360. package/dist/runtime/subsystems/bridge/index.js +60 -3470
  361. package/dist/runtime/subsystems/bridge/index.js.map +1 -1
  362. package/dist/runtime/subsystems/bridge/reserved-pools.js +4 -6
  363. package/dist/runtime/subsystems/bridge/reserved-pools.js.map +1 -1
  364. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js +10 -133
  365. package/dist/runtime/subsystems/cache/cache.drizzle-backend.js.map +1 -1
  366. package/dist/runtime/subsystems/cache/cache.memory-backend.js +6 -101
  367. package/dist/runtime/subsystems/cache/cache.memory-backend.js.map +1 -1
  368. package/dist/runtime/subsystems/cache/cache.module.js +10 -278
  369. package/dist/runtime/subsystems/cache/cache.module.js.map +1 -1
  370. package/dist/runtime/subsystems/cache/cache.schema.js +4 -14
  371. package/dist/runtime/subsystems/cache/cache.schema.js.map +1 -1
  372. package/dist/runtime/subsystems/cache/cache.tokens.js +6 -7
  373. package/dist/runtime/subsystems/cache/cache.tokens.js.map +1 -1
  374. package/dist/runtime/subsystems/cache/index.js +20 -278
  375. package/dist/runtime/subsystems/cache/index.js.map +1 -1
  376. package/dist/runtime/subsystems/events/domain-events.schema.js +3 -72
  377. package/dist/runtime/subsystems/events/domain-events.schema.js.map +1 -1
  378. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js +9 -413
  379. package/dist/runtime/subsystems/events/event-bus.drizzle-backend.js.map +1 -1
  380. package/dist/runtime/subsystems/events/event-bus.memory-backend.js +7 -235
  381. package/dist/runtime/subsystems/events/event-bus.memory-backend.js.map +1 -1
  382. package/dist/runtime/subsystems/events/event-bus.redis-backend.js +8 -20
  383. package/dist/runtime/subsystems/events/event-bus.redis-backend.js.map +1 -1
  384. package/dist/runtime/subsystems/events/event-keyset-cursor.js +8 -30
  385. package/dist/runtime/subsystems/events/event-keyset-cursor.js.map +1 -1
  386. package/dist/runtime/subsystems/events/event-read.protocol.js +2 -0
  387. package/dist/runtime/subsystems/events/event-read.protocol.js.map +1 -1
  388. package/dist/runtime/subsystems/events/events-errors.js +4 -11
  389. package/dist/runtime/subsystems/events/events-errors.js.map +1 -1
  390. package/dist/runtime/subsystems/events/events.module.js +15 -949
  391. package/dist/runtime/subsystems/events/events.module.js.map +1 -1
  392. package/dist/runtime/subsystems/events/events.tokens.js +10 -11
  393. package/dist/runtime/subsystems/events/events.tokens.js.map +1 -1
  394. package/dist/runtime/subsystems/events/generated/bus.js +9 -240
  395. package/dist/runtime/subsystems/events/generated/bus.js.map +1 -1
  396. package/dist/runtime/subsystems/events/generated/index.js +23 -240
  397. package/dist/runtime/subsystems/events/generated/index.js.map +1 -1
  398. package/dist/runtime/subsystems/events/generated/registry.js +5 -82
  399. package/dist/runtime/subsystems/events/generated/registry.js.map +1 -1
  400. package/dist/runtime/subsystems/events/generated/schemas.js +12 -52
  401. package/dist/runtime/subsystems/events/generated/schemas.js.map +1 -1
  402. package/dist/runtime/subsystems/events/generated/types.js +1 -0
  403. package/dist/runtime/subsystems/events/index.js +32 -949
  404. package/dist/runtime/subsystems/events/index.js.map +1 -1
  405. package/dist/runtime/subsystems/index.d.ts +5 -1
  406. package/dist/runtime/subsystems/index.js +182 -5912
  407. package/dist/runtime/subsystems/index.js.map +1 -1
  408. package/dist/runtime/subsystems/integration/build-change-source.js +6 -178
  409. package/dist/runtime/subsystems/integration/build-change-source.js.map +1 -1
  410. package/dist/runtime/subsystems/integration/deep-equal.differ.js +4 -109
  411. package/dist/runtime/subsystems/integration/deep-equal.differ.js.map +1 -1
  412. package/dist/runtime/subsystems/integration/detection-config.schema.js +11 -78
  413. package/dist/runtime/subsystems/integration/detection-config.schema.js.map +1 -1
  414. package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js +5 -30
  415. package/dist/runtime/subsystems/integration/entity-change-source-registry.memory.js.map +1 -1
  416. package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js +4 -9
  417. package/dist/runtime/subsystems/integration/entity-change-source-registry.protocol.js.map +1 -1
  418. package/dist/runtime/subsystems/integration/execute-integration.use-case.js +6 -239
  419. package/dist/runtime/subsystems/integration/execute-integration.use-case.js.map +1 -1
  420. package/dist/runtime/subsystems/integration/incremental-read.js +5 -144
  421. package/dist/runtime/subsystems/integration/incremental-read.js.map +1 -1
  422. package/dist/runtime/subsystems/integration/index.js +83 -1352
  423. package/dist/runtime/subsystems/integration/index.js.map +1 -1
  424. package/dist/runtime/subsystems/integration/integration-audit.schema.js +10 -155
  425. package/dist/runtime/subsystems/integration/integration-audit.schema.js.map +1 -1
  426. package/dist/runtime/subsystems/integration/integration-cursor-store.drizzle-backend.js +7 -270
  427. package/dist/runtime/subsystems/integration/integration-cursor-store.drizzle-backend.js.map +1 -1
  428. package/dist/runtime/subsystems/integration/integration-cursor-store.memory-backend.js +4 -65
  429. package/dist/runtime/subsystems/integration/integration-cursor-store.memory-backend.js.map +1 -1
  430. package/dist/runtime/subsystems/integration/integration-errors.js +5 -15
  431. package/dist/runtime/subsystems/integration/integration-errors.js.map +1 -1
  432. package/dist/runtime/subsystems/integration/integration-field-diff.protocol.js +5 -7
  433. package/dist/runtime/subsystems/integration/integration-field-diff.protocol.js.map +1 -1
  434. package/dist/runtime/subsystems/integration/integration-run-recorder.drizzle-backend.js +8 -303
  435. package/dist/runtime/subsystems/integration/integration-run-recorder.drizzle-backend.js.map +1 -1
  436. package/dist/runtime/subsystems/integration/integration-run-recorder.memory-backend.js +5 -125
  437. package/dist/runtime/subsystems/integration/integration-run-recorder.memory-backend.js.map +1 -1
  438. package/dist/runtime/subsystems/integration/integration.module.js +13 -700
  439. package/dist/runtime/subsystems/integration/integration.module.js.map +1 -1
  440. package/dist/runtime/subsystems/integration/integration.tokens.js +11 -9
  441. package/dist/runtime/subsystems/integration/integration.tokens.js.map +1 -1
  442. package/dist/runtime/subsystems/integration/loopback.middleware.js +4 -16
  443. package/dist/runtime/subsystems/integration/loopback.middleware.js.map +1 -1
  444. package/dist/runtime/subsystems/integration/poll-change-source.d.ts +1 -1
  445. package/dist/runtime/subsystems/integration/poll-change-source.js +4 -89
  446. package/dist/runtime/subsystems/integration/poll-change-source.js.map +1 -1
  447. package/dist/runtime/subsystems/integration/webhook-change-source.d.ts +4 -3
  448. package/dist/runtime/subsystems/integration/webhook-change-source.js +4 -70
  449. package/dist/runtime/subsystems/integration/webhook-change-source.js.map +1 -1
  450. package/dist/runtime/subsystems/jobs/bullmq.config.js +9 -140
  451. package/dist/runtime/subsystems/jobs/bullmq.config.js.map +1 -1
  452. package/dist/runtime/subsystems/jobs/index.js +88 -2691
  453. package/dist/runtime/subsystems/jobs/index.js.map +1 -1
  454. package/dist/runtime/subsystems/jobs/job-handler.base.js +10 -49
  455. package/dist/runtime/subsystems/jobs/job-handler.base.js.map +1 -1
  456. package/dist/runtime/subsystems/jobs/job-orchestration.schema.js +13 -152
  457. package/dist/runtime/subsystems/jobs/job-orchestration.schema.js.map +1 -1
  458. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js +36 -699
  459. package/dist/runtime/subsystems/jobs/job-orchestrator.bullmq-backend.js.map +1 -1
  460. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js +10 -564
  461. package/dist/runtime/subsystems/jobs/job-orchestrator.drizzle-backend.js.map +1 -1
  462. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js +10 -824
  463. package/dist/runtime/subsystems/jobs/job-orchestrator.memory-backend.js.map +1 -1
  464. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.js +9 -51
  465. package/dist/runtime/subsystems/jobs/job-run-keyset-cursor.js.map +1 -1
  466. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js +9 -416
  467. package/dist/runtime/subsystems/jobs/job-run-service.drizzle-backend.js.map +1 -1
  468. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js +9 -290
  469. package/dist/runtime/subsystems/jobs/job-run-service.memory-backend.js.map +1 -1
  470. package/dist/runtime/subsystems/jobs/job-step-service.drizzle-backend.js +5 -213
  471. package/dist/runtime/subsystems/jobs/job-step-service.drizzle-backend.js.map +1 -1
  472. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js +5 -131
  473. package/dist/runtime/subsystems/jobs/job-step-service.memory-backend.js.map +1 -1
  474. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js +9 -175
  475. package/dist/runtime/subsystems/jobs/job-worker.bullmq-backend.js.map +1 -1
  476. package/dist/runtime/subsystems/jobs/job-worker.js +14 -613
  477. package/dist/runtime/subsystems/jobs/job-worker.js.map +1 -1
  478. package/dist/runtime/subsystems/jobs/job-worker.module.js +23 -2647
  479. package/dist/runtime/subsystems/jobs/job-worker.module.js.map +1 -1
  480. package/dist/runtime/subsystems/jobs/jobs-domain.module.js +19 -1897
  481. package/dist/runtime/subsystems/jobs/jobs-domain.module.js.map +1 -1
  482. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js +8 -9
  483. package/dist/runtime/subsystems/jobs/jobs-domain.tokens.js.map +1 -1
  484. package/dist/runtime/subsystems/jobs/jobs-errors.js +10 -78
  485. package/dist/runtime/subsystems/jobs/jobs-errors.js.map +1 -1
  486. package/dist/runtime/subsystems/jobs/memory-job-store.js +4 -15
  487. package/dist/runtime/subsystems/jobs/memory-job-store.js.map +1 -1
  488. package/dist/runtime/subsystems/jobs/pool-config.loader.js +9 -124
  489. package/dist/runtime/subsystems/jobs/pool-config.loader.js.map +1 -1
  490. package/dist/runtime/subsystems/observability/index.js +21 -310
  491. package/dist/runtime/subsystems/observability/index.js.map +1 -1
  492. package/dist/runtime/subsystems/observability/observability-errors.js +4 -9
  493. package/dist/runtime/subsystems/observability/observability-errors.js.map +1 -1
  494. package/dist/runtime/subsystems/observability/observability.module.js +11 -300
  495. package/dist/runtime/subsystems/observability/observability.module.js.map +1 -1
  496. package/dist/runtime/subsystems/observability/observability.service.js +9 -197
  497. package/dist/runtime/subsystems/observability/observability.service.js.map +1 -1
  498. package/dist/runtime/subsystems/observability/observability.tokens.js +5 -3
  499. package/dist/runtime/subsystems/observability/observability.tokens.js.map +1 -1
  500. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js +4 -84
  501. package/dist/runtime/subsystems/observability/reporters/bridge-metrics.reporter.js.map +1 -1
  502. package/dist/runtime/subsystems/observability/reporters/index.js +5 -84
  503. package/dist/runtime/subsystems/observability/reporters/index.js.map +1 -1
  504. package/dist/runtime/subsystems/storage/index.js +15 -200
  505. package/dist/runtime/subsystems/storage/index.js.map +1 -1
  506. package/dist/runtime/subsystems/storage/storage.local-backend.js +4 -103
  507. package/dist/runtime/subsystems/storage/storage.local-backend.js.map +1 -1
  508. package/dist/runtime/subsystems/storage/storage.memory-backend.js +5 -68
  509. package/dist/runtime/subsystems/storage/storage.memory-backend.js.map +1 -1
  510. package/dist/runtime/subsystems/storage/storage.module.js +8 -200
  511. package/dist/runtime/subsystems/storage/storage.module.js.map +1 -1
  512. package/dist/runtime/subsystems/storage/storage.tokens.js +5 -6
  513. package/dist/runtime/subsystems/storage/storage.tokens.js.map +1 -1
  514. package/dist/runtime/subsystems/storage/storage.utils.js +4 -14
  515. package/dist/runtime/subsystems/storage/storage.utils.js.map +1 -1
  516. package/dist/runtime/subsystems/token-key.js +5 -3
  517. package/dist/runtime/subsystems/token-key.js.map +1 -1
  518. package/dist/src/cli/index.js +637 -5454
  519. package/dist/src/cli/index.js.map +1 -1
  520. package/dist/src/index.js +68 -4170
  521. package/dist/src/index.js.map +1 -1
  522. package/package.json +1 -1
  523. package/runtime/subsystems/bridge/bridge-outbox-drain-hook.ts +44 -21
  524. package/runtime/subsystems/index.ts +27 -0
  525. package/runtime/subsystems/integration/poll-change-source.ts +10 -7
  526. package/runtime/subsystems/integration/webhook-change-source.ts +12 -8
  527. package/runtime/subsystems/jobs/job-worker.ts +17 -11
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../runtime/base-classes/lifecycle-events.ts"],"sourcesContent":["/**\n * Lifecycle event emission for BaseService.\n *\n * Ported from pattern-stack/atoms/patterns/services/base.py — the Python\n * BaseService emits LIFECYCLE and CHANGE events on every CRUD operation.\n * This module provides the same capability for the TypeScript codegen stack.\n *\n * Design:\n * - Fire-and-forget: event emission never fails the CRUD operation.\n * - IEventBus is optional: if no EVENT_BUS is injected, emission is silently\n * skipped. This means base classes work in projects that haven't installed\n * the events subsystem.\n * - LIFECYCLE events carry an entity snapshot in payload.\n * - CHANGE events carry per-field old/new diffs.\n * - Controlled per-entity via `emitLifecycleEvents` flag (default: true).\n *\n * @deprecated EVT-7 — Lifecycle events are untyped and emit outside of the\n * CRUD transaction. New work should declare an `emits:` block on the entity\n * and publish typed domain events from use-cases via TYPED_EVENT_BUS inside\n * the same Drizzle transaction. See `docs/specs/EVT-7.md`. This helper is\n * retained for BaseService backward compatibility until all entities have\n * migrated to typed emits.\n */\n\nimport { randomUUID } from 'crypto';\nimport type { IEventBus, DomainEvent } from '../subsystems/events/event-bus.protocol';\n\n// ============================================================================\n// Event categories (subset of pattern-stack's EventCategory)\n// ============================================================================\n\nexport type EventCategory = 'lifecycle' | 'change';\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** System fields excluded from entity snapshots and change diffs. */\nconst SYSTEM_FIELDS = new Set([\n\t'id',\n\t'createdAt',\n\t'updatedAt',\n\t'deletedAt',\n]);\n\n/**\n * Snapshot an entity's field values, excluding system fields.\n * Mirrors pattern-stack's `_get_entity_snapshot()`.\n */\nexport function entitySnapshot(entity: Record<string, unknown>): Record<string, unknown> {\n\tconst snap: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(entity)) {\n\t\tif (!SYSTEM_FIELDS.has(key)) {\n\t\t\tsnap[key] = value;\n\t\t}\n\t}\n\treturn snap;\n}\n\n/**\n * Diff two entity snapshots, returning per-field old/new pairs.\n * Only includes fields that actually changed.\n */\nexport function diffSnapshots(\n\tbefore: Record<string, unknown>,\n\tafter: Record<string, unknown>,\n): Array<{ field: string; oldValue: unknown; newValue: unknown }> {\n\tconst changes: Array<{ field: string; oldValue: unknown; newValue: unknown }> = [];\n\tconst allKeys = new Set([...Object.keys(before), ...Object.keys(after)]);\n\n\tfor (const key of allKeys) {\n\t\tif (SYSTEM_FIELDS.has(key)) continue;\n\t\tconst oldVal = before[key];\n\t\tconst newVal = after[key];\n\t\t// Simple equality — good enough for primitives and nulls.\n\t\t// For deep objects, JSON.stringify comparison.\n\t\tif (oldVal !== newVal && JSON.stringify(oldVal) !== JSON.stringify(newVal)) {\n\t\t\tchanges.push({ field: key, oldValue: oldVal, newValue: newVal });\n\t\t}\n\t}\n\n\treturn changes;\n}\n\n// ============================================================================\n// Event builders\n// ============================================================================\n\nexport function buildLifecycleEvent(\n\tentityName: string,\n\taction: 'created' | 'updated' | 'deleted',\n\tentityId: string,\n\tsnapshot?: Record<string, unknown>,\n): DomainEvent {\n\treturn {\n\t\tid: randomUUID(),\n\t\ttype: `${entityName}.${action}`,\n\t\taggregateId: entityId,\n\t\taggregateType: entityName,\n\t\tpayload: snapshot ? { snapshot } : {},\n\t\toccurredAt: new Date(),\n\t\tmetadata: { category: 'lifecycle' as EventCategory },\n\t};\n}\n\nexport function buildChangeEvents(\n\tentityName: string,\n\tentityId: string,\n\tchanges: Array<{ field: string; oldValue: unknown; newValue: unknown }>,\n): DomainEvent[] {\n\treturn changes.map((c) => ({\n\t\tid: randomUUID(),\n\t\ttype: `${entityName}.field_changed`,\n\t\taggregateId: entityId,\n\t\taggregateType: entityName,\n\t\tpayload: {\n\t\t\tfieldName: c.field,\n\t\t\toldValue: c.oldValue,\n\t\t\tnewValue: c.newValue,\n\t\t},\n\t\toccurredAt: new Date(),\n\t\tmetadata: { category: 'change' as EventCategory },\n\t}));\n}\n\n// ============================================================================\n// Emission helper (fire-and-forget)\n// ============================================================================\n\n/**\n * Emit events to the bus, swallowing errors.\n * Mirrors pattern-stack's `_emit_lifecycle_event()` try/except.\n */\nexport async function emitSafely(\n\teventBus: IEventBus | undefined,\n\tevents: DomainEvent[],\n): Promise<void> {\n\tif (!eventBus || events.length === 0) return;\n\ttry {\n\t\tif (events.length === 1) {\n\t\t\tconst only = events[0];\n\t\t\tif (!only) return;\n\t\t\tawait eventBus.publish(only);\n\t\t} else {\n\t\t\tawait eventBus.publishMany(events);\n\t\t}\n\t} catch {\n\t\t// Log but never fail the CRUD operation.\n\t\t// In production, this would use a structured logger.\n\t\tconsole.warn(`[lifecycle-events] failed to emit ${events.length} event(s)`);\n\t}\n}\n"],"mappings":";AAwBA,SAAS,kBAAkB;AAc3B,IAAM,gBAAgB,oBAAI,IAAI;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACD,CAAC;AAMM,SAAS,eAAe,QAA0D;AACxF,QAAM,OAAgC,CAAC;AACvC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AAClD,QAAI,CAAC,cAAc,IAAI,GAAG,GAAG;AAC5B,WAAK,GAAG,IAAI;AAAA,IACb;AAAA,EACD;AACA,SAAO;AACR;AAMO,SAAS,cACf,QACA,OACiE;AACjE,QAAM,UAA0E,CAAC;AACjF,QAAM,UAAU,oBAAI,IAAI,CAAC,GAAG,OAAO,KAAK,MAAM,GAAG,GAAG,OAAO,KAAK,KAAK,CAAC,CAAC;AAEvE,aAAW,OAAO,SAAS;AAC1B,QAAI,cAAc,IAAI,GAAG,EAAG;AAC5B,UAAM,SAAS,OAAO,GAAG;AACzB,UAAM,SAAS,MAAM,GAAG;AAGxB,QAAI,WAAW,UAAU,KAAK,UAAU,MAAM,MAAM,KAAK,UAAU,MAAM,GAAG;AAC3E,cAAQ,KAAK,EAAE,OAAO,KAAK,UAAU,QAAQ,UAAU,OAAO,CAAC;AAAA,IAChE;AAAA,EACD;AAEA,SAAO;AACR;AAMO,SAAS,oBACf,YACA,QACA,UACA,UACc;AACd,SAAO;AAAA,IACN,IAAI,WAAW;AAAA,IACf,MAAM,GAAG,UAAU,IAAI,MAAM;AAAA,IAC7B,aAAa;AAAA,IACb,eAAe;AAAA,IACf,SAAS,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,IACpC,YAAY,oBAAI,KAAK;AAAA,IACrB,UAAU,EAAE,UAAU,YAA6B;AAAA,EACpD;AACD;AAEO,SAAS,kBACf,YACA,UACA,SACgB;AAChB,SAAO,QAAQ,IAAI,CAAC,OAAO;AAAA,IAC1B,IAAI,WAAW;AAAA,IACf,MAAM,GAAG,UAAU;AAAA,IACnB,aAAa;AAAA,IACb,eAAe;AAAA,IACf,SAAS;AAAA,MACR,WAAW,EAAE;AAAA,MACb,UAAU,EAAE;AAAA,MACZ,UAAU,EAAE;AAAA,IACb;AAAA,IACA,YAAY,oBAAI,KAAK;AAAA,IACrB,UAAU,EAAE,UAAU,SAA0B;AAAA,EACjD,EAAE;AACH;AAUA,eAAsB,WACrB,UACA,QACgB;AAChB,MAAI,CAAC,YAAY,OAAO,WAAW,EAAG;AACtC,MAAI;AACH,QAAI,OAAO,WAAW,GAAG;AACxB,YAAM,OAAO,OAAO,CAAC;AACrB,UAAI,CAAC,KAAM;AACX,YAAM,SAAS,QAAQ,IAAI;AAAA,IAC5B,OAAO;AACN,YAAM,SAAS,YAAY,MAAM;AAAA,IAClC;AAAA,EACD,QAAQ;AAGP,YAAQ,KAAK,qCAAqC,OAAO,MAAM,WAAW;AAAA,EAC3E;AACD;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,333 +1,9 @@
1
- // runtime/base-classes/metadata-entity-repository.ts
2
- import { eq as eq2, and as and2, desc } from "drizzle-orm";
3
-
4
- // runtime/base-classes/base-repository.ts
5
- import { and, eq, inArray, isNull, sql } from "drizzle-orm";
6
-
7
- // runtime/base-classes/tenant-context.ts
8
- import { AsyncLocalStorage } from "async_hooks";
9
- var als = new AsyncLocalStorage();
10
- function requireRequester() {
11
- const ctx = als.getStore();
12
- if (!ctx) {
13
- throw new Error(
14
- "No requester context active. Wrap the entry point in withRequester({ userId, organizationId }, fn). See tenant-context.ts."
15
- );
16
- }
17
- return ctx;
18
- }
19
- function tryGetRequester() {
20
- return als.getStore();
21
- }
22
-
23
- // runtime/base-classes/base-repository.ts
24
- var BaseRepository = class {
25
- // eslint-disable-line @typescript-eslint/no-explicit-any
26
- /**
27
- * Behavior flags controlling automatic behavior injection.
28
- * Override in concrete repositories to enable behaviors.
29
- */
30
- behaviors = {
31
- timestamps: false,
32
- softDelete: false,
33
- userTracking: false
34
- };
35
- /**
36
- * Ambient tenant-scope enforcement for `userTracking` repos (see
37
- * `scopePredicate`). Only has effect when `behaviors.userTracking === true`.
38
- *
39
- * - `'lenient'` (default): when no ambient requester context is active,
40
- * reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting
41
- * ambient scoping is additive. Scoping kicks in automatically once a
42
- * boundary installs `withRequester(...)`.
43
- * - `'strict'`: a missing ambient context throws (`requireRequester`),
44
- * making a forgotten boundary fail loud instead of silently returning
45
- * cross-tenant rows. Recommended for new multi-tenant consumers — override
46
- * in a concrete repo or a family base class.
47
- */
48
- scopeEnforcement = "lenient";
49
- db;
50
- constructor(db) {
51
- this.db = db;
52
- }
53
- /**
54
- * Pick the runner for a write: the caller-supplied transaction handle
55
- * if present, otherwise the repository's own client. Keeps the `tx`
56
- * parameter purely additive — callers without a transaction call as
57
- * before. Used by the write methods below + consumer overrides (e.g.
58
- * the generated `upsertCurrentValues` on EAV value tables).
59
- */
60
- runner(tx) {
61
- return tx ?? this.db;
62
- }
63
- // ============================================================================
64
- // Read Operations
65
- // ============================================================================
66
- /**
67
- * Find a single entity by its primary key.
68
- * Returns null if not found (or soft-deleted when softDelete=true).
69
- */
70
- async findById(id) {
71
- const rows = await this.baseQuery(eq(this.table["id"], id)).limit(1);
72
- return rows[0] ?? null;
73
- }
74
- /**
75
- * Find multiple entities by their primary keys.
76
- * Returns empty array immediately for empty input (avoids DB errors).
77
- */
78
- async findByIds(ids) {
79
- if (ids.length === 0) return [];
80
- const rows = await this.baseQuery(inArray(this.table["id"], ids));
81
- return rows;
82
- }
83
- /**
84
- * List entities with optional filtering, pagination, and ordering.
85
- */
86
- async list(options) {
87
- let query = this.baseQuery(options?.where);
88
- if (options?.orderBy) {
89
- query = query.orderBy(options.orderBy);
90
- }
91
- if (options?.limit !== void 0) {
92
- query = query.limit(options.limit);
93
- }
94
- if (options?.offset !== void 0) {
95
- query = query.offset(options.offset);
96
- }
97
- const rows = await query;
98
- return rows;
99
- }
100
- /**
101
- * Count entities matching an optional WHERE clause.
102
- * Soft-deleted rows are always excluded when softDelete=true.
103
- */
104
- async count(where) {
105
- let query = this.db.select({ count: sql`cast(count(*) as integer)` }).from(this.table);
106
- const conditions = [];
107
- if (this.behaviors.softDelete) {
108
- conditions.push(isNull(this.table["deletedAt"]));
109
- }
110
- const scope = this.scopePredicate();
111
- if (scope) {
112
- conditions.push(scope);
113
- }
114
- if (where) {
115
- conditions.push(where);
116
- }
117
- if (conditions.length === 1) {
118
- query = query.where(conditions[0]);
119
- } else if (conditions.length > 1) {
120
- query = query.where(and(...conditions));
121
- }
122
- const rows = await query;
123
- return rows[0]?.count ?? 0;
124
- }
125
- /**
126
- * Check whether an entity with the given id exists.
127
- */
128
- async exists(id) {
129
- const result = await this.findById(id);
130
- return result !== null;
131
- }
132
- // ============================================================================
133
- // Write Operations
134
- // ============================================================================
135
- /**
136
- * Insert a new entity. Timestamps are auto-injected when timestamps=true.
137
- */
138
- async create(input, tx) {
139
- const data = this.withTimestamps(input, "create");
140
- const rows = await this.runner(tx).insert(this.table).values(data).returning();
141
- return rows[0];
142
- }
143
- /**
144
- * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.
145
- * Returns the updated entity.
146
- */
147
- async update(id, input, tx) {
148
- const data = this.withTimestamps(input, "update");
149
- const rows = await this.runner(tx).update(this.table).set(data).where(this.scopeAnd(eq(this.table["id"], id))).returning();
150
- return rows[0];
151
- }
152
- /**
153
- * Delete an entity by id.
154
- * - softDelete=true: sets deletedAt to current timestamp
155
- * - softDelete=false: hard-deletes the row
156
- */
157
- async delete(id, tx) {
158
- const runner = this.runner(tx);
159
- if (this.behaviors.softDelete) {
160
- await runner.update(this.table).set({ deletedAt: /* @__PURE__ */ new Date() }).where(this.scopeAnd(eq(this.table["id"], id)));
161
- } else {
162
- await runner.delete(this.table).where(this.scopeAnd(eq(this.table["id"], id)));
163
- }
164
- }
165
- /**
166
- * Insert or update multiple entities.
167
- * Default naive implementation — family repositories override with
168
- * proper conflict-target upsert (e.g., CrmEntityRepository).
169
- */
170
- async upsertMany(inputs, tx) {
171
- return Promise.all(inputs.map((input) => this.create(input, tx)));
172
- }
173
- // ============================================================================
174
- // Protected Helpers
175
- // ============================================================================
176
- /**
177
- * Base SELECT query that automatically applies the ambient guards —
178
- * soft-delete exclusion (when `softDelete`) and tenant scope (when
179
- * `userTracking` + an active requester context) — combined with an optional
180
- * caller `extra` predicate into a SINGLE `WHERE`.
181
- *
182
- * Pass the leaf predicate as `extra` rather than chaining a second
183
- * `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior
184
- * `.where()` on a `$dynamic()` query, so a chained call would silently drop
185
- * the soft-delete and scope guards. `baseQuery(extra)` is the safe form.
186
- */
187
- baseQuery(extra) {
188
- const query = this.db.select().from(this.table).$dynamic();
189
- const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });
190
- return where ? query.where(where) : query;
191
- }
192
- /**
193
- * Build the ambient tenant-scope predicate for this repo's table.
194
- *
195
- * Returns `undefined` (no scoping) when:
196
- * - `behaviors.userTracking` is false (repo is not user-owned), or
197
- * - no ambient requester context is active AND `scopeEnforcement` is
198
- * `'lenient'` (the default — preserves pre-scoping behavior).
199
- *
200
- * When a requester context is active, scopes by `user_id` per the ambient
201
- * scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN
202
- * ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`
203
- * → no filter. See `tenant-context.ts` for the boundary-install contract.
204
- */
205
- scopePredicate() {
206
- if (!this.behaviors.userTracking) return void 0;
207
- const ctx = this.scopeEnforcement === "strict" ? requireRequester() : tryGetRequester();
208
- if (!ctx) return void 0;
209
- const scope = ctx.scope ?? "user";
210
- switch (scope) {
211
- case "superuser":
212
- return void 0;
213
- case "org":
214
- return ctx.orgUserIds && ctx.orgUserIds.length > 0 ? inArray(this.table["userId"], ctx.orgUserIds) : sql`false`;
215
- case "user":
216
- default:
217
- return eq(this.table["userId"], ctx.userId);
218
- }
219
- }
220
- /**
221
- * Combine the ambient scope predicate (and, optionally, the soft-delete
222
- * guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`
223
- * when nothing applies. Used by read + by-id write paths so a single
224
- * `.where(...)` carries every guard.
225
- */
226
- scopeAnd(extra, opts) {
227
- const conditions = [];
228
- if (opts?.softDelete) conditions.push(isNull(this.table["deletedAt"]));
229
- const scope = this.scopePredicate();
230
- if (scope) conditions.push(scope);
231
- if (extra) conditions.push(extra);
232
- if (conditions.length === 0) return void 0;
233
- if (conditions.length === 1) return conditions[0];
234
- return and(...conditions);
235
- }
236
- /**
237
- * Merge timestamp fields into an input object.
238
- * - mode='create': adds createdAt and updatedAt
239
- * - mode='update': adds updatedAt only
240
- *
241
- * No-op when timestamps behavior is disabled.
242
- */
243
- withTimestamps(input, mode) {
244
- if (!this.behaviors.timestamps) return input;
245
- const now = /* @__PURE__ */ new Date();
246
- if (mode === "create") {
247
- return { ...input, createdAt: now, updatedAt: now };
248
- }
249
- return { ...input, updatedAt: now };
250
- }
251
- /**
252
- * Build a WHERE clause fragment that restricts results to rows whose
253
- * parent (identified by a belongs_to FK) is not soft-deleted.
254
- *
255
- * Use this in custom repository methods when you need "rows reachable
256
- * from an active parent". The default findAll / findById behavior is
257
- * NOT changed by this helper — opt in explicitly where needed.
258
- *
259
- * ADR-021 — Soft-delete cascade: Option A (filter at query time).
260
- * `on_delete` FK rules do not fire for soft-deletes; use this helper
261
- * instead of expecting cascade semantics on the DB level.
262
- *
263
- * Example:
264
- * async listActiveMessages(): Promise<Message[]> {
265
- * return this.list({
266
- * where: this.activeParentFilter(conversations, this.table['conversationId']),
267
- * });
268
- * }
269
- *
270
- * @param parentTable The Drizzle table object for the parent entity.
271
- * @param parentFkColumn The FK column on this (child) table that references parent.id.
272
- */
273
- activeParentFilter(parentTable, parentFkColumn) {
274
- return sql`EXISTS (
275
- SELECT 1 FROM ${parentTable} p
276
- WHERE p.id = ${parentFkColumn}
277
- AND p.deleted_at IS NULL
278
- )`;
279
- }
280
- };
281
-
282
- // runtime/base-classes/metadata-entity-repository.ts
283
- var MetadataEntityRepository = class extends BaseRepository {
284
- /**
285
- * Bulk upsert with a caller-specified conflict target.
286
- * Uses Drizzle's onConflictDoUpdate to merge records.
287
- */
288
- async upsertMany(inputs, tx, options) {
289
- if (inputs.length === 0) return [];
290
- const conflictTarget = options?.conflictTarget;
291
- if (!conflictTarget) {
292
- return super.upsertMany(inputs, tx);
293
- }
294
- const data = inputs.map(
295
- (input) => this.withTimestamps(input, "create")
296
- );
297
- const rows = await this.runner(tx).insert(this.table).values(data).onConflictDoUpdate({
298
- target: this.table[conflictTarget],
299
- set: data[0]
300
- // eslint-disable-line @typescript-eslint/no-explicit-any
301
- }).returning();
302
- return rows;
303
- }
304
- /**
305
- * Find metadata by entity ID and entity type (compound lookup).
306
- */
307
- async findByEntityIdAndType(entityId, entityType) {
308
- const rows = await this.baseQuery().where(
309
- and2(
310
- eq2(this.table["entityId"], entityId),
311
- eq2(this.table["entityType"], entityType)
312
- )
313
- );
314
- return rows;
315
- }
316
- /**
317
- * List all metadata records for an entity.
318
- */
319
- async listByEntityId(entityId) {
320
- const rows = await this.baseQuery().where(eq2(this.table["entityId"], entityId));
321
- return rows;
322
- }
323
- /**
324
- * List metadata history for an entity, ordered by validFrom descending.
325
- */
326
- async listHistoryByEntityId(entityId) {
327
- const rows = await this.baseQuery().where(eq2(this.table["entityId"], entityId)).orderBy(desc(this.table["validFrom"]));
328
- return rows;
329
- }
330
- };
1
+ import {
2
+ MetadataEntityRepository
3
+ } from "../../chunk-7KOW6PU6.js";
4
+ import "../../chunk-J6KZS54B.js";
5
+ import "../../chunk-ZUKFQL6E.js";
6
+ import "../../chunk-2E224ZSN.js";
331
7
  export {
332
8
  MetadataEntityRepository
333
9
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../runtime/base-classes/metadata-entity-repository.ts","../../../runtime/base-classes/base-repository.ts","../../../runtime/base-classes/tenant-context.ts"],"sourcesContent":["/**\n * MetadataEntityRepository<TEntity>\n *\n * Family-specific base for metadata entities (field values, field history, tags).\n * Adds entity-scoped lookups, type filtering, history ordering, and bulk upsert.\n *\n * Concrete repos extend this and declare their table + behaviors.\n */\nimport { eq, and, desc } from 'drizzle-orm';\nimport type { PgTableWithColumns } from 'drizzle-orm/pg-core';\nimport { BaseRepository } from './base-repository';\nimport type { DrizzleTx } from '../types/drizzle';\n\nexport abstract class MetadataEntityRepository<TEntity> extends BaseRepository<TEntity> {\n /**\n * Bulk upsert with a caller-specified conflict target.\n * Uses Drizzle's onConflictDoUpdate to merge records.\n */\n override async upsertMany(\n inputs: Array<Partial<TEntity>>,\n tx?: DrizzleTx,\n options?: { conflictTarget?: keyof PgTableWithColumns<any>['_']['columns'] }, // eslint-disable-line @typescript-eslint/no-explicit-any\n ): Promise<TEntity[]> {\n if (inputs.length === 0) return [];\n const conflictTarget = options?.conflictTarget;\n\n // Fall back to base class naive upsert when no conflict target provided.\n if (!conflictTarget) {\n return super.upsertMany(inputs, tx);\n }\n\n const data = inputs.map((input) =>\n this.withTimestamps(input as Record<string, unknown>, 'create'),\n );\n\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .onConflictDoUpdate({\n target: this.table[conflictTarget as string],\n set: data[0] as any, // eslint-disable-line @typescript-eslint/no-explicit-any\n })\n .returning();\n\n return rows as TEntity[];\n }\n\n /**\n * Find metadata by entity ID and entity type (compound lookup).\n */\n async findByEntityIdAndType(entityId: string, entityType: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(\n and(\n eq(this.table['entityId'], entityId),\n eq(this.table['entityType'], entityType),\n ),\n );\n return rows as TEntity[];\n }\n\n /**\n * List all metadata records for an entity.\n */\n async listByEntityId(entityId: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(eq(this.table['entityId'], entityId));\n return rows as TEntity[];\n }\n\n /**\n * List metadata history for an entity, ordered by validFrom descending.\n */\n async listHistoryByEntityId(entityId: string): Promise<TEntity[]> {\n const rows = await this.baseQuery()\n .where(eq(this.table['entityId'], entityId))\n .orderBy(desc(this.table['validFrom']));\n return rows as TEntity[];\n }\n}\n","/**\n * BaseRepository<TEntity>\n *\n * Abstract base class providing standard CRUD operations via Drizzle ORM.\n * Every generated repository extends this class.\n *\n * Family-specific bases (CrmEntityRepository, etc.) extend this in v0.1\n * without any changes to BaseRepository.\n *\n * NOT @Injectable — concrete repositories are @Injectable and inject DRIZZLE.\n */\nimport { and, eq, inArray, isNull, sql } from 'drizzle-orm';\nimport type { PgTableWithColumns, PgColumn } from 'drizzle-orm/pg-core';\nimport type { SQL } from 'drizzle-orm';\nimport type { DrizzleClient, DrizzleTx } from '../types/drizzle';\nimport {\n requireRequester,\n tryGetRequester,\n type RequesterScope,\n} from './tenant-context';\n\n// ============================================================================\n// Interfaces\n// ============================================================================\n\n/**\n * Behavior flags for the repository. Controls automatic timestamp injection\n * and soft-delete filtering.\n */\nexport interface BehaviorConfig {\n timestamps: boolean;\n softDelete: boolean;\n userTracking: boolean;\n}\n\n/**\n * Options for the list() method.\n */\nexport interface ListOptions {\n where?: SQL;\n limit?: number;\n offset?: number;\n orderBy?: PgColumn | SQL;\n}\n\n// ============================================================================\n// BaseRepository\n// ============================================================================\n\nexport abstract class BaseRepository<TEntity> {\n /**\n * The Drizzle table schema for this entity.\n * Concrete repositories declare this as a class property.\n */\n protected abstract readonly table: PgTableWithColumns<any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n\n /**\n * Behavior flags controlling automatic behavior injection.\n * Override in concrete repositories to enable behaviors.\n */\n protected readonly behaviors: BehaviorConfig = {\n timestamps: false,\n softDelete: false,\n userTracking: false,\n };\n\n /**\n * Ambient tenant-scope enforcement for `userTracking` repos (see\n * `scopePredicate`). Only has effect when `behaviors.userTracking === true`.\n *\n * - `'lenient'` (default): when no ambient requester context is active,\n * reads/writes are NOT scoped — preserves pre-scoping behavior, so adopting\n * ambient scoping is additive. Scoping kicks in automatically once a\n * boundary installs `withRequester(...)`.\n * - `'strict'`: a missing ambient context throws (`requireRequester`),\n * making a forgotten boundary fail loud instead of silently returning\n * cross-tenant rows. Recommended for new multi-tenant consumers — override\n * in a concrete repo or a family base class.\n */\n protected readonly scopeEnforcement: 'lenient' | 'strict' = 'lenient';\n\n protected readonly db: DrizzleClient;\n\n constructor(db: DrizzleClient) {\n this.db = db;\n }\n\n /**\n * Pick the runner for a write: the caller-supplied transaction handle\n * if present, otherwise the repository's own client. Keeps the `tx`\n * parameter purely additive — callers without a transaction call as\n * before. Used by the write methods below + consumer overrides (e.g.\n * the generated `upsertCurrentValues` on EAV value tables).\n */\n protected runner(tx?: DrizzleTx): DrizzleClient {\n return tx ?? this.db;\n }\n\n // ============================================================================\n // Read Operations\n // ============================================================================\n\n /**\n * Find a single entity by its primary key.\n * Returns null if not found (or soft-deleted when softDelete=true).\n */\n async findById(id: string): Promise<TEntity | null> {\n const rows = await this.baseQuery(eq(this.table['id'], id)).limit(1);\n return (rows[0] as TEntity) ?? null;\n }\n\n /**\n * Find multiple entities by their primary keys.\n * Returns empty array immediately for empty input (avoids DB errors).\n */\n async findByIds(ids: string[]): Promise<TEntity[]> {\n if (ids.length === 0) return [];\n const rows = await this.baseQuery(inArray(this.table['id'], ids));\n return rows as TEntity[];\n }\n\n /**\n * List entities with optional filtering, pagination, and ordering.\n */\n async list(options?: ListOptions): Promise<TEntity[]> {\n let query = this.baseQuery(options?.where);\n\n if (options?.orderBy) {\n query = query.orderBy(options.orderBy as SQL) as typeof query;\n }\n if (options?.limit !== undefined) {\n query = query.limit(options.limit) as typeof query;\n }\n if (options?.offset !== undefined) {\n query = query.offset(options.offset) as typeof query;\n }\n\n const rows = await query;\n return rows as TEntity[];\n }\n\n /**\n * Count entities matching an optional WHERE clause.\n * Soft-deleted rows are always excluded when softDelete=true.\n */\n async count(where?: SQL): Promise<number> {\n let query = this.db\n .select({ count: sql<number>`cast(count(*) as integer)` })\n .from(this.table);\n\n const conditions: SQL[] = [];\n if (this.behaviors.softDelete) {\n conditions.push(isNull(this.table['deletedAt']));\n }\n const scope = this.scopePredicate();\n if (scope) {\n conditions.push(scope);\n }\n if (where) {\n conditions.push(where);\n }\n\n if (conditions.length === 1) {\n query = query.where(conditions[0]) as typeof query;\n } else if (conditions.length > 1) {\n query = query.where(and(...conditions)) as typeof query;\n }\n\n const rows = await query;\n return rows[0]?.count ?? 0;\n }\n\n /**\n * Check whether an entity with the given id exists.\n */\n async exists(id: string): Promise<boolean> {\n const result = await this.findById(id);\n return result !== null;\n }\n\n // ============================================================================\n // Write Operations\n // ============================================================================\n\n /**\n * Insert a new entity. Timestamps are auto-injected when timestamps=true.\n */\n async create(input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'create');\n const rows = await this.runner(tx)\n .insert(this.table)\n .values(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Update an existing entity by id. updatedAt is auto-injected when timestamps=true.\n * Returns the updated entity.\n */\n async update(id: string, input: Partial<TEntity>, tx?: DrizzleTx): Promise<TEntity> {\n const data = this.withTimestamps(input as Record<string, unknown>, 'update');\n const rows = await this.runner(tx)\n .update(this.table)\n .set(data as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)))\n .returning();\n return rows[0] as TEntity;\n }\n\n /**\n * Delete an entity by id.\n * - softDelete=true: sets deletedAt to current timestamp\n * - softDelete=false: hard-deletes the row\n */\n async delete(id: string, tx?: DrizzleTx): Promise<void> {\n const runner = this.runner(tx);\n if (this.behaviors.softDelete) {\n await runner\n .update(this.table)\n .set({ deletedAt: new Date() } as any) // eslint-disable-line @typescript-eslint/no-explicit-any\n .where(this.scopeAnd(eq(this.table['id'], id)));\n } else {\n await runner\n .delete(this.table)\n .where(this.scopeAnd(eq(this.table['id'], id)));\n }\n }\n\n /**\n * Insert or update multiple entities.\n * Default naive implementation — family repositories override with\n * proper conflict-target upsert (e.g., CrmEntityRepository).\n */\n async upsertMany(inputs: Array<Partial<TEntity>>, tx?: DrizzleTx): Promise<TEntity[]> {\n return Promise.all(inputs.map((input) => this.create(input, tx)));\n }\n\n // ============================================================================\n // Protected Helpers\n // ============================================================================\n\n /**\n * Base SELECT query that automatically applies the ambient guards —\n * soft-delete exclusion (when `softDelete`) and tenant scope (when\n * `userTracking` + an active requester context) — combined with an optional\n * caller `extra` predicate into a SINGLE `WHERE`.\n *\n * Pass the leaf predicate as `extra` rather than chaining a second\n * `.where(...)`: Drizzle's `.where()` OVERRIDES (does not AND) a prior\n * `.where()` on a `$dynamic()` query, so a chained call would silently drop\n * the soft-delete and scope guards. `baseQuery(extra)` is the safe form.\n */\n protected baseQuery(extra?: SQL) {\n const query = this.db.select().from(this.table).$dynamic();\n const where = this.scopeAnd(extra, { softDelete: this.behaviors.softDelete });\n return where ? query.where(where) : query;\n }\n\n /**\n * Build the ambient tenant-scope predicate for this repo's table.\n *\n * Returns `undefined` (no scoping) when:\n * - `behaviors.userTracking` is false (repo is not user-owned), or\n * - no ambient requester context is active AND `scopeEnforcement` is\n * `'lenient'` (the default — preserves pre-scoping behavior).\n *\n * When a requester context is active, scopes by `user_id` per the ambient\n * scope: `'user'` → `user_id = ctx.userId`; `'org'` → `user_id IN\n * ctx.orgUserIds` (empty list matches nothing — fail-closed); `'superuser'`\n * → no filter. See `tenant-context.ts` for the boundary-install contract.\n */\n protected scopePredicate(): SQL | undefined {\n if (!this.behaviors.userTracking) return undefined;\n const ctx =\n this.scopeEnforcement === 'strict'\n ? requireRequester()\n : tryGetRequester();\n if (!ctx) return undefined;\n const scope: RequesterScope = ctx.scope ?? 'user';\n switch (scope) {\n case 'superuser':\n return undefined;\n case 'org':\n return ctx.orgUserIds && ctx.orgUserIds.length > 0\n ? inArray(this.table['userId'], ctx.orgUserIds as string[])\n : sql`false`;\n case 'user':\n default:\n return eq(this.table['userId'], ctx.userId);\n }\n }\n\n /**\n * Combine the ambient scope predicate (and, optionally, the soft-delete\n * guard) with a caller `extra` predicate into one `SQL`. Returns `undefined`\n * when nothing applies. Used by read + by-id write paths so a single\n * `.where(...)` carries every guard.\n */\n protected scopeAnd(\n extra?: SQL,\n opts?: { softDelete?: boolean },\n ): SQL | undefined {\n const conditions: SQL[] = [];\n if (opts?.softDelete) conditions.push(isNull(this.table['deletedAt']));\n const scope = this.scopePredicate();\n if (scope) conditions.push(scope);\n if (extra) conditions.push(extra);\n if (conditions.length === 0) return undefined;\n if (conditions.length === 1) return conditions[0];\n return and(...conditions);\n }\n\n /**\n * Merge timestamp fields into an input object.\n * - mode='create': adds createdAt and updatedAt\n * - mode='update': adds updatedAt only\n *\n * No-op when timestamps behavior is disabled.\n */\n protected withTimestamps(\n input: Record<string, unknown>,\n mode: 'create' | 'update',\n ): Record<string, unknown> {\n if (!this.behaviors.timestamps) return input;\n const now = new Date();\n if (mode === 'create') {\n return { ...input, createdAt: now, updatedAt: now };\n }\n return { ...input, updatedAt: now };\n }\n\n /**\n * Build a WHERE clause fragment that restricts results to rows whose\n * parent (identified by a belongs_to FK) is not soft-deleted.\n *\n * Use this in custom repository methods when you need \"rows reachable\n * from an active parent\". The default findAll / findById behavior is\n * NOT changed by this helper — opt in explicitly where needed.\n *\n * ADR-021 — Soft-delete cascade: Option A (filter at query time).\n * `on_delete` FK rules do not fire for soft-deletes; use this helper\n * instead of expecting cascade semantics on the DB level.\n *\n * Example:\n * async listActiveMessages(): Promise<Message[]> {\n * return this.list({\n * where: this.activeParentFilter(conversations, this.table['conversationId']),\n * });\n * }\n *\n * @param parentTable The Drizzle table object for the parent entity.\n * @param parentFkColumn The FK column on this (child) table that references parent.id.\n */\n protected activeParentFilter(\n parentTable: PgTableWithColumns<any>, // eslint-disable-line @typescript-eslint/no-explicit-any\n parentFkColumn: PgColumn,\n ): SQL {\n return sql`EXISTS (\n SELECT 1 FROM ${parentTable} p\n WHERE p.id = ${parentFkColumn}\n AND p.deleted_at IS NULL\n )`;\n }\n}\n","/**\n * Ambient requester context — AsyncLocalStorage-backed tenant scope.\n *\n * The alternative to threading `userId`/`organizationId` through every\n * repository/service signature. Set ONCE at each boundary the generated app\n * owns, read implicitly inside `BaseRepository` (see `scopePredicate`).\n *\n * ## Where to set it (boundaries)\n *\n * - HTTP / tRPC handlers — from the authenticated `ctx.user`\n * - OAuth callback controllers — from the authenticated session\n * - Queue/worker `process()` — from the job's owning user after the\n * job's record is loaded\n *\n * Each boundary wraps the rest of the request in `withRequester({ userId,\n * organizationId }, () => ...)`. The context propagates through every `await`\n * to all downstream repo/service calls without being passed explicitly.\n *\n * ## Where to read it\n *\n * - `BaseRepository.scopePredicate()` reads it (via `tryGetRequester` in\n * lenient mode, `requireRequester` in strict mode) and filters every read\n * by the ambient scope when the repo declares `userTracking: true`.\n *\n * ## Why AsyncLocalStorage over an explicit parameter\n *\n * Threading `userId` (and later `organizationId`) through dozens of method\n * signatures is pure parameter pollution. Ambient context also lets a repo\n * make the \"I forgot to scope\" mistake impossible at runtime: in strict mode\n * `requireRequester()` throws when no context is active, surfacing a missing\n * boundary call loudly rather than silently leaking cross-tenant data.\n *\n * ## Not-found semantics\n *\n * When a row exists but belongs to a different requester, scoped reads return\n * `null`/`[]` — identical to \"truly doesn't exist\". No existence oracle;\n * callers throw NotFound uniformly. Standard security practice.\n *\n * ## Testing\n *\n * Tests that exercise scoped repos must wrap the call in `withRequester(...)`.\n * In strict mode an unwrapped call hitting `requireRequester()` throws — by\n * design. In lenient mode (the default) an unwrapped call is simply unscoped.\n */\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/**\n * Data-visibility scope. The auth layer decides which scope a request is\n * allowed to claim; the repo trusts whatever the ambient context says.\n *\n * - `'user'`: filter every read by `user_id = ctx.userId`. Default.\n * - `'org'`: filter every read by membership in the requester's org, resolved\n * via `user_id IN (ctx.orgUserIds)` rather than via a per-entity\n * `organization_id` column. Works for every user-owned table and keeps repos\n * single-table — the org member list is pre-resolved at the boundary.\n * - `'superuser'`: no scope filter. Engineering / internal-tools only.\n *\n * AUTHORIZATION (who is allowed to claim each scope) lives in boundary\n * middleware, not in the repo. The repo trusts the ambient context — same\n * trust model as a threaded `userId`.\n */\nexport type RequesterScope = 'user' | 'org' | 'superuser';\n\nexport interface RequesterContext {\n /**\n * The user making the request. Always present — even in `'org'` and\n * `'superuser'` scopes it is the audit-trail \"who actually did this\".\n */\n readonly userId: string;\n /**\n * The organization the requester belongs to. Required when\n * `scope === 'org'`; may be null for `'user'` (users with no org) and for\n * `'superuser'` (cross-org reads).\n */\n readonly organizationId: string | null;\n /**\n * Data-visibility scope. Defaults to `'user'` when omitted.\n */\n readonly scope?: RequesterScope;\n /**\n * For `scope === 'org'`: the list of user IDs in the requester's org,\n * pre-resolved by the boundary middleware that established the `'org'`\n * scope (one `SELECT users.id WHERE organization_id = X` at the trust\n * boundary). Repos use this as a literal `IN (...)` filter — they never\n * JOIN to `users` themselves. Required when `scope === 'org'`.\n */\n readonly orgUserIds?: readonly string[];\n}\n\nconst als = new AsyncLocalStorage<RequesterContext>();\n\n/**\n * Set the ambient requester context for the duration of `fn`. The context\n * propagates through `await` boundaries to all downstream calls. Nesting is\n * fine — an inner `withRequester` overrides the outer for its callback.\n */\nexport function withRequester<T>(\n ctx: RequesterContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return als.run(ctx, fn);\n}\n\n/**\n * Read the ambient requester context. Throws if no context is active — by\n * design. Used by repos in strict scope-enforcement mode; an unwrapped call\n * site is a missing boundary.\n */\nexport function requireRequester(): RequesterContext {\n const ctx = als.getStore();\n if (!ctx) {\n throw new Error(\n 'No requester context active. Wrap the entry point in ' +\n 'withRequester({ userId, organizationId }, fn). See tenant-context.ts.',\n );\n }\n return ctx;\n}\n\n/**\n * Read the ambient requester context without throwing. Returns `undefined`\n * when no context is active. Used by repos in lenient scope-enforcement mode\n * (the default) and by code paths that legitimately run outside a request.\n */\nexport function tryGetRequester(): RequesterContext | undefined {\n return als.getStore();\n}\n\n/**\n * Resolve the effective scope for the ambient context, defaulting to `'user'`.\n */\nexport function requireRequesterScope(): RequesterScope {\n return requireRequester().scope ?? 'user';\n}\n\n/**\n * Convenience helpers for setting scope explicitly. All three preserve\n * `userId` in the context (audit trail) regardless of scope.\n *\n * - `withUserScope`: regular end-user requests. Most call sites.\n * - `withOrgScope`: admin / org-shared resource access. The caller MUST verify\n * the requester's role permits `'org'` before calling — the helper does not\n * enforce authorization. `orgUserIds` is pre-resolved at the boundary.\n * - `withSuperuserScope`: engineering scripts / internal tools. `organizationId`\n * is null (cross-org is the point). Same authorization caveat applies.\n */\nexport function withUserScope<T>(\n userId: string,\n organizationId: string | null,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester({ userId, organizationId, scope: 'user' }, fn);\n}\n\nexport function withOrgScope<T>(\n userId: string,\n organizationId: string,\n orgUserIds: readonly string[],\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId, scope: 'org', orgUserIds },\n fn,\n );\n}\n\nexport function withSuperuserScope<T>(\n userId: string,\n fn: () => Promise<T>,\n): Promise<T> {\n return withRequester(\n { userId, organizationId: null, scope: 'superuser' },\n fn,\n );\n}\n"],"mappings":";AAQA,SAAS,MAAAA,KAAI,OAAAC,MAAK,YAAY;;;ACG9B,SAAS,KAAK,IAAI,SAAS,QAAQ,WAAW;;;ACiC9C,SAAS,yBAAyB;AA6ClC,IAAM,MAAM,IAAI,kBAAoC;AAmB7C,SAAS,mBAAqC;AACnD,QAAM,MAAM,IAAI,SAAS;AACzB,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,kBAAgD;AAC9D,SAAO,IAAI,SAAS;AACtB;;;AD7EO,IAAe,iBAAf,MAAuC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWzB,YAA4B;AAAA,IAC7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
- import { randomUUID } from "crypto";
3
- var SYSTEM_FIELDS = /* @__PURE__ */ new Set([
4
- "id",
5
- "createdAt",
6
- "updatedAt",
7
- "deletedAt"
8
- ]);
9
- function entitySnapshot(entity) {
10
- const snap = {};
11
- for (const [key, value] of Object.entries(entity)) {
12
- if (!SYSTEM_FIELDS.has(key)) {
13
- snap[key] = value;
14
- }
15
- }
16
- return snap;
17
- }
18
- function diffSnapshots(before, after) {
19
- const changes = [];
20
- const allKeys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)]);
21
- for (const key of allKeys) {
22
- if (SYSTEM_FIELDS.has(key)) continue;
23
- const oldVal = before[key];
24
- const newVal = after[key];
25
- if (oldVal !== newVal && JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
26
- changes.push({ field: key, oldValue: oldVal, newValue: newVal });
27
- }
28
- }
29
- return changes;
30
- }
31
- function buildLifecycleEvent(entityName, action, entityId, snapshot) {
32
- return {
33
- id: randomUUID(),
34
- type: `${entityName}.${action}`,
35
- aggregateId: entityId,
36
- aggregateType: entityName,
37
- payload: snapshot ? { snapshot } : {},
38
- occurredAt: /* @__PURE__ */ new Date(),
39
- metadata: { category: "lifecycle" }
40
- };
41
- }
42
- function buildChangeEvents(entityName, entityId, changes) {
43
- return changes.map((c) => ({
44
- id: randomUUID(),
45
- type: `${entityName}.field_changed`,
46
- aggregateId: entityId,
47
- aggregateType: entityName,
48
- payload: {
49
- fieldName: c.field,
50
- oldValue: c.oldValue,
51
- newValue: c.newValue
52
- },
53
- occurredAt: /* @__PURE__ */ new Date(),
54
- metadata: { category: "change" }
55
- }));
56
- }
57
- async function emitSafely(eventBus, events) {
58
- if (!eventBus || events.length === 0) return;
59
- try {
60
- if (events.length === 1) {
61
- const only = events[0];
62
- if (!only) return;
63
- await eventBus.publish(only);
64
- } else {
65
- await eventBus.publishMany(events);
66
- }
67
- } catch {
68
- console.warn(`[lifecycle-events] failed to emit ${events.length} event(s)`);
69
- }
70
- }
71
-
72
- // runtime/base-classes/base-service.ts
73
- var BaseService = class {
74
- constructor(repository) {
75
- this.repository = repository;
76
- }
77
- repository;
78
- /**
79
- * Entity name for event types (e.g., 'account' → 'account.created').
80
- * Set by generated services. If empty, lifecycle events are skipped.
81
- */
82
- entityName;
83
- /**
84
- * Event bus for lifecycle/change event emission.
85
- * Injected via @Inject(EVENT_BUS) @Optional() on generated services.
86
- * If undefined (no events subsystem installed), emission is silently skipped.
87
- */
88
- eventBus;
89
- /**
90
- * Whether to emit lifecycle events. Default: true.
91
- * Override to false in entity YAML via behaviors or in the service class.
92
- */
93
- emitLifecycleEvents = true;
94
- /**
95
- * Find a single entity by its primary key.
96
- * Returns null if not found.
97
- */
98
- findById(id) {
99
- return this.repository.findById(id);
100
- }
101
- /**
102
- * Find multiple entities by their primary keys.
103
- */
104
- findByIds(ids) {
105
- return this.repository.findByIds(ids);
106
- }
107
- /**
108
- * List entities with optional filtering/pagination options.
109
- */
110
- list(options) {
111
- return this.repository.list(options);
112
- }
113
- /**
114
- * Count entities matching an optional filter.
115
- */
116
- count(where) {
117
- return this.repository.count(where);
118
- }
119
- /**
120
- * Check whether an entity with the given id exists.
121
- */
122
- exists(id) {
123
- return this.repository.exists(id);
124
- }
125
- /**
126
- * Insert a new entity.
127
- * Emits a LIFECYCLE 'created' event with entity snapshot.
128
- */
129
- async create(input, tx) {
130
- const result = await this.repository.create(input, tx);
131
- if (this._shouldEmit()) {
132
- const snap = entitySnapshot(result);
133
- const id = result.id;
134
- const event = buildLifecycleEvent(this.entityName, "created", id, snap);
135
- void emitSafely(this.eventBus, [event]);
136
- }
137
- return result;
138
- }
139
- /**
140
- * Update an existing entity by id.
141
- * Emits a LIFECYCLE 'updated' event + CHANGE events for each modified field.
142
- */
143
- async update(id, input, tx) {
144
- let before;
145
- if (this._shouldEmit()) {
146
- const existing = await this.repository.findById(id);
147
- if (existing) {
148
- before = entitySnapshot(existing);
149
- }
150
- }
151
- const result = await this.repository.update(id, input, tx);
152
- if (this._shouldEmit()) {
153
- const after = entitySnapshot(result);
154
- const events = [
155
- buildLifecycleEvent(this.entityName, "updated", id, after)
156
- ];
157
- if (before) {
158
- const changes = diffSnapshots(before, after);
159
- if (changes.length > 0) {
160
- events.push(...buildChangeEvents(this.entityName, id, changes));
161
- }
162
- }
163
- void emitSafely(this.eventBus, events);
164
- }
165
- return result;
166
- }
167
- /**
168
- * Delete an entity by id.
169
- * Emits a LIFECYCLE 'deleted' event.
170
- */
171
- async delete(id, tx) {
172
- await this.repository.delete(id, tx);
173
- if (this._shouldEmit()) {
174
- const event = buildLifecycleEvent(this.entityName, "deleted", id);
175
- void emitSafely(this.eventBus, [event]);
176
- }
177
- }
178
- /** Check whether lifecycle event emission is active. */
179
- _shouldEmit() {
180
- return Boolean(
181
- this.emitLifecycleEvents && this.entityName && this.eventBus
182
- );
183
- }
184
- };
185
-
186
- // runtime/base-classes/metadata-entity-service.ts
187
- var MetadataEntityService = class extends BaseService {
188
- /**
189
- * Find metadata records by entity ID and entity type (EAV polymorphic lookup).
190
- */
191
- findByEntityIdAndType(entityId, entityType) {
192
- return this.repository.findByEntityIdAndType(entityId, entityType);
193
- }
194
- /**
195
- * List all metadata records for an entity.
196
- */
197
- listByEntity(entityId) {
198
- return this.repository.listByEntityId(entityId);
199
- }
200
- /**
201
- * List metadata history for an entity, ordered by validFrom desc.
202
- */
203
- listHistory(entityId) {
204
- return this.repository.listHistoryByEntityId(entityId);
205
- }
206
- /**
207
- * Bulk upsert metadata values.
208
- */
209
- upsertValues(inputs, conflictTarget, tx) {
210
- return this.repository.upsertMany(inputs, tx, { conflictTarget });
211
- }
212
- };
1
+ import {
2
+ MetadataEntityService
3
+ } from "../../chunk-RFH7N6EP.js";
4
+ import "../../chunk-W72PRNJY.js";
5
+ import "../../chunk-KYR3B3OW.js";
6
+ import "../../chunk-2E224ZSN.js";
213
7
  export {
214
8
  MetadataEntityService
215
9
  };