@open-mercato/core 0.6.8-develop.6984.1.f0cf23f0f6 → 0.6.8-develop.6985.1.fb93574faa

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 (597) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/dist/generated/entities/notification/index.js +6 -0
  3. package/dist/generated/entities/notification/index.js.map +2 -2
  4. package/dist/generated/entities/notification_preference/index.js +19 -0
  5. package/dist/generated/entities/notification_preference/index.js.map +7 -0
  6. package/dist/generated/entities/notification_type/index.js +21 -0
  7. package/dist/generated/entities/notification_type/index.js.map +7 -0
  8. package/dist/generated/entities/notification_type_override/index.js +17 -0
  9. package/dist/generated/entities/notification_type_override/index.js.map +7 -0
  10. package/dist/generated/entities/push_notification_delivery/index.js +41 -0
  11. package/dist/generated/entities/push_notification_delivery/index.js.map +7 -0
  12. package/dist/generated/entities/user_device/index.js +35 -0
  13. package/dist/generated/entities/user_device/index.js.map +7 -0
  14. package/dist/generated/entities.ids.generated.js +12 -1
  15. package/dist/generated/entities.ids.generated.js.map +2 -2
  16. package/dist/generated/entity-fields-registry.js +72 -0
  17. package/dist/generated/entity-fields-registry.js.map +2 -2
  18. package/dist/helpers/integration/api.js +2 -1
  19. package/dist/helpers/integration/api.js.map +2 -2
  20. package/dist/helpers/integration/appRoot.js +9 -0
  21. package/dist/helpers/integration/appRoot.js.map +7 -0
  22. package/dist/helpers/integration/dbFixtures.js +1 -4
  23. package/dist/helpers/integration/dbFixtures.js.map +2 -2
  24. package/dist/helpers/integration/pushFake.js +126 -0
  25. package/dist/helpers/integration/pushFake.js.map +7 -0
  26. package/dist/modules/auth/notifications.js +16 -0
  27. package/dist/modules/auth/notifications.js.map +2 -2
  28. package/dist/modules/business_rules/notifications.js +2 -0
  29. package/dist/modules/business_rules/notifications.js.map +2 -2
  30. package/dist/modules/catalog/notifications.js +2 -0
  31. package/dist/modules/catalog/notifications.js.map +2 -2
  32. package/dist/modules/communication_channels/acl.js +9 -0
  33. package/dist/modules/communication_channels/acl.js.map +2 -2
  34. package/dist/modules/communication_channels/api/delete/admin/channels/[id]/route.js +133 -0
  35. package/dist/modules/communication_channels/api/delete/admin/channels/[id]/route.js.map +7 -0
  36. package/dist/modules/communication_channels/api/get/channels/[id]/health/route.js +6 -2
  37. package/dist/modules/communication_channels/api/get/channels/[id]/health/route.js.map +2 -2
  38. package/dist/modules/communication_channels/api/get/channels/[id]/route.js +6 -2
  39. package/dist/modules/communication_channels/api/get/channels/[id]/route.js.map +2 -2
  40. package/dist/modules/communication_channels/api/get/channels/route.js +2 -1
  41. package/dist/modules/communication_channels/api/get/channels/route.js.map +2 -2
  42. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js +10 -5
  43. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js.map +2 -2
  44. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js +29 -1
  45. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js.map +2 -2
  46. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js +157 -0
  47. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js.map +7 -0
  48. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js +8 -1
  49. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js.map +2 -2
  50. package/dist/modules/communication_channels/commands/admin-delete-channel.js +141 -0
  51. package/dist/modules/communication_channels/commands/admin-delete-channel.js.map +7 -0
  52. package/dist/modules/communication_channels/commands/connect-credential-channel.js +25 -8
  53. package/dist/modules/communication_channels/commands/connect-credential-channel.js.map +2 -2
  54. package/dist/modules/communication_channels/commands/deliver-outbound-message.js +2 -2
  55. package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +2 -2
  56. package/dist/modules/communication_channels/commands/push-register.js +1 -1
  57. package/dist/modules/communication_channels/commands/push-register.js.map +2 -2
  58. package/dist/modules/communication_channels/commands/push-unregister.js +4 -3
  59. package/dist/modules/communication_channels/commands/push-unregister.js.map +2 -2
  60. package/dist/modules/communication_channels/data/entities.js +4 -0
  61. package/dist/modules/communication_channels/data/entities.js.map +2 -2
  62. package/dist/modules/communication_channels/data/validators.js +2 -1
  63. package/dist/modules/communication_channels/data/validators.js.map +2 -2
  64. package/dist/modules/communication_channels/lib/access-control.js +11 -1
  65. package/dist/modules/communication_channels/lib/access-control.js.map +2 -2
  66. package/dist/modules/communication_channels/lib/connect-channel.js +20 -12
  67. package/dist/modules/communication_channels/lib/connect-channel.js.map +2 -2
  68. package/dist/modules/communication_channels/lib/push-adapter.js +68 -0
  69. package/dist/modules/communication_channels/lib/push-adapter.js.map +7 -0
  70. package/dist/modules/communication_channels/lib/push-capabilities.js +31 -0
  71. package/dist/modules/communication_channels/lib/push-capabilities.js.map +7 -0
  72. package/dist/modules/communication_channels/lib/push-connect-error.js +20 -0
  73. package/dist/modules/communication_channels/lib/push-connect-error.js.map +7 -0
  74. package/dist/modules/communication_channels/lib/push-credential-errors.js +41 -0
  75. package/dist/modules/communication_channels/lib/push-credential-errors.js.map +7 -0
  76. package/dist/modules/communication_channels/lib/push-envelope.js +46 -0
  77. package/dist/modules/communication_channels/lib/push-envelope.js.map +7 -0
  78. package/dist/modules/communication_channels/lib/refcounted-client-cache.js +64 -0
  79. package/dist/modules/communication_channels/lib/refcounted-client-cache.js.map +7 -0
  80. package/dist/modules/communication_channels/migrations/Migration20260703123630_communication_channels.js +13 -0
  81. package/dist/modules/communication_channels/migrations/Migration20260703123630_communication_channels.js.map +7 -0
  82. package/dist/modules/communication_channels/notifications.js +4 -0
  83. package/dist/modules/communication_channels/notifications.js.map +2 -2
  84. package/dist/modules/communication_channels/setup.js +2 -0
  85. package/dist/modules/communication_channels/setup.js.map +2 -2
  86. package/dist/modules/configs/lib/upgrade-actions.js +21 -0
  87. package/dist/modules/configs/lib/upgrade-actions.js.map +2 -2
  88. package/dist/modules/customer_accounts/notifications.js +12 -0
  89. package/dist/modules/customer_accounts/notifications.js.map +2 -2
  90. package/dist/modules/customers/notifications.js +4 -0
  91. package/dist/modules/customers/notifications.js.map +2 -2
  92. package/dist/modules/devices/acl.js +11 -0
  93. package/dist/modules/devices/acl.js.map +7 -0
  94. package/dist/modules/devices/api/[id]/route.js +167 -0
  95. package/dist/modules/devices/api/[id]/route.js.map +7 -0
  96. package/dist/modules/devices/api/admin/devices/[id]/route.js +219 -0
  97. package/dist/modules/devices/api/admin/devices/[id]/route.js.map +7 -0
  98. package/dist/modules/devices/api/admin/devices/route.js +140 -0
  99. package/dist/modules/devices/api/admin/devices/route.js.map +7 -0
  100. package/dist/modules/devices/api/auth.js +9 -0
  101. package/dist/modules/devices/api/auth.js.map +7 -0
  102. package/dist/modules/devices/api/deviceList.js +53 -0
  103. package/dist/modules/devices/api/deviceList.js.map +7 -0
  104. package/dist/modules/devices/api/deviceOps.js +118 -0
  105. package/dist/modules/devices/api/deviceOps.js.map +7 -0
  106. package/dist/modules/devices/api/openapi.js +19 -0
  107. package/dist/modules/devices/api/openapi.js.map +7 -0
  108. package/dist/modules/devices/api/route.js +143 -0
  109. package/dist/modules/devices/api/route.js.map +7 -0
  110. package/dist/modules/devices/backend/devices/[id]/page.js +135 -0
  111. package/dist/modules/devices/backend/devices/[id]/page.js.map +7 -0
  112. package/dist/modules/devices/backend/devices/[id]/page.meta.js +16 -0
  113. package/dist/modules/devices/backend/devices/[id]/page.meta.js.map +7 -0
  114. package/dist/modules/devices/backend/devices/create/page.js +68 -0
  115. package/dist/modules/devices/backend/devices/create/page.js.map +7 -0
  116. package/dist/modules/devices/backend/devices/create/page.meta.js +16 -0
  117. package/dist/modules/devices/backend/devices/create/page.meta.js.map +7 -0
  118. package/dist/modules/devices/backend/devices/page.js +235 -0
  119. package/dist/modules/devices/backend/devices/page.js.map +7 -0
  120. package/dist/modules/devices/backend/devices/page.meta.js +23 -0
  121. package/dist/modules/devices/backend/devices/page.meta.js.map +7 -0
  122. package/dist/modules/devices/commands/deactivate.js +107 -0
  123. package/dist/modules/devices/commands/deactivate.js.map +7 -0
  124. package/dist/modules/devices/commands/index.js +4 -0
  125. package/dist/modules/devices/commands/index.js.map +7 -0
  126. package/dist/modules/devices/commands/register.js +183 -0
  127. package/dist/modules/devices/commands/register.js.map +7 -0
  128. package/dist/modules/devices/commands/shared.js +74 -0
  129. package/dist/modules/devices/commands/shared.js.map +7 -0
  130. package/dist/modules/devices/commands/update.js +126 -0
  131. package/dist/modules/devices/commands/update.js.map +7 -0
  132. package/dist/modules/devices/data/entities.js +83 -0
  133. package/dist/modules/devices/data/entities.js.map +7 -0
  134. package/dist/modules/devices/data/validators.js +49 -0
  135. package/dist/modules/devices/data/validators.js.map +7 -0
  136. package/dist/modules/devices/di.js +11 -0
  137. package/dist/modules/devices/di.js.map +7 -0
  138. package/dist/modules/devices/encryption.js +12 -0
  139. package/dist/modules/devices/encryption.js.map +7 -0
  140. package/dist/modules/devices/events.js +19 -0
  141. package/dist/modules/devices/events.js.map +7 -0
  142. package/dist/modules/devices/index.js +17 -0
  143. package/dist/modules/devices/index.js.map +7 -0
  144. package/dist/modules/devices/lib/operationMetadata.js +20 -0
  145. package/dist/modules/devices/lib/operationMetadata.js.map +7 -0
  146. package/dist/modules/devices/migrations/Migration20260602120000.js +15 -0
  147. package/dist/modules/devices/migrations/Migration20260602120000.js.map +7 -0
  148. package/dist/modules/devices/migrations/Migration20260630120000.js +15 -0
  149. package/dist/modules/devices/migrations/Migration20260630120000.js.map +7 -0
  150. package/dist/modules/devices/migrations/Migration20260701120000.js +13 -0
  151. package/dist/modules/devices/migrations/Migration20260701120000.js.map +7 -0
  152. package/dist/modules/devices/migrations/Migration20260721120000.js +15 -0
  153. package/dist/modules/devices/migrations/Migration20260721120000.js.map +7 -0
  154. package/dist/modules/devices/setup.js +13 -0
  155. package/dist/modules/devices/setup.js.map +7 -0
  156. package/dist/modules/entities/cli.js +8 -3
  157. package/dist/modules/entities/cli.js.map +2 -2
  158. package/dist/modules/entities/migrations/Migration20260722120000.js +28 -0
  159. package/dist/modules/entities/migrations/Migration20260722120000.js.map +7 -0
  160. package/dist/modules/inbox_ops/notifications.js +2 -0
  161. package/dist/modules/inbox_ops/notifications.js.map +2 -2
  162. package/dist/modules/messages/notifications.js +2 -0
  163. package/dist/modules/messages/notifications.js.map +2 -2
  164. package/dist/modules/notifications/acl.js +3 -1
  165. package/dist/modules/notifications/acl.js.map +2 -2
  166. package/dist/modules/notifications/api/admin/preferences/route.js +167 -0
  167. package/dist/modules/notifications/api/admin/preferences/route.js.map +7 -0
  168. package/dist/modules/notifications/api/channels/route.js +54 -0
  169. package/dist/modules/notifications/api/channels/route.js.map +7 -0
  170. package/dist/modules/notifications/api/preferences/route.js +126 -0
  171. package/dist/modules/notifications/api/preferences/route.js.map +7 -0
  172. package/dist/modules/notifications/api/route.js +8 -1
  173. package/dist/modules/notifications/api/route.js.map +2 -2
  174. package/dist/modules/notifications/api/types/[id]/channels/[channel]/route.js +187 -0
  175. package/dist/modules/notifications/api/types/[id]/channels/[channel]/route.js.map +7 -0
  176. package/dist/modules/notifications/api/types/route.js +225 -0
  177. package/dist/modules/notifications/api/types/route.js.map +7 -0
  178. package/dist/modules/notifications/api/unread-count/route.js +5 -1
  179. package/dist/modules/notifications/api/unread-count/route.js.map +2 -2
  180. package/dist/modules/notifications/backend/notifications/user-preferences/page.js +10 -0
  181. package/dist/modules/notifications/backend/notifications/user-preferences/page.js.map +7 -0
  182. package/dist/modules/notifications/backend/notifications/user-preferences/page.meta.js +28 -0
  183. package/dist/modules/notifications/backend/notifications/user-preferences/page.meta.js.map +7 -0
  184. package/dist/modules/notifications/backend/profile/notification-preferences/page.js +10 -0
  185. package/dist/modules/notifications/backend/profile/notification-preferences/page.js.map +7 -0
  186. package/dist/modules/notifications/backend/profile/notification-preferences/page.meta.js +33 -0
  187. package/dist/modules/notifications/backend/profile/notification-preferences/page.meta.js.map +7 -0
  188. package/dist/modules/notifications/data/entities.js +128 -1
  189. package/dist/modules/notifications/data/entities.js.map +2 -2
  190. package/dist/modules/notifications/data/validators.js +95 -2
  191. package/dist/modules/notifications/data/validators.js.map +2 -2
  192. package/dist/modules/notifications/di.js +7 -0
  193. package/dist/modules/notifications/di.js.map +2 -2
  194. package/dist/modules/notifications/events.js +17 -0
  195. package/dist/modules/notifications/events.js.map +2 -2
  196. package/dist/modules/notifications/frontend/NotificationPreferenceMatrix.js +190 -0
  197. package/dist/modules/notifications/frontend/NotificationPreferenceMatrix.js.map +7 -0
  198. package/dist/modules/notifications/frontend/NotificationPreferencesPageClient.js +124 -0
  199. package/dist/modules/notifications/frontend/NotificationPreferencesPageClient.js.map +7 -0
  200. package/dist/modules/notifications/frontend/NotificationSettingsPageClient.js +166 -1
  201. package/dist/modules/notifications/frontend/NotificationSettingsPageClient.js.map +2 -2
  202. package/dist/modules/notifications/frontend/NotificationUserPreferencesAdminPageClient.js +172 -0
  203. package/dist/modules/notifications/frontend/NotificationUserPreferencesAdminPageClient.js.map +7 -0
  204. package/dist/modules/notifications/generators.js +63 -0
  205. package/dist/modules/notifications/generators.js.map +7 -0
  206. package/dist/modules/notifications/lib/delivery-strategies-registry.js +19 -0
  207. package/dist/modules/notifications/lib/delivery-strategies-registry.js.map +7 -0
  208. package/dist/modules/notifications/lib/deliveryStrategies.js.map +2 -2
  209. package/dist/modules/notifications/lib/derive-category.js +8 -0
  210. package/dist/modules/notifications/lib/derive-category.js.map +7 -0
  211. package/dist/modules/notifications/lib/notification-channel-registry.js +35 -0
  212. package/dist/modules/notifications/lib/notification-channel-registry.js.map +7 -0
  213. package/dist/modules/notifications/lib/notification-type-registry.js +87 -0
  214. package/dist/modules/notifications/lib/notification-type-registry.js.map +7 -0
  215. package/dist/modules/notifications/lib/notificationCopy.js +14 -0
  216. package/dist/modules/notifications/lib/notificationCopy.js.map +7 -0
  217. package/dist/modules/notifications/lib/notificationFactory.js +4 -1
  218. package/dist/modules/notifications/lib/notificationFactory.js.map +2 -2
  219. package/dist/modules/notifications/lib/notificationMapper.js +2 -0
  220. package/dist/modules/notifications/lib/notificationMapper.js.map +2 -2
  221. package/dist/modules/notifications/lib/notificationPreferenceService.js +83 -0
  222. package/dist/modules/notifications/lib/notificationPreferenceService.js.map +7 -0
  223. package/dist/modules/notifications/lib/notificationService.js +83 -28
  224. package/dist/modules/notifications/lib/notificationService.js.map +2 -2
  225. package/dist/modules/notifications/lib/notificationVisibility.js +24 -0
  226. package/dist/modules/notifications/lib/notificationVisibility.js.map +7 -0
  227. package/dist/modules/notifications/lib/routeHelpers.js +11 -1
  228. package/dist/modules/notifications/lib/routeHelpers.js.map +2 -2
  229. package/dist/modules/notifications/lib/shouldDeliver.js +46 -0
  230. package/dist/modules/notifications/lib/shouldDeliver.js.map +7 -0
  231. package/dist/modules/notifications/lib/strategies/email-delivery-strategy.js +54 -0
  232. package/dist/modules/notifications/lib/strategies/email-delivery-strategy.js.map +7 -0
  233. package/dist/modules/notifications/lib/strategies/in-app-delivery-strategy.js +12 -0
  234. package/dist/modules/notifications/lib/strategies/in-app-delivery-strategy.js.map +7 -0
  235. package/dist/modules/notifications/lib/typeCatalogue.js +71 -0
  236. package/dist/modules/notifications/lib/typeCatalogue.js.map +7 -0
  237. package/dist/modules/notifications/lib/typeChannelSettings.js +12 -0
  238. package/dist/modules/notifications/lib/typeChannelSettings.js.map +7 -0
  239. package/dist/modules/notifications/lib/typeOverrides.js +19 -0
  240. package/dist/modules/notifications/lib/typeOverrides.js.map +7 -0
  241. package/dist/modules/notifications/migrations/Migration20260625122947_notifications.js +14 -0
  242. package/dist/modules/notifications/migrations/Migration20260625122947_notifications.js.map +7 -0
  243. package/dist/modules/notifications/migrations/Migration20260626120500_notifications_push_payload.js +15 -0
  244. package/dist/modules/notifications/migrations/Migration20260626120500_notifications_push_payload.js.map +7 -0
  245. package/dist/modules/notifications/migrations/Migration20260626130000_notifications_non_opt_out.js +13 -0
  246. package/dist/modules/notifications/migrations/Migration20260626130000_notifications_non_opt_out.js.map +7 -0
  247. package/dist/modules/notifications/migrations/Migration20260626140000_notifications_type_category_silent.js +15 -0
  248. package/dist/modules/notifications/migrations/Migration20260626140000_notifications_type_category_silent.js.map +7 -0
  249. package/dist/modules/notifications/migrations/Migration20260706120000_notifications_channels.js +13 -0
  250. package/dist/modules/notifications/migrations/Migration20260706120000_notifications_channels.js.map +7 -0
  251. package/dist/modules/notifications/migrations/Migration20260716123121_notifications.js +14 -0
  252. package/dist/modules/notifications/migrations/Migration20260716123121_notifications.js.map +7 -0
  253. package/dist/modules/notifications/notification-channels.js +26 -0
  254. package/dist/modules/notifications/notification-channels.js.map +7 -0
  255. package/dist/modules/notifications/notifications.delivery-strategies.js +12 -0
  256. package/dist/modules/notifications/notifications.delivery-strategies.js.map +7 -0
  257. package/dist/modules/notifications/setup.js +16 -1
  258. package/dist/modules/notifications/setup.js.map +2 -2
  259. package/dist/modules/notifications/subscribers/deliver-notification.js +66 -57
  260. package/dist/modules/notifications/subscribers/deliver-notification.js.map +2 -2
  261. package/dist/modules/notifications/subscribers/sync-notification-types.js +16 -0
  262. package/dist/modules/notifications/subscribers/sync-notification-types.js.map +7 -0
  263. package/dist/modules/notifications/widgets/injection/profile-preferences-menu/widget.js +23 -0
  264. package/dist/modules/notifications/widgets/injection/profile-preferences-menu/widget.js.map +7 -0
  265. package/dist/modules/notifications/widgets/injection-table.js +14 -0
  266. package/dist/modules/notifications/widgets/injection-table.js.map +7 -0
  267. package/dist/modules/push_notifications/acl.js +13 -0
  268. package/dist/modules/push_notifications/acl.js.map +7 -0
  269. package/dist/modules/push_notifications/api/custom-send/route.js +141 -0
  270. package/dist/modules/push_notifications/api/custom-send/route.js.map +7 -0
  271. package/dist/modules/push_notifications/api/deliveries/[id]/route.js +110 -0
  272. package/dist/modules/push_notifications/api/deliveries/[id]/route.js.map +7 -0
  273. package/dist/modules/push_notifications/api/deliveries/route.js +56 -0
  274. package/dist/modules/push_notifications/api/deliveries/route.js.map +7 -0
  275. package/dist/modules/push_notifications/api/openapi.js +19 -0
  276. package/dist/modules/push_notifications/api/openapi.js.map +7 -0
  277. package/dist/modules/push_notifications/backend/push_notifications/[id]/page.js +103 -0
  278. package/dist/modules/push_notifications/backend/push_notifications/[id]/page.js.map +7 -0
  279. package/dist/modules/push_notifications/backend/push_notifications/[id]/page.meta.js +13 -0
  280. package/dist/modules/push_notifications/backend/push_notifications/[id]/page.meta.js.map +7 -0
  281. package/dist/modules/push_notifications/backend/push_notifications/page.js +213 -0
  282. package/dist/modules/push_notifications/backend/push_notifications/page.js.map +7 -0
  283. package/dist/modules/push_notifications/backend/push_notifications/page.meta.js +23 -0
  284. package/dist/modules/push_notifications/backend/push_notifications/page.meta.js.map +7 -0
  285. package/dist/modules/push_notifications/backend/push_notifications/send/page.js +245 -0
  286. package/dist/modules/push_notifications/backend/push_notifications/send/page.js.map +7 -0
  287. package/dist/modules/push_notifications/backend/push_notifications/send/page.meta.js +26 -0
  288. package/dist/modules/push_notifications/backend/push_notifications/send/page.meta.js.map +7 -0
  289. package/dist/modules/push_notifications/data/entities.js +92 -0
  290. package/dist/modules/push_notifications/data/entities.js.map +7 -0
  291. package/dist/modules/push_notifications/data/extensions.js +23 -0
  292. package/dist/modules/push_notifications/data/extensions.js.map +7 -0
  293. package/dist/modules/push_notifications/data/validators.js +89 -0
  294. package/dist/modules/push_notifications/data/validators.js.map +7 -0
  295. package/dist/modules/push_notifications/di.js +17 -0
  296. package/dist/modules/push_notifications/di.js.map +7 -0
  297. package/dist/modules/push_notifications/events.js +24 -0
  298. package/dist/modules/push_notifications/events.js.map +7 -0
  299. package/dist/modules/push_notifications/index.js +16 -0
  300. package/dist/modules/push_notifications/index.js.map +7 -0
  301. package/dist/modules/push_notifications/lib/fake-provider-recorder.js +80 -0
  302. package/dist/modules/push_notifications/lib/fake-provider-recorder.js.map +7 -0
  303. package/dist/modules/push_notifications/lib/push-delivery-strategy.js +54 -0
  304. package/dist/modules/push_notifications/lib/push-delivery-strategy.js.map +7 -0
  305. package/dist/modules/push_notifications/lib/push-delivery.js +297 -0
  306. package/dist/modules/push_notifications/lib/push-delivery.js.map +7 -0
  307. package/dist/modules/push_notifications/lib/push-fanout.js +138 -0
  308. package/dist/modules/push_notifications/lib/push-fanout.js.map +7 -0
  309. package/dist/modules/push_notifications/lib/push-health.js +32 -0
  310. package/dist/modules/push_notifications/lib/push-health.js.map +7 -0
  311. package/dist/modules/push_notifications/lib/push-reaper.js +87 -0
  312. package/dist/modules/push_notifications/lib/push-reaper.js.map +7 -0
  313. package/dist/modules/push_notifications/lib/push-receipt-reaper.js +136 -0
  314. package/dist/modules/push_notifications/lib/push-receipt-reaper.js.map +7 -0
  315. package/dist/modules/push_notifications/lib/push-stub-adapter.js +63 -0
  316. package/dist/modules/push_notifications/lib/push-stub-adapter.js.map +7 -0
  317. package/dist/modules/push_notifications/lib/queue.js +53 -0
  318. package/dist/modules/push_notifications/lib/queue.js.map +7 -0
  319. package/dist/modules/push_notifications/lib/reclaim-window.js +13 -0
  320. package/dist/modules/push_notifications/lib/reclaim-window.js.map +7 -0
  321. package/dist/modules/push_notifications/lib/send-custom-push.js +48 -0
  322. package/dist/modules/push_notifications/lib/send-custom-push.js.map +7 -0
  323. package/dist/modules/push_notifications/migrations/Migration20260625150049_push_notifications.js +16 -0
  324. package/dist/modules/push_notifications/migrations/Migration20260625150049_push_notifications.js.map +7 -0
  325. package/dist/modules/push_notifications/migrations/Migration20260626120000_push_notifications_silent.js +13 -0
  326. package/dist/modules/push_notifications/migrations/Migration20260626120000_push_notifications_silent.js.map +7 -0
  327. package/dist/modules/push_notifications/notifications.delivery-strategies.js +8 -0
  328. package/dist/modules/push_notifications/notifications.delivery-strategies.js.map +7 -0
  329. package/dist/modules/push_notifications/notifications.js +40 -0
  330. package/dist/modules/push_notifications/notifications.js.map +7 -0
  331. package/dist/modules/push_notifications/setup.js +52 -0
  332. package/dist/modules/push_notifications/setup.js.map +7 -0
  333. package/dist/modules/push_notifications/workers/reclaim-stuck.worker.js +57 -0
  334. package/dist/modules/push_notifications/workers/reclaim-stuck.worker.js.map +7 -0
  335. package/dist/modules/push_notifications/workers/send-push.worker.js +27 -0
  336. package/dist/modules/push_notifications/workers/send-push.worker.js.map +7 -0
  337. package/dist/modules/sales/notifications.js +8 -0
  338. package/dist/modules/sales/notifications.js.map +2 -2
  339. package/dist/modules/staff/notifications.js +6 -0
  340. package/dist/modules/staff/notifications.js.map +2 -2
  341. package/dist/modules/workflows/notifications.js +2 -0
  342. package/dist/modules/workflows/notifications.js.map +2 -2
  343. package/generated/entities/notification/index.ts +3 -0
  344. package/generated/entities/notification_preference/index.ts +8 -0
  345. package/generated/entities/notification_type/index.ts +9 -0
  346. package/generated/entities/notification_type_override/index.ts +7 -0
  347. package/generated/entities/push_notification_delivery/index.ts +19 -0
  348. package/generated/entities/user_device/index.ts +16 -0
  349. package/generated/entities.ids.generated.ts +12 -1
  350. package/generated/entity-fields-registry.ts +72 -0
  351. package/package.json +7 -7
  352. package/src/helpers/integration/api.ts +2 -1
  353. package/src/helpers/integration/appRoot.ts +13 -0
  354. package/src/helpers/integration/dbFixtures.ts +1 -5
  355. package/src/helpers/integration/pushFake.ts +219 -0
  356. package/src/modules/auth/i18n/de.json +1 -0
  357. package/src/modules/auth/i18n/en.json +1 -0
  358. package/src/modules/auth/i18n/es.json +1 -0
  359. package/src/modules/auth/i18n/ko.json +1 -0
  360. package/src/modules/auth/i18n/pl.json +1 -0
  361. package/src/modules/auth/notifications.ts +16 -0
  362. package/src/modules/business_rules/i18n/de.json +2 -1
  363. package/src/modules/business_rules/i18n/en.json +2 -1
  364. package/src/modules/business_rules/i18n/es.json +2 -1
  365. package/src/modules/business_rules/i18n/ko.json +2 -1
  366. package/src/modules/business_rules/i18n/pl.json +2 -1
  367. package/src/modules/business_rules/notifications.ts +2 -0
  368. package/src/modules/catalog/i18n/de.json +2 -1
  369. package/src/modules/catalog/i18n/en.json +2 -1
  370. package/src/modules/catalog/i18n/es.json +2 -1
  371. package/src/modules/catalog/i18n/ko.json +2 -1
  372. package/src/modules/catalog/i18n/pl.json +2 -1
  373. package/src/modules/catalog/notifications.ts +2 -0
  374. package/src/modules/communication_channels/acl.ts +9 -0
  375. package/src/modules/communication_channels/api/delete/admin/channels/[id]/route.ts +168 -0
  376. package/src/modules/communication_channels/api/get/channels/[id]/health/route.ts +6 -2
  377. package/src/modules/communication_channels/api/get/channels/[id]/route.ts +6 -2
  378. package/src/modules/communication_channels/api/get/channels/route.ts +2 -1
  379. package/src/modules/communication_channels/api/post/channels/[id]/test-send/route.ts +16 -5
  380. package/src/modules/communication_channels/api/post/channels/connect/credentials/route.ts +37 -1
  381. package/src/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.ts +175 -0
  382. package/src/modules/communication_channels/backend/communication_channels/channels/page.tsx +11 -1
  383. package/src/modules/communication_channels/commands/admin-delete-channel.ts +203 -0
  384. package/src/modules/communication_channels/commands/connect-credential-channel.ts +63 -15
  385. package/src/modules/communication_channels/commands/deliver-outbound-message.ts +10 -2
  386. package/src/modules/communication_channels/commands/push-register.ts +7 -1
  387. package/src/modules/communication_channels/commands/push-unregister.ts +14 -3
  388. package/src/modules/communication_channels/data/entities.ts +10 -0
  389. package/src/modules/communication_channels/data/validators.ts +1 -0
  390. package/src/modules/communication_channels/i18n/de.json +35 -1
  391. package/src/modules/communication_channels/i18n/en.json +35 -1
  392. package/src/modules/communication_channels/i18n/es.json +35 -1
  393. package/src/modules/communication_channels/i18n/ko.json +35 -1
  394. package/src/modules/communication_channels/i18n/pl.json +35 -1
  395. package/src/modules/communication_channels/lib/access-control.ts +42 -0
  396. package/src/modules/communication_channels/lib/adapter.ts +25 -0
  397. package/src/modules/communication_channels/lib/connect-channel.ts +61 -26
  398. package/src/modules/communication_channels/lib/push-adapter.ts +139 -0
  399. package/src/modules/communication_channels/lib/push-capabilities.ts +42 -0
  400. package/src/modules/communication_channels/lib/push-connect-error.ts +52 -0
  401. package/src/modules/communication_channels/lib/push-credential-errors.ts +58 -0
  402. package/src/modules/communication_channels/lib/push-envelope.ts +104 -0
  403. package/src/modules/communication_channels/lib/refcounted-client-cache.ts +123 -0
  404. package/src/modules/communication_channels/migrations/.snapshot-open-mercato.json +9 -0
  405. package/src/modules/communication_channels/migrations/Migration20260703123630_communication_channels.ts +20 -0
  406. package/src/modules/communication_channels/notifications.ts +4 -0
  407. package/src/modules/communication_channels/setup.ts +2 -0
  408. package/src/modules/configs/i18n/de.json +5 -1
  409. package/src/modules/configs/i18n/en.json +5 -1
  410. package/src/modules/configs/i18n/es.json +5 -1
  411. package/src/modules/configs/i18n/ko.json +5 -1
  412. package/src/modules/configs/i18n/pl.json +5 -1
  413. package/src/modules/configs/lib/upgrade-actions.ts +21 -0
  414. package/src/modules/customer_accounts/i18n/de.json +2 -1
  415. package/src/modules/customer_accounts/i18n/en.json +2 -1
  416. package/src/modules/customer_accounts/i18n/es.json +2 -1
  417. package/src/modules/customer_accounts/i18n/ko.json +2 -1
  418. package/src/modules/customer_accounts/i18n/pl.json +2 -1
  419. package/src/modules/customer_accounts/notifications.ts +12 -0
  420. package/src/modules/customers/i18n/de.json +2 -1
  421. package/src/modules/customers/i18n/en.json +2 -1
  422. package/src/modules/customers/i18n/es.json +2 -1
  423. package/src/modules/customers/i18n/ko.json +2 -1
  424. package/src/modules/customers/i18n/pl.json +2 -1
  425. package/src/modules/customers/notifications.ts +4 -0
  426. package/src/modules/devices/AGENTS.md +101 -0
  427. package/src/modules/devices/acl.ts +7 -0
  428. package/src/modules/devices/api/[id]/route.ts +180 -0
  429. package/src/modules/devices/api/admin/devices/[id]/route.ts +235 -0
  430. package/src/modules/devices/api/admin/devices/route.ts +160 -0
  431. package/src/modules/devices/api/auth.ts +13 -0
  432. package/src/modules/devices/api/deviceList.ts +54 -0
  433. package/src/modules/devices/api/deviceOps.ts +186 -0
  434. package/src/modules/devices/api/openapi.ts +23 -0
  435. package/src/modules/devices/api/route.ts +165 -0
  436. package/src/modules/devices/backend/devices/[id]/page.meta.ts +12 -0
  437. package/src/modules/devices/backend/devices/[id]/page.tsx +164 -0
  438. package/src/modules/devices/backend/devices/create/page.meta.ts +12 -0
  439. package/src/modules/devices/backend/devices/create/page.tsx +81 -0
  440. package/src/modules/devices/backend/devices/page.meta.ts +21 -0
  441. package/src/modules/devices/backend/devices/page.tsx +259 -0
  442. package/src/modules/devices/commands/deactivate.ts +126 -0
  443. package/src/modules/devices/commands/index.ts +3 -0
  444. package/src/modules/devices/commands/register.ts +199 -0
  445. package/src/modules/devices/commands/shared.ts +119 -0
  446. package/src/modules/devices/commands/update.ts +142 -0
  447. package/src/modules/devices/data/entities.ts +79 -0
  448. package/src/modules/devices/data/validators.ts +65 -0
  449. package/src/modules/devices/di.ts +9 -0
  450. package/src/modules/devices/encryption.ts +15 -0
  451. package/src/modules/devices/events.ts +16 -0
  452. package/src/modules/devices/i18n/de.json +45 -0
  453. package/src/modules/devices/i18n/en.json +45 -0
  454. package/src/modules/devices/i18n/es.json +45 -0
  455. package/src/modules/devices/i18n/ko.json +45 -0
  456. package/src/modules/devices/i18n/pl.json +45 -0
  457. package/src/modules/devices/index.ts +15 -0
  458. package/src/modules/devices/lib/operationMetadata.ts +35 -0
  459. package/src/modules/devices/migrations/.snapshot-open-mercato.json +200 -0
  460. package/src/modules/devices/migrations/Migration20260602120000.ts +15 -0
  461. package/src/modules/devices/migrations/Migration20260630120000.ts +20 -0
  462. package/src/modules/devices/migrations/Migration20260701120000.ts +13 -0
  463. package/src/modules/devices/migrations/Migration20260721120000.ts +18 -0
  464. package/src/modules/devices/setup.ts +11 -0
  465. package/src/modules/entities/cli.ts +16 -2
  466. package/src/modules/entities/migrations/Migration20260722120000.ts +38 -0
  467. package/src/modules/inbox_ops/i18n/de.json +2 -1
  468. package/src/modules/inbox_ops/i18n/en.json +2 -1
  469. package/src/modules/inbox_ops/i18n/es.json +2 -1
  470. package/src/modules/inbox_ops/i18n/ko.json +2 -1
  471. package/src/modules/inbox_ops/i18n/pl.json +2 -1
  472. package/src/modules/inbox_ops/notifications.ts +2 -0
  473. package/src/modules/messages/i18n/de.json +2 -1
  474. package/src/modules/messages/i18n/en.json +2 -1
  475. package/src/modules/messages/i18n/es.json +2 -1
  476. package/src/modules/messages/i18n/ko.json +2 -1
  477. package/src/modules/messages/i18n/pl.json +2 -1
  478. package/src/modules/messages/notifications.ts +2 -0
  479. package/src/modules/notifications/AGENTS.md +54 -0
  480. package/src/modules/notifications/acl.ts +2 -0
  481. package/src/modules/notifications/api/admin/preferences/route.ts +193 -0
  482. package/src/modules/notifications/api/channels/route.ts +54 -0
  483. package/src/modules/notifications/api/preferences/route.ts +131 -0
  484. package/src/modules/notifications/api/route.ts +8 -1
  485. package/src/modules/notifications/api/types/[id]/channels/[channel]/route.ts +226 -0
  486. package/src/modules/notifications/api/types/route.ts +239 -0
  487. package/src/modules/notifications/api/unread-count/route.ts +5 -1
  488. package/src/modules/notifications/backend/notifications/user-preferences/page.meta.ts +26 -0
  489. package/src/modules/notifications/backend/notifications/user-preferences/page.tsx +12 -0
  490. package/src/modules/notifications/backend/profile/notification-preferences/page.meta.ts +31 -0
  491. package/src/modules/notifications/backend/profile/notification-preferences/page.tsx +12 -0
  492. package/src/modules/notifications/data/entities.ts +144 -0
  493. package/src/modules/notifications/data/validators.ts +116 -0
  494. package/src/modules/notifications/di.ts +7 -0
  495. package/src/modules/notifications/events.ts +23 -0
  496. package/src/modules/notifications/frontend/NotificationPreferenceMatrix.tsx +287 -0
  497. package/src/modules/notifications/frontend/NotificationPreferencesPageClient.tsx +155 -0
  498. package/src/modules/notifications/frontend/NotificationSettingsPageClient.tsx +273 -2
  499. package/src/modules/notifications/frontend/NotificationUserPreferencesAdminPageClient.tsx +214 -0
  500. package/src/modules/notifications/generators.ts +82 -0
  501. package/src/modules/notifications/i18n/de.json +43 -0
  502. package/src/modules/notifications/i18n/en.json +43 -0
  503. package/src/modules/notifications/i18n/es.json +43 -0
  504. package/src/modules/notifications/i18n/ko.json +43 -0
  505. package/src/modules/notifications/i18n/pl.json +44 -1
  506. package/src/modules/notifications/lib/delivery-strategies-registry.ts +30 -0
  507. package/src/modules/notifications/lib/deliveryStrategies.ts +40 -4
  508. package/src/modules/notifications/lib/derive-category.ts +15 -0
  509. package/src/modules/notifications/lib/notification-channel-registry.ts +59 -0
  510. package/src/modules/notifications/lib/notification-type-registry.ts +182 -0
  511. package/src/modules/notifications/lib/notificationCopy.ts +34 -0
  512. package/src/modules/notifications/lib/notificationFactory.ts +5 -1
  513. package/src/modules/notifications/lib/notificationMapper.ts +2 -0
  514. package/src/modules/notifications/lib/notificationPreferenceService.ts +138 -0
  515. package/src/modules/notifications/lib/notificationService.ts +129 -25
  516. package/src/modules/notifications/lib/notificationVisibility.ts +48 -0
  517. package/src/modules/notifications/lib/routeHelpers.ts +14 -1
  518. package/src/modules/notifications/lib/shouldDeliver.ts +112 -0
  519. package/src/modules/notifications/lib/strategies/email-delivery-strategy.ts +63 -0
  520. package/src/modules/notifications/lib/strategies/in-app-delivery-strategy.ts +21 -0
  521. package/src/modules/notifications/lib/typeCatalogue.ts +141 -0
  522. package/src/modules/notifications/lib/typeChannelSettings.ts +29 -0
  523. package/src/modules/notifications/lib/typeOverrides.ts +46 -0
  524. package/src/modules/notifications/migrations/.snapshot-open-mercato.json +874 -100
  525. package/src/modules/notifications/migrations/Migration20260625122947_notifications.ts +14 -0
  526. package/src/modules/notifications/migrations/Migration20260626120500_notifications_push_payload.ts +15 -0
  527. package/src/modules/notifications/migrations/Migration20260626130000_notifications_non_opt_out.ts +13 -0
  528. package/src/modules/notifications/migrations/Migration20260626140000_notifications_type_category_silent.ts +15 -0
  529. package/src/modules/notifications/migrations/Migration20260706120000_notifications_channels.ts +13 -0
  530. package/src/modules/notifications/migrations/Migration20260716123121_notifications.ts +14 -0
  531. package/src/modules/notifications/notification-channels.ts +30 -0
  532. package/src/modules/notifications/notifications.delivery-strategies.ts +15 -0
  533. package/src/modules/notifications/setup.ts +23 -1
  534. package/src/modules/notifications/subscribers/deliver-notification.ts +105 -71
  535. package/src/modules/notifications/subscribers/sync-notification-types.ts +18 -0
  536. package/src/modules/notifications/widgets/injection/profile-preferences-menu/widget.ts +35 -0
  537. package/src/modules/notifications/widgets/injection-table.ts +18 -0
  538. package/src/modules/push_notifications/AGENTS.md +92 -0
  539. package/src/modules/push_notifications/acl.ts +9 -0
  540. package/src/modules/push_notifications/api/custom-send/route.ts +175 -0
  541. package/src/modules/push_notifications/api/deliveries/[id]/route.ts +122 -0
  542. package/src/modules/push_notifications/api/deliveries/route.ts +58 -0
  543. package/src/modules/push_notifications/api/openapi.ts +22 -0
  544. package/src/modules/push_notifications/backend/push_notifications/[id]/page.meta.ts +9 -0
  545. package/src/modules/push_notifications/backend/push_notifications/[id]/page.tsx +149 -0
  546. package/src/modules/push_notifications/backend/push_notifications/page.meta.ts +21 -0
  547. package/src/modules/push_notifications/backend/push_notifications/page.tsx +239 -0
  548. package/src/modules/push_notifications/backend/push_notifications/send/page.meta.ts +24 -0
  549. package/src/modules/push_notifications/backend/push_notifications/send/page.tsx +327 -0
  550. package/src/modules/push_notifications/data/entities.ts +111 -0
  551. package/src/modules/push_notifications/data/extensions.ts +29 -0
  552. package/src/modules/push_notifications/data/validators.ts +102 -0
  553. package/src/modules/push_notifications/di.ts +20 -0
  554. package/src/modules/push_notifications/events.ts +21 -0
  555. package/src/modules/push_notifications/i18n/de.json +79 -0
  556. package/src/modules/push_notifications/i18n/en.json +79 -0
  557. package/src/modules/push_notifications/i18n/es.json +79 -0
  558. package/src/modules/push_notifications/i18n/ko.json +79 -0
  559. package/src/modules/push_notifications/i18n/pl.json +79 -0
  560. package/src/modules/push_notifications/index.ts +15 -0
  561. package/src/modules/push_notifications/lib/fake-provider-recorder.ts +154 -0
  562. package/src/modules/push_notifications/lib/push-delivery-strategy.ts +90 -0
  563. package/src/modules/push_notifications/lib/push-delivery.ts +455 -0
  564. package/src/modules/push_notifications/lib/push-fanout.ts +237 -0
  565. package/src/modules/push_notifications/lib/push-health.ts +47 -0
  566. package/src/modules/push_notifications/lib/push-reaper.ts +140 -0
  567. package/src/modules/push_notifications/lib/push-receipt-reaper.ts +210 -0
  568. package/src/modules/push_notifications/lib/push-stub-adapter.ts +80 -0
  569. package/src/modules/push_notifications/lib/queue.ts +74 -0
  570. package/src/modules/push_notifications/lib/reclaim-window.ts +16 -0
  571. package/src/modules/push_notifications/lib/send-custom-push.ts +100 -0
  572. package/src/modules/push_notifications/migrations/.snapshot-open-mercato.json +386 -0
  573. package/src/modules/push_notifications/migrations/Migration20260625150049_push_notifications.ts +16 -0
  574. package/src/modules/push_notifications/migrations/Migration20260626120000_push_notifications_silent.ts +13 -0
  575. package/src/modules/push_notifications/notifications.delivery-strategies.ts +8 -0
  576. package/src/modules/push_notifications/notifications.ts +50 -0
  577. package/src/modules/push_notifications/setup.ts +92 -0
  578. package/src/modules/push_notifications/workers/reclaim-stuck.worker.ts +78 -0
  579. package/src/modules/push_notifications/workers/send-push.worker.ts +34 -0
  580. package/src/modules/sales/i18n/de.json +1 -0
  581. package/src/modules/sales/i18n/en.json +1 -0
  582. package/src/modules/sales/i18n/es.json +1 -0
  583. package/src/modules/sales/i18n/ko.json +1 -0
  584. package/src/modules/sales/i18n/pl.json +1 -0
  585. package/src/modules/sales/notifications.ts +8 -0
  586. package/src/modules/staff/i18n/de.json +1 -0
  587. package/src/modules/staff/i18n/en.json +1 -0
  588. package/src/modules/staff/i18n/es.json +1 -0
  589. package/src/modules/staff/i18n/ko.json +1 -0
  590. package/src/modules/staff/i18n/pl.json +1 -0
  591. package/src/modules/staff/notifications.ts +6 -0
  592. package/src/modules/workflows/i18n/de.json +1 -0
  593. package/src/modules/workflows/i18n/en.json +1 -0
  594. package/src/modules/workflows/i18n/es.json +1 -0
  595. package/src/modules/workflows/i18n/ko.json +1 -0
  596. package/src/modules/workflows/i18n/pl.json +1 -0
  597. package/src/modules/workflows/notifications.ts +2 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/commands/deliver-outbound-message.ts"],
4
- "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { emitCommunicationChannelsEvent } from '../events'\nimport { refreshCredentialsIfNeeded } from '../lib/credential-refresh'\nimport { classifyOutboundError, isReauthError } from '../lib/error-classification'\nimport {\n buildBodyFooter,\n buildReferencesId,\n getOrCreateThreadToken,\n} from '../lib/thread-token'\nimport { stringOrUndefined, stripBrackets } from '../lib/email-mime'\nimport type { ChannelAdapterRegistry } from '../lib/registry'\nimport { isUniqueViolation } from '../lib/pg-errors'\nimport { Message } from '../../messages/data/entities'\nimport {\n ChannelThreadMapping,\n CommunicationChannel,\n ExternalMessage,\n MessageChannelLink,\n} from '../data/entities'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst moduleLogger = createLogger('communication_channels').child({ component: 'deliver-outbound-message' })\n\n/**\n * Sentinel \u2014 `Message.threadId` of an internal-only (no channel link) message\n * has no matching `ChannelThreadMapping`. In that case outbound delivery is a no-op.\n */\nconst NO_THREAD_MAPPING_RESULT = { status: 'no_channel_link' as const }\n\nconst deliverInputSchema = z.object({\n messageId: z.string().uuid(),\n scope: z.object({\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid().nullable(),\n }),\n /**\n * If true, force a credential refresh before sending \u2014 used by retry attempts\n * after a 401 from the provider.\n */\n forceCredentialRefresh: z.boolean().optional(),\n})\n\nexport type DeliverOutboundMessageInput = z.infer<typeof deliverInputSchema>\n\nexport type DeliverOutboundMessageResult =\n | { status: 'no_channel_link' }\n | { status: 'already_delivered'; messageId: string; channelLinkId: string }\n | {\n status: 'delivered'\n messageId: string\n channelLinkId: string\n externalMessageId: string\n providerKey: string\n }\n | {\n status: 'failed'\n messageId: string\n channelLinkId: string\n providerKey: string\n error: string\n transient: boolean\n /**\n * True when the failure was a 401 / invalid_grant \u2014 the channel was\n * flipped to `requires_reauth`. The worker uses this to attempt one\n * forced credential refresh before giving up.\n */\n requiresReauth: boolean\n }\n\nexport const COMMUNICATION_CHANNELS_DELIVER_OUTBOUND_COMMAND_ID =\n 'communication_channels.message.deliver_outbound'\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\ntype IntegrationLogLike = {\n log?: (entry: Record<string, unknown>) => Promise<void> | void\n warn?: (entry: Record<string, unknown>) => Promise<void> | void\n error?: (entry: Record<string, unknown>) => Promise<void> | void\n}\n\n/**\n * Outbound delivery command. Called from the outbound worker.\n *\n * Steps (SPEC-045d \u00A77):\n * 1. Re-fetch the Message by ID. Bail if internal-only (no ChannelThreadMapping).\n * 2. Resolve channel + adapter + credentials.\n * 3. Idempotently upsert a 'pending' MessageChannelLink (unique on `messageId`).\n * Skip if a 'sent'/'delivered' link already exists.\n * 4. Refresh credentials when OAuth + near expiry (or when caller forces it).\n * 5. Call `adapter.convertOutbound(...)` \u2192 channel-native content.\n * 6. Call `adapter.sendMessage(...)`.\n * 7. On success: persist ExternalMessage + flip link to 'sent', emit `.message.sent`.\n * 8. On failure: flip link to 'failed' + classify error, log to integrationLog,\n * emit `.delivery_failed`. The worker decides whether to retry based on\n * `result.transient`.\n *\n * Idempotency: the unique constraint on `message_channel_links.message_id`\n * prevents the same Message being sent twice through the channel even if the\n * subscriber fires repeatedly. Combined with the link's lifecycle state\n * (pending \u2192 sent | failed), we get safe retries.\n */\nconst deliverOutboundMessageCommand: CommandHandler<\n DeliverOutboundMessageInput,\n DeliverOutboundMessageResult\n> = {\n id: COMMUNICATION_CHANNELS_DELIVER_OUTBOUND_COMMAND_ID,\n async execute(rawInput, ctx) {\n const input = deliverInputSchema.parse(rawInput) as DeliverOutboundMessageInput\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dscope = {\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n }\n\n // (1) Re-fetch Message by ID \u2014 never trust the event payload shape.\n const message = await findOneWithDecryption(\n em,\n Message,\n {\n id: input.messageId,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!message) {\n // Message was deleted before we got to deliver. Treat as no-op.\n return NO_THREAD_MAPPING_RESULT\n }\n if (!message.threadId) {\n // Message has no thread \u2192 no channel routing.\n return NO_THREAD_MAPPING_RESULT\n }\n\n // (1 cont.) Look up the channel link via ChannelThreadMapping.threadId.\n const mapping = await findOneWithDecryption(\n em,\n ChannelThreadMapping,\n {\n messageThreadId: message.threadId,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n if (!mapping) {\n // Internal-only message \u2014 no channel delivery needed.\n return NO_THREAD_MAPPING_RESULT\n }\n\n // (2) Channel + adapter.\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: mapping.channelId,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!channel) {\n throw new Error(\n `[internal] Channel ${mapping.channelId} not found for tenant ${input.scope.tenantId} (or has been deleted)`,\n )\n }\n if (!channel.isActive) {\n throw new Error(`[internal] Channel ${mapping.channelId} is inactive; refusing to deliver outbound`)\n }\n\n const adapterRegistry = ctx.container.resolve('channelAdapterRegistry') as ChannelAdapterRegistry\n const adapter = adapterRegistry.get(channel.providerKey)\n if (!adapter) {\n throw new Error(\n `[internal] No ChannelAdapter registered for providerKey '${channel.providerKey}'. ` +\n 'Check that the provider package is enabled in modules.ts.',\n )\n }\n\n // (3) Idempotently upsert a 'pending' MessageChannelLink.\n let link = await findOneWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: message.id,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n if (\n link &&\n (link.deliveryStatus === 'queued' ||\n link.deliveryStatus === 'sent' ||\n link.deliveryStatus === 'delivered' ||\n link.deliveryStatus === 'read')\n ) {\n // Already sent (or accepted by the provider as 'queued') \u2014 short-circuit\n // so a retried job does not re-invoke the adapter and double-send.\n return {\n status: 'already_delivered',\n messageId: message.id,\n channelLinkId: link.id,\n }\n }\n if (!link) {\n link = em.create(MessageChannelLink, {\n messageId: message.id,\n externalConversationId: mapping.externalConversationId,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n direction: 'outbound',\n deliveryStatus: 'pending',\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n })\n em.persist(link)\n try {\n await em.flush()\n } catch (flushErr) {\n // Concurrency guard: the link lookup above is not atomic with this\n // insert, so two deliveries of the same message (a replayed\n // `messages.message.sent`, or an overlapping worker retry) can both\n // reach here. The `message_channel_links_message_uq` index rejects the\n // loser with a 23505. Defer to the winning job \u2014 re-read its link on a\n // fresh fork and report `already_delivered` \u2014 instead of re-invoking the\n // adapter (double send) or letting the raw error dead-letter the job.\n if (isUniqueViolation(flushErr)) {\n const winner = await findOneWithDecryption(\n em.fork(),\n MessageChannelLink,\n {\n messageId: message.id,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n if (winner) {\n return {\n status: 'already_delivered',\n messageId: message.id,\n channelLinkId: winner.id,\n }\n }\n }\n throw flushErr\n }\n }\n\n // (2 cont.) Decrypted credentials via the integrations module (if available).\n let credentialsService: CredentialsServiceLike | null = null\n try {\n credentialsService = ctx.container.resolve(\n 'integrationCredentialsService',\n ) as CredentialsServiceLike\n } catch {\n credentialsService = null\n }\n // Per-user credentials scope: pass `channel.userId` so the credentials\n // service returns this user's row, not whoever connected last. See\n // review R2-C1 / N1 (2026-05-26).\n const credentialsScope = {\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? input.scope.tenantId,\n userId: channel.userId ?? null,\n }\n let credentials: Record<string, unknown> = {}\n if (channel.credentialsRef && credentialsService) {\n try {\n credentials =\n (await credentialsService.resolve(`channel_${channel.providerKey}`, credentialsScope)) ?? {}\n } catch {\n credentials = {}\n }\n }\n\n // (4) Credential refresh if OAuth + near expiry, or forced by retry.\n let integrationLog: IntegrationLogLike | null = null\n try {\n integrationLog = ctx.container.resolve('integrationLogService') as IntegrationLogLike\n } catch {\n integrationLog = null\n }\n const refreshResult = await refreshCredentialsIfNeeded(\n {\n adapter,\n channelId: channel.id,\n credentials,\n scope: credentialsScope,\n force: Boolean(input.forceCredentialRefresh),\n },\n {\n credentialsService,\n logger: (...args) => moduleLogger.warn('credential refresh diagnostic', { details: args }),\n },\n )\n credentials = refreshResult.credentials\n\n // (4b) Spec B \u2014 get-or-create the per-thread crypto token and inject it\n // into the outbound payload BEFORE the adapter converts it. The token\n // travels as both a `References` header (via channelMetadata.references)\n // and a hidden body marker so inbound replies can be threaded back to\n // this conversation even when the recipient's MUA strips RFC 5322\n // headers. Idempotent on retry \u2014 same token reused per thread.\n let threadToken: string | null = null\n try {\n const { token } = await getOrCreateThreadToken(em, {\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n messageThreadId: mapping.messageThreadId,\n })\n threadToken = token\n } catch (tokenErr) {\n // Token creation should never block a send \u2014 if it fails, the message\n // still goes out, just without our thread-token attachment point.\n // Threading falls back to the JWZ strategy via Message-Id headers.\n moduleLogger.warn('thread token unavailable, proceeding without it', { err: tokenErr })\n }\n\n // (5) + (6) Convert + send.\n try {\n const outboundPayload = (link.channelPayload as Record<string, unknown> | null) ?? {}\n const outboundHtml = typeof outboundPayload.html === 'string' ? outboundPayload.html : null\n const outboundText = typeof outboundPayload.text === 'string' ? outboundPayload.text : null\n let outboundBody = outboundHtml ?? outboundText ?? message.body ?? ''\n const outboundBodyFormat = outboundHtml\n ? 'html'\n : ((message.bodyFormat as 'text' | 'markdown' | 'html') ?? 'text')\n\n // Pre-existing channelMetadata.references (string[]) so we can extend\n // it with the synthetic thread-token id without disturbing other refs\n // (e.g. the recipient's own reply chain).\n const baseMetadata = (link.channelMetadata as Record<string, unknown> | undefined) ?? {}\n const existingRefs = Array.isArray(baseMetadata.references)\n ? (baseMetadata.references as unknown[]).filter(\n (value): value is string => typeof value === 'string',\n )\n : []\n let mergedReferences = existingRefs\n if (threadToken && !outboundBody.includes(`[OM:${threadToken}]`)) {\n // Append the body footer for the corresponding format. The hidden\n // HTML span is `display:none`; the plain-text trailer is a small\n // bracketed marker on its own line. Both survive most reply clients.\n const footer = buildBodyFooter(threadToken)\n if (outboundBodyFormat === 'html') {\n const closingBody = outboundBody.lastIndexOf('</body>')\n outboundBody =\n closingBody >= 0\n ? `${outboundBody.slice(0, closingBody)}${footer.html}${outboundBody.slice(closingBody)}`\n : `${outboundBody}${footer.html}`\n } else {\n outboundBody = `${outboundBody}${footer.plain}`\n }\n const refId = buildReferencesId(threadToken)\n if (!mergedReferences.includes(refId)) {\n mergedReferences = [...mergedReferences, refId]\n }\n }\n const converted = await adapter.convertOutbound({\n body: outboundBody,\n bodyFormat: outboundBodyFormat,\n channelMetadata: {\n thread_id: mapping.externalThreadRef,\n ...baseMetadata,\n references: mergedReferences,\n ...(threadToken ? { omThreadToken: threadToken } : {}),\n },\n })\n\n // NOTE \u2014 at-least-once delivery (accepted v1 semantics). This provider\n // send is a non-transactional external side effect. The terminal-status\n // short-circuit above and the `message_channel_links_message_uq` index\n // prevent duplicate link records and re-sends after a *completed*\n // delivery, but if the process crashes in the narrow window between this\n // call returning and the success flush below, the link stays `pending`\n // and a worker retry re-invokes the adapter \u2014 the recipient may receive a\n // duplicate. This is deliberate: email providers (Gmail/SMTP) expose no\n // idempotent-send key nor a reliable \"did message X send?\" query, so\n // re-sending is preferred over risking a dropped message.\n const sendResult = await adapter.sendMessage({\n conversationId: mapping.externalThreadRef,\n content: converted.content,\n credentials,\n scope: {\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? input.scope.tenantId,\n },\n metadata: converted.metadata,\n })\n\n if (sendResult.status === 'failed') {\n throw new Error(sendResult.error ?? `Adapter '${adapter.providerKey}' reported send failure`)\n }\n\n // (7) Persist success records.\n //\n // Pre-generate the ExternalMessage PK client-side. The PK uses\n // `defaultRaw: 'gen_random_uuid()'`, so `externalMessage.id` is undefined\n // until after the INSERT returns \u2014 writing `link.externalMessageId =\n // externalMessage.id` before the flush would silently persist NULL on the\n // link's FK. Mirrors the inbound ingest path (ingest-inbound-message.ts).\n const externalMessageRowId = randomUUID()\n const externalMessage = em.create(ExternalMessage, {\n id: externalMessageRowId,\n channelId: channel.id,\n conversationId: mapping.externalConversationId,\n externalMessageId: sendResult.externalMessageId,\n direction: 'outbound',\n senderIdentifier: null,\n senderDisplayName: null,\n providerTimestamp: new Date(),\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n })\n em.persist(externalMessage)\n\n // A successful send proves the credentials are valid \u2014 clear any prior\n // `requires_reauth` / `error` state so a recovered channel doesn't keep\n // showing a stale reconnect banner (e.g. after a forced-refresh retry).\n if (channel.status === 'requires_reauth' || channel.status === 'error') {\n channel.status = 'connected'\n }\n\n link.deliveryStatus = sendResult.status === 'sent' ? 'sent' : 'queued'\n link.externalMessageId = externalMessageRowId\n link.channelMetadata = {\n ...((link.channelMetadata as Record<string, unknown> | undefined) ?? {}),\n ...(converted.metadata ?? {}),\n externalMessageId: sendResult.externalMessageId,\n // Always persist the RFC2822 Message-ID so inbound reply matching (JWZ\n // strategy in lib/thread-matcher) and sent-folder dedup can resolve this\n // outbound message. Adapters that build the message themselves (Gmail)\n // return it in `converted.metadata.messageId`; IMAP/SMTP lets\n // the transport mint it, surfacing it only as `sendResult.externalMessageId`\n // (the RFC2822 id the recipient replies to) \u2014 fall back to that.\n // Store it bracket-stripped to match the inbound convention\n // (`normalizeMimeInbound` strips), so the JWZ matcher and sent-folder dedup \u2014\n // which compare against stripped ids \u2014 resolve it. `assembleRfc2822`\n // re-applies brackets when this id is later used to build reply headers.\n messageId: stripBrackets(\n stringOrUndefined((converted.metadata as Record<string, unknown> | undefined)?.messageId) ??\n sendResult.externalMessageId,\n ),\n }\n await em.flush()\n\n await emitCommunicationChannelsEvent(\n 'communication_channels.message.sent',\n {\n messageId: message.id,\n externalMessageId: externalMessage.id,\n channelLinkId: link.id,\n conversationId: mapping.externalConversationId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n direction: 'outbound',\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n { persistent: true },\n )\n\n return {\n status: 'delivered',\n messageId: message.id,\n channelLinkId: link.id,\n externalMessageId: externalMessage.id,\n providerKey: channel.providerKey,\n }\n } catch (sendErr) {\n // (8) Failure path \u2014 classify, persist, emit, return.\n const classification = classifyOutboundError(sendErr)\n const requiresReauth = isReauthError(classification)\n link.deliveryStatus = 'failed'\n link.channelMetadata = {\n ...((link.channelMetadata as Record<string, unknown> | undefined) ?? {}),\n lastError: classification.message,\n lastErrorAt: new Date().toISOString(),\n transient: classification.transient,\n requiresReauth,\n }\n // A 401 / invalid_grant means the stored credentials are dead and no\n // retry will help \u2014 flip the channel to `requires_reauth` (mirrors the\n // inbound poll path) so the operator gets a reconnect signal instead of\n // silently-failing sends. A later successful send self-heals back to\n // `connected` (see the success path above).\n if (requiresReauth) {\n channel.status = 'requires_reauth'\n }\n await em.flush()\n\n try {\n await integrationLog?.error?.({\n integrationId: `channel_${channel.providerKey}`,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n channelId: channel.id,\n messageId: message.id,\n status: classification.status ?? null,\n transient: classification.transient,\n message: classification.message,\n })\n } catch {\n // best-effort logging\n }\n\n if (requiresReauth) {\n await emitCommunicationChannelsEvent(\n 'communication_channels.channel.requires_reauth',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n reason: classification.message,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n { persistent: true },\n )\n }\n\n await emitCommunicationChannelsEvent(\n 'communication_channels.message.delivery_failed',\n {\n messageId: message.id,\n channelLinkId: link.id,\n conversationId: mapping.externalConversationId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n transient: classification.transient,\n error: classification.message,\n status: classification.status ?? null,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n { persistent: true },\n )\n\n return {\n status: 'failed',\n messageId: message.id,\n channelLinkId: link.id,\n providerKey: channel.providerKey,\n error: classification.message,\n transient: classification.transient,\n requiresReauth,\n }\n }\n },\n}\n\nregisterCommand(deliverOutboundMessageCommand)\n\nexport default deliverOutboundMessageCommand\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAGlB,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAC/C,SAAS,kCAAkC;AAC3C,SAAS,uBAAuB,qBAAqB;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,qBAAqB;AAEjD,SAAS,yBAAyB;AAClC,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAE7B,MAAM,eAAe,aAAa,wBAAwB,EAAE,MAAM,EAAE,WAAW,2BAA2B,CAAC;AAM3G,MAAM,2BAA2B,EAAE,QAAQ,kBAA2B;AAEtE,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,WAAW,EAAE,OAAO,EAAE,KAAK;AAAA,EAC3B,OAAO,EAAE,OAAO;AAAA,IACd,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,IAC1B,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC7C,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA,EAKD,wBAAwB,EAAE,QAAQ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UAC1B,SAAS,eAAe;AAAA,QAC1B,CAAC;AAAA,MACH,QAAQ;AAAA,MAER;AAEA,UAAI,gBAAgB;AAClB,cAAM;AAAA,UACJ;AAAA,UACA;AAAA,YACE,WAAW,QAAQ;AAAA,YACnB,aAAa,QAAQ;AAAA,YACrB,aAAa,QAAQ;AAAA,YACrB,QAAQ,eAAe;AAAA,YACvB,UAAU,MAAM,MAAM;AAAA,YACtB,gBAAgB,MAAM,MAAM,kBAAkB;AAAA,UAChD;AAAA,UACA,EAAE,YAAY,KAAK;AAAA,QACrB;AAAA,MACF;AAEA,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,UACE,WAAW,QAAQ;AAAA,UACnB,eAAe,KAAK;AAAA,UACpB,gBAAgB,QAAQ;AAAA,UACxB,WAAW,QAAQ;AAAA,UACnB,aAAa,QAAQ;AAAA,UACrB,aAAa,QAAQ;AAAA,UACrB,WAAW,eAAe;AAAA,UAC1B,OAAO,eAAe;AAAA,UACtB,QAAQ,eAAe,UAAU;AAAA,UACjC,UAAU,MAAM,MAAM;AAAA,UACtB,gBAAgB,MAAM,MAAM,kBAAkB;AAAA,QAChD;AAAA,QACA,EAAE,YAAY,KAAK;AAAA,MACrB;AAEA,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,WAAW,QAAQ;AAAA,QACnB,eAAe,KAAK;AAAA,QACpB,aAAa,QAAQ;AAAA,QACrB,OAAO,eAAe;AAAA,QACtB,WAAW,eAAe;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,gBAAgB,6BAA6B;AAE7C,IAAO,mCAAQ;",
4
+ "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { registerCommand } from '@open-mercato/shared/lib/commands'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { emitCommunicationChannelsEvent } from '../events'\nimport { refreshCredentialsIfNeeded } from '../lib/credential-refresh'\nimport { classifyOutboundError, isReauthError } from '../lib/error-classification'\nimport {\n buildBodyFooter,\n buildReferencesId,\n getOrCreateThreadToken,\n} from '../lib/thread-token'\nimport { stringOrUndefined, stripBrackets } from '../lib/email-mime'\nimport type { ChannelAdapterRegistry } from '../lib/registry'\nimport { isUniqueViolation } from '../lib/pg-errors'\nimport { Message } from '../../messages/data/entities'\nimport {\n ChannelThreadMapping,\n CommunicationChannel,\n ExternalMessage,\n MessageChannelLink,\n} from '../data/entities'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst moduleLogger = createLogger('communication_channels').child({ component: 'deliver-outbound-message' })\n\n/**\n * Sentinel \u2014 `Message.threadId` of an internal-only (no channel link) message\n * has no matching `ChannelThreadMapping`. In that case outbound delivery is a no-op.\n */\nconst NO_THREAD_MAPPING_RESULT = { status: 'no_channel_link' as const }\n\nconst deliverInputSchema = z.object({\n messageId: z.string().uuid(),\n scope: z.object({\n tenantId: z.string().uuid(),\n organizationId: z.string().uuid().nullable(),\n }),\n /**\n * If true, force a credential refresh before sending \u2014 used by retry attempts\n * after a 401 from the provider.\n */\n forceCredentialRefresh: z.boolean().optional(),\n})\n\nexport type DeliverOutboundMessageInput = z.infer<typeof deliverInputSchema>\n\nexport type DeliverOutboundMessageResult =\n | { status: 'no_channel_link' }\n | { status: 'already_delivered'; messageId: string; channelLinkId: string }\n | {\n status: 'delivered'\n messageId: string\n channelLinkId: string\n externalMessageId: string\n providerKey: string\n }\n | {\n status: 'failed'\n messageId: string\n channelLinkId: string\n providerKey: string\n error: string\n transient: boolean\n /**\n * True when the failure was a 401 / invalid_grant \u2014 the channel was\n * flipped to `requires_reauth`. The worker uses this to attempt one\n * forced credential refresh before giving up.\n */\n requiresReauth: boolean\n }\n\nexport const COMMUNICATION_CHANNELS_DELIVER_OUTBOUND_COMMAND_ID =\n 'communication_channels.message.deliver_outbound'\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\ntype IntegrationLogLike = {\n log?: (entry: Record<string, unknown>) => Promise<void> | void\n warn?: (entry: Record<string, unknown>) => Promise<void> | void\n error?: (entry: Record<string, unknown>) => Promise<void> | void\n}\n\n/**\n * Outbound delivery command. Called from the outbound worker.\n *\n * Steps (SPEC-045d \u00A77):\n * 1. Re-fetch the Message by ID. Bail if internal-only (no ChannelThreadMapping).\n * 2. Resolve channel + adapter + credentials.\n * 3. Idempotently upsert a 'pending' MessageChannelLink (unique on `messageId`).\n * Skip if a 'sent'/'delivered' link already exists.\n * 4. Refresh credentials when OAuth + near expiry (or when caller forces it).\n * 5. Call `adapter.convertOutbound(...)` \u2192 channel-native content.\n * 6. Call `adapter.sendMessage(...)`.\n * 7. On success: persist ExternalMessage + flip link to 'sent', emit `.message.sent`.\n * 8. On failure: flip link to 'failed' + classify error, log to integrationLog,\n * emit `.delivery_failed`. The worker decides whether to retry based on\n * `result.transient`.\n *\n * Idempotency: the unique constraint on `message_channel_links.message_id`\n * prevents the same Message being sent twice through the channel even if the\n * subscriber fires repeatedly. Combined with the link's lifecycle state\n * (pending \u2192 sent | failed), we get safe retries.\n */\nconst deliverOutboundMessageCommand: CommandHandler<\n DeliverOutboundMessageInput,\n DeliverOutboundMessageResult\n> = {\n id: COMMUNICATION_CHANNELS_DELIVER_OUTBOUND_COMMAND_ID,\n async execute(rawInput, ctx) {\n const input = deliverInputSchema.parse(rawInput) as DeliverOutboundMessageInput\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const dscope = {\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n }\n\n // (1) Re-fetch Message by ID \u2014 never trust the event payload shape.\n const message = await findOneWithDecryption(\n em,\n Message,\n {\n id: input.messageId,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!message) {\n // Message was deleted before we got to deliver. Treat as no-op.\n return NO_THREAD_MAPPING_RESULT\n }\n if (!message.threadId) {\n // Message has no thread \u2192 no channel routing.\n return NO_THREAD_MAPPING_RESULT\n }\n\n // (1 cont.) Look up the channel link via ChannelThreadMapping.threadId.\n const mapping = await findOneWithDecryption(\n em,\n ChannelThreadMapping,\n {\n messageThreadId: message.threadId,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n if (!mapping) {\n // Internal-only message \u2014 no channel delivery needed.\n return NO_THREAD_MAPPING_RESULT\n }\n\n // (2) Channel + adapter.\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: mapping.channelId,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!channel) {\n throw new Error(\n `[internal] Channel ${mapping.channelId} not found for tenant ${input.scope.tenantId} (or has been deleted)`,\n )\n }\n if (!channel.isActive) {\n throw new Error(`[internal] Channel ${mapping.channelId} is inactive; refusing to deliver outbound`)\n }\n\n const adapterRegistry = ctx.container.resolve('channelAdapterRegistry') as ChannelAdapterRegistry\n const adapter = adapterRegistry.get(channel.providerKey)\n if (!adapter) {\n throw new Error(\n `[internal] No ChannelAdapter registered for providerKey '${channel.providerKey}'. ` +\n 'Check that the provider package is enabled in modules.ts.',\n )\n }\n\n // (3) Idempotently upsert a 'pending' MessageChannelLink.\n let link = await findOneWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: message.id,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n if (\n link &&\n (link.deliveryStatus === 'queued' ||\n link.deliveryStatus === 'sent' ||\n link.deliveryStatus === 'delivered' ||\n link.deliveryStatus === 'read')\n ) {\n // Already sent (or accepted by the provider as 'queued') \u2014 short-circuit\n // so a retried job does not re-invoke the adapter and double-send.\n return {\n status: 'already_delivered',\n messageId: message.id,\n channelLinkId: link.id,\n }\n }\n if (!link) {\n link = em.create(MessageChannelLink, {\n messageId: message.id,\n externalConversationId: mapping.externalConversationId,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n direction: 'outbound',\n deliveryStatus: 'pending',\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n })\n em.persist(link)\n try {\n await em.flush()\n } catch (flushErr) {\n // Concurrency guard: the link lookup above is not atomic with this\n // insert, so two deliveries of the same message (a replayed\n // `messages.message.sent`, or an overlapping worker retry) can both\n // reach here. The `message_channel_links_message_uq` index rejects the\n // loser with a 23505. Defer to the winning job \u2014 re-read its link on a\n // fresh fork and report `already_delivered` \u2014 instead of re-invoking the\n // adapter (double send) or letting the raw error dead-letter the job.\n if (isUniqueViolation(flushErr)) {\n const winner = await findOneWithDecryption(\n em.fork(),\n MessageChannelLink,\n {\n messageId: message.id,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n if (winner) {\n return {\n status: 'already_delivered',\n messageId: message.id,\n channelLinkId: winner.id,\n }\n }\n }\n throw flushErr\n }\n }\n\n // (2 cont.) Decrypted credentials via the integrations module (if available).\n let credentialsService: CredentialsServiceLike | null = null\n try {\n credentialsService = ctx.container.resolve(\n 'integrationCredentialsService',\n ) as CredentialsServiceLike\n } catch {\n credentialsService = null\n }\n // Per-user credentials scope: pass `channel.userId` so the credentials\n // service returns this user's row, not whoever connected last. See\n // review R2-C1 / N1 (2026-05-26).\n //\n // Key the org on the CHANNEL's own org, not the message's org. Tenant-wide\n // channels store `organization_id = NULL` and their credentials live at\n // `organization_id = tenantId` (see connect-credential-channel.ts), so\n // `channel.organizationId ?? tenantId` matches the write key for both\n // org-scoped and tenant-wide channels. Keying on the message org would\n // resolve `{}` the moment a tenant-wide provider delivers from a message\n // that carries a non-null org.\n const credentialsScope = {\n tenantId: input.scope.tenantId,\n organizationId: channel.organizationId ?? input.scope.tenantId,\n userId: channel.userId ?? null,\n }\n let credentials: Record<string, unknown> = {}\n if (channel.credentialsRef && credentialsService) {\n try {\n credentials =\n (await credentialsService.resolve(`channel_${channel.providerKey}`, credentialsScope)) ?? {}\n } catch {\n credentials = {}\n }\n }\n\n // (4) Credential refresh if OAuth + near expiry, or forced by retry.\n let integrationLog: IntegrationLogLike | null = null\n try {\n integrationLog = ctx.container.resolve('integrationLogService') as IntegrationLogLike\n } catch {\n integrationLog = null\n }\n const refreshResult = await refreshCredentialsIfNeeded(\n {\n adapter,\n channelId: channel.id,\n credentials,\n scope: credentialsScope,\n force: Boolean(input.forceCredentialRefresh),\n },\n {\n credentialsService,\n logger: (...args) => moduleLogger.warn('credential refresh diagnostic', { details: args }),\n },\n )\n credentials = refreshResult.credentials\n\n // (4b) Spec B \u2014 get-or-create the per-thread crypto token and inject it\n // into the outbound payload BEFORE the adapter converts it. The token\n // travels as both a `References` header (via channelMetadata.references)\n // and a hidden body marker so inbound replies can be threaded back to\n // this conversation even when the recipient's MUA strips RFC 5322\n // headers. Idempotent on retry \u2014 same token reused per thread.\n let threadToken: string | null = null\n try {\n const { token } = await getOrCreateThreadToken(em, {\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n messageThreadId: mapping.messageThreadId,\n })\n threadToken = token\n } catch (tokenErr) {\n // Token creation should never block a send \u2014 if it fails, the message\n // still goes out, just without our thread-token attachment point.\n // Threading falls back to the JWZ strategy via Message-Id headers.\n moduleLogger.warn('thread token unavailable, proceeding without it', { err: tokenErr })\n }\n\n // (5) + (6) Convert + send.\n try {\n const outboundPayload = (link.channelPayload as Record<string, unknown> | null) ?? {}\n const outboundHtml = typeof outboundPayload.html === 'string' ? outboundPayload.html : null\n const outboundText = typeof outboundPayload.text === 'string' ? outboundPayload.text : null\n let outboundBody = outboundHtml ?? outboundText ?? message.body ?? ''\n const outboundBodyFormat = outboundHtml\n ? 'html'\n : ((message.bodyFormat as 'text' | 'markdown' | 'html') ?? 'text')\n\n // Pre-existing channelMetadata.references (string[]) so we can extend\n // it with the synthetic thread-token id without disturbing other refs\n // (e.g. the recipient's own reply chain).\n const baseMetadata = (link.channelMetadata as Record<string, unknown> | undefined) ?? {}\n const existingRefs = Array.isArray(baseMetadata.references)\n ? (baseMetadata.references as unknown[]).filter(\n (value): value is string => typeof value === 'string',\n )\n : []\n let mergedReferences = existingRefs\n if (threadToken && !outboundBody.includes(`[OM:${threadToken}]`)) {\n // Append the body footer for the corresponding format. The hidden\n // HTML span is `display:none`; the plain-text trailer is a small\n // bracketed marker on its own line. Both survive most reply clients.\n const footer = buildBodyFooter(threadToken)\n if (outboundBodyFormat === 'html') {\n const closingBody = outboundBody.lastIndexOf('</body>')\n outboundBody =\n closingBody >= 0\n ? `${outboundBody.slice(0, closingBody)}${footer.html}${outboundBody.slice(closingBody)}`\n : `${outboundBody}${footer.html}`\n } else {\n outboundBody = `${outboundBody}${footer.plain}`\n }\n const refId = buildReferencesId(threadToken)\n if (!mergedReferences.includes(refId)) {\n mergedReferences = [...mergedReferences, refId]\n }\n }\n const converted = await adapter.convertOutbound({\n body: outboundBody,\n bodyFormat: outboundBodyFormat,\n channelMetadata: {\n thread_id: mapping.externalThreadRef,\n ...baseMetadata,\n references: mergedReferences,\n ...(threadToken ? { omThreadToken: threadToken } : {}),\n },\n })\n\n // NOTE \u2014 at-least-once delivery (accepted v1 semantics). This provider\n // send is a non-transactional external side effect. The terminal-status\n // short-circuit above and the `message_channel_links_message_uq` index\n // prevent duplicate link records and re-sends after a *completed*\n // delivery, but if the process crashes in the narrow window between this\n // call returning and the success flush below, the link stays `pending`\n // and a worker retry re-invokes the adapter \u2014 the recipient may receive a\n // duplicate. This is deliberate: email providers (Gmail/SMTP) expose no\n // idempotent-send key nor a reliable \"did message X send?\" query, so\n // re-sending is preferred over risking a dropped message.\n const sendResult = await adapter.sendMessage({\n conversationId: mapping.externalThreadRef,\n content: converted.content,\n credentials,\n scope: {\n tenantId: input.scope.tenantId,\n organizationId: channel.organizationId ?? input.scope.tenantId,\n },\n metadata: converted.metadata,\n })\n\n if (sendResult.status === 'failed') {\n throw new Error(sendResult.error ?? `Adapter '${adapter.providerKey}' reported send failure`)\n }\n\n // (7) Persist success records.\n //\n // Pre-generate the ExternalMessage PK client-side. The PK uses\n // `defaultRaw: 'gen_random_uuid()'`, so `externalMessage.id` is undefined\n // until after the INSERT returns \u2014 writing `link.externalMessageId =\n // externalMessage.id` before the flush would silently persist NULL on the\n // link's FK. Mirrors the inbound ingest path (ingest-inbound-message.ts).\n const externalMessageRowId = randomUUID()\n const externalMessage = em.create(ExternalMessage, {\n id: externalMessageRowId,\n channelId: channel.id,\n conversationId: mapping.externalConversationId,\n externalMessageId: sendResult.externalMessageId,\n direction: 'outbound',\n senderIdentifier: null,\n senderDisplayName: null,\n providerTimestamp: new Date(),\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n })\n em.persist(externalMessage)\n\n // A successful send proves the credentials are valid \u2014 clear any prior\n // `requires_reauth` / `error` state so a recovered channel doesn't keep\n // showing a stale reconnect banner (e.g. after a forced-refresh retry).\n if (channel.status === 'requires_reauth' || channel.status === 'error') {\n channel.status = 'connected'\n }\n\n link.deliveryStatus = sendResult.status === 'sent' ? 'sent' : 'queued'\n link.externalMessageId = externalMessageRowId\n link.channelMetadata = {\n ...((link.channelMetadata as Record<string, unknown> | undefined) ?? {}),\n ...(converted.metadata ?? {}),\n externalMessageId: sendResult.externalMessageId,\n // Always persist the RFC2822 Message-ID so inbound reply matching (JWZ\n // strategy in lib/thread-matcher) and sent-folder dedup can resolve this\n // outbound message. Adapters that build the message themselves (Gmail)\n // return it in `converted.metadata.messageId`; IMAP/SMTP lets\n // the transport mint it, surfacing it only as `sendResult.externalMessageId`\n // (the RFC2822 id the recipient replies to) \u2014 fall back to that.\n // Store it bracket-stripped to match the inbound convention\n // (`normalizeMimeInbound` strips), so the JWZ matcher and sent-folder dedup \u2014\n // which compare against stripped ids \u2014 resolve it. `assembleRfc2822`\n // re-applies brackets when this id is later used to build reply headers.\n messageId: stripBrackets(\n stringOrUndefined((converted.metadata as Record<string, unknown> | undefined)?.messageId) ??\n sendResult.externalMessageId,\n ),\n }\n await em.flush()\n\n await emitCommunicationChannelsEvent(\n 'communication_channels.message.sent',\n {\n messageId: message.id,\n externalMessageId: externalMessage.id,\n channelLinkId: link.id,\n conversationId: mapping.externalConversationId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n direction: 'outbound',\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n { persistent: true },\n )\n\n return {\n status: 'delivered',\n messageId: message.id,\n channelLinkId: link.id,\n externalMessageId: externalMessage.id,\n providerKey: channel.providerKey,\n }\n } catch (sendErr) {\n // (8) Failure path \u2014 classify, persist, emit, return.\n const classification = classifyOutboundError(sendErr)\n const requiresReauth = isReauthError(classification)\n link.deliveryStatus = 'failed'\n link.channelMetadata = {\n ...((link.channelMetadata as Record<string, unknown> | undefined) ?? {}),\n lastError: classification.message,\n lastErrorAt: new Date().toISOString(),\n transient: classification.transient,\n requiresReauth,\n }\n // A 401 / invalid_grant means the stored credentials are dead and no\n // retry will help \u2014 flip the channel to `requires_reauth` (mirrors the\n // inbound poll path) so the operator gets a reconnect signal instead of\n // silently-failing sends. A later successful send self-heals back to\n // `connected` (see the success path above).\n if (requiresReauth) {\n channel.status = 'requires_reauth'\n }\n await em.flush()\n\n try {\n await integrationLog?.error?.({\n integrationId: `channel_${channel.providerKey}`,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n channelId: channel.id,\n messageId: message.id,\n status: classification.status ?? null,\n transient: classification.transient,\n message: classification.message,\n })\n } catch {\n // best-effort logging\n }\n\n if (requiresReauth) {\n await emitCommunicationChannelsEvent(\n 'communication_channels.channel.requires_reauth',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n reason: classification.message,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n { persistent: true },\n )\n }\n\n await emitCommunicationChannelsEvent(\n 'communication_channels.message.delivery_failed',\n {\n messageId: message.id,\n channelLinkId: link.id,\n conversationId: mapping.externalConversationId,\n channelId: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n transient: classification.transient,\n error: classification.message,\n status: classification.status ?? null,\n tenantId: input.scope.tenantId,\n organizationId: input.scope.organizationId ?? null,\n },\n { persistent: true },\n )\n\n return {\n status: 'failed',\n messageId: message.id,\n channelLinkId: link.id,\n providerKey: channel.providerKey,\n error: classification.message,\n transient: classification.transient,\n requiresReauth,\n }\n }\n },\n}\n\nregisterCommand(deliverOutboundMessageCommand)\n\nexport default deliverOutboundMessageCommand\n"],
5
+ "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,SAAS;AAGlB,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAC/C,SAAS,kCAAkC;AAC3C,SAAS,uBAAuB,qBAAqB;AACrD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,qBAAqB;AAEjD,SAAS,yBAAyB;AAClC,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAE7B,MAAM,eAAe,aAAa,wBAAwB,EAAE,MAAM,EAAE,WAAW,2BAA2B,CAAC;AAM3G,MAAM,2BAA2B,EAAE,QAAQ,kBAA2B;AAEtE,MAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,WAAW,EAAE,OAAO,EAAE,KAAK;AAAA,EAC3B,OAAO,EAAE,OAAO;AAAA,IACd,UAAU,EAAE,OAAO,EAAE,KAAK;AAAA,IAC1B,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS;AAAA,EAC7C,CAAC;AAAA;AAAA;AAAA;AAAA;AA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AAW,eAAe;AAAA,UAC1B,SAAS,eAAe;AAAA,QAC1B,CAAC;AAAA,MACH,QAAQ;AAAA,MAER;AAEA,UAAI,gBAAgB;AAClB,cAAM;AAAA,UACJ;AAAA,UACA;AAAA,YACE,WAAW,QAAQ;AAAA,YACnB,aAAa,QAAQ;AAAA,YACrB,aAAa,QAAQ;AAAA,YACrB,QAAQ,eAAe;AAAA,YACvB,UAAU,MAAM,MAAM;AAAA,YACtB,gBAAgB,MAAM,MAAM,kBAAkB;AAAA,UAChD;AAAA,UACA,EAAE,YAAY,KAAK;AAAA,QACrB;AAAA,MACF;AAEA,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,UACE,WAAW,QAAQ;AAAA,UACnB,eAAe,KAAK;AAAA,UACpB,gBAAgB,QAAQ;AAAA,UACxB,WAAW,QAAQ;AAAA,UACnB,aAAa,QAAQ;AAAA,UACrB,aAAa,QAAQ;AAAA,UACrB,WAAW,eAAe;AAAA,UAC1B,OAAO,eAAe;AAAA,UACtB,QAAQ,eAAe,UAAU;AAAA,UACjC,UAAU,MAAM,MAAM;AAAA,UACtB,gBAAgB,MAAM,MAAM,kBAAkB;AAAA,QAChD;AAAA,QACA,EAAE,YAAY,KAAK;AAAA,MACrB;AAEA,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,WAAW,QAAQ;AAAA,QACnB,eAAe,KAAK;AAAA,QACpB,aAAa,QAAQ;AAAA,QACrB,OAAO,eAAe;AAAA,QACtB,WAAW,eAAe;AAAA,QAC1B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,gBAAgB,6BAA6B;AAE7C,IAAO,mCAAQ;",
6
6
  "names": []
7
7
  }
@@ -62,7 +62,7 @@ async function pushRegister(params) {
62
62
  }
63
63
  const credentialsScope = {
64
64
  tenantId: scope.tenantId,
65
- organizationId: scope.organizationId,
65
+ organizationId: channel.organizationId ?? scope.tenantId,
66
66
  userId: channel.userId ?? null
67
67
  };
68
68
  let credentials = {};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/commands/push-register.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\nimport type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel } from '../data/entities'\nimport { getChannelAdapterRegistry } from '../lib/adapter-registry-singleton'\nimport { refreshCredentialsIfNeeded } from '../lib/credential-refresh'\nimport { emitCommunicationChannelsEvent } from '../events'\nimport type { PushRegistration } from '../lib/adapter'\n\n/**\n * Spec C \u00A7 Phase C5 \u2014 Register provider push delivery for a channel.\n *\n * Resolves credentials + tenant OAuth client config, then calls\n * `adapter.registerPush(...)`. Applies the returned state patch to\n * `channel.channelState` and flips `pollIntervalSeconds` to the\n * adapter's recommendation (or leaves it as-is on failure so polling\n * fallback continues).\n *\n * Idempotent: calling on a channel that already has `pushStatus='active'`\n * is OK \u2014 the adapter re-issues the underlying registration and we update\n * the cursor / expiry to the new value.\n */\n\nexport const pushRegisterSchema = z.object({\n channelId: z.string().uuid(),\n})\n\nexport interface PushRegisterScope {\n tenantId: string\n organizationId: string\n userId?: string | null\n}\n\nexport interface PushRegisterResult {\n channelId: string\n pushStatus: 'active' | 'failed'\n channelState: Record<string, unknown>\n error?: { code: string; message: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\nexport async function pushRegister(params: {\n container: AwilixContainer\n scope: PushRegisterScope\n input: { channelId: string }\n}): Promise<PushRegisterResult> {\n const input = pushRegisterSchema.parse(params.input)\n const { container, scope } = params\n\n const em = (container.resolve('em') as EntityManager).fork()\n const dscope = { tenantId: scope.tenantId, organizationId: scope.organizationId }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: input.channelId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!channel) {\n throw createCrudFormError(\n 'Channel not found',\n { channelId: 'Channel not found' },\n { status: 404 },\n )\n }\n if (!channel.isActive || channel.status !== 'connected') {\n throw createCrudFormError(\n 'Channel must be connected to register push',\n { channelId: `Channel status is ${channel.status}` },\n { status: 400 },\n )\n }\n\n const adapter = getChannelAdapterRegistry().get(channel.providerKey)\n if (!adapter) {\n throw createCrudFormError(\n 'Channel provider is not available',\n { channelId: `No adapter for provider \"${channel.providerKey}\"` },\n { status: 400 },\n )\n }\n if (typeof adapter.registerPush !== 'function') {\n throw createCrudFormError(\n 'Push delivery is not supported on this provider',\n { channelId: `Provider \"${channel.providerKey}\" does not implement registerPush` },\n { status: 409 },\n )\n }\n\n // Credentials.\n let credentialsService: CredentialsServiceLike | null = null\n try {\n credentialsService = container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n credentialsService = null\n }\n const credentialsScope = {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: channel.userId ?? null,\n }\n let credentials: Record<string, unknown> = {}\n if (channel.credentialsRef && credentialsService) {\n try {\n credentials =\n (await credentialsService.resolve(`channel_${channel.providerKey}`, credentialsScope)) ?? {}\n } catch {\n credentials = {}\n }\n }\n const refreshed = await refreshCredentialsIfNeeded(\n { adapter, channelId: channel.id, credentials, scope: credentialsScope },\n { credentialsService },\n )\n credentials = refreshed.credentials\n\n // Per-provider provider config.\n let providerConfig: Record<string, unknown> | undefined\n let notificationUrl = ''\n\n if (channel.providerKey === 'gmail') {\n const topic = process.env.OM_GMAIL_PUBSUB_TOPIC\n providerConfig = { pubsubTopic: topic ?? '' }\n notificationUrl = '' // Gmail does not use a per-call URL; Pub/Sub subscription is preconfigured.\n }\n\n let registration: PushRegistration\n try {\n registration = await adapter.registerPush({\n channelId: channel.id,\n credentials,\n scope: { tenantId: scope.tenantId, organizationId: scope.organizationId },\n notificationUrl,\n providerConfig,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : 'registerPush threw'\n throw createCrudFormError(\n 'Push registration failed',\n { channelId: message.slice(0, 500) },\n { status: 502 },\n )\n }\n\n // Persist results.\n const previousState = (channel.channelState as Record<string, unknown> | null) ?? {}\n channel.channelState = { ...previousState, ...registration.channelStatePatch }\n if (registration.status === 'active' && typeof registration.recommendedPollIntervalSeconds === 'number') {\n channel.pollIntervalSeconds = registration.recommendedPollIntervalSeconds\n }\n await em.flush()\n\n if (registration.status === 'active') {\n await emitCommunicationChannelsEvent(\n 'communication_channels.push.registered',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n { persistent: true },\n )\n } else {\n await emitCommunicationChannelsEvent(\n 'communication_channels.push.failed',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n error: registration.error ?? null,\n },\n { persistent: true },\n )\n }\n\n return {\n channelId: channel.id,\n pushStatus: registration.status,\n channelState: (channel.channelState as Record<string, unknown> | null) ?? {},\n error: registration.error,\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,4BAA4B;AACrC,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,sCAAsC;AAiBxC,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,WAAW,EAAE,OAAO,EAAE,KAAK;AAC7B,CAAC;AA2BD,eAAsB,aAAa,QAIH;AAC9B,QAAM,QAAQ,mBAAmB,MAAM,OAAO,KAAK;AACnD,QAAM,EAAE,WAAW,MAAM,IAAI;AAE7B,QAAM,KAAM,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAC3D,QAAM,SAAS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AAAA,MACA,EAAE,YAAY,KAAK;AAAA,IACrB;AAAA,EACF,OAAO;AACL,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,QACE,WAAW,QAAQ;AAAA,QACnB,aAAa,QAAQ;AAAA,QACrB,UAAU,MAAM;AAAA,QAChB,gBAAgB,MAAM;AAAA,QACtB,OAAO,aAAa,SAAS;AAAA,MAC/B;AAAA,MACA,EAAE,YAAY,KAAK;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,WAAW,QAAQ;AAAA,IACnB,YAAY,aAAa;AAAA,IACzB,cAAe,QAAQ,gBAAmD,CAAC;AAAA,IAC3E,OAAO,aAAa;AAAA,EACtB;AACF;",
4
+ "sourcesContent": ["import { z } from 'zod'\nimport type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel } from '../data/entities'\nimport { getChannelAdapterRegistry } from '../lib/adapter-registry-singleton'\nimport { refreshCredentialsIfNeeded } from '../lib/credential-refresh'\nimport { emitCommunicationChannelsEvent } from '../events'\nimport type { PushRegistration } from '../lib/adapter'\n\n/**\n * Spec C \u00A7 Phase C5 \u2014 Register provider push delivery for a channel.\n *\n * Resolves credentials + tenant OAuth client config, then calls\n * `adapter.registerPush(...)`. Applies the returned state patch to\n * `channel.channelState` and flips `pollIntervalSeconds` to the\n * adapter's recommendation (or leaves it as-is on failure so polling\n * fallback continues).\n *\n * Idempotent: calling on a channel that already has `pushStatus='active'`\n * is OK \u2014 the adapter re-issues the underlying registration and we update\n * the cursor / expiry to the new value.\n */\n\nexport const pushRegisterSchema = z.object({\n channelId: z.string().uuid(),\n})\n\nexport interface PushRegisterScope {\n tenantId: string\n organizationId: string\n userId?: string | null\n}\n\nexport interface PushRegisterResult {\n channelId: string\n pushStatus: 'active' | 'failed'\n channelState: Record<string, unknown>\n error?: { code: string; message: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\nexport async function pushRegister(params: {\n container: AwilixContainer\n scope: PushRegisterScope\n input: { channelId: string }\n}): Promise<PushRegisterResult> {\n const input = pushRegisterSchema.parse(params.input)\n const { container, scope } = params\n\n const em = (container.resolve('em') as EntityManager).fork()\n const dscope = { tenantId: scope.tenantId, organizationId: scope.organizationId }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: input.channelId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!channel) {\n throw createCrudFormError(\n 'Channel not found',\n { channelId: 'Channel not found' },\n { status: 404 },\n )\n }\n if (!channel.isActive || channel.status !== 'connected') {\n throw createCrudFormError(\n 'Channel must be connected to register push',\n { channelId: `Channel status is ${channel.status}` },\n { status: 400 },\n )\n }\n\n const adapter = getChannelAdapterRegistry().get(channel.providerKey)\n if (!adapter) {\n throw createCrudFormError(\n 'Channel provider is not available',\n { channelId: `No adapter for provider \"${channel.providerKey}\"` },\n { status: 400 },\n )\n }\n if (typeof adapter.registerPush !== 'function') {\n throw createCrudFormError(\n 'Push delivery is not supported on this provider',\n { channelId: `Provider \"${channel.providerKey}\" does not implement registerPush` },\n { status: 409 },\n )\n }\n\n // Credentials.\n let credentialsService: CredentialsServiceLike | null = null\n try {\n credentialsService = container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n credentialsService = null\n }\n // Resolve credentials at the channel's OWN org, not the caller's scope org.\n // Tenant-wide channels store `organization_id = NULL` and their credentials\n // live at `organization_id = tenantId` (see connect-credential-channel.ts).\n // Keying on `channel.organizationId ?? tenantId` matches the write key for\n // both org-scoped (per-user) and tenant-wide channels; keying on the caller's\n // scope org would silently resolve `{}` for a tenant-wide channel.\n const credentialsScope = {\n tenantId: scope.tenantId,\n organizationId: channel.organizationId ?? scope.tenantId,\n userId: channel.userId ?? null,\n }\n let credentials: Record<string, unknown> = {}\n if (channel.credentialsRef && credentialsService) {\n try {\n credentials =\n (await credentialsService.resolve(`channel_${channel.providerKey}`, credentialsScope)) ?? {}\n } catch {\n credentials = {}\n }\n }\n const refreshed = await refreshCredentialsIfNeeded(\n { adapter, channelId: channel.id, credentials, scope: credentialsScope },\n { credentialsService },\n )\n credentials = refreshed.credentials\n\n // Per-provider provider config.\n let providerConfig: Record<string, unknown> | undefined\n let notificationUrl = ''\n\n if (channel.providerKey === 'gmail') {\n const topic = process.env.OM_GMAIL_PUBSUB_TOPIC\n providerConfig = { pubsubTopic: topic ?? '' }\n notificationUrl = '' // Gmail does not use a per-call URL; Pub/Sub subscription is preconfigured.\n }\n\n let registration: PushRegistration\n try {\n registration = await adapter.registerPush({\n channelId: channel.id,\n credentials,\n scope: { tenantId: scope.tenantId, organizationId: scope.organizationId },\n notificationUrl,\n providerConfig,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : 'registerPush threw'\n throw createCrudFormError(\n 'Push registration failed',\n { channelId: message.slice(0, 500) },\n { status: 502 },\n )\n }\n\n // Persist results.\n const previousState = (channel.channelState as Record<string, unknown> | null) ?? {}\n channel.channelState = { ...previousState, ...registration.channelStatePatch }\n if (registration.status === 'active' && typeof registration.recommendedPollIntervalSeconds === 'number') {\n channel.pollIntervalSeconds = registration.recommendedPollIntervalSeconds\n }\n await em.flush()\n\n if (registration.status === 'active') {\n await emitCommunicationChannelsEvent(\n 'communication_channels.push.registered',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n { persistent: true },\n )\n } else {\n await emitCommunicationChannelsEvent(\n 'communication_channels.push.failed',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n error: registration.error ?? null,\n },\n { persistent: true },\n )\n }\n\n return {\n channelId: channel.id,\n pushStatus: registration.status,\n channelState: (channel.channelState as Record<string, unknown> | null) ?? {},\n error: registration.error,\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAGlB,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,4BAA4B;AACrC,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,sCAAsC;AAiBxC,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,WAAW,EAAE,OAAO,EAAE,KAAK;AAC7B,CAAC;AA2BD,eAAsB,aAAa,QAIH;AAC9B,QAAM,QAAQ,mBAAmB,MAAM,OAAO,KAAK;AACnD,QAAM,EAAE,WAAW,MAAM,IAAI;AAE7B,QAAM,KAAM,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAC3D,QAAM,SAAS,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAEhF,QAAM,UAAU,MAAM;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,MACE,IAAI,MAAM;AAAA,MACV,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB,WAAW;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,SAAS;AACZ,UAAM;AAAA,MACJ;AAAA,MACA,EAAE,WAAW,oBAAoB;AAAA,MACjC,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AACA,MAAI,CAAC,QAAQ,YAAY,QAAQ,WAAW,aAAa;AACvD,UAAM;AAAA,MACJ;AAAA,MACA,EAAE,WAAW,qBAAqB,QAAQ,MAAM,GAAG;AAAA,MACnD,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AAEA,QAAM,UAAU,0BAA0B,EAAE,IAAI,QAAQ,WAAW;AACnE,MAAI,CAAC,SAAS;AACZ,UAAM;AAAA,MACJ;AA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;AAAA,EACH,SAAS,KAAK;AACZ,UAAM,UAAU,eAAe,QAAQ,IAAI,UAAU;AACrD,UAAM;AAAA,MACJ;AAAA,MACA,EAAE,WAAW,QAAQ,MAAM,GAAG,GAAG,EAAE;AAAA,MACnC,EAAE,QAAQ,IAAI;AAAA,IAChB;AAAA,EACF;AAGA,QAAM,gBAAiB,QAAQ,gBAAmD,CAAC;AACnF,UAAQ,eAAe,EAAE,GAAG,eAAe,GAAG,aAAa,kBAAkB;AAC7E,MAAI,aAAa,WAAW,YAAY,OAAO,aAAa,mCAAmC,UAAU;AACvG,YAAQ,sBAAsB,aAAa;AAAA,EAC7C;AACA,QAAM,GAAG,MAAM;AAEf,MAAI,aAAa,WAAW,UAAU;AACpC,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,QACE,WAAW,QAAQ;AAAA,QACnB,aAAa,QAAQ;AAAA,QACrB,UAAU,MAAM;AAAA,QAChB,gBAAgB,MAAM;AAAA,MACxB;AAAA,MACA,EAAE,YAAY,KAAK;AAAA,IACrB;AAAA,EACF,OAAO;AACL,UAAM;AAAA,MACJ;AAAA,MACA;AAAA,QACE,WAAW,QAAQ;AAAA,QACnB,aAAa,QAAQ;AAAA,QACrB,UAAU,MAAM;AAAA,QAChB,gBAAgB,MAAM;AAAA,QACtB,OAAO,aAAa,SAAS;AAAA,MAC/B;AAAA,MACA,EAAE,YAAY,KAAK;AAAA,IACrB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,WAAW,QAAQ;AAAA,IACnB,YAAY,aAAa;AAAA,IACzB,cAAe,QAAQ,gBAAmD,CAAC;AAAA,IAC3E,OAAO,aAAa;AAAA,EACtB;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
3
3
  import { CommunicationChannel } from "../data/entities.js";
4
+ import { channelOrgScopeWhere } from "../lib/access-control.js";
4
5
  import { getChannelAdapterRegistry } from "../lib/adapter-registry-singleton.js";
5
6
  import { refreshCredentialsIfNeeded } from "../lib/credential-refresh.js";
6
7
  import { POLLING_ONLY_DEFAULT_INTERVAL_SECONDS } from "../lib/connect-channel.js";
@@ -14,14 +15,14 @@ async function pushUnregister(params) {
14
15
  const input = pushUnregisterSchema.parse(params.input);
15
16
  const { container, scope } = params;
16
17
  const em = container.resolve("em").fork();
17
- const dscope = { tenantId: scope.tenantId, organizationId: scope.organizationId };
18
+ const dscope = { tenantId: scope.tenantId, organizationId: null };
18
19
  const channel = await findOneWithDecryption(
19
20
  em,
20
21
  CommunicationChannel,
21
22
  {
22
23
  id: input.channelId,
23
24
  tenantId: scope.tenantId,
24
- organizationId: scope.organizationId
25
+ ...channelOrgScopeWhere(scope.organizationId)
25
26
  },
26
27
  void 0,
27
28
  dscope
@@ -46,7 +47,7 @@ async function pushUnregister(params) {
46
47
  }
47
48
  const credentialsScope = {
48
49
  tenantId: scope.tenantId,
49
- organizationId: scope.organizationId,
50
+ organizationId: channel.organizationId ?? scope.tenantId,
50
51
  userId: channel.userId ?? null
51
52
  };
52
53
  let credentials = {};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/commands/push-unregister.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CommunicationChannel } from '../data/entities'\nimport { getChannelAdapterRegistry } from '../lib/adapter-registry-singleton'\nimport { refreshCredentialsIfNeeded } from '../lib/credential-refresh'\nimport { POLLING_ONLY_DEFAULT_INTERVAL_SECONDS } from '../lib/connect-channel'\nimport { emitCommunicationChannelsEvent } from '../events'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels').child({ component: 'push-unregister' })\n\n/**\n * Spec C \u00A7 Phase C5 \u2014 Tear down a previously-registered push delivery.\n *\n * Called from `disconnect-channel.ts` (per-user disconnect path) so the\n * provider-side `users.watch` subscription doesn't keep firing\n * notifications at a webhook that no longer recognises the channel.\n *\n * Idempotent + best-effort: a missing registration, a 404 from the provider,\n * or any adapter error is logged but never raised. The caller still proceeds\n * with the disconnect (the channel row is cleared regardless of whether the\n * provider-side teardown succeeded).\n *\n * Companion to `commands/push-register.ts` \u2014 same lib-style helper shape,\n * not a `registerCommand`-style command (push lifecycle has no undo).\n */\n\nexport const pushUnregisterSchema = z.object({\n channelId: z.string().uuid(),\n})\n\nexport interface PushUnregisterScope {\n tenantId: string\n organizationId: string\n userId?: string | null\n}\n\nexport interface PushUnregisterResult {\n channelId: string\n status: 'unregistered' | 'noop' | 'failed'\n error?: { code: string; message: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\nexport async function pushUnregister(params: {\n container: AwilixContainer\n scope: PushUnregisterScope\n input: { channelId: string }\n}): Promise<PushUnregisterResult> {\n const input = pushUnregisterSchema.parse(params.input)\n const { container, scope } = params\n\n const em = (container.resolve('em') as EntityManager).fork()\n const dscope = { tenantId: scope.tenantId, organizationId: scope.organizationId }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: input.channelId,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n },\n undefined,\n dscope,\n )\n if (!channel) {\n return { channelId: input.channelId, status: 'noop' }\n }\n\n const adapter = getChannelAdapterRegistry().get(channel.providerKey)\n if (!adapter || typeof adapter.unregisterPush !== 'function') {\n return { channelId: channel.id, status: 'noop' }\n }\n\n const channelState = (channel.channelState as Record<string, unknown> | null) ?? {}\n const pushStatus = typeof channelState.pushStatus === 'string' ? channelState.pushStatus : null\n if (!pushStatus || pushStatus === 'inactive') {\n return { channelId: channel.id, status: 'noop' }\n }\n\n let credentialsService: CredentialsServiceLike | null = null\n try {\n credentialsService = container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n credentialsService = null\n }\n const credentialsScope = {\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n userId: channel.userId ?? null,\n }\n let credentials: Record<string, unknown> = {}\n if (channel.credentialsRef && credentialsService) {\n try {\n credentials =\n (await credentialsService.resolve(`channel_${channel.providerKey}`, credentialsScope)) ?? {}\n } catch {\n credentials = {}\n }\n }\n try {\n const refreshed = await refreshCredentialsIfNeeded(\n { adapter, channelId: channel.id, credentials, scope: credentialsScope },\n { credentialsService },\n )\n credentials = refreshed.credentials\n } catch {\n // Refresh failure is non-fatal \u2014 unregister tolerates expired tokens\n // because the provider will simply return 401, which the adapter swallows\n // or we ignore below.\n }\n\n try {\n await adapter.unregisterPush({\n channelId: channel.id,\n credentials,\n scope: { tenantId: scope.tenantId, organizationId: scope.organizationId },\n channelState,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n logger.warn('adapter.unregisterPush failed for channel', { channelId: channel.id, reason: message })\n return {\n channelId: channel.id,\n status: 'failed',\n error: { code: 'adapter_unregister_failed', message: message.slice(0, 500) },\n }\n }\n\n // Clear push markers from channel state so a subsequent reconnect starts\n // fresh.\n channel.channelState = {\n ...channelState,\n pushStatus: 'inactive',\n watchExpirationMs: null,\n }\n // Restore the polling-only default cadence (matching connect) so the channel\n // keeps working until disconnect itself flips `isActive: false`.\n channel.pollIntervalSeconds = POLLING_ONLY_DEFAULT_INTERVAL_SECONDS\n await em.flush()\n\n await emitCommunicationChannelsEvent(\n 'communication_channels.push.deactivated',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n reason: 'unregistered',\n },\n { persistent: true },\n )\n\n return { channelId: channel.id, status: 'unregistered' }\n}\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAElB,SAAS,6BAA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ACrB,UAAU,MAAM;AAAA,MAChB,gBAAgB,MAAM;AAAA,MACtB,QAAQ;AAAA,IACV;AAAA,IACA,EAAE,YAAY,KAAK;AAAA,EACrB;AAEA,SAAO,EAAE,WAAW,QAAQ,IAAI,QAAQ,eAAe;AACzD;",
4
+ "sourcesContent": ["import { z } from 'zod'\nimport type { AwilixContainer } from 'awilix'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CommunicationChannel } from '../data/entities'\nimport { channelOrgScopeWhere } from '../lib/access-control'\nimport { getChannelAdapterRegistry } from '../lib/adapter-registry-singleton'\nimport { refreshCredentialsIfNeeded } from '../lib/credential-refresh'\nimport { POLLING_ONLY_DEFAULT_INTERVAL_SECONDS } from '../lib/connect-channel'\nimport { emitCommunicationChannelsEvent } from '../events'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels').child({ component: 'push-unregister' })\n\n/**\n * Spec C \u00A7 Phase C5 \u2014 Tear down a previously-registered push delivery.\n *\n * Called from `disconnect-channel.ts` (per-user disconnect path) so the\n * provider-side `users.watch` subscription doesn't keep firing\n * notifications at a webhook that no longer recognises the channel.\n *\n * Idempotent + best-effort: a missing registration, a 404 from the provider,\n * or any adapter error is logged but never raised. The caller still proceeds\n * with the disconnect (the channel row is cleared regardless of whether the\n * provider-side teardown succeeded).\n *\n * Companion to `commands/push-register.ts` \u2014 same lib-style helper shape,\n * not a `registerCommand`-style command (push lifecycle has no undo).\n */\n\nexport const pushUnregisterSchema = z.object({\n channelId: z.string().uuid(),\n})\n\nexport interface PushUnregisterScope {\n tenantId: string\n organizationId: string\n userId?: string | null\n}\n\nexport interface PushUnregisterResult {\n channelId: string\n status: 'unregistered' | 'noop' | 'failed'\n error?: { code: string; message: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\nexport async function pushUnregister(params: {\n container: AwilixContainer\n scope: PushUnregisterScope\n input: { channelId: string }\n}): Promise<PushUnregisterResult> {\n const input = pushUnregisterSchema.parse(params.input)\n const { container, scope } = params\n\n const em = (container.resolve('em') as EntityManager).fork()\n // The channel ROW and the credentials store use DIFFERENT orgs. A tenant-wide push channel is\n // stored with `organization_id = NULL` (its encrypted columns are keyed at org=null) even though\n // its credentials are pinned at `organization_id = tenantId`. `scope.organizationId` here is the\n // credentials/delivery org (tenantId for tenant-wide) \u2014 so it must NOT be used as an exact row\n // filter (it would never match a null-org row) nor as the row decryption org. Look the row up\n // null-aware and decrypt at the row's own org (null column \u21D2 null fallback); credential resolution\n // below keeps using the credentials org.\n const dscope = { tenantId: scope.tenantId, organizationId: null }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id: input.channelId,\n tenantId: scope.tenantId,\n ...channelOrgScopeWhere(scope.organizationId),\n },\n undefined,\n dscope,\n )\n if (!channel) {\n return { channelId: input.channelId, status: 'noop' }\n }\n\n const adapter = getChannelAdapterRegistry().get(channel.providerKey)\n if (!adapter || typeof adapter.unregisterPush !== 'function') {\n return { channelId: channel.id, status: 'noop' }\n }\n\n const channelState = (channel.channelState as Record<string, unknown> | null) ?? {}\n const pushStatus = typeof channelState.pushStatus === 'string' ? channelState.pushStatus : null\n if (!pushStatus || pushStatus === 'inactive') {\n return { channelId: channel.id, status: 'noop' }\n }\n\n let credentialsService: CredentialsServiceLike | null = null\n try {\n credentialsService = container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n credentialsService = null\n }\n // Resolve credentials at the channel's OWN org (tenant-wide channels store\n // their credentials at `organization_id = tenantId`; see push-register.ts /\n // connect-credential-channel.ts), never the caller's scope org.\n const credentialsScope = {\n tenantId: scope.tenantId,\n organizationId: channel.organizationId ?? scope.tenantId,\n userId: channel.userId ?? null,\n }\n let credentials: Record<string, unknown> = {}\n if (channel.credentialsRef && credentialsService) {\n try {\n credentials =\n (await credentialsService.resolve(`channel_${channel.providerKey}`, credentialsScope)) ?? {}\n } catch {\n credentials = {}\n }\n }\n try {\n const refreshed = await refreshCredentialsIfNeeded(\n { adapter, channelId: channel.id, credentials, scope: credentialsScope },\n { credentialsService },\n )\n credentials = refreshed.credentials\n } catch {\n // Refresh failure is non-fatal \u2014 unregister tolerates expired tokens\n // because the provider will simply return 401, which the adapter swallows\n // or we ignore below.\n }\n\n try {\n await adapter.unregisterPush({\n channelId: channel.id,\n credentials,\n scope: { tenantId: scope.tenantId, organizationId: scope.organizationId },\n channelState,\n })\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n logger.warn('adapter.unregisterPush failed for channel', { channelId: channel.id, reason: message })\n return {\n channelId: channel.id,\n status: 'failed',\n error: { code: 'adapter_unregister_failed', message: message.slice(0, 500) },\n }\n }\n\n // Clear push markers from channel state so a subsequent reconnect starts\n // fresh.\n channel.channelState = {\n ...channelState,\n pushStatus: 'inactive',\n watchExpirationMs: null,\n }\n // Restore the polling-only default cadence (matching connect) so the channel\n // keeps working until disconnect itself flips `isActive: false`.\n channel.pollIntervalSeconds = POLLING_ONLY_DEFAULT_INTERVAL_SECONDS\n await em.flush()\n\n await emitCommunicationChannelsEvent(\n 'communication_channels.push.deactivated',\n {\n channelId: channel.id,\n providerKey: channel.providerKey,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n reason: 'unregistered',\n },\n { persistent: true },\n )\n\n return { channelId: channel.id, status: 'unregistered' }\n}\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAElB,SAAS,6BAA6B;AAEtC,SAAS,4BAA4B;AACrC,SAAS,4BAA4B;AACrC,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAC3C,SAAS,6CAA6C;AACtD,SAAS,sCAAsC;AAC/C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa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E,WAAW,QAAQ,IAAI,QAAQ,eAAe;AACzD;",
6
6
  "names": []
7
7
  }
@@ -103,6 +103,10 @@ CommunicationChannel = __decorateClass([
103
103
  Index({
104
104
  name: "communication_channels_user_provider_external_uq",
105
105
  expression: `create unique index "communication_channels_user_provider_external_uq" on "communication_channels" ("tenant_id", "user_id", "provider_key", "external_identifier") where "deleted_at" is null and "user_id" is not null and "external_identifier" is not null`
106
+ }),
107
+ Index({
108
+ name: "communication_channels_tenant_push_provider_uq",
109
+ expression: `create unique index "communication_channels_tenant_push_provider_uq" on "communication_channels" ("tenant_id", "provider_key") where "channel_type" = 'push' and "user_id" is null and "deleted_at" is null`
106
110
  })
107
111
  ], CommunicationChannel);
108
112
  OptionalProps;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/data/entities.ts"],
4
- "sourcesContent": ["import { OptionalProps } from '@mikro-orm/core'\nimport { Check, Entity, Index, PrimaryKey, Property, Unique } from '@mikro-orm/decorators/legacy'\n\n/**\n * Hub entities for the Communication Channels module.\n *\n * Cross-module references (e.g. `MessageChannelLink.messageId \u2192 messages.message.id`)\n * use plain `uuid` columns, NOT MikroORM `@ManyToOne` decorators. Project rule:\n * \"No direct ORM relationships between modules \u2014 use foreign key IDs, fetch separately.\"\n * Cross-module links are declared in `data/extensions.ts` via `EntityExtension`.\n *\n * See SPEC-045d \u00A72.2.\n */\n\n// \u2500\u2500 CommunicationChannel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Per-channel lifecycle status. Set by the polling worker / outbound subscriber\n * + the `markChannelRequiresReauth` command. Existing `isActive` remains for the\n * coarse admin enable/disable toggle; `status` is the finer-grained operational\n * state used by per-user reconnect flows.\n *\n * Email integration spec \u00A7 Hub Deltas \u2192 Delta 2.\n */\nexport type CommunicationChannelStatus =\n | 'connected'\n | 'requires_reauth'\n | 'error'\n | 'disconnected'\n\n@Entity({ tableName: 'communication_channels' })\n@Index({ name: 'communication_channels_tenant_provider_idx', properties: ['tenantId', 'providerKey'] })\n// Provider-push webhooks (Gmail Pub/Sub) resolve channels by (provider_key,\n// external_identifier) WITHOUT a tenant_id \u2014 they only know the mailbox address.\n// Without this index that lookup is a full scan over every channel of the\n// provider, which a (signature-verified) push or replay repeats on every hit.\n@Index({\n name: 'communication_channels_provider_external_idx',\n expression:\n `create index \"communication_channels_provider_external_idx\" on \"communication_channels\" (\"provider_key\", \"external_identifier\") where \"deleted_at\" is null`,\n})\n@Index({ name: 'communication_channels_tenant_type_active_idx', properties: ['tenantId', 'channelType', 'isActive'] })\n@Index({\n name: 'communication_channels_user_lookup_idx',\n properties: ['userId', 'channelType', 'deletedAt'],\n})\n@Index({\n name: 'communication_channels_poll_due_idx',\n expression:\n `create index \"communication_channels_poll_due_idx\" on \"communication_channels\" (\"is_active\", \"last_polled_at\") where \"deleted_at\" is null`,\n})\n@Index({\n name: 'communication_channels_one_primary_per_user_uq',\n expression:\n `create unique index \"communication_channels_one_primary_per_user_uq\" on \"communication_channels\" (\"user_id\") where \"is_primary\" and \"user_id\" is not null and \"deleted_at\" is null`,\n})\n// One channel per (tenant, user, provider, mailbox): a reconnect heals the\n// existing row in place (see `createConnectedChannelRow`) instead of inserting a\n// duplicate that would stay polled + keep its own push subscription. Partial so\n// tenant-wide channels (null user_id) and identifier-less rows are exempt.\n@Index({\n name: 'communication_channels_user_provider_external_uq',\n expression:\n `create unique index \"communication_channels_user_provider_external_uq\" on \"communication_channels\" (\"tenant_id\", \"user_id\", \"provider_key\", \"external_identifier\") where \"deleted_at\" is null and \"user_id\" is not null and \"external_identifier\" is not null`,\n})\nexport class CommunicationChannel {\n [OptionalProps]?:\n | 'createdAt'\n | 'updatedAt'\n | 'isActive'\n | 'capabilities'\n | 'deletedAt'\n | 'externalIdentifier'\n | 'credentialsRef'\n | 'organizationId'\n | 'userId'\n | 'isPrimary'\n | 'pollIntervalSeconds'\n | 'lastPolledAt'\n | 'status'\n | 'lastError'\n | 'channelState'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n @Property({ name: 'channel_type', type: 'text' })\n channelType!: string\n\n @Property({ name: 'display_name', type: 'text' })\n displayName!: string\n\n @Property({ name: 'external_identifier', type: 'text', nullable: true })\n externalIdentifier?: string | null\n\n @Property({ name: 'credentials_ref', type: 'uuid', nullable: true })\n credentialsRef?: string | null\n\n @Property({ name: 'capabilities', type: 'json', nullable: true })\n capabilities?: Record<string, unknown> | null\n\n @Property({ name: 'is_active', type: 'boolean', default: true })\n isActive: boolean = true\n\n /**\n * Per-user channel owner. NULL = tenant-scoped (existing behaviour, e.g. WhatsApp Business).\n * Set = user-scoped (e.g. Jane's personal Gmail). Visible only to the owning user\n * and to admins with `communication_channels.admin`. Linked to `auth:user` via\n * `EntityExtension` in `data/extensions.ts` \u2014 never a raw DB FK.\n */\n @Property({ name: 'user_id', type: 'uuid', nullable: true })\n userId?: string | null\n\n /**\n * Per-user \"primary\" flag. Only meaningful when `userId IS NOT NULL`; ignored\n * for tenant-scoped channels. Enforced as one-primary-per-user by the partial\n * unique index `communication_channels_one_primary_per_user_uq`.\n */\n @Property({ name: 'is_primary', type: 'boolean', default: false })\n isPrimary: boolean = false\n\n /**\n * Polling cadence in seconds. NULL means \"this channel does not poll\" \u2014 i.e. it\n * is push-only (webhook) or its provider opted out via\n * `ChannelCapabilities.realtimePush !== false`. Set means hub-managed polling\n * at that interval via the `poll-tick` scheduler entry.\n */\n @Property({ name: 'poll_interval_seconds', type: 'int', nullable: true })\n pollIntervalSeconds?: number | null\n\n /** Last successful poll timestamp; the scheduler enumerates by this column. */\n @Property({ name: 'last_polled_at', type: Date, nullable: true })\n lastPolledAt?: Date | null\n\n /**\n * Per-channel lifecycle status. See {@link CommunicationChannelStatus}.\n * Migration sets `status = 'connected'` for all existing active channels (default value).\n */\n @Property({ name: 'status', type: 'text', default: 'connected' })\n status: CommunicationChannelStatus = 'connected'\n\n /** Most recent classified error message for diagnostics. */\n @Property({ name: 'last_error', type: 'text', nullable: true })\n lastError?: string | null\n\n /**\n * Provider-specific resumption state, opaque to the hub. Polling adapters\n * encode their incremental cursor here (Gmail historyId, IMAP\n * UIDVALIDITY+UIDNEXT). The polling worker reads it before each\n * `fetchHistory` call and writes the adapter's returned `nextCursor` back\n * after a successful poll. Empty / NULL means \"bootstrap on next poll\".\n */\n @Property({ name: 'channel_state', type: 'json', nullable: true })\n channelState?: Record<string, unknown> | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n// \u2500\u2500 ExternalConversation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'external_conversations' })\n@Index({ name: 'external_conversations_channel_idx', properties: ['channelId', 'externalConversationId'] })\n@Index({ name: 'external_conversations_contact_person_idx', properties: ['contactPersonId'] })\n@Index({ name: 'external_conversations_assigned_user_idx', properties: ['assignedUserId'] })\n@Unique({ name: 'external_conversations_channel_external_uq', properties: ['channelId', 'externalConversationId'] })\nexport class ExternalConversation {\n [OptionalProps]?: 'createdAt' | 'updatedAt' | 'lastMessageAt' | 'subject' | 'contactPersonId' | 'assignedUserId' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'external_conversation_id', type: 'text' })\n externalConversationId!: string\n\n @Property({ name: 'subject', type: 'text', nullable: true })\n subject?: string | null\n\n @Property({ name: 'contact_person_id', type: 'uuid', nullable: true })\n contactPersonId?: string | null\n\n @Property({ name: 'assigned_user_id', type: 'uuid', nullable: true })\n assignedUserId?: string | null\n\n @Property({ name: 'last_message_at', type: Date, nullable: true })\n lastMessageAt?: Date | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n}\n\n// \u2500\u2500 ExternalMessage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'external_messages' })\n@Index({ name: 'external_messages_conversation_idx', properties: ['conversationId'] })\n@Index({ name: 'external_messages_channel_external_idx', properties: ['channelId', 'externalMessageId'] })\n@Unique({ name: 'external_messages_channel_external_uq', properties: ['channelId', 'externalMessageId'] })\nexport class ExternalMessage {\n [OptionalProps]?: 'createdAt' | 'senderIdentifier' | 'senderDisplayName' | 'providerTimestamp' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'conversation_id', type: 'uuid' })\n conversationId!: string\n\n @Property({ name: 'external_message_id', type: 'text' })\n externalMessageId!: string\n\n @Property({ name: 'direction', type: 'text' })\n direction!: 'inbound' | 'outbound'\n\n @Property({ name: 'sender_identifier', type: 'text', nullable: true })\n senderIdentifier?: string | null\n\n @Property({ name: 'sender_display_name', type: 'text', nullable: true })\n senderDisplayName?: string | null\n\n @Property({ name: 'provider_timestamp', type: Date, nullable: true })\n providerTimestamp?: Date | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n\n// \u2500\u2500 MessageChannelLink \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'message_channel_links' })\n@Index({ name: 'message_channel_links_message_idx', properties: ['messageId'] })\n@Index({ name: 'message_channel_links_ext_conv_idx', properties: ['externalConversationId'] })\n@Index({ name: 'message_channel_links_ext_msg_idx', properties: ['externalMessageId'] })\n@Unique({ name: 'message_channel_links_message_uq', properties: ['messageId'] })\nexport class MessageChannelLink {\n [OptionalProps]?: 'createdAt' | 'deliveryStatus' | 'externalMessageId' | 'channelPayload' | 'channelContentType' | 'interactiveState' | 'channelMetadata' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n /** Logical link to messages.message.id (no DB FK \u2014 cross-module via EntityExtension). */\n @Property({ name: 'message_id', type: 'uuid' })\n messageId!: string\n\n /** FK to external_conversations.id (intra-module \u2014 DB FK acceptable but kept as plain uuid for symmetry). */\n @Property({ name: 'external_conversation_id', type: 'uuid' })\n externalConversationId!: string\n\n @Property({ name: 'external_message_id', type: 'uuid', nullable: true })\n externalMessageId?: string | null\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n @Property({ name: 'channel_type', type: 'text' })\n channelType!: string\n\n @Property({ name: 'direction', type: 'text' })\n direction!: 'inbound' | 'outbound'\n\n @Property({ name: 'delivery_status', type: 'text' })\n deliveryStatus: string = 'pending'\n\n @Property({ name: 'channel_payload', type: 'json', nullable: true })\n channelPayload?: Record<string, unknown> | null\n\n @Property({ name: 'channel_content_type', type: 'text', nullable: true })\n channelContentType?: string | null\n\n @Property({ name: 'interactive_state', type: 'json', nullable: true })\n interactiveState?: Record<string, unknown> | null\n\n @Property({ name: 'channel_metadata', type: 'json', nullable: true })\n channelMetadata?: Record<string, unknown> | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n\n// \u2500\u2500 ChannelThreadMapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'channel_thread_mappings' })\n@Index({ name: 'channel_thread_mappings_ext_conv_idx', properties: ['externalConversationId', 'tenantId'] })\n@Index({ name: 'channel_thread_mappings_thread_idx', properties: ['messageThreadId', 'tenantId'] })\n@Unique({ name: 'channel_thread_mappings_ext_conv_uq', properties: ['externalConversationId', 'tenantId'] })\nexport class ChannelThreadMapping {\n [OptionalProps]?: 'createdAt' | 'updatedAt' | 'assignedUserId' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'external_conversation_id', type: 'uuid' })\n externalConversationId!: string\n\n /** Logical link to messages.message.thread_id (no DB FK \u2014 cross-module). */\n @Property({ name: 'message_thread_id', type: 'uuid' })\n messageThreadId!: string\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n @Property({ name: 'external_thread_ref', type: 'text' })\n externalThreadRef!: string\n\n /** Logical link to auth.user.id (no DB FK \u2014 cross-module). */\n @Property({ name: 'assigned_user_id', type: 'uuid', nullable: true })\n assignedUserId?: string | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n}\n\n// \u2500\u2500 MessageReaction \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'message_reactions' })\n@Index({ name: 'message_reactions_message_idx', properties: ['messageId'] })\n@Index({ name: 'message_reactions_message_emoji_idx', properties: ['messageId', 'emoji'] })\n@Index({\n name: 'message_reactions_internal_actor_uq',\n expression:\n `create unique index \"message_reactions_internal_actor_uq\" on \"message_reactions\" (\"tenant_id\", \"message_id\", \"emoji\", \"reacted_by_user_id\") where \"reacted_by_user_id\" is not null`,\n})\n@Index({\n name: 'message_reactions_external_actor_uq',\n expression:\n `create unique index \"message_reactions_external_actor_uq\" on \"message_reactions\" (\"tenant_id\", \"message_id\", \"emoji\", \"reacted_by_external_id\") where \"reacted_by_external_id\" is not null`,\n})\n@Check({\n name: 'message_reactions_exactly_one_actor_chk',\n expression: `(\"reacted_by_user_id\" is null) <> (\"reacted_by_external_id\" is null)`,\n})\nexport class MessageReaction {\n [OptionalProps]?: 'createdAt' | 'reactedByUserId' | 'reactedByExternalId' | 'reactedByDisplayName' | 'providerKey' | 'externalReactionId' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n /** Logical link to messages.message.id (no DB FK \u2014 cross-module). */\n @Property({ name: 'message_id', type: 'uuid' })\n messageId!: string\n\n @Property({ name: 'emoji', type: 'text' })\n emoji!: string\n\n /** Logical link to auth.user.id (no DB FK \u2014 cross-module). NULL for external reactions. */\n @Property({ name: 'reacted_by_user_id', type: 'uuid', nullable: true })\n reactedByUserId?: string | null\n\n @Property({ name: 'reacted_by_external_id', type: 'text', nullable: true })\n reactedByExternalId?: string | null\n\n @Property({ name: 'reacted_by_display_name', type: 'text', nullable: true })\n reactedByDisplayName?: string | null\n\n @Property({ name: 'provider_key', type: 'text', nullable: true })\n providerKey?: string | null\n\n @Property({ name: 'external_reaction_id', type: 'text', nullable: true })\n externalReactionId?: string | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n\n// \u2500\u2500 ChannelThreadToken \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Per-thread HMAC-signed opaque token used by the layered thread-matcher to\n * reliably attach inbound replies to the originating Open Mercato message\n * thread, even when the recipient's mail client strips RFC 5322 headers.\n *\n * Created lazily on the first outbound message in a thread by the\n * `outbound-bridge` subscriber. The token is injected into:\n * 1. The MIME `References:` header as `<om_TOKEN@open-mercato.invalid>` \u2014\n * invisible to the recipient and survives most reply clients.\n * 2. A hidden HTML body span `<span style=\"display:none\">[OM:om_TOKEN]</span>` \u2014\n * survives when References is stripped (e.g. some mobile clients).\n * 3. A plain-text trailer `[OM:om_TOKEN]` \u2014 survives plain-text-only replies.\n *\n * The unique constraint is `(tenantId, token)` \u2014 tenant isolation by\n * construction. HMAC verification (via `lib/thread-token.ts`) defends against\n * forged inbound messages: tokens that don't HMAC-verify never reach the DB\n * lookup.\n *\n * See `.ai/specs/implemented/2026-05-27-email-integration-inbound-reliability-and-threading.md`.\n */\n@Entity({ tableName: 'channel_thread_tokens' })\n// One token row per (tenant, thread): the matcher resolves every reply to the\n// same thread regardless of which outbound send minted the token. The unique\n// constraint also makes `getOrCreateThreadToken` race-safe (insert-on-conflict).\n@Unique({ name: 'channel_thread_tokens_thread_uq', properties: ['tenantId', 'messageThreadId'] })\n@Unique({ name: 'channel_thread_tokens_token_uq', properties: ['tenantId', 'token'] })\nexport class ChannelThreadToken {\n [OptionalProps]?: 'createdAt' | 'lastSeenAt' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n /** Logical link to messages.message.thread_id (no DB FK \u2014 cross-module). */\n @Property({ name: 'message_thread_id', type: 'uuid' })\n messageThreadId!: string\n\n /**\n * HMAC-signed opaque token, format: `om_<22b64url>_<11b64url>` (16 random\n * bytes + 8 HMAC bytes, each base64url-encoded without padding), ~37 chars.\n */\n @Property({ name: 'token', type: 'text' })\n token!: string\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n /**\n * Updated whenever a thread-matcher token-based strategy resolves to this\n * row. Used for future GC: tokens with `last_seen_at < now() - 90 days`\n * are pruning candidates.\n */\n @Property({ name: 'last_seen_at', type: Date, nullable: true })\n lastSeenAt?: Date | null\n}\n\n// \u2500\u2500 ChannelIngestDeadLetter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Inbound messages that fail permanently during ingest land here so an\n * operator can replay them after fixing parsers / schemas. Transient\n * failures (DB blip, network timeout) DO NOT write here \u2014 those abort the\n * poll loop without advancing the cursor so the message is re-fetched on\n * the next tick.\n *\n * `raw_body` is encrypted at rest via the module's `encryption.ts`\n * `defaultEncryptionMaps` entry (MIME bodies may contain PII).\n *\n * See `.ai/specs/implemented/2026-05-27-email-integration-inbound-reliability-and-threading.md`\n * (\u00A7 3 Data Model).\n */\n@Entity({ tableName: 'channel_ingest_dead_letters' })\n@Index({ name: 'channel_ingest_dead_letters_channel_idx', properties: ['channelId', 'tenantId'] })\n@Index({ name: 'channel_ingest_dead_letters_created_idx', properties: ['tenantId', 'createdAt'] })\nexport class ChannelIngestDeadLetter {\n [OptionalProps]?:\n | 'createdAt'\n | 'organizationId'\n | 'externalMessageId'\n | 'externalUid'\n | 'rawBody'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n /** External UID / sequence-number for the provider (e.g. IMAP UID, Gmail messageId). */\n @Property({ name: 'external_uid', type: 'text', nullable: true })\n externalUid?: string | null\n\n @Property({ name: 'external_message_id', type: 'text', nullable: true })\n externalMessageId?: string | null\n\n @Property({ name: 'error_class', type: 'text' })\n errorClass!: string\n\n @Property({ name: 'error_message', type: 'text' })\n errorMessage!: string\n\n /** Truncated source \u2014 first N bytes of the raw MIME / payload (encrypted at rest). */\n @Property({ name: 'raw_body', type: 'text', nullable: true })\n rawBody?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n"],
5
- "mappings": ";;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,OAAO,QAAQ,OAAO,YAAY,UAAU,cAAc;AAiEhE;AADI,IAAM,uBAAN,MAA2B;AAAA,EAA3B;AAwCL,oBAAoB;AAiBpB,qBAAqB;AAoBrB,kBAAqC;AAuBrC,qBAAkB,oBAAI,KAAK;AAG3B,qBAAkB,oBAAI,KAAK;AAAA;AAI7B;AAxFE;AAAA,EADC,WAAW,EAAE,MAAM,QAAQ,YAAY,oBAAoB,CAAC;AAAA,GAlBlD,qBAmBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,OAAO,CAAC;AAAA,GArBrC,qBAsBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,OAAO,CAAC;AAAA,GAxBrC,qBAyBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,OAAO,CAAC;AAAA,GA3BrC,qBA4BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,uBAAuB,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GA9B5D,qBA+BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,mBAAmB,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GAjCxD,qBAkCX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GApCrD,qBAqCX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,aAAa,MAAM,WAAW,SAAS,KAAK,CAAC;AAAA,GAvCpD,qBAwCX;AASA;AAAA,EADC,SAA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,GA9BpC,wBA+BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,iBAAiB,MAAM,OAAO,CAAC;AAAA,GAjCtC,wBAkCX;AAIA;AAAA,EADC,SAAS,EAAE,MAAM,YAAY,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GArCjD,wBAsCX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,MAAM,oBAAI,KAAK,EAAE,CAAC;AAAA,GAxC7D,wBAyCX;AAzCW,0BAAN;AAAA,EAHN,OAAO,EAAE,WAAW,8BAA8B,CAAC;AAAA,EACnD,MAAM,EAAE,MAAM,2CAA2C,YAAY,CAAC,aAAa,UAAU,EAAE,CAAC;AAAA,EAChG,MAAM,EAAE,MAAM,2CAA2C,YAAY,CAAC,YAAY,WAAW,EAAE,CAAC;AAAA,GACpF;",
4
+ "sourcesContent": ["import { OptionalProps } from '@mikro-orm/core'\nimport { Check, Entity, Index, PrimaryKey, Property, Unique } from '@mikro-orm/decorators/legacy'\n\n/**\n * Hub entities for the Communication Channels module.\n *\n * Cross-module references (e.g. `MessageChannelLink.messageId \u2192 messages.message.id`)\n * use plain `uuid` columns, NOT MikroORM `@ManyToOne` decorators. Project rule:\n * \"No direct ORM relationships between modules \u2014 use foreign key IDs, fetch separately.\"\n * Cross-module links are declared in `data/extensions.ts` via `EntityExtension`.\n *\n * See SPEC-045d \u00A72.2.\n */\n\n// \u2500\u2500 CommunicationChannel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Per-channel lifecycle status. Set by the polling worker / outbound subscriber\n * + the `markChannelRequiresReauth` command. Existing `isActive` remains for the\n * coarse admin enable/disable toggle; `status` is the finer-grained operational\n * state used by per-user reconnect flows.\n *\n * Email integration spec \u00A7 Hub Deltas \u2192 Delta 2.\n */\nexport type CommunicationChannelStatus =\n | 'connected'\n | 'requires_reauth'\n | 'error'\n | 'disconnected'\n\n@Entity({ tableName: 'communication_channels' })\n@Index({ name: 'communication_channels_tenant_provider_idx', properties: ['tenantId', 'providerKey'] })\n// Provider-push webhooks (Gmail Pub/Sub) resolve channels by (provider_key,\n// external_identifier) WITHOUT a tenant_id \u2014 they only know the mailbox address.\n// Without this index that lookup is a full scan over every channel of the\n// provider, which a (signature-verified) push or replay repeats on every hit.\n@Index({\n name: 'communication_channels_provider_external_idx',\n expression:\n `create index \"communication_channels_provider_external_idx\" on \"communication_channels\" (\"provider_key\", \"external_identifier\") where \"deleted_at\" is null`,\n})\n@Index({ name: 'communication_channels_tenant_type_active_idx', properties: ['tenantId', 'channelType', 'isActive'] })\n@Index({\n name: 'communication_channels_user_lookup_idx',\n properties: ['userId', 'channelType', 'deletedAt'],\n})\n@Index({\n name: 'communication_channels_poll_due_idx',\n expression:\n `create index \"communication_channels_poll_due_idx\" on \"communication_channels\" (\"is_active\", \"last_polled_at\") where \"deleted_at\" is null`,\n})\n@Index({\n name: 'communication_channels_one_primary_per_user_uq',\n expression:\n `create unique index \"communication_channels_one_primary_per_user_uq\" on \"communication_channels\" (\"user_id\") where \"is_primary\" and \"user_id\" is not null and \"deleted_at\" is null`,\n})\n// One channel per (tenant, user, provider, mailbox): a reconnect heals the\n// existing row in place (see `createConnectedChannelRow`) instead of inserting a\n// duplicate that would stay polled + keep its own push subscription. Partial so\n// tenant-wide channels (null user_id) and identifier-less rows are exempt.\n@Index({\n name: 'communication_channels_user_provider_external_uq',\n expression:\n `create unique index \"communication_channels_user_provider_external_uq\" on \"communication_channels\" (\"tenant_id\", \"user_id\", \"provider_key\", \"external_identifier\") where \"deleted_at\" is null and \"user_id\" is not null and \"external_identifier\" is not null`,\n})\n// One tenant-wide push channel per (tenant, provider): push providers (FCM/APNs/\n// Expo) have no `external_identifier` and `user_id IS NULL`, so the mailbox\n// unique index above does not cover them. This keeps an admin reconnect healing\n// the single shared row (see `createConnectedChannelRow`) instead of inserting\n// duplicates the fan-out would silently ignore.\n@Index({\n name: 'communication_channels_tenant_push_provider_uq',\n expression:\n `create unique index \"communication_channels_tenant_push_provider_uq\" on \"communication_channels\" (\"tenant_id\", \"provider_key\") where \"channel_type\" = 'push' and \"user_id\" is null and \"deleted_at\" is null`,\n})\nexport class CommunicationChannel {\n [OptionalProps]?:\n | 'createdAt'\n | 'updatedAt'\n | 'isActive'\n | 'capabilities'\n | 'deletedAt'\n | 'externalIdentifier'\n | 'credentialsRef'\n | 'organizationId'\n | 'userId'\n | 'isPrimary'\n | 'pollIntervalSeconds'\n | 'lastPolledAt'\n | 'status'\n | 'lastError'\n | 'channelState'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n @Property({ name: 'channel_type', type: 'text' })\n channelType!: string\n\n @Property({ name: 'display_name', type: 'text' })\n displayName!: string\n\n @Property({ name: 'external_identifier', type: 'text', nullable: true })\n externalIdentifier?: string | null\n\n @Property({ name: 'credentials_ref', type: 'uuid', nullable: true })\n credentialsRef?: string | null\n\n @Property({ name: 'capabilities', type: 'json', nullable: true })\n capabilities?: Record<string, unknown> | null\n\n @Property({ name: 'is_active', type: 'boolean', default: true })\n isActive: boolean = true\n\n /**\n * Per-user channel owner. NULL = tenant-scoped (existing behaviour, e.g. WhatsApp Business).\n * Set = user-scoped (e.g. Jane's personal Gmail). Visible only to the owning user\n * and to admins with `communication_channels.admin`. Linked to `auth:user` via\n * `EntityExtension` in `data/extensions.ts` \u2014 never a raw DB FK.\n */\n @Property({ name: 'user_id', type: 'uuid', nullable: true })\n userId?: string | null\n\n /**\n * Per-user \"primary\" flag. Only meaningful when `userId IS NOT NULL`; ignored\n * for tenant-scoped channels. Enforced as one-primary-per-user by the partial\n * unique index `communication_channels_one_primary_per_user_uq`.\n */\n @Property({ name: 'is_primary', type: 'boolean', default: false })\n isPrimary: boolean = false\n\n /**\n * Polling cadence in seconds. NULL means \"this channel does not poll\" \u2014 i.e. it\n * is push-only (webhook) or its provider opted out via\n * `ChannelCapabilities.realtimePush !== false`. Set means hub-managed polling\n * at that interval via the `poll-tick` scheduler entry.\n */\n @Property({ name: 'poll_interval_seconds', type: 'int', nullable: true })\n pollIntervalSeconds?: number | null\n\n /** Last successful poll timestamp; the scheduler enumerates by this column. */\n @Property({ name: 'last_polled_at', type: Date, nullable: true })\n lastPolledAt?: Date | null\n\n /**\n * Per-channel lifecycle status. See {@link CommunicationChannelStatus}.\n * Migration sets `status = 'connected'` for all existing active channels (default value).\n */\n @Property({ name: 'status', type: 'text', default: 'connected' })\n status: CommunicationChannelStatus = 'connected'\n\n /** Most recent classified error message for diagnostics. */\n @Property({ name: 'last_error', type: 'text', nullable: true })\n lastError?: string | null\n\n /**\n * Provider-specific resumption state, opaque to the hub. Polling adapters\n * encode their incremental cursor here (Gmail historyId, IMAP\n * UIDVALIDITY+UIDNEXT). The polling worker reads it before each\n * `fetchHistory` call and writes the adapter's returned `nextCursor` back\n * after a successful poll. Empty / NULL means \"bootstrap on next poll\".\n */\n @Property({ name: 'channel_state', type: 'json', nullable: true })\n channelState?: Record<string, unknown> | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n\n @Property({ name: 'deleted_at', type: Date, nullable: true })\n deletedAt?: Date | null\n}\n\n// \u2500\u2500 ExternalConversation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'external_conversations' })\n@Index({ name: 'external_conversations_channel_idx', properties: ['channelId', 'externalConversationId'] })\n@Index({ name: 'external_conversations_contact_person_idx', properties: ['contactPersonId'] })\n@Index({ name: 'external_conversations_assigned_user_idx', properties: ['assignedUserId'] })\n@Unique({ name: 'external_conversations_channel_external_uq', properties: ['channelId', 'externalConversationId'] })\nexport class ExternalConversation {\n [OptionalProps]?: 'createdAt' | 'updatedAt' | 'lastMessageAt' | 'subject' | 'contactPersonId' | 'assignedUserId' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'external_conversation_id', type: 'text' })\n externalConversationId!: string\n\n @Property({ name: 'subject', type: 'text', nullable: true })\n subject?: string | null\n\n @Property({ name: 'contact_person_id', type: 'uuid', nullable: true })\n contactPersonId?: string | null\n\n @Property({ name: 'assigned_user_id', type: 'uuid', nullable: true })\n assignedUserId?: string | null\n\n @Property({ name: 'last_message_at', type: Date, nullable: true })\n lastMessageAt?: Date | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n}\n\n// \u2500\u2500 ExternalMessage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'external_messages' })\n@Index({ name: 'external_messages_conversation_idx', properties: ['conversationId'] })\n@Index({ name: 'external_messages_channel_external_idx', properties: ['channelId', 'externalMessageId'] })\n@Unique({ name: 'external_messages_channel_external_uq', properties: ['channelId', 'externalMessageId'] })\nexport class ExternalMessage {\n [OptionalProps]?: 'createdAt' | 'senderIdentifier' | 'senderDisplayName' | 'providerTimestamp' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'conversation_id', type: 'uuid' })\n conversationId!: string\n\n @Property({ name: 'external_message_id', type: 'text' })\n externalMessageId!: string\n\n @Property({ name: 'direction', type: 'text' })\n direction!: 'inbound' | 'outbound'\n\n @Property({ name: 'sender_identifier', type: 'text', nullable: true })\n senderIdentifier?: string | null\n\n @Property({ name: 'sender_display_name', type: 'text', nullable: true })\n senderDisplayName?: string | null\n\n @Property({ name: 'provider_timestamp', type: Date, nullable: true })\n providerTimestamp?: Date | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n\n// \u2500\u2500 MessageChannelLink \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'message_channel_links' })\n@Index({ name: 'message_channel_links_message_idx', properties: ['messageId'] })\n@Index({ name: 'message_channel_links_ext_conv_idx', properties: ['externalConversationId'] })\n@Index({ name: 'message_channel_links_ext_msg_idx', properties: ['externalMessageId'] })\n@Unique({ name: 'message_channel_links_message_uq', properties: ['messageId'] })\nexport class MessageChannelLink {\n [OptionalProps]?: 'createdAt' | 'deliveryStatus' | 'externalMessageId' | 'channelPayload' | 'channelContentType' | 'interactiveState' | 'channelMetadata' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n /** Logical link to messages.message.id (no DB FK \u2014 cross-module via EntityExtension). */\n @Property({ name: 'message_id', type: 'uuid' })\n messageId!: string\n\n /** FK to external_conversations.id (intra-module \u2014 DB FK acceptable but kept as plain uuid for symmetry). */\n @Property({ name: 'external_conversation_id', type: 'uuid' })\n externalConversationId!: string\n\n @Property({ name: 'external_message_id', type: 'uuid', nullable: true })\n externalMessageId?: string | null\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n @Property({ name: 'channel_type', type: 'text' })\n channelType!: string\n\n @Property({ name: 'direction', type: 'text' })\n direction!: 'inbound' | 'outbound'\n\n @Property({ name: 'delivery_status', type: 'text' })\n deliveryStatus: string = 'pending'\n\n @Property({ name: 'channel_payload', type: 'json', nullable: true })\n channelPayload?: Record<string, unknown> | null\n\n @Property({ name: 'channel_content_type', type: 'text', nullable: true })\n channelContentType?: string | null\n\n @Property({ name: 'interactive_state', type: 'json', nullable: true })\n interactiveState?: Record<string, unknown> | null\n\n @Property({ name: 'channel_metadata', type: 'json', nullable: true })\n channelMetadata?: Record<string, unknown> | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n\n// \u2500\u2500 ChannelThreadMapping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'channel_thread_mappings' })\n@Index({ name: 'channel_thread_mappings_ext_conv_idx', properties: ['externalConversationId', 'tenantId'] })\n@Index({ name: 'channel_thread_mappings_thread_idx', properties: ['messageThreadId', 'tenantId'] })\n@Unique({ name: 'channel_thread_mappings_ext_conv_uq', properties: ['externalConversationId', 'tenantId'] })\nexport class ChannelThreadMapping {\n [OptionalProps]?: 'createdAt' | 'updatedAt' | 'assignedUserId' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'external_conversation_id', type: 'uuid' })\n externalConversationId!: string\n\n /** Logical link to messages.message.thread_id (no DB FK \u2014 cross-module). */\n @Property({ name: 'message_thread_id', type: 'uuid' })\n messageThreadId!: string\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n @Property({ name: 'external_thread_ref', type: 'text' })\n externalThreadRef!: string\n\n /** Logical link to auth.user.id (no DB FK \u2014 cross-module). */\n @Property({ name: 'assigned_user_id', type: 'uuid', nullable: true })\n assignedUserId?: string | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n @Property({ name: 'updated_at', type: Date, onUpdate: () => new Date() })\n updatedAt: Date = new Date()\n}\n\n// \u2500\u2500 MessageReaction \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n@Entity({ tableName: 'message_reactions' })\n@Index({ name: 'message_reactions_message_idx', properties: ['messageId'] })\n@Index({ name: 'message_reactions_message_emoji_idx', properties: ['messageId', 'emoji'] })\n@Index({\n name: 'message_reactions_internal_actor_uq',\n expression:\n `create unique index \"message_reactions_internal_actor_uq\" on \"message_reactions\" (\"tenant_id\", \"message_id\", \"emoji\", \"reacted_by_user_id\") where \"reacted_by_user_id\" is not null`,\n})\n@Index({\n name: 'message_reactions_external_actor_uq',\n expression:\n `create unique index \"message_reactions_external_actor_uq\" on \"message_reactions\" (\"tenant_id\", \"message_id\", \"emoji\", \"reacted_by_external_id\") where \"reacted_by_external_id\" is not null`,\n})\n@Check({\n name: 'message_reactions_exactly_one_actor_chk',\n expression: `(\"reacted_by_user_id\" is null) <> (\"reacted_by_external_id\" is null)`,\n})\nexport class MessageReaction {\n [OptionalProps]?: 'createdAt' | 'reactedByUserId' | 'reactedByExternalId' | 'reactedByDisplayName' | 'providerKey' | 'externalReactionId' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n /** Logical link to messages.message.id (no DB FK \u2014 cross-module). */\n @Property({ name: 'message_id', type: 'uuid' })\n messageId!: string\n\n @Property({ name: 'emoji', type: 'text' })\n emoji!: string\n\n /** Logical link to auth.user.id (no DB FK \u2014 cross-module). NULL for external reactions. */\n @Property({ name: 'reacted_by_user_id', type: 'uuid', nullable: true })\n reactedByUserId?: string | null\n\n @Property({ name: 'reacted_by_external_id', type: 'text', nullable: true })\n reactedByExternalId?: string | null\n\n @Property({ name: 'reacted_by_display_name', type: 'text', nullable: true })\n reactedByDisplayName?: string | null\n\n @Property({ name: 'provider_key', type: 'text', nullable: true })\n providerKey?: string | null\n\n @Property({ name: 'external_reaction_id', type: 'text', nullable: true })\n externalReactionId?: string | null\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n\n// \u2500\u2500 ChannelThreadToken \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Per-thread HMAC-signed opaque token used by the layered thread-matcher to\n * reliably attach inbound replies to the originating Open Mercato message\n * thread, even when the recipient's mail client strips RFC 5322 headers.\n *\n * Created lazily on the first outbound message in a thread by the\n * `outbound-bridge` subscriber. The token is injected into:\n * 1. The MIME `References:` header as `<om_TOKEN@open-mercato.invalid>` \u2014\n * invisible to the recipient and survives most reply clients.\n * 2. A hidden HTML body span `<span style=\"display:none\">[OM:om_TOKEN]</span>` \u2014\n * survives when References is stripped (e.g. some mobile clients).\n * 3. A plain-text trailer `[OM:om_TOKEN]` \u2014 survives plain-text-only replies.\n *\n * The unique constraint is `(tenantId, token)` \u2014 tenant isolation by\n * construction. HMAC verification (via `lib/thread-token.ts`) defends against\n * forged inbound messages: tokens that don't HMAC-verify never reach the DB\n * lookup.\n *\n * See `.ai/specs/implemented/2026-05-27-email-integration-inbound-reliability-and-threading.md`.\n */\n@Entity({ tableName: 'channel_thread_tokens' })\n// One token row per (tenant, thread): the matcher resolves every reply to the\n// same thread regardless of which outbound send minted the token. The unique\n// constraint also makes `getOrCreateThreadToken` race-safe (insert-on-conflict).\n@Unique({ name: 'channel_thread_tokens_thread_uq', properties: ['tenantId', 'messageThreadId'] })\n@Unique({ name: 'channel_thread_tokens_token_uq', properties: ['tenantId', 'token'] })\nexport class ChannelThreadToken {\n [OptionalProps]?: 'createdAt' | 'lastSeenAt' | 'organizationId'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n /** Logical link to messages.message.thread_id (no DB FK \u2014 cross-module). */\n @Property({ name: 'message_thread_id', type: 'uuid' })\n messageThreadId!: string\n\n /**\n * HMAC-signed opaque token, format: `om_<22b64url>_<11b64url>` (16 random\n * bytes + 8 HMAC bytes, each base64url-encoded without padding), ~37 chars.\n */\n @Property({ name: 'token', type: 'text' })\n token!: string\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n\n /**\n * Updated whenever a thread-matcher token-based strategy resolves to this\n * row. Used for future GC: tokens with `last_seen_at < now() - 90 days`\n * are pruning candidates.\n */\n @Property({ name: 'last_seen_at', type: Date, nullable: true })\n lastSeenAt?: Date | null\n}\n\n// \u2500\u2500 ChannelIngestDeadLetter \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Inbound messages that fail permanently during ingest land here so an\n * operator can replay them after fixing parsers / schemas. Transient\n * failures (DB blip, network timeout) DO NOT write here \u2014 those abort the\n * poll loop without advancing the cursor so the message is re-fetched on\n * the next tick.\n *\n * `raw_body` is encrypted at rest via the module's `encryption.ts`\n * `defaultEncryptionMaps` entry (MIME bodies may contain PII).\n *\n * See `.ai/specs/implemented/2026-05-27-email-integration-inbound-reliability-and-threading.md`\n * (\u00A7 3 Data Model).\n */\n@Entity({ tableName: 'channel_ingest_dead_letters' })\n@Index({ name: 'channel_ingest_dead_letters_channel_idx', properties: ['channelId', 'tenantId'] })\n@Index({ name: 'channel_ingest_dead_letters_created_idx', properties: ['tenantId', 'createdAt'] })\nexport class ChannelIngestDeadLetter {\n [OptionalProps]?:\n | 'createdAt'\n | 'organizationId'\n | 'externalMessageId'\n | 'externalUid'\n | 'rawBody'\n\n @PrimaryKey({ type: 'uuid', defaultRaw: 'gen_random_uuid()' })\n id!: string\n\n @Property({ name: 'tenant_id', type: 'uuid' })\n tenantId!: string\n\n @Property({ name: 'organization_id', type: 'uuid', nullable: true })\n organizationId?: string | null\n\n @Property({ name: 'channel_id', type: 'uuid' })\n channelId!: string\n\n @Property({ name: 'provider_key', type: 'text' })\n providerKey!: string\n\n /** External UID / sequence-number for the provider (e.g. IMAP UID, Gmail messageId). */\n @Property({ name: 'external_uid', type: 'text', nullable: true })\n externalUid?: string | null\n\n @Property({ name: 'external_message_id', type: 'text', nullable: true })\n externalMessageId?: string | null\n\n @Property({ name: 'error_class', type: 'text' })\n errorClass!: string\n\n @Property({ name: 'error_message', type: 'text' })\n errorMessage!: string\n\n /** Truncated source \u2014 first N bytes of the raw MIME / payload (encrypted at rest). */\n @Property({ name: 'raw_body', type: 'text', nullable: true })\n rawBody?: string | null\n\n @Property({ name: 'created_at', type: Date, onCreate: () => new Date() })\n createdAt: Date = new Date()\n}\n"],
5
+ "mappings": ";;;;;;;;;;AAAA,SAAS,qBAAqB;AAC9B,SAAS,OAAO,QAAQ,OAAO,YAAY,UAAU,cAAc;AA2EhE;AADI,IAAM,uBAAN,MAA2B;AAAA,EAA3B;AAwCL,oBAAoB;AAiBpB,qBAAqB;AAoBrB,kBAAqC;AAuBrC,qBAAkB,oBAAI,KAAK;AAG3B,qBAAkB,oBAAI,KAAK;AAAA;AAI7B;AAxFE;AAAA,EADC,WAAW,EAAE,MAAM,QAAQ,YAAY,oBAAoB,CAAC;AAAA,GAlBlD,qBAmBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,OAAO,CAAC;AAAA,GArBrC,qBAsBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,OAAO,CAAC;AAAA,GAxBrC,qBAyBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,OAAO,CAAC;AAAA,GA3BrC,qBA4BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,uBAAuB,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,G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M,cAAc,MAAM,OAAO,CAAC;AAAA,GAjBnC,wBAkBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,OAAO,CAAC;AAAA,GApBrC,wBAqBX;AAIA;AAAA,EADC,SAAS,EAAE,MAAM,gBAAgB,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GAxBrD,wBAyBX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,uBAAuB,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GA3B5D,wBA4BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,eAAe,MAAM,OAAO,CAAC;AAAA,GA9BpC,wBA+BX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,iBAAiB,MAAM,OAAO,CAAC;AAAA,GAjCtC,wBAkCX;AAIA;AAAA,EADC,SAAS,EAAE,MAAM,YAAY,MAAM,QAAQ,UAAU,KAAK,CAAC;AAAA,GArCjD,wBAsCX;AAGA;AAAA,EADC,SAAS,EAAE,MAAM,cAAc,MAAM,MAAM,UAAU,MAAM,oBAAI,KAAK,EAAE,CAAC;AAAA,GAxC7D,wBAyCX;AAzCW,0BAAN;AAAA,EAHN,OAAO,EAAE,WAAW,8BAA8B,CAAC;AAAA,EACnD,MAAM,EAAE,MAAM,2CAA2C,YAAY,CAAC,aAAa,UAAU,EAAE,CAAC;AAAA,EAChG,MAAM,EAAE,MAAM,2CAA2C,YAAY,CAAC,YAAY,WAAW,EAAE,CAAC;AAAA,GACpF;",
6
6
  "names": []
7
7
  }
@@ -57,7 +57,8 @@ const validateCredentialsInputSchema = z.object({
57
57
  });
58
58
  const validateCredentialsResultSchema = z.object({
59
59
  ok: z.boolean(),
60
- errors: z.record(z.string(), z.string()).optional()
60
+ errors: z.record(z.string(), z.string()).optional(),
61
+ errorCodes: z.record(z.string(), z.string()).optional()
61
62
  });
62
63
  const refreshCredentialsInputSchema = z.object({
63
64
  channelId: z.string().uuid(),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/data/validators.ts"],
4
- "sourcesContent": ["import { z } from 'zod'\n\n/**\n * Zod schemas for adapter inputs and API request/response bodies.\n *\n * These mirror the TypeScript interfaces in `lib/adapter.ts`. They are used by:\n * - API route handlers to validate incoming requests\n * - Adapter implementations that prefer runtime validation over TypeScript-only types\n * - `validateCredentials?(...)` flow on credential-based providers\n */\n\nexport const tenantScopeSchema = z.object({\n organizationId: z.string().uuid().nullable().optional(),\n tenantId: z.string().uuid(),\n})\n\nexport const channelCapabilitiesSchema = z.object({\n threading: z.boolean(),\n richText: z.boolean(),\n fileSharing: z.boolean(),\n maxFileSize: z.number().int().nonnegative().optional(),\n supportedMimeTypes: z.array(z.string()).optional(),\n readReceipts: z.boolean(),\n deliveryReceipts: z.boolean(),\n typingIndicators: z.boolean(),\n reactions: z.boolean(),\n multiReactionPerUser: z.boolean(),\n editMessage: z.boolean(),\n deleteMessage: z.boolean(),\n presence: z.boolean(),\n richBlocks: z.boolean(),\n interactiveComponents: z.boolean(),\n inlineImages: z.boolean(),\n conversationHistory: z.boolean(),\n contactCards: z.boolean(),\n locationSharing: z.boolean(),\n voiceNotes: z.boolean(),\n stickers: z.boolean(),\n supportedBodyFormats: z.array(z.enum(['text', 'markdown', 'html'])),\n maxBodyLength: z.number().int().positive().optional(),\n realtimePush: z.boolean().optional(),\n})\n\nexport const normalizedAttachmentSchema = z.object({\n url: z.string().url(),\n mimeType: z.string().min(1),\n fileName: z.string().min(1),\n fileSize: z.number().int().nonnegative().optional(),\n inline: z.boolean().optional(),\n})\n\nexport const messageContentSchema = z.object({\n text: z.string().optional(),\n html: z.string().optional(),\n bodyFormat: z.enum(['text', 'markdown', 'html']).optional(),\n attachments: z.array(normalizedAttachmentSchema).optional(),\n raw: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const sendMessageInputSchema = z.object({\n conversationId: z.string().optional(),\n content: messageContentSchema,\n credentials: z.record(z.string(), z.unknown()),\n scope: tenantScopeSchema,\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const validateCredentialsInputSchema = z.object({\n providerKey: z.string().min(1),\n credentials: z.record(z.string(), z.unknown()),\n scope: tenantScopeSchema,\n})\n\nexport const validateCredentialsResultSchema = z.object({\n ok: z.boolean(),\n errors: z.record(z.string(), z.string()).optional(),\n})\n\nexport const refreshCredentialsInputSchema = z.object({\n channelId: z.string().uuid(),\n credentials: z.record(z.string(), z.unknown()),\n scope: tenantScopeSchema,\n})\n\nexport const refreshedCredentialsSchema = z.object({\n credentials: z.record(z.string(), z.unknown()),\n expiresAt: z.date().optional(),\n})\n\nexport const inboundReactionSchema = z.object({\n emoji: z.string().min(1),\n userIdentifier: z.string().min(1),\n userDisplayName: z.string().optional(),\n timestamp: z.date().optional(),\n})\n\n/**\n * Canonical normalized inbound reaction event \u2014 matches `InboundReactionEvent`\n * in `lib/adapter.ts`. Used by the reactions queue for type-safe payloads.\n */\nexport const inboundReactionEventSchema = z.object({\n externalMessageId: z.string().min(1),\n externalConversationId: z.string().min(1).optional(),\n externalReactionId: z.string().min(1).optional(),\n emoji: z.string().min(1).max(64),\n userIdentifier: z.string().min(1),\n userDisplayName: z.string().optional(),\n action: z.enum(['added', 'removed']),\n timestamp: z.date().optional(),\n raw: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const normalizedInboundMessageSchema = z.object({\n externalMessageId: z.string().min(1),\n externalConversationId: z.string().min(1),\n senderIdentifier: z.string().min(1),\n senderDisplayName: z.string().optional(),\n senderAvatarUrl: z.string().url().optional(),\n subject: z.string().optional(),\n body: z.string(),\n bodyFormat: z.enum(['text', 'markdown', 'html']),\n attachments: z.array(normalizedAttachmentSchema).optional(),\n timestamp: z.date(),\n replyToExternalId: z.string().optional(),\n channelPayload: z.record(z.string(), z.unknown()),\n channelContentType: z.string().min(1),\n channelMetadata: z.record(z.string(), z.unknown()),\n reactions: z.array(inboundReactionSchema).optional(),\n})\n\nexport const reactionApiBodySchema = z.object({\n emoji: z.string().min(1).max(64),\n})\n\nexport type SendMessageInputDto = z.infer<typeof sendMessageInputSchema>\nexport type NormalizedInboundMessageDto = z.infer<typeof normalizedInboundMessageSchema>\nexport type ChannelCapabilitiesDto = z.infer<typeof channelCapabilitiesSchema>\nexport type ReactionApiBodyDto = z.infer<typeof reactionApiBodySchema>\n"],
5
- "mappings": "AAAA,SAAS,SAAS;AAWX,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,gBAAgB,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS;AAAA,EACtD,UAAU,EAAE,OAAO,EAAE,KAAK;AAC5B,CAAC;AAEM,MAAM,4BAA4B,EAAE,OAAO;AAAA,EAChD,WAAW,EAAE,QAAQ;AAAA,EACrB,UAAU,EAAE,QAAQ;AAAA,EACpB,aAAa,EAAE,QAAQ;AAAA,EACvB,aAAa,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,SAAS;AAAA,EACrD,oBAAoB,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,SAAS;AAAA,EACjD,cAAc,EAAE,QAAQ;AAAA,EACxB,kBAAkB,EAAE,QAAQ;AAAA,EAC5B,kBAAkB,EAAE,QAAQ;AAAA,EAC5B,WAAW,EAAE,QAAQ;AAAA,EACrB,sBAAsB,EAAE,QAAQ;AAAA,EAChC,aAAa,EAAE,QAAQ;AAAA,EACvB,eAAe,EAAE,QAAQ;AAAA,EACzB,UAAU,EAAE,QAAQ;AAAA,EACpB,YAAY,EAAE,QAAQ;AAAA,EACtB,uBAAuB,EAAE,QAAQ;AAAA,EACjC,cAAc,EAAE,QAAQ;AAAA,EACxB,qBAAqB,EAAE,QAAQ;AAAA,EAC/B,cAAc,EAAE,QAAQ;AAAA,EACxB,iBAAiB,EAAE,QAAQ;AAAA,EAC3B,YAAY,EAAE,QAAQ;AAAA,EACtB,UAAU,EAAE,QAAQ;AAAA,EACpB,sBAAsB,EAAE,MAAM,EAAE,KAAK,CAAC,QAAQ,YAAY,MA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QAAQ,CAAC,EAAE,SAAS;AAClD,CAAC;AAEM,MAAM,iCAAiC,EAAE,OAAO;AAAA,EACrD,mBAAmB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACnC,wBAAwB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACxC,kBAAkB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAClC,mBAAmB,EAAE,OAAO,EAAE,SAAS;AAAA,EACvC,iBAAiB,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAAA,EAC3C,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,EAC7B,MAAM,EAAE,OAAO;AAAA,EACf,YAAY,EAAE,KAAK,CAAC,QAAQ,YAAY,MAAM,CAAC;AAAA,EAC/C,aAAa,EAAE,MAAM,0BAA0B,EAAE,SAAS;AAAA,EAC1D,WAAW,EAAE,KAAK;AAAA,EAClB,mBAAmB,EAAE,OAAO,EAAE,SAAS;AAAA,EACvC,gBAAgB,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC;AAAA,EAChD,oBAAoB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACpC,iBAAiB,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,QAAQ,CAAC;AAAA,EACjD,WAAW,EAAE,MAAM,qBAAqB,EAAE,SAAS;AACrD,CAAC;AAEM,MAAM,wBAAwB,EAAE,OAAO;AAAA,EAC5C,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AACjC,CAAC;",
4
+ "sourcesContent": ["import { z } from 'zod'\n\n/**\n * Zod schemas for adapter inputs and API request/response bodies.\n *\n * These mirror the TypeScript interfaces in `lib/adapter.ts`. They are used by:\n * - API route handlers to validate incoming requests\n * - Adapter implementations that prefer runtime validation over TypeScript-only types\n * - `validateCredentials?(...)` flow on credential-based providers\n */\n\nexport const tenantScopeSchema = z.object({\n organizationId: z.string().uuid().nullable().optional(),\n tenantId: z.string().uuid(),\n})\n\nexport const channelCapabilitiesSchema = z.object({\n threading: z.boolean(),\n richText: z.boolean(),\n fileSharing: z.boolean(),\n maxFileSize: z.number().int().nonnegative().optional(),\n supportedMimeTypes: z.array(z.string()).optional(),\n readReceipts: z.boolean(),\n deliveryReceipts: z.boolean(),\n typingIndicators: z.boolean(),\n reactions: z.boolean(),\n multiReactionPerUser: z.boolean(),\n editMessage: z.boolean(),\n deleteMessage: z.boolean(),\n presence: z.boolean(),\n richBlocks: z.boolean(),\n interactiveComponents: z.boolean(),\n inlineImages: z.boolean(),\n conversationHistory: z.boolean(),\n contactCards: z.boolean(),\n locationSharing: z.boolean(),\n voiceNotes: z.boolean(),\n stickers: z.boolean(),\n supportedBodyFormats: z.array(z.enum(['text', 'markdown', 'html'])),\n maxBodyLength: z.number().int().positive().optional(),\n realtimePush: z.boolean().optional(),\n})\n\nexport const normalizedAttachmentSchema = z.object({\n url: z.string().url(),\n mimeType: z.string().min(1),\n fileName: z.string().min(1),\n fileSize: z.number().int().nonnegative().optional(),\n inline: z.boolean().optional(),\n})\n\nexport const messageContentSchema = z.object({\n text: z.string().optional(),\n html: z.string().optional(),\n bodyFormat: z.enum(['text', 'markdown', 'html']).optional(),\n attachments: z.array(normalizedAttachmentSchema).optional(),\n raw: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const sendMessageInputSchema = z.object({\n conversationId: z.string().optional(),\n content: messageContentSchema,\n credentials: z.record(z.string(), z.unknown()),\n scope: tenantScopeSchema,\n metadata: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const validateCredentialsInputSchema = z.object({\n providerKey: z.string().min(1),\n credentials: z.record(z.string(), z.unknown()),\n scope: tenantScopeSchema,\n})\n\nexport const validateCredentialsResultSchema = z.object({\n ok: z.boolean(),\n errors: z.record(z.string(), z.string()).optional(),\n errorCodes: z.record(z.string(), z.string()).optional(),\n})\n\nexport const refreshCredentialsInputSchema = z.object({\n channelId: z.string().uuid(),\n credentials: z.record(z.string(), z.unknown()),\n scope: tenantScopeSchema,\n})\n\nexport const refreshedCredentialsSchema = z.object({\n credentials: z.record(z.string(), z.unknown()),\n expiresAt: z.date().optional(),\n})\n\nexport const inboundReactionSchema = z.object({\n emoji: z.string().min(1),\n userIdentifier: z.string().min(1),\n userDisplayName: z.string().optional(),\n timestamp: z.date().optional(),\n})\n\n/**\n * Canonical normalized inbound reaction event \u2014 matches `InboundReactionEvent`\n * in `lib/adapter.ts`. Used by the reactions queue for type-safe payloads.\n */\nexport const inboundReactionEventSchema = z.object({\n externalMessageId: z.string().min(1),\n externalConversationId: z.string().min(1).optional(),\n externalReactionId: z.string().min(1).optional(),\n emoji: z.string().min(1).max(64),\n userIdentifier: z.string().min(1),\n userDisplayName: z.string().optional(),\n action: z.enum(['added', 'removed']),\n timestamp: z.date().optional(),\n raw: z.record(z.string(), z.unknown()).optional(),\n})\n\nexport const normalizedInboundMessageSchema = z.object({\n externalMessageId: z.string().min(1),\n externalConversationId: z.string().min(1),\n senderIdentifier: z.string().min(1),\n senderDisplayName: z.string().optional(),\n senderAvatarUrl: z.string().url().optional(),\n subject: z.string().optional(),\n body: z.string(),\n bodyFormat: z.enum(['text', 'markdown', 'html']),\n attachments: z.array(normalizedAttachmentSchema).optional(),\n timestamp: z.date(),\n replyToExternalId: z.string().optional(),\n channelPayload: z.record(z.string(), z.unknown()),\n channelContentType: z.string().min(1),\n channelMetadata: z.record(z.string(), z.unknown()),\n reactions: z.array(inboundReactionSchema).optional(),\n})\n\nexport const reactionApiBodySchema = z.object({\n emoji: z.string().min(1).max(64),\n})\n\nexport type SendMessageInputDto = z.infer<typeof sendMessageInputSchema>\nexport type NormalizedInboundMessageDto = z.infer<typeof normalizedInboundMessageSchema>\nexport type ChannelCapabilitiesDto = z.infer<typeof channelCapabilitiesSchema>\nexport type ReactionApiBodyDto = z.infer<typeof reactionApiBodySchema>\n"],
5
+ "mappings": "AAAA,SAAS,SAAS;AAWX,MAAM,oBAAoB,EAAE,OAAO;AAAA,EACxC,gBAAgB,EAAE,OAA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