@open-mercato/core 0.9.0 → 0.9.1-develop.7462.1.94c09f158f

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 (276) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/customer_dictionary_entry/index.js +2 -0
  3. package/dist/generated/entities/customer_dictionary_entry/index.js.map +2 -2
  4. package/dist/generated/entities/customer_interaction/index.js +2 -0
  5. package/dist/generated/entities/customer_interaction/index.js.map +2 -2
  6. package/dist/generated/entity-fields-registry.js +2 -0
  7. package/dist/generated/entity-fields-registry.js.map +2 -2
  8. package/dist/modules/attachments/api/route.js +29 -3
  9. package/dist/modules/attachments/api/route.js.map +2 -2
  10. package/dist/modules/attachments/lib/ocrLimits.js +49 -0
  11. package/dist/modules/attachments/lib/ocrLimits.js.map +7 -0
  12. package/dist/modules/attachments/lib/ocrQueue.js +76 -2
  13. package/dist/modules/attachments/lib/ocrQueue.js.map +2 -2
  14. package/dist/modules/attachments/lib/ocrService.js +4 -0
  15. package/dist/modules/attachments/lib/ocrService.js.map +2 -2
  16. package/dist/modules/attachments/lib/pdfProcessing.js +14 -2
  17. package/dist/modules/attachments/lib/pdfProcessing.js.map +2 -2
  18. package/dist/modules/attachments/lib/scoped-upload-service.js +4 -2
  19. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  20. package/dist/modules/attachments/lib/textExtraction.js +13 -1
  21. package/dist/modules/attachments/lib/textExtraction.js.map +2 -2
  22. package/dist/modules/catalog/commands/categories.js +1 -1
  23. package/dist/modules/catalog/commands/categories.js.map +2 -2
  24. package/dist/modules/catalog/commands/productDeleteChildren.js +389 -0
  25. package/dist/modules/catalog/commands/productDeleteChildren.js.map +7 -0
  26. package/dist/modules/catalog/commands/products.js +52 -17
  27. package/dist/modules/catalog/commands/products.js.map +2 -2
  28. package/dist/modules/catalog/search.js +3 -1
  29. package/dist/modules/catalog/search.js.map +2 -2
  30. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js +2 -1
  31. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js.map +2 -2
  32. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js +4 -6
  33. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js.map +2 -2
  34. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js +4 -6
  35. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js.map +2 -2
  36. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js +47 -11
  37. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js.map +3 -3
  38. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +10 -7
  39. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +2 -2
  40. package/dist/modules/communication_channels/commands/deliver-outbound-message.js +5 -1
  41. package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +2 -2
  42. package/dist/modules/communication_channels/lib/inbound-message-origin.js +1 -1
  43. package/dist/modules/communication_channels/lib/inbound-message-origin.js.map +2 -2
  44. package/dist/modules/communication_channels/lib/oauth-result.js +12 -0
  45. package/dist/modules/communication_channels/lib/oauth-result.js.map +7 -0
  46. package/dist/modules/communication_channels/lib/oauth-state.js +4 -1
  47. package/dist/modules/communication_channels/lib/oauth-state.js.map +2 -2
  48. package/dist/modules/communication_channels/lib/use-connect-channel.js +10 -0
  49. package/dist/modules/communication_channels/lib/use-connect-channel.js.map +2 -2
  50. package/dist/modules/customers/api/activity-types/route.js +151 -0
  51. package/dist/modules/customers/api/activity-types/route.js.map +7 -0
  52. package/dist/modules/customers/api/deals/[id]/people/route.js +58 -5
  53. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  54. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +13 -5
  55. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  56. package/dist/modules/customers/api/dictionaries/[kind]/route.js +20 -5
  57. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  58. package/dist/modules/customers/api/interactions/route.js +3 -0
  59. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  60. package/dist/modules/customers/api/interactions/tasks/route.js +1 -0
  61. package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
  62. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js +18 -0
  63. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js.map +2 -2
  64. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js +0 -23
  65. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js.map +2 -2
  66. package/dist/modules/customers/backend/customers/deals/[id]/page.js +15 -17
  67. package/dist/modules/customers/backend/customers/deals/[id]/page.js.map +2 -2
  68. package/dist/modules/customers/calendar-event-types.js +548 -0
  69. package/dist/modules/customers/calendar-event-types.js.map +7 -0
  70. package/dist/modules/customers/commands/dictionaries.js +70 -10
  71. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  72. package/dist/modules/customers/commands/interactions.js +187 -22
  73. package/dist/modules/customers/commands/interactions.js.map +3 -3
  74. package/dist/modules/customers/components/ActivityTypeEditor.js +288 -0
  75. package/dist/modules/customers/components/ActivityTypeEditor.js.map +7 -0
  76. package/dist/modules/customers/components/DictionarySettings.js +3 -1
  77. package/dist/modules/customers/components/DictionarySettings.js.map +2 -2
  78. package/dist/modules/customers/components/calendar/CalendarEventEditor.js +391 -297
  79. package/dist/modules/customers/components/calendar/CalendarEventEditor.js.map +3 -3
  80. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js +9 -74
  81. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js.map +2 -2
  82. package/dist/modules/customers/components/calendar/TimeGrid.js +20 -16
  83. package/dist/modules/customers/components/calendar/TimeGrid.js.map +2 -2
  84. package/dist/modules/customers/components/calendar/editor/EventTypePanel.js +218 -0
  85. package/dist/modules/customers/components/calendar/editor/EventTypePanel.js.map +7 -0
  86. package/dist/modules/customers/components/calendar/editor/LocationField.js +7 -3
  87. package/dist/modules/customers/components/calendar/editor/LocationField.js.map +2 -2
  88. package/dist/modules/customers/components/calendar/editor/PeopleField.js +5 -2
  89. package/dist/modules/customers/components/calendar/editor/PeopleField.js.map +2 -2
  90. package/dist/modules/customers/components/calendar/editor/PriorityField.js +3 -1
  91. package/dist/modules/customers/components/calendar/editor/PriorityField.js.map +2 -2
  92. package/dist/modules/customers/components/calendar/editor/RepeatField.js +9 -1
  93. package/dist/modules/customers/components/calendar/editor/RepeatField.js.map +2 -2
  94. package/dist/modules/customers/components/calendar/editor/ResourcesField.js +4 -1
  95. package/dist/modules/customers/components/calendar/editor/ResourcesField.js.map +2 -2
  96. package/dist/modules/customers/components/calendar/editor/ScheduleSection.js +15 -7
  97. package/dist/modules/customers/components/calendar/editor/ScheduleSection.js.map +2 -2
  98. package/dist/modules/customers/components/calendar/editor/SegmentGroup.js +3 -1
  99. package/dist/modules/customers/components/calendar/editor/SegmentGroup.js.map +2 -2
  100. package/dist/modules/customers/components/calendar/editor/hooks.js +28 -13
  101. package/dist/modules/customers/components/calendar/editor/hooks.js.map +3 -3
  102. package/dist/modules/customers/components/calendar/editor/inputs.js +14 -6
  103. package/dist/modules/customers/components/calendar/editor/inputs.js.map +2 -2
  104. package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js +54 -0
  105. package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js.map +7 -0
  106. package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js +82 -0
  107. package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js.map +7 -0
  108. package/dist/modules/customers/components/calendar/types.js +1 -0
  109. package/dist/modules/customers/components/calendar/types.js.map +2 -2
  110. package/dist/modules/customers/components/detail/CompanyPeopleSection.js +78 -343
  111. package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
  112. package/dist/modules/customers/components/detail/CreatePersonDialog.js +12 -11
  113. package/dist/modules/customers/components/detail/CreatePersonDialog.js.map +2 -2
  114. package/dist/modules/customers/components/detail/DealForm.js +7 -3
  115. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  116. package/dist/modules/customers/components/detail/DealPeopleSection.js +206 -0
  117. package/dist/modules/customers/components/detail/DealPeopleSection.js.map +7 -0
  118. package/dist/modules/customers/components/detail/LinkedPeopleSection.js +342 -0
  119. package/dist/modules/customers/components/detail/LinkedPeopleSection.js.map +7 -0
  120. package/dist/modules/customers/components/detail/PersonCard.js +5 -2
  121. package/dist/modules/customers/components/detail/PersonCard.js.map +2 -2
  122. package/dist/modules/customers/components/linking/adapters/personAdapter.js +3 -0
  123. package/dist/modules/customers/components/linking/adapters/personAdapter.js.map +2 -2
  124. package/dist/modules/customers/data/entities.js +6 -0
  125. package/dist/modules/customers/data/entities.js.map +2 -2
  126. package/dist/modules/customers/data/validators.js +39 -10
  127. package/dist/modules/customers/data/validators.js.map +2 -2
  128. package/dist/modules/customers/di.js +20 -1
  129. package/dist/modules/customers/di.js.map +2 -2
  130. package/dist/modules/customers/extension-points.js +13 -0
  131. package/dist/modules/customers/extension-points.js.map +2 -2
  132. package/dist/modules/customers/lib/calendar/conflicts.js +59 -16
  133. package/dist/modules/customers/lib/calendar/conflicts.js.map +2 -2
  134. package/dist/modules/customers/lib/calendar/editorPayload.js +34 -16
  135. package/dist/modules/customers/lib/calendar/editorPayload.js.map +2 -2
  136. package/dist/modules/customers/lib/calendar/eventTypeResolver.js +197 -0
  137. package/dist/modules/customers/lib/calendar/eventTypeResolver.js.map +7 -0
  138. package/dist/modules/customers/lib/calendar/interactionApplicability.js +67 -0
  139. package/dist/modules/customers/lib/calendar/interactionApplicability.js.map +7 -0
  140. package/dist/modules/customers/lib/calendar/mapItem.js +5 -2
  141. package/dist/modules/customers/lib/calendar/mapItem.js.map +2 -2
  142. package/dist/modules/customers/lib/calendar/recurrence.js +62 -1
  143. package/dist/modules/customers/lib/calendar/recurrence.js.map +2 -2
  144. package/dist/modules/customers/lib/calendar/timezone.js +111 -0
  145. package/dist/modules/customers/lib/calendar/timezone.js.map +7 -0
  146. package/dist/modules/customers/lib/interactionReadModel.js +1 -0
  147. package/dist/modules/customers/lib/interactionReadModel.js.map +2 -2
  148. package/dist/modules/customers/lib/todoCompatibility.js +1 -0
  149. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  150. package/dist/modules/customers/migrations/Migration20260928175058_customers.js +17 -0
  151. package/dist/modules/customers/migrations/Migration20260928175058_customers.js.map +7 -0
  152. package/dist/modules/customers/migrations/Migration20260930110235_customers.js +17 -0
  153. package/dist/modules/customers/migrations/Migration20260930110235_customers.js.map +7 -0
  154. package/dist/modules/dictionaries/components/DictionaryTable.js +60 -51
  155. package/dist/modules/dictionaries/components/DictionaryTable.js.map +2 -2
  156. package/dist/modules/messages/subscribers/message-notification.js +13 -1
  157. package/dist/modules/messages/subscribers/message-notification.js.map +2 -2
  158. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js +201 -53
  159. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js.map +2 -2
  160. package/dist/modules/payment_gateways/lib/gateway-service.js +37 -11
  161. package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
  162. package/dist/modules/planner/lib/availabilityMerge.js +101 -38
  163. package/dist/modules/planner/lib/availabilityMerge.js.map +3 -3
  164. package/dist/modules/planner/services/plannerAvailabilityService.js.map +2 -2
  165. package/dist/modules/sales/components/documents/LineItemDialog.js +159 -81
  166. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  167. package/dist/modules/sales/components/documents/lineItemUtils.js +7 -0
  168. package/dist/modules/sales/components/documents/lineItemUtils.js.map +2 -2
  169. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js +12 -7
  170. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js.map +2 -2
  171. package/dist/modules/sync_excel/lib/adapters/customers.js +28 -25
  172. package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
  173. package/generated/entities/customer_dictionary_entry/index.ts +1 -0
  174. package/generated/entities/customer_interaction/index.ts +1 -0
  175. package/generated/entity-fields-registry.ts +2 -0
  176. package/package.json +9 -8
  177. package/src/modules/attachments/api/route.ts +36 -3
  178. package/src/modules/attachments/lib/ocrLimits.ts +62 -0
  179. package/src/modules/attachments/lib/ocrQueue.ts +95 -2
  180. package/src/modules/attachments/lib/ocrService.ts +4 -0
  181. package/src/modules/attachments/lib/pdfProcessing.ts +14 -2
  182. package/src/modules/attachments/lib/scoped-upload-service.ts +4 -2
  183. package/src/modules/attachments/lib/textExtraction.ts +14 -1
  184. package/src/modules/auth/i18n/de.json +3 -0
  185. package/src/modules/auth/i18n/en.json +3 -0
  186. package/src/modules/auth/i18n/es.json +3 -0
  187. package/src/modules/auth/i18n/ko.json +3 -0
  188. package/src/modules/auth/i18n/pl.json +3 -0
  189. package/src/modules/catalog/commands/categories.ts +1 -1
  190. package/src/modules/catalog/commands/productDeleteChildren.ts +557 -0
  191. package/src/modules/catalog/commands/products.ts +58 -17
  192. package/src/modules/catalog/search.ts +5 -1
  193. package/src/modules/communication_channels/api/get/oauth/[provider]/callback/route.ts +2 -1
  194. package/src/modules/communication_channels/api/post/channels/connect/credentials/route.ts +4 -6
  195. package/src/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.ts +4 -6
  196. package/src/modules/communication_channels/api/post/oauth/[provider]/initiate/route.ts +46 -10
  197. package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +12 -9
  198. package/src/modules/communication_channels/commands/deliver-outbound-message.ts +6 -1
  199. package/src/modules/communication_channels/i18n/de.json +4 -1
  200. package/src/modules/communication_channels/i18n/en.json +4 -1
  201. package/src/modules/communication_channels/i18n/es.json +4 -1
  202. package/src/modules/communication_channels/i18n/ko.json +4 -1
  203. package/src/modules/communication_channels/i18n/pl.json +4 -1
  204. package/src/modules/communication_channels/lib/inbound-message-origin.ts +2 -6
  205. package/src/modules/communication_channels/lib/oauth-result.ts +13 -0
  206. package/src/modules/communication_channels/lib/oauth-state.ts +4 -1
  207. package/src/modules/communication_channels/lib/use-connect-channel.ts +10 -0
  208. package/src/modules/customers/api/activity-types/route.ts +154 -0
  209. package/src/modules/customers/api/deals/[id]/people/route.ts +82 -3
  210. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +9 -1
  211. package/src/modules/customers/api/dictionaries/[kind]/route.ts +18 -2
  212. package/src/modules/customers/api/interactions/route.ts +4 -0
  213. package/src/modules/customers/api/interactions/tasks/route.ts +1 -0
  214. package/src/modules/customers/backend/config/customers/pipeline-stages/page.meta.ts +20 -0
  215. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.ts +0 -29
  216. package/src/modules/customers/backend/customers/deals/[id]/page.tsx +15 -17
  217. package/src/modules/customers/calendar-event-types.ts +674 -0
  218. package/src/modules/customers/commands/dictionaries.ts +84 -8
  219. package/src/modules/customers/commands/interactions.ts +244 -21
  220. package/src/modules/customers/components/ActivityTypeEditor.tsx +239 -0
  221. package/src/modules/customers/components/DictionarySettings.tsx +5 -3
  222. package/src/modules/customers/components/calendar/CalendarEventEditor.tsx +347 -218
  223. package/src/modules/customers/components/calendar/CalendarSettingsModal.tsx +18 -96
  224. package/src/modules/customers/components/calendar/TimeGrid.tsx +20 -18
  225. package/src/modules/customers/components/calendar/editor/EventTypePanel.tsx +230 -0
  226. package/src/modules/customers/components/calendar/editor/LocationField.tsx +7 -1
  227. package/src/modules/customers/components/calendar/editor/PeopleField.tsx +4 -0
  228. package/src/modules/customers/components/calendar/editor/PriorityField.tsx +3 -0
  229. package/src/modules/customers/components/calendar/editor/RepeatField.tsx +10 -0
  230. package/src/modules/customers/components/calendar/editor/ResourcesField.tsx +4 -0
  231. package/src/modules/customers/components/calendar/editor/ScheduleSection.tsx +16 -4
  232. package/src/modules/customers/components/calendar/editor/SegmentGroup.tsx +3 -0
  233. package/src/modules/customers/components/calendar/editor/hooks.ts +29 -13
  234. package/src/modules/customers/components/calendar/editor/inputs.tsx +17 -5
  235. package/src/modules/customers/components/calendar/editor/useCalendarCustomFields.ts +49 -0
  236. package/src/modules/customers/components/calendar/editor/useEventTypeCatalog.ts +100 -0
  237. package/src/modules/customers/components/calendar/types.ts +1 -0
  238. package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +94 -388
  239. package/src/modules/customers/components/detail/CreatePersonDialog.tsx +39 -19
  240. package/src/modules/customers/components/detail/DealForm.tsx +7 -3
  241. package/src/modules/customers/components/detail/DealPeopleSection.tsx +256 -0
  242. package/src/modules/customers/components/detail/LinkedPeopleSection.tsx +474 -0
  243. package/src/modules/customers/components/detail/PersonCard.tsx +12 -4
  244. package/src/modules/customers/components/detail/types.ts +1 -0
  245. package/src/modules/customers/components/linking/adapters/personAdapter.tsx +4 -0
  246. package/src/modules/customers/data/entities.ts +8 -1
  247. package/src/modules/customers/data/validators.ts +42 -7
  248. package/src/modules/customers/di.ts +21 -0
  249. package/src/modules/customers/extension-points.ts +13 -0
  250. package/src/modules/customers/i18n/de.json +104 -8
  251. package/src/modules/customers/i18n/en.json +104 -8
  252. package/src/modules/customers/i18n/es.json +104 -8
  253. package/src/modules/customers/i18n/ko.json +104 -8
  254. package/src/modules/customers/i18n/pl.json +104 -8
  255. package/src/modules/customers/lib/calendar/conflicts.ts +106 -27
  256. package/src/modules/customers/lib/calendar/editorPayload.ts +39 -19
  257. package/src/modules/customers/lib/calendar/eventTypeResolver.ts +258 -0
  258. package/src/modules/customers/lib/calendar/interactionApplicability.ts +99 -0
  259. package/src/modules/customers/lib/calendar/mapItem.ts +6 -2
  260. package/src/modules/customers/lib/calendar/recurrence.ts +65 -1
  261. package/src/modules/customers/lib/calendar/timezone.ts +117 -0
  262. package/src/modules/customers/lib/interactionReadModel.ts +1 -0
  263. package/src/modules/customers/lib/todoCompatibility.ts +2 -0
  264. package/src/modules/customers/migrations/.snapshot-open-mercato.json +34 -0
  265. package/src/modules/customers/migrations/Migration20260928175058_customers.ts +15 -0
  266. package/src/modules/customers/migrations/Migration20260930110235_customers.ts +15 -0
  267. package/src/modules/dictionaries/components/DictionaryTable.tsx +63 -56
  268. package/src/modules/messages/subscribers/message-notification.ts +13 -3
  269. package/src/modules/payment_gateways/api/webhook/[provider]/route.ts +243 -62
  270. package/src/modules/payment_gateways/lib/gateway-service.ts +39 -12
  271. package/src/modules/planner/lib/availabilityMerge.ts +106 -41
  272. package/src/modules/planner/services/plannerAvailabilityService.ts +4 -0
  273. package/src/modules/sales/components/documents/LineItemDialog.tsx +194 -111
  274. package/src/modules/sales/components/documents/lineItemUtils.ts +18 -0
  275. package/src/modules/staff/backend/staff/time-tracking/projects/[id]/page.tsx +25 -13
  276. package/src/modules/sync_excel/lib/adapters/customers.ts +33 -27
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/attachments/lib/ocrService.ts"],
4
- "sourcesContent": ["import { generateText } from 'ai'\nimport { createOpenAI } from '@ai-sdk/openai'\nimport fs from 'fs/promises'\nimport path from 'path'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('attachments').child({ component: 'ocr-service' })\n\nexport type OcrServiceOptions = {\n apiKey?: string\n model?: string\n}\n\nexport type OcrInput = {\n filePath: string\n mimeType: string | null\n model?: string\n}\n\nexport type OcrResult = {\n content: string\n pageCount?: number\n processingTimeMs: number\n}\n\nconst DEFAULT_MODEL = 'gpt-4o'\nconst OCR_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.tiff']\n\nconst DEFAULT_OCR_PROMPT = `Extract all text content from this image. Preserve the structure and formatting where possible. Output the text in markdown format. If there are tables, preserve them as markdown tables. If there is no text visible, respond with an empty string.`\n\nfunction isImageMimeType(mimeType: string | null, filePath?: string): boolean {\n const normalized = (mimeType || '').toLowerCase()\n if (normalized.startsWith('image/')) return true\n if (filePath) {\n const ext = path.extname(filePath).toLowerCase()\n return OCR_IMAGE_EXTENSIONS.includes(ext)\n }\n return false\n}\n\nfunction isPdfMimeType(mimeType: string | null, filePath?: string): boolean {\n const normalized = (mimeType || '').toLowerCase()\n if (normalized === 'application/pdf') return true\n if (filePath) {\n const ext = path.extname(filePath).toLowerCase()\n return ext === '.pdf'\n }\n return false\n}\n\nfunction getImageMediaType(mimeType: string | null, filePath: string): string {\n if (mimeType && mimeType.startsWith('image/')) {\n return mimeType\n }\n const ext = path.extname(filePath).toLowerCase()\n const mimeMap: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.bmp': 'image/bmp',\n '.webp': 'image/webp',\n '.tiff': 'image/tiff',\n }\n return mimeMap[ext] || 'image/png'\n}\n\nexport class OcrService {\n private readonly apiKey: string | null\n private readonly defaultModel: string\n private client: ReturnType<typeof createOpenAI> | null = null\n\n constructor(opts: OcrServiceOptions = {}) {\n this.apiKey = opts.apiKey ?? process.env.OPENAI_API_KEY ?? null\n this.defaultModel = opts.model ?? process.env.OCR_MODEL ?? DEFAULT_MODEL\n }\n\n get available(): boolean {\n return Boolean(this.apiKey)\n }\n\n private ensureClient() {\n if (!this.apiKey) {\n throw new Error('[attachments.ocr] Missing OPENAI_API_KEY environment variable')\n }\n if (!this.client) {\n this.client = createOpenAI({ apiKey: this.apiKey })\n }\n return this.client\n }\n\n private async generateTextFromImageBuffer(params: {\n imageBuffer: Buffer\n mediaType: string\n model: string\n }): Promise<string> {\n const { imageBuffer, mediaType, model } = params\n const client = this.ensureClient()\n const base64 = imageBuffer.toString('base64')\n const dataUrl = `data:${mediaType};base64,${base64}`\n\n try {\n const result = await generateText({\n model: client(model),\n messages: [\n {\n role: 'user',\n content: [\n {\n type: 'image',\n image: dataUrl,\n },\n {\n type: 'text',\n text: process.env.OCR_DEFAULT_PROMPT ?? DEFAULT_OCR_PROMPT,\n },\n ],\n },\n ],\n })\n\n return result.text.trim()\n } catch (err: any) {\n const statusCandidate =\n err?.statusCode ?? err?.status ?? err?.response?.status ?? err?.response?.statusCode\n const status =\n typeof statusCandidate === 'number'\n ? Number.isFinite(statusCandidate) ? statusCandidate : undefined\n : typeof statusCandidate === 'string'\n ? Number.parseInt(statusCandidate, 10)\n : undefined\n const apiError = err?.data?.error ?? err?.body?.error ?? err?.response?.data?.error\n const apiMessage = apiError?.message ?? err?.response?.data?.message\n const apiCode = typeof apiError?.code === 'string' ? apiError.code : undefined\n const rawMessage = typeof apiMessage === 'string'\n ? apiMessage\n : (typeof err?.message === 'string' ? err.message : 'OCR request failed')\n\n let guidance: string\n switch (apiCode) {\n case 'insufficient_quota':\n guidance = 'OpenAI usage quota exceeded. Please review your plan and billing.'\n break\n case 'invalid_api_key':\n guidance = 'Invalid OpenAI API key. Update the key and retry.'\n break\n case 'account_deactivated':\n guidance = 'OpenAI account is disabled. Contact OpenAI support or provide a different key.'\n break\n case 'rate_limit_exceeded':\n guidance = 'Rate limit exceeded. Please try again later.'\n break\n default:\n guidance = rawMessage.includes('https://')\n ? rawMessage\n : `${rawMessage}. Check OPENAI_API_KEY.`\n }\n\n const wrapped = new Error(`[attachments.ocr] ${guidance}`)\n if (typeof status === 'number' && Number.isFinite(status)) {\n const normalizedStatus = status === 401 || status === 403 ? 502 : status\n if (normalizedStatus >= 400 && normalizedStatus < 600) {\n (wrapped as any).status = normalizedStatus\n }\n }\n if (apiCode) {\n (wrapped as any).code = apiCode\n }\n (wrapped as any).cause = err\n throw wrapped\n }\n }\n\n async processImage(input: OcrInput): Promise<OcrResult> {\n const startTime = Date.now()\n const { filePath, mimeType, model } = input\n const resolvedModel = model ?? this.defaultModel\n const imageBuffer = await fs.readFile(filePath)\n\n return {\n content: await this.generateTextFromImageBuffer({\n imageBuffer,\n mediaType: getImageMediaType(mimeType, filePath),\n model: resolvedModel,\n }),\n processingTimeMs: Date.now() - startTime,\n }\n }\n\n async processPdf(input: OcrInput): Promise<OcrResult> {\n const startTime = Date.now()\n const { filePath, model } = input\n const resolvedModel = model ?? this.defaultModel\n const { preparePdfPagesForOcr } = await import('./pdfProcessing')\n const preparedPdf = await preparePdfPagesForOcr(filePath)\n\n if (preparedPdf.pageCount === 0) {\n return {\n content: '',\n pageCount: 0,\n processingTimeMs: Date.now() - startTime,\n }\n }\n\n const pageContents: string[] = []\n\n for (const page of preparedPdf.pages) {\n try {\n let pageContent = page.extractedText\n\n if (!pageContent && page.imageBuffer) {\n pageContent = await this.generateTextFromImageBuffer({\n imageBuffer: page.imageBuffer,\n mediaType: 'image/png',\n model: resolvedModel,\n })\n }\n\n if (pageContent) {\n if (preparedPdf.pageCount > 1) {\n pageContents.push(`--- Page ${page.pageNumber} ---\\n\\n${pageContent}`)\n } else {\n pageContents.push(pageContent)\n }\n }\n } catch (error) {\n logger.error('Failed to process PDF page', { pageNumber: page.pageNumber, err: error })\n }\n }\n\n return {\n content: pageContents.join('\\n\\n'),\n pageCount: preparedPdf.pageCount,\n processingTimeMs: Date.now() - startTime,\n }\n }\n\n async processFile(input: OcrInput): Promise<OcrResult | null> {\n const { filePath, mimeType } = input\n\n if (isPdfMimeType(mimeType, filePath)) {\n logger.info('Processing PDF attachment via pdfjs-dist')\n return this.processPdf(input)\n }\n\n if (isImageMimeType(mimeType, filePath)) {\n logger.info('Processing image attachment via LLM OCR')\n return this.processImage(input)\n }\n\n logger.info('Unsupported file type for OCR', { mimeType: mimeType || 'unknown' })\n return null\n }\n}\n\nexport function shouldUseLlmOcr(mimeType: string | null, fileName: string): boolean {\n if (isPdfMimeType(mimeType, fileName)) return true\n return isImageMimeType(mimeType, fileName)\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAmB7E,MAAM,gBAAgB;AACtB,MAAM,uBAAuB,CAAC,QAAQ,QAAQ,SAAS,QAAQ,QAAQ,SAAS,OAAO;AAEvF,MAAM,qB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AEhC,eAAW,QAAQ,YAAY,OAAO;AACpC,UAAI;AACF,YAAI,cAAc,KAAK;AAEvB,YAAI,CAAC,eAAe,KAAK,aAAa;AACpC,wBAAc,MAAM,KAAK,4BAA4B;AAAA,YACnD,aAAa,KAAK;AAAA,YAClB,WAAW;AAAA,YACX,OAAO;AAAA,UACT,CAAC;AAAA,QACH;AAEA,YAAI,aAAa;AACf,cAAI,YAAY,YAAY,GAAG;AAC7B,yBAAa,KAAK,YAAY,KAAK,UAAU;AAAA;AAAA,EAAW,WAAW,EAAE;AAAA,UACvE,OAAO;AACL,yBAAa,KAAK,WAAW;AAAA,UAC/B;AAAA,QACF;AAAA,MACF,SAAS,OAAO;AACd,eAAO,MAAM,8BAA8B,EAAE,YAAY,KAAK,YAAY,KAAK,MAAM,CAAC;AAAA,MACxF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,SAAS,aAAa,KAAK,MAAM;AAAA,MACjC,WAAW,YAAY;AAAA,MACvB,kBAAkB,KAAK,IAAI,IAAI;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,MAAM,YAAY,OAA4C;AAC5D,UAAM,EAAE,UAAU,SAAS,IAAI;AAE/B,QAAI,cAAc,UAAU,QAAQ,GAAG;AACrC,aAAO,KAAK,0CAA0C;AACtD,aAAO,KAAK,WAAW,KAAK;AAAA,IAC9B;AAEA,QAAI,gBAAgB,UAAU,QAAQ,GAAG;AACvC,aAAO,KAAK,yCAAyC;AACrD,aAAO,KAAK,aAAa,KAAK;AAAA,IAChC;AAEA,WAAO,KAAK,iCAAiC,EAAE,UAAU,YAAY,UAAU,CAAC;AAChF,WAAO;AAAA,EACT;AACF;AAEO,SAAS,gBAAgB,UAAyB,UAA2B;AAClF,MAAI,cAAc,UAAU,QAAQ,EAAG,QAAO;AAC9C,SAAO,gBAAgB,UAAU,QAAQ;AAC3C;",
4
+ "sourcesContent": ["import { generateText } from 'ai'\nimport { createOpenAI } from '@ai-sdk/openai'\nimport fs from 'fs/promises'\nimport path from 'path'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { resolveOcrMaxOutputTokens, resolveOcrPageTimeoutMs } from './ocrLimits'\n\nconst logger = createLogger('attachments').child({ component: 'ocr-service' })\n\nexport type OcrServiceOptions = {\n apiKey?: string\n model?: string\n}\n\nexport type OcrInput = {\n filePath: string\n mimeType: string | null\n model?: string\n}\n\nexport type OcrResult = {\n content: string\n pageCount?: number\n processingTimeMs: number\n}\n\nconst DEFAULT_MODEL = 'gpt-4o'\nconst OCR_IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.tiff']\n\nconst DEFAULT_OCR_PROMPT = `Extract all text content from this image. Preserve the structure and formatting where possible. Output the text in markdown format. If there are tables, preserve them as markdown tables. If there is no text visible, respond with an empty string.`\n\nfunction isImageMimeType(mimeType: string | null, filePath?: string): boolean {\n const normalized = (mimeType || '').toLowerCase()\n if (normalized.startsWith('image/')) return true\n if (filePath) {\n const ext = path.extname(filePath).toLowerCase()\n return OCR_IMAGE_EXTENSIONS.includes(ext)\n }\n return false\n}\n\nfunction isPdfMimeType(mimeType: string | null, filePath?: string): boolean {\n const normalized = (mimeType || '').toLowerCase()\n if (normalized === 'application/pdf') return true\n if (filePath) {\n const ext = path.extname(filePath).toLowerCase()\n return ext === '.pdf'\n }\n return false\n}\n\nfunction getImageMediaType(mimeType: string | null, filePath: string): string {\n if (mimeType && mimeType.startsWith('image/')) {\n return mimeType\n }\n const ext = path.extname(filePath).toLowerCase()\n const mimeMap: Record<string, string> = {\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.bmp': 'image/bmp',\n '.webp': 'image/webp',\n '.tiff': 'image/tiff',\n }\n return mimeMap[ext] || 'image/png'\n}\n\nexport class OcrService {\n private readonly apiKey: string | null\n private readonly defaultModel: string\n private client: ReturnType<typeof createOpenAI> | null = null\n\n constructor(opts: OcrServiceOptions = {}) {\n this.apiKey = opts.apiKey ?? process.env.OPENAI_API_KEY ?? null\n this.defaultModel = opts.model ?? process.env.OCR_MODEL ?? DEFAULT_MODEL\n }\n\n get available(): boolean {\n return Boolean(this.apiKey)\n }\n\n private ensureClient() {\n if (!this.apiKey) {\n throw new Error('[attachments.ocr] Missing OPENAI_API_KEY environment variable')\n }\n if (!this.client) {\n this.client = createOpenAI({ apiKey: this.apiKey })\n }\n return this.client\n }\n\n private async generateTextFromImageBuffer(params: {\n imageBuffer: Buffer\n mediaType: string\n model: string\n }): Promise<string> {\n const { imageBuffer, mediaType, model } = params\n const client = this.ensureClient()\n const base64 = imageBuffer.toString('base64')\n const dataUrl = `data:${mediaType};base64,${base64}`\n\n try {\n const result = await generateText({\n model: client(model),\n abortSignal: AbortSignal.timeout(resolveOcrPageTimeoutMs()),\n maxRetries: 0,\n maxOutputTokens: resolveOcrMaxOutputTokens(),\n messages: [\n {\n role: 'user',\n content: [\n {\n type: 'image',\n image: dataUrl,\n },\n {\n type: 'text',\n text: process.env.OCR_DEFAULT_PROMPT ?? DEFAULT_OCR_PROMPT,\n },\n ],\n },\n ],\n })\n\n return result.text.trim()\n } catch (err: any) {\n const statusCandidate =\n err?.statusCode ?? err?.status ?? err?.response?.status ?? err?.response?.statusCode\n const status =\n typeof statusCandidate === 'number'\n ? Number.isFinite(statusCandidate) ? statusCandidate : undefined\n : typeof statusCandidate === 'string'\n ? Number.parseInt(statusCandidate, 10)\n : undefined\n const apiError = err?.data?.error ?? err?.body?.error ?? err?.response?.data?.error\n const apiMessage = apiError?.message ?? err?.response?.data?.message\n const apiCode = typeof apiError?.code === 'string' ? apiError.code : undefined\n const rawMessage = typeof apiMessage === 'string'\n ? apiMessage\n : (typeof err?.message === 'string' ? err.message : 'OCR request failed')\n\n let guidance: string\n switch (apiCode) {\n case 'insufficient_quota':\n guidance = 'OpenAI usage quota exceeded. Please review your plan and billing.'\n break\n case 'invalid_api_key':\n guidance = 'Invalid OpenAI API key. Update the key and retry.'\n break\n case 'account_deactivated':\n guidance = 'OpenAI account is disabled. Contact OpenAI support or provide a different key.'\n break\n case 'rate_limit_exceeded':\n guidance = 'Rate limit exceeded. Please try again later.'\n break\n default:\n guidance = rawMessage.includes('https://')\n ? rawMessage\n : `${rawMessage}. Check OPENAI_API_KEY.`\n }\n\n const wrapped = new Error(`[attachments.ocr] ${guidance}`)\n if (typeof status === 'number' && Number.isFinite(status)) {\n const normalizedStatus = status === 401 || status === 403 ? 502 : status\n if (normalizedStatus >= 400 && normalizedStatus < 600) {\n (wrapped as any).status = normalizedStatus\n }\n }\n if (apiCode) {\n (wrapped as any).code = apiCode\n }\n (wrapped as any).cause = err\n throw wrapped\n }\n }\n\n async processImage(input: OcrInput): Promise<OcrResult> {\n const startTime = Date.now()\n const { filePath, mimeType, model } = input\n const resolvedModel = model ?? this.defaultModel\n const imageBuffer = await fs.readFile(filePath)\n\n return {\n content: await this.generateTextFromImageBuffer({\n imageBuffer,\n mediaType: getImageMediaType(mimeType, filePath),\n model: resolvedModel,\n }),\n processingTimeMs: Date.now() - startTime,\n }\n }\n\n async processPdf(input: OcrInput): Promise<OcrResult> {\n const startTime = Date.now()\n const { filePath, model } = input\n const resolvedModel = model ?? this.defaultModel\n const { preparePdfPagesForOcr } = await import('./pdfProcessing')\n const preparedPdf = await preparePdfPagesForOcr(filePath)\n\n if (preparedPdf.pageCount === 0) {\n return {\n content: '',\n pageCount: 0,\n processingTimeMs: Date.now() - startTime,\n }\n }\n\n const pageContents: string[] = []\n\n for (const page of preparedPdf.pages) {\n try {\n let pageContent = page.extractedText\n\n if (!pageContent && page.imageBuffer) {\n pageContent = await this.generateTextFromImageBuffer({\n imageBuffer: page.imageBuffer,\n mediaType: 'image/png',\n model: resolvedModel,\n })\n }\n\n if (pageContent) {\n if (preparedPdf.pageCount > 1) {\n pageContents.push(`--- Page ${page.pageNumber} ---\\n\\n${pageContent}`)\n } else {\n pageContents.push(pageContent)\n }\n }\n } catch (error) {\n logger.error('Failed to process PDF page', { pageNumber: page.pageNumber, err: error })\n }\n }\n\n return {\n content: pageContents.join('\\n\\n'),\n pageCount: preparedPdf.pageCount,\n processingTimeMs: Date.now() - startTime,\n }\n }\n\n async processFile(input: OcrInput): Promise<OcrResult | null> {\n const { filePath, mimeType } = input\n\n if (isPdfMimeType(mimeType, filePath)) {\n logger.info('Processing PDF attachment via pdfjs-dist')\n return this.processPdf(input)\n }\n\n if (isImageMimeType(mimeType, filePath)) {\n logger.info('Processing image attachment via LLM OCR')\n return this.processImage(input)\n }\n\n logger.info('Unsupported file type for OCR', { mimeType: mimeType || 'unknown' })\n return null\n }\n}\n\nexport function shouldUseLlmOcr(mimeType: string | null, fileName: string): boolean {\n if (isPdfMimeType(mimeType, fileName)) return true\n return isImageMimeType(mimeType, fileName)\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B,+BAA+B;AAEnE,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AAmB7E,MAAM,gBAAgB;AACtB,MAAM,uBAAuB,CAAC,QAAQ,QAAQ,SAAS,QAAQ,QAAQ,SAAS,OAAO;AAEvF,MAAM,qBAAqB;AAE3B,SAAS,gBAAgB,UAAyB,UAA4B;AAC5E,QAAM,cAAc,YAAY,IAAI,YAAY;AAChD,MAAI,WAAW,WAAW,QAAQ,EAAG,QAAO;AAC5C,MAAI,UAAU;AACZ,UAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAC/C,WAAO,qBAAqB,SAAS,GAAG;AAAA,EAC1C;AACA,SAAO;AACT;AAEA,SAAS,cAAc,UAAyB,UAA4B;AAC1E,QAAM,cAAc,YAAY,IAAI,YAAY;AAChD,MAAI,eAAe,kBAAmB,QAAO;AAC7C,MAAI,UAAU;AACZ,UAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAC/C,WA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AA,UACvE,OAAO;AACL,yBAAa,KAAK,WAAW;AAAA,UAC/B;AAAA,QACF;AAAA,MACF,SAAS,OAAO;AACd,eAAO,MAAM,8BAA8B,EAAE,YAAY,KAAK,YAAY,KAAK,MAAM,CAAC;AAAA,MACxF;AAAA,IACF;AAEA,WAAO;AAAA,MACL,SAAS,aAAa,KAAK,MAAM;AAAA,MACjC,WAAW,YAAY;AAAA,MACvB,kBAAkB,KAAK,IAAI,IAAI;AAAA,IACjC;AAAA,EACF;AAAA,EAEA,MAAM,YAAY,OAA4C;AAC5D,UAAM,EAAE,UAAU,SAAS,IAAI;AAE/B,QAAI,cAAc,UAAU,QAAQ,GAAG;AACrC,aAAO,KAAK,0CAA0C;AACtD,aAAO,KAAK,WAAW,KAAK;AAAA,IAC9B;AAEA,QAAI,gBAAgB,UAAU,QAAQ,GAAG;AACvC,aAAO,KAAK,yCAAyC;AACrD,aAAO,KAAK,aAAa,KAAK;AAAA,IAChC;AAEA,WAAO,KAAK,iCAAiC,EAAE,UAAU,YAAY,UAAU,CAAC;AAChF,WAAO;AAAA,EACT;AACF;AAEO,SAAS,gBAAgB,UAAyB,UAA2B;AAClF,MAAI,cAAc,UAAU,QAAQ,EAAG,QAAO;AAC9C,SAAO,gBAAgB,UAAU,QAAQ;AAC3C;",
6
6
  "names": []
7
7
  }
@@ -1,10 +1,13 @@
1
1
  import fs from "fs/promises";
2
2
  import path from "path";
3
3
  import { createRequire } from "module";
4
+ import { createLogger } from "@open-mercato/shared/lib/logger";
5
+ import { resolveMaxOcrPages, resolvePdfPageIterationLimit } from "./ocrLimits.js";
4
6
  const moduleRequire = createRequire(path.join(process.cwd(), "package.json"));
5
7
  const pdfJsPackageRoot = path.dirname(moduleRequire.resolve("pdfjs-dist/package.json"));
6
8
  const cMapUrl = `${path.join(pdfJsPackageRoot, "cmaps")}${path.sep}`;
7
9
  const standardFontDataUrl = `${path.join(pdfJsPackageRoot, "standard_fonts")}${path.sep}`;
10
+ const logger = createLogger("attachments").child({ component: "pdf-processing" });
8
11
  const MIN_RENDER_SCALE = 2;
9
12
  const MAX_RENDER_SCALE = 4;
10
13
  const MAX_RENDER_DIMENSION = 2200;
@@ -60,7 +63,16 @@ async function preparePdfPagesForOcr(filePath) {
60
63
  const pdfDocument = await loadingTask.promise;
61
64
  try {
62
65
  const pages = [];
63
- for (let pageNumber = 1; pageNumber <= pdfDocument.numPages; pageNumber += 1) {
66
+ const maxPages = resolveMaxOcrPages();
67
+ const pageLimit = resolvePdfPageIterationLimit(pdfDocument.numPages, maxPages);
68
+ if (pdfDocument.numPages > pageLimit) {
69
+ logger.warn("PDF page count exceeds OCR cap; truncating", {
70
+ numPages: pdfDocument.numPages,
71
+ maxPages: pageLimit,
72
+ filePath
73
+ });
74
+ }
75
+ for (let pageNumber = 1; pageNumber <= pageLimit; pageNumber += 1) {
64
76
  const page = await pdfDocument.getPage(pageNumber);
65
77
  try {
66
78
  const textContent = await page.getTextContent();
@@ -83,7 +95,7 @@ async function preparePdfPagesForOcr(filePath) {
83
95
  }
84
96
  }
85
97
  return {
86
- pageCount: pdfDocument.numPages,
98
+ pageCount: pages.length,
87
99
  pages
88
100
  };
89
101
  } finally {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/attachments/lib/pdfProcessing.ts"],
4
- "sourcesContent": ["import fs from 'fs/promises'\nimport path from 'path'\nimport { createRequire } from 'module'\n\nconst moduleRequire = createRequire(path.join(process.cwd(), 'package.json'))\nconst pdfJsPackageRoot = path.dirname(moduleRequire.resolve('pdfjs-dist/package.json'))\nconst cMapUrl = `${path.join(pdfJsPackageRoot, 'cmaps')}${path.sep}`\nconst standardFontDataUrl = `${path.join(pdfJsPackageRoot, 'standard_fonts')}${path.sep}`\n\nconst MIN_RENDER_SCALE = 2\nconst MAX_RENDER_SCALE = 4\nconst MAX_RENDER_DIMENSION = 2200\nconst MAX_RENDER_PIXELS = 8_000_000\n\ntype PdfPageProxyLike = {\n cleanup: () => void\n getTextContent: () => Promise<{ items?: Array<{ str?: string }> }>\n getViewport: (args: { scale: number }) => { width: number; height: number }\n render: (args: { canvasContext: unknown; viewport: { width: number; height: number } }) => { promise: Promise<void> }\n}\n\ntype PdfCanvasFactoryLike = {\n create: (width: number, height: number) => {\n canvas: { toBuffer: (mimeType: string) => Buffer | Uint8Array }\n context: unknown\n }\n destroy: (canvasAndContext: {\n canvas: { toBuffer: (mimeType: string) => Buffer | Uint8Array } | null\n context: unknown\n }) => void\n}\n\ntype PdfDocumentProxyLike = {\n numPages: number\n canvasFactory: PdfCanvasFactoryLike\n getPage: (pageNumber: number) => Promise<PdfPageProxyLike>\n}\n\nexport type PdfPageOcrInput = {\n pageNumber: number\n extractedText: string | null\n imageBuffer: Buffer | null\n}\n\nexport type PdfOcrPreparationResult = {\n pageCount: number\n pages: PdfPageOcrInput[]\n}\n\nfunction normalizePdfText(rawText: string): string | null {\n const normalized = rawText.replace(/\\s+/g, ' ').trim()\n return normalized.length > 0 ? normalized : null\n}\n\nfunction extractPdfTextContent(items: Array<{ str?: string }> | undefined): string | null {\n if (!Array.isArray(items) || items.length === 0) return null\n const collected = items\n .map((item) => (typeof item?.str === 'string' ? item.str : ''))\n .filter((value) => value.length > 0)\n .join(' ')\n return normalizePdfText(collected)\n}\n\nfunction resolvePdfRenderScale(page: PdfPageProxyLike): number {\n const baseViewport = page.getViewport({ scale: 1 })\n const baseLargestDimension = Math.max(baseViewport.width, baseViewport.height)\n let scale = Math.min(\n MAX_RENDER_SCALE,\n Math.max(MIN_RENDER_SCALE, MAX_RENDER_DIMENSION / Math.max(baseLargestDimension, 1)),\n )\n\n let viewport = page.getViewport({ scale })\n const pixelCount = viewport.width * viewport.height\n if (pixelCount > MAX_RENDER_PIXELS) {\n scale *= Math.sqrt(MAX_RENDER_PIXELS / pixelCount)\n viewport = page.getViewport({ scale })\n }\n\n return Math.max(1, scale)\n}\n\nasync function renderPdfPageToImageBuffer(\n page: PdfPageProxyLike,\n canvasFactory: PdfCanvasFactoryLike,\n): Promise<Buffer> {\n const viewport = page.getViewport({ scale: resolvePdfRenderScale(page) })\n const canvasAndContext = canvasFactory.create(viewport.width, viewport.height)\n\n try {\n const renderTask = page.render({\n canvasContext: canvasAndContext.context,\n viewport,\n })\n await renderTask.promise\n const imageBuffer = canvasAndContext.canvas.toBuffer('image/png')\n return Buffer.isBuffer(imageBuffer) ? imageBuffer : Buffer.from(imageBuffer)\n } finally {\n canvasFactory.destroy(canvasAndContext)\n }\n}\n\nexport async function preparePdfPagesForOcr(filePath: string): Promise<PdfOcrPreparationResult> {\n const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs')\n const data = new Uint8Array(await fs.readFile(filePath))\n const loadingTask = getDocument({\n data,\n cMapUrl,\n cMapPacked: true,\n standardFontDataUrl,\n })\n\n const pdfDocument = (await loadingTask.promise) as unknown as PdfDocumentProxyLike\n\n try {\n const pages: PdfPageOcrInput[] = []\n\n for (let pageNumber = 1; pageNumber <= pdfDocument.numPages; pageNumber += 1) {\n const page = await pdfDocument.getPage(pageNumber)\n\n try {\n const textContent = await page.getTextContent()\n const extractedText = extractPdfTextContent(textContent.items)\n\n if (extractedText) {\n pages.push({\n pageNumber,\n extractedText,\n imageBuffer: null,\n })\n continue\n }\n\n pages.push({\n pageNumber,\n extractedText: null,\n imageBuffer: await renderPdfPageToImageBuffer(page, pdfDocument.canvasFactory),\n })\n } finally {\n page.cleanup()\n }\n }\n\n return {\n pageCount: pdfDocument.numPages,\n pages,\n }\n } finally {\n await loadingTask.destroy()\n }\n}\n"],
5
- "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAE9B,MAAM,gBAAgB,cAAc,KAAK,KAAK,QAAQ,IAAI,GAAG,cAAc,CAAC;AAC5E,MAAM,mBAAmB,KAAK,QAAQ,cAAc,QAAQ,yBAAyB,CAAC;AACtF,MAAM,UAAU,GAAG,KAAK,KAAK,kBAAkB,OAAO,CAAC,GAAG,KAAK,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ire } from 'module'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { resolveMaxOcrPages, resolvePdfPageIterationLimit } from './ocrLimits'\n\nconst moduleRequire = createRequire(path.join(process.cwd(), 'package.json'))\nconst pdfJsPackageRoot = path.dirname(moduleRequire.resolve('pdfjs-dist/package.json'))\nconst cMapUrl = `${path.join(pdfJsPackageRoot, 'cmaps')}${path.sep}`\nconst standardFontDataUrl = `${path.join(pdfJsPackageRoot, 'standard_fonts')}${path.sep}`\nconst logger = createLogger('attachments').child({ component: 'pdf-processing' })\n\nconst MIN_RENDER_SCALE = 2\nconst MAX_RENDER_SCALE = 4\nconst MAX_RENDER_DIMENSION = 2200\nconst MAX_RENDER_PIXELS = 8_000_000\n\ntype PdfPageProxyLike = {\n cleanup: () => void\n getTextContent: () => Promise<{ items?: Array<{ str?: string }> }>\n getViewport: (args: { scale: number }) => { width: number; height: number }\n render: (args: { canvasContext: unknown; viewport: { width: number; height: number } }) => { promise: Promise<void> }\n}\n\ntype PdfCanvasFactoryLike = {\n create: (width: number, height: number) => {\n canvas: { toBuffer: (mimeType: string) => Buffer | Uint8Array }\n context: unknown\n }\n destroy: (canvasAndContext: {\n canvas: { toBuffer: (mimeType: string) => Buffer | Uint8Array } | null\n context: unknown\n }) => void\n}\n\ntype PdfDocumentProxyLike = {\n numPages: number\n canvasFactory: PdfCanvasFactoryLike\n getPage: (pageNumber: number) => Promise<PdfPageProxyLike>\n}\n\nexport type PdfPageOcrInput = {\n pageNumber: number\n extractedText: string | null\n imageBuffer: Buffer | null\n}\n\nexport type PdfOcrPreparationResult = {\n pageCount: number\n pages: PdfPageOcrInput[]\n}\n\nfunction normalizePdfText(rawText: string): string | null {\n const normalized = rawText.replace(/\\s+/g, ' ').trim()\n return normalized.length > 0 ? normalized : null\n}\n\nfunction extractPdfTextContent(items: Array<{ str?: string }> | undefined): string | null {\n if (!Array.isArray(items) || items.length === 0) return null\n const collected = items\n .map((item) => (typeof item?.str === 'string' ? item.str : ''))\n .filter((value) => value.length > 0)\n .join(' ')\n return normalizePdfText(collected)\n}\n\nfunction resolvePdfRenderScale(page: PdfPageProxyLike): number {\n const baseViewport = page.getViewport({ scale: 1 })\n const baseLargestDimension = Math.max(baseViewport.width, baseViewport.height)\n let scale = Math.min(\n MAX_RENDER_SCALE,\n Math.max(MIN_RENDER_SCALE, MAX_RENDER_DIMENSION / Math.max(baseLargestDimension, 1)),\n )\n\n let viewport = page.getViewport({ scale })\n const pixelCount = viewport.width * viewport.height\n if (pixelCount > MAX_RENDER_PIXELS) {\n scale *= Math.sqrt(MAX_RENDER_PIXELS / pixelCount)\n viewport = page.getViewport({ scale })\n }\n\n return Math.max(1, scale)\n}\n\nasync function renderPdfPageToImageBuffer(\n page: PdfPageProxyLike,\n canvasFactory: PdfCanvasFactoryLike,\n): Promise<Buffer> {\n const viewport = page.getViewport({ scale: resolvePdfRenderScale(page) })\n const canvasAndContext = canvasFactory.create(viewport.width, viewport.height)\n\n try {\n const renderTask = page.render({\n canvasContext: canvasAndContext.context,\n viewport,\n })\n await renderTask.promise\n const imageBuffer = canvasAndContext.canvas.toBuffer('image/png')\n return Buffer.isBuffer(imageBuffer) ? imageBuffer : Buffer.from(imageBuffer)\n } finally {\n canvasFactory.destroy(canvasAndContext)\n }\n}\n\nexport async function preparePdfPagesForOcr(filePath: string): Promise<PdfOcrPreparationResult> {\n const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs')\n const data = new Uint8Array(await fs.readFile(filePath))\n const loadingTask = getDocument({\n data,\n cMapUrl,\n cMapPacked: true,\n standardFontDataUrl,\n })\n\n const pdfDocument = (await loadingTask.promise) as unknown as PdfDocumentProxyLike\n\n try {\n const pages: PdfPageOcrInput[] = []\n const maxPages = resolveMaxOcrPages()\n const pageLimit = resolvePdfPageIterationLimit(pdfDocument.numPages, maxPages)\n if (pdfDocument.numPages > pageLimit) {\n logger.warn('PDF page count exceeds OCR cap; truncating', {\n numPages: pdfDocument.numPages,\n maxPages: pageLimit,\n filePath,\n })\n }\n\n for (let pageNumber = 1; pageNumber <= pageLimit; pageNumber += 1) {\n const page = await pdfDocument.getPage(pageNumber)\n\n try {\n const textContent = await page.getTextContent()\n const extractedText = extractPdfTextContent(textContent.items)\n\n if (extractedText) {\n pages.push({\n pageNumber,\n extractedText,\n imageBuffer: null,\n })\n continue\n }\n\n pages.push({\n pageNumber,\n extractedText: null,\n imageBuffer: await renderPdfPageToImageBuffer(page, pdfDocument.canvasFactory),\n })\n } finally {\n page.cleanup()\n }\n }\n\n return {\n pageCount: pages.length,\n pages,\n }\n } finally {\n await loadingTask.destroy()\n }\n}\n"],
5
+ "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,oCAAoC;AAEjE,MAAM,gBAAgB,cAAc,KAAK,KAAK,QAAQ,IAAI,GAAG,cAAc,CAAC;AAC5E,MAAM,mBAAmB,KAAK,QAAQ,cAAc,QAAQ,yBAAyB,CAAC;AACtF,MAAM,UAAU,GAAG,KAAK,KAAK,kBAAkB,OAAO,CAAC,GAAG,KAAK,GAAG;AAClE,MAAM,sBAAsB,GAAG,KAAK,KAAK,kBAAkB,gBAAgB,CAAC,GAAG,KAAK,GAAG;AACvF,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,iBAAiB,CAAC;AAEhF,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AACzB,MAAM,uBAAuB;AAC7B,MAAM,oBAAoB;AAqC1B,SAAS,iBAAiB,SAAgC;AACxD,QAAM,aAAa,QAAQ,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACrD,SAAO,WAAW,SAAS,IAAI,aAAa;AAC9C;AAEA,SAAS,sBAAsB,OAA2D;AACxF,MAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,MAAM,WAAW,EAAG,QAAO;AACxD,QAAM,YAAY,MACf,IAAI,CAAC,SAAU,OAAO,MAAM,QAAQ,WAA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,IAC9B;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,EACF,CAAC;AAED,QAAM,cAAe,MAAM,YAAY;AAEvC,MAAI;AACF,UAAM,QAA2B,CAAC;AAClC,UAAM,WAAW,mBAAmB;AACpC,UAAM,YAAY,6BAA6B,YAAY,UAAU,QAAQ;AAC7E,QAAI,YAAY,WAAW,WAAW;AACpC,aAAO,KAAK,8CAA8C;AAAA,QACxD,UAAU,YAAY;AAAA,QACtB,UAAU;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH;AAEA,aAAS,aAAa,GAAG,cAAc,WAAW,cAAc,GAAG;AACjE,YAAM,OAAO,MAAM,YAAY,QAAQ,UAAU;AAEjD,UAAI;AACF,cAAM,cAAc,MAAM,KAAK,eAAe;AAC9C,cAAM,gBAAgB,sBAAsB,YAAY,KAAK;AAE7D,YAAI,eAAe;AACjB,gBAAM,KAAK;AAAA,YACT;AAAA,YACA;AAAA,YACA,aAAa;AAAA,UACf,CAAC;AACD;AAAA,QACF;AAEA,cAAM,KAAK;AAAA,UACT;AAAA,UACA,eAAe;AAAA,UACf,aAAa,MAAM,2BAA2B,MAAM,YAAY,aAAa;AAAA,QAC/E,CAAC;AAAA,MACH,UAAE;AACA,aAAK,QAAQ;AAAA,MACf;AAAA,IACF;AAEA,WAAO;AAAA,MACL,WAAW,MAAM;AAAA,MACjB;AAAA,IACF;AAAA,EACF,UAAE;AACA,UAAM,YAAY,QAAQ;AAAA,EAC5B;AACF;",
6
6
  "names": []
7
7
  }
@@ -177,9 +177,11 @@ class ScopedAttachmentUploadService {
177
177
  throw new ScopedAttachmentUploadError("persistence_failed", 500);
178
178
  }
179
179
  if (useLlmOcr) {
180
- requestOcrProcessing(em, attachment, driver, storedPath).catch((error) => {
180
+ try {
181
+ await requestOcrProcessing(em, attachment, driver, storedPath);
182
+ } catch (error) {
181
183
  logger.error("Scoped attachment OCR scheduling failed", { err: error });
182
- });
184
+ }
183
185
  }
184
186
  if (this.deps.dataEngine) {
185
187
  await emitCrudSideEffects({
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/attachments/lib/scoped-upload-service.ts"],
4
- "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { extractAttachmentContent } from './textExtraction'\nimport { requestOcrProcessing } from './ocrQueue'\nimport { OcrService, shouldUseLlmOcr } from './ocrService'\nimport { assertAttachmentScopeInvariant } from './access'\nimport {\n mergeAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from './metadata'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from './security'\nimport { resolveAttachmentMaxBytes } from './upload-limits'\nimport type { AttachmentQuotaService } from './quota-service'\n\nconst logger = createLogger('attachments')\n\nexport type ScopedAttachmentUploadErrorCode =\n | 'dangerous_executable'\n | 'max_upload_size'\n | 'active_content'\n | 'partition_unavailable'\n | 'quota_exceeded'\n | 'quota_target_exists'\n | 'quota_unavailable'\n | 'quota_recovery_unsupported'\n | 'storage_failed'\n | 'persistence_failed'\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries. The production build emits this module into several server\n// chunks, so a consumer's `instanceof` compares against a different copy of the\n// class than the DI-resolved service threw from: the check silently fails, the\n// error escapes the caller's catch, and a deliberate 400/413 surfaces as a 500.\nconst SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER = Symbol.for('@open-mercato/ScopedAttachmentUploadError')\n\nexport class ScopedAttachmentUploadError extends Error {\n readonly [SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] = true\n\n constructor(\n public readonly code: ScopedAttachmentUploadErrorCode,\n public readonly status: number,\n ) {\n super(code)\n this.name = 'ScopedAttachmentUploadError'\n }\n}\n\n/**\n * Bundle-safe check for `ScopedAttachmentUploadError`. Prefer this over\n * `instanceof` at every call site \u2014 the class is duplicated across server\n * chunks, so `instanceof` is only reliable inside this module.\n */\nexport function isScopedAttachmentUploadError(error: unknown): error is ScopedAttachmentUploadError {\n return Boolean(error)\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] === true\n}\n\nexport type ScopedAttachmentUploadInput = {\n tenantId: string\n organizationId: string\n entityId: string\n recordId: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n tags?: string[]\n assignments?: AttachmentAssignment[]\n partitionCode?: string | null\n maxBytes?: number\n /**\n * Reject a partition flagged public, so a module-owned upload (documents,\n * warranty claims) never lands where an anonymous reader can reach it. The\n * tenant/organization half of that guarantee is not this flag's job: the\n * partition lookup below already matches only a global partition or one owned\n * by this tenant and organization, whether or not the flag is set.\n */\n requirePrivatePartition?: boolean\n /**\n * Persists a module-owned link row inside the same transaction as the\n * Attachment, so a link failure cannot leave a committed orphan attachment.\n * The callback receives only the generated id, never the entity or the\n * storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\ntype QuotaRecoveryScheduler = (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n) => Promise<void>\n\nexport class ScopedAttachmentUploadService {\n constructor(private readonly deps: {\n em: EntityManager\n dataEngine?: DataEngine | null\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: QuotaRecoveryScheduler\n }) {}\n\n async upload(input: ScopedAttachmentUploadInput): Promise<Attachment> {\n const safeName = sanitizeUploadedFileName(input.fileName)\n if (hasDangerousExecutableExtension(safeName)) {\n throw new ScopedAttachmentUploadError('dangerous_executable', 400)\n }\n if (input.buffer.length > (input.maxBytes ?? resolveAttachmentMaxBytes())) {\n throw new ScopedAttachmentUploadError('max_upload_size', 413)\n }\n const mimeType = detectAttachmentMimeType(input.buffer, safeName, input.declaredMimeType ?? '')\n if (isActiveContentAttachment(input.buffer, safeName, mimeType)) {\n throw new ScopedAttachmentUploadError('active_content', 400)\n }\n\n const { em, storageDriverFactory, attachmentQuotaService, attachmentQuotaRecoveryScheduler } = this.deps\n await ensureDefaultPartitions(em)\n const partitionCode = input.partitionCode ?? resolveDefaultPartitionCode(input.entityId)\n const partition = await em.findOne(AttachmentPartition, {\n code: partitionCode,\n $or: [\n { tenantId: null, organizationId: null },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n ],\n })\n if (!partition) throw new ScopedAttachmentUploadError('partition_unavailable', 400)\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new ScopedAttachmentUploadError('partition_unavailable', 403)\n }\n\n const driver = await storageDriverFactory.resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const preparedStoragePath = driver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n })\n if (!preparedStoragePath) {\n throw new ScopedAttachmentUploadError('quota_recovery_unsupported', 500)\n }\n\n let reservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n try {\n reservation = await attachmentQuotaService.reserve({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n bytes: input.buffer.length,\n source: 'attachment',\n storageDriver: driver.key,\n storagePath: preparedStoragePath,\n partitionCode: partition.code,\n })\n await attachmentQuotaRecoveryScheduler({\n reservationId: reservation.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n }, Math.max(1_000, reservation.expiresAt.getTime() - Date.now()))\n await attachmentQuotaService.beginStorage(reservation.id, reservation.leaseToken)\n } catch (error) {\n if (reservation) {\n await attachmentQuotaService.release(reservation.id, reservation.leaseToken).catch(() => undefined)\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') throw new ScopedAttachmentUploadError('quota_exceeded', 413)\n if (code === 'quota_target_exists') throw new ScopedAttachmentUploadError('quota_target_exists', 409)\n throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n }\n\n if (!reservation) throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n\n let storedPath = preparedStoragePath\n try {\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n buffer: input.buffer,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n await attachmentQuotaService.markStored(reservation.id, reservation.leaseToken)\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment storage failed', { err: error })\n throw new ScopedAttachmentUploadError('storage_failed', 500)\n }\n\n let extractedContent: string | null = null\n const wantsLlmOcr = partition.requiresOcr && shouldUseLlmOcr(mimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n if (partition.requiresOcr && !useLlmOcr) {\n try {\n const { filePath, cleanup } = await driver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({ filePath, mimeType })\n } finally {\n await cleanup().catch(() => undefined)\n }\n } catch (error) {\n logger.error('Scoped attachment text extraction failed', { err: error })\n }\n }\n\n let assignments = input.assignments?.slice() ?? []\n assignments = upsertAssignment(assignments, { type: input.entityId, id: input.recordId })\n const metadata = mergeAttachmentMetadata(null, {\n assignments,\n tags: input.tags ?? [],\n })\n const attachmentId = randomUUID()\n let attachment!: Attachment\n\n try {\n await em.transactional(async (tx) => {\n attachment = tx.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n mimeType,\n fileSize: input.buffer.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n assertAttachmentScopeInvariant({ tenantId: attachment.tenantId, organizationId: attachment.organizationId })\n await tx.persist(attachment).flush()\n await input.persistLink?.(tx, attachmentId)\n await attachmentQuotaService.completeAttachment(reservation.id, reservation.leaseToken, tx)\n })\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment persistence failed', { err: error })\n // `persistLink` is where callers run their own authorization (the\n // documents module re-checks the edit capability inside this\n // transaction), so a deliberate HTTP error from it must reach the route\n // with its own status. Flattening it to 500 turns a documented 403 into\n // an apparent server fault.\n if (isCrudHttpError(error)) throw error\n throw new ScopedAttachmentUploadError('persistence_failed', 500)\n }\n\n if (useLlmOcr) {\n requestOcrProcessing(em, attachment, driver, storedPath).catch((error) => {\n logger.error('Scoped attachment OCR scheduling failed', { err: error })\n })\n }\n if (this.deps.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: this.deps.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await this.deps.dataEngine.flushOrmEntityChanges()\n }\n return attachment\n }\n\n private async compensateStorage(\n driver: Awaited<ReturnType<StorageDriverFactory['resolveForPartition']>>,\n partitionCode: string,\n storagePath: string,\n reservation: { id: string; leaseToken: string },\n ): Promise<void> {\n try {\n await (driver.deleteStrict?.(partitionCode, storagePath) ?? driver.delete(partitionCode, storagePath))\n await this.deps.attachmentQuotaService.release(reservation.id, reservation.leaseToken)\n } catch (error) {\n logger.error('Scoped attachment compensation failed', { err: error })\n }\n }\n}\n"],
5
- "mappings": "AAAA;AA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O,MAAM,wCAAwC,EAAE,KAAK,MAAM,CAAC;AAMnE,UAAI,gBAAgB,KAAK,EAAG,OAAM;AAClC,YAAM,IAAI,4BAA4B,sBAAsB,GAAG;AAAA,IACjE;AAEA,QAAI,WAAW;AACb,2BAAqB,IAAI,YAAY,QAAQ,UAAU,EAAE,MAAM,CAAC,UAAU;AACxE,eAAO,MAAM,2CAA2C,EAAE,KAAK,MAAM,CAAC;AAAA,MACxE,CAAC;AAAA,IACH;AACA,QAAI,KAAK,KAAK,YAAY;AACxB,YAAM,oBAAoB;AAAA,QACxB,YAAY,KAAK,KAAK;AAAA,QACtB,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,UACX,IAAI,WAAW;AAAA,UACf,gBAAgB,WAAW,kBAAkB;AAAA,UAC7C,UAAU,WAAW,YAAY;AAAA,QACnC;AAAA,QACA,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AACD,YAAM,KAAK,KAAK,WAAW,sBAAsB;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBACZ,QACA,eACA,aACA,aACe;AACf,QAAI;AACF,aAAO,OAAO,eAAe,eAAe,WAAW,KAAK,OAAO,OAAO,eAAe,WAAW;AACpG,YAAM,KAAK,KAAK,uBAAuB,QAAQ,YAAY,IAAI,YAAY,UAAU;AAAA,IACvF,SAAS,OAAO;AACd,aAAO,MAAM,yCAAyC,EAAE,KAAK,MAAM,CAAC;AAAA,IACtE;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { randomUUID } from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { Attachment, AttachmentPartition } from '../data/entities'\nimport { attachmentCrudEvents, attachmentCrudIndexer } from './crud'\nimport type { StorageDriverFactory } from './drivers'\nimport { buildAttachmentFileUrl } from './imageUrls'\nimport { ensureDefaultPartitions, resolveDefaultPartitionCode } from './partitions'\nimport { extractAttachmentContent } from './textExtraction'\nimport { requestOcrProcessing } from './ocrQueue'\nimport { OcrService, shouldUseLlmOcr } from './ocrService'\nimport { assertAttachmentScopeInvariant } from './access'\nimport {\n mergeAttachmentMetadata,\n upsertAssignment,\n type AttachmentAssignment,\n} from './metadata'\nimport {\n detectAttachmentMimeType,\n hasDangerousExecutableExtension,\n isActiveContentAttachment,\n sanitizeUploadedFileName,\n} from './security'\nimport { resolveAttachmentMaxBytes } from './upload-limits'\nimport type { AttachmentQuotaService } from './quota-service'\n\nconst logger = createLogger('attachments')\n\nexport type ScopedAttachmentUploadErrorCode =\n | 'dangerous_executable'\n | 'max_upload_size'\n | 'active_content'\n | 'partition_unavailable'\n | 'quota_exceeded'\n | 'quota_target_exists'\n | 'quota_unavailable'\n | 'quota_recovery_unsupported'\n | 'storage_failed'\n | 'persistence_failed'\n\n// Use Symbol.for so the marker survives module duplication across bundle\n// boundaries. The production build emits this module into several server\n// chunks, so a consumer's `instanceof` compares against a different copy of the\n// class than the DI-resolved service threw from: the check silently fails, the\n// error escapes the caller's catch, and a deliberate 400/413 surfaces as a 500.\nconst SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER = Symbol.for('@open-mercato/ScopedAttachmentUploadError')\n\nexport class ScopedAttachmentUploadError extends Error {\n readonly [SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] = true\n\n constructor(\n public readonly code: ScopedAttachmentUploadErrorCode,\n public readonly status: number,\n ) {\n super(code)\n this.name = 'ScopedAttachmentUploadError'\n }\n}\n\n/**\n * Bundle-safe check for `ScopedAttachmentUploadError`. Prefer this over\n * `instanceof` at every call site \u2014 the class is duplicated across server\n * chunks, so `instanceof` is only reliable inside this module.\n */\nexport function isScopedAttachmentUploadError(error: unknown): error is ScopedAttachmentUploadError {\n return Boolean(error)\n && typeof error === 'object'\n && (error as Record<symbol, unknown>)[SCOPED_ATTACHMENT_UPLOAD_ERROR_MARKER] === true\n}\n\nexport type ScopedAttachmentUploadInput = {\n tenantId: string\n organizationId: string\n entityId: string\n recordId: string\n fileName: string\n declaredMimeType?: string | null\n buffer: Buffer\n tags?: string[]\n assignments?: AttachmentAssignment[]\n partitionCode?: string | null\n maxBytes?: number\n /**\n * Reject a partition flagged public, so a module-owned upload (documents,\n * warranty claims) never lands where an anonymous reader can reach it. The\n * tenant/organization half of that guarantee is not this flag's job: the\n * partition lookup below already matches only a global partition or one owned\n * by this tenant and organization, whether or not the flag is set.\n */\n requirePrivatePartition?: boolean\n /**\n * Persists a module-owned link row inside the same transaction as the\n * Attachment, so a link failure cannot leave a committed orphan attachment.\n * The callback receives only the generated id, never the entity or the\n * storage implementation.\n */\n persistLink?: (tx: EntityManager, attachmentId: string) => Promise<void> | void\n}\n\ntype QuotaRecoveryScheduler = (\n payload: { reservationId: string; tenantId: string; organizationId: string },\n delayMs: number,\n) => Promise<void>\n\nexport class ScopedAttachmentUploadService {\n constructor(private readonly deps: {\n em: EntityManager\n dataEngine?: DataEngine | null\n storageDriverFactory: StorageDriverFactory\n attachmentQuotaService: AttachmentQuotaService\n attachmentQuotaRecoveryScheduler: QuotaRecoveryScheduler\n }) {}\n\n async upload(input: ScopedAttachmentUploadInput): Promise<Attachment> {\n const safeName = sanitizeUploadedFileName(input.fileName)\n if (hasDangerousExecutableExtension(safeName)) {\n throw new ScopedAttachmentUploadError('dangerous_executable', 400)\n }\n if (input.buffer.length > (input.maxBytes ?? resolveAttachmentMaxBytes())) {\n throw new ScopedAttachmentUploadError('max_upload_size', 413)\n }\n const mimeType = detectAttachmentMimeType(input.buffer, safeName, input.declaredMimeType ?? '')\n if (isActiveContentAttachment(input.buffer, safeName, mimeType)) {\n throw new ScopedAttachmentUploadError('active_content', 400)\n }\n\n const { em, storageDriverFactory, attachmentQuotaService, attachmentQuotaRecoveryScheduler } = this.deps\n await ensureDefaultPartitions(em)\n const partitionCode = input.partitionCode ?? resolveDefaultPartitionCode(input.entityId)\n const partition = await em.findOne(AttachmentPartition, {\n code: partitionCode,\n $or: [\n { tenantId: null, organizationId: null },\n { tenantId: input.tenantId, organizationId: input.organizationId },\n ],\n })\n if (!partition) throw new ScopedAttachmentUploadError('partition_unavailable', 400)\n if (input.requirePrivatePartition && partition.isPublic) {\n throw new ScopedAttachmentUploadError('partition_unavailable', 403)\n }\n\n const driver = await storageDriverFactory.resolveForPartition(partition.code, {\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n })\n const preparedStoragePath = driver.prepareStoragePath?.({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n })\n if (!preparedStoragePath) {\n throw new ScopedAttachmentUploadError('quota_recovery_unsupported', 500)\n }\n\n let reservation: { id: string; leaseToken: string; expiresAt: Date } | null = null\n try {\n reservation = await attachmentQuotaService.reserve({\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n bytes: input.buffer.length,\n source: 'attachment',\n storageDriver: driver.key,\n storagePath: preparedStoragePath,\n partitionCode: partition.code,\n })\n await attachmentQuotaRecoveryScheduler({\n reservationId: reservation.id,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n }, Math.max(1_000, reservation.expiresAt.getTime() - Date.now()))\n await attachmentQuotaService.beginStorage(reservation.id, reservation.leaseToken)\n } catch (error) {\n if (reservation) {\n await attachmentQuotaService.release(reservation.id, reservation.leaseToken).catch(() => undefined)\n }\n const code = (error as { code?: unknown })?.code\n if (code === 'quota_exceeded') throw new ScopedAttachmentUploadError('quota_exceeded', 413)\n if (code === 'quota_target_exists') throw new ScopedAttachmentUploadError('quota_target_exists', 409)\n throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n }\n\n if (!reservation) throw new ScopedAttachmentUploadError('quota_unavailable', 500)\n\n let storedPath = preparedStoragePath\n try {\n const stored = await driver.store({\n partitionCode: partition.code,\n orgId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n buffer: input.buffer,\n storagePath: preparedStoragePath,\n })\n storedPath = stored.storagePath\n await attachmentQuotaService.markStored(reservation.id, reservation.leaseToken)\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment storage failed', { err: error })\n throw new ScopedAttachmentUploadError('storage_failed', 500)\n }\n\n let extractedContent: string | null = null\n const wantsLlmOcr = partition.requiresOcr && shouldUseLlmOcr(mimeType, safeName)\n const ocrService = wantsLlmOcr ? new OcrService() : null\n const useLlmOcr = Boolean(wantsLlmOcr && ocrService?.available)\n if (partition.requiresOcr && !useLlmOcr) {\n try {\n const { filePath, cleanup } = await driver.toLocalPath(partition.code, storedPath)\n try {\n extractedContent = await extractAttachmentContent({ filePath, mimeType })\n } finally {\n await cleanup().catch(() => undefined)\n }\n } catch (error) {\n logger.error('Scoped attachment text extraction failed', { err: error })\n }\n }\n\n let assignments = input.assignments?.slice() ?? []\n assignments = upsertAssignment(assignments, { type: input.entityId, id: input.recordId })\n const metadata = mergeAttachmentMetadata(null, {\n assignments,\n tags: input.tags ?? [],\n })\n const attachmentId = randomUUID()\n let attachment!: Attachment\n\n try {\n await em.transactional(async (tx) => {\n attachment = tx.create(Attachment, {\n id: attachmentId,\n entityId: input.entityId,\n recordId: input.recordId,\n organizationId: input.organizationId,\n tenantId: input.tenantId,\n fileName: safeName,\n mimeType,\n fileSize: input.buffer.length,\n partitionCode: partition.code,\n storageDriver: partition.storageDriver || 'local',\n storagePath: storedPath,\n url: buildAttachmentFileUrl(attachmentId),\n content: extractedContent,\n storageMetadata: metadata,\n })\n assertAttachmentScopeInvariant({ tenantId: attachment.tenantId, organizationId: attachment.organizationId })\n await tx.persist(attachment).flush()\n await input.persistLink?.(tx, attachmentId)\n await attachmentQuotaService.completeAttachment(reservation.id, reservation.leaseToken, tx)\n })\n } catch (error) {\n await this.compensateStorage(driver, partition.code, storedPath, reservation)\n logger.error('Scoped attachment persistence failed', { err: error })\n // `persistLink` is where callers run their own authorization (the\n // documents module re-checks the edit capability inside this\n // transaction), so a deliberate HTTP error from it must reach the route\n // with its own status. Flattening it to 500 turns a documented 403 into\n // an apparent server fault.\n if (isCrudHttpError(error)) throw error\n throw new ScopedAttachmentUploadError('persistence_failed', 500)\n }\n\n if (useLlmOcr) {\n try {\n await requestOcrProcessing(em, attachment, driver, storedPath)\n } catch (error) {\n logger.error('Scoped attachment OCR scheduling failed', { err: error })\n }\n }\n if (this.deps.dataEngine) {\n await emitCrudSideEffects({\n dataEngine: this.deps.dataEngine,\n action: 'created',\n entity: attachment,\n identifiers: {\n id: attachment.id,\n organizationId: attachment.organizationId ?? null,\n tenantId: attachment.tenantId ?? null,\n },\n events: attachmentCrudEvents,\n indexer: attachmentCrudIndexer,\n })\n await this.deps.dataEngine.flushOrmEntityChanges()\n }\n return attachment\n }\n\n private async compensateStorage(\n driver: Awaited<ReturnType<StorageDriverFactory['resolveForPartition']>>,\n partitionCode: string,\n storagePath: string,\n reservation: { id: string; leaseToken: string },\n ): Promise<void> {\n try {\n await (driver.deleteStrict?.(partitionCode, storagePath) ?? driver.delete(partitionCode, storagePath))\n await this.deps.attachmentQuotaService.release(reservation.id, reservation.leaseToken)\n } catch (error) {\n logger.error('Scoped attachment compensation failed', { err: error })\n }\n }\n}\n"],
5
+ "mappings": "AAAA;AAAA,SAAS,kBAAkB;AAG3B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,YAAY,2BAA2B;AAChD,SAAS,sBAAsB,6BAA6B;AAE5D,SAAS,8BAA8B;AACvC,SAAS,yBAAyB,mCAAmC;AACrE,SAAS,gCAAgC;AACzC,SAAS,4BAA4B;AACrC,SAAS,YAAY,uBAAuB;AAC5C,SAAS,sCAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iCAAiC;AAG1C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;AAAA,QACR,QAAQ;AAAA,QACR,aAAa;AAAA,UACX,IAAI,WAAW;AAAA,UACf,gBAAgB,WAAW,kBAAkB;AAAA,UAC7C,UAAU,WAAW,YAAY;AAAA,QACnC;AAAA,QACA,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AACD,YAAM,KAAK,KAAK,WAAW,sBAAsB;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAc,kBACZ,QACA,eACA,aACA,aACe;AACf,QAAI;AACF,aAAO,OAAO,eAAe,eAAe,WAAW,KAAK,OAAO,OAAO,eAAe,WAAW;AACpG,YAAM,KAAK,KAAK,uBAAuB,QAAQ,YAAY,IAAI,YAAY,UAAU;AAAA,IACvF,SAAS,OAAO;AACd,aAAO,MAAM,yCAAyC,EAAE,KAAK,MAAM,CAAC;AAAA,IACtE;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,9 @@
1
1
  import fs from "fs/promises";
2
2
  import path from "path";
3
3
  import { createRequire } from "module";
4
+ import { createLogger } from "@open-mercato/shared/lib/logger";
5
+ import { resolveMaxOcrPages, resolvePdfPageIterationLimit } from "./ocrLimits.js";
6
+ const logger = createLogger("attachments").child({ component: "text-extraction" });
4
7
  const moduleRequire = createRequire(path.join(process.cwd(), "package.json"));
5
8
  const pdfJsPackageRoot = path.dirname(moduleRequire.resolve("pdfjs-dist/package.json"));
6
9
  const PDF_CMAP_URL = `${path.join(pdfJsPackageRoot, "cmaps")}${path.sep}`;
@@ -44,8 +47,17 @@ async function extractPdfText(filePath) {
44
47
  });
45
48
  const pdfDocument = await loadingTask.promise;
46
49
  const textParts = [];
50
+ const maxPages = resolveMaxOcrPages();
51
+ const pageLimit = resolvePdfPageIterationLimit(pdfDocument.numPages, maxPages);
52
+ if (pdfDocument.numPages > pageLimit) {
53
+ logger.warn("PDF page count exceeds text-extraction cap; truncating", {
54
+ numPages: pdfDocument.numPages,
55
+ maxPages: pageLimit,
56
+ filePath
57
+ });
58
+ }
47
59
  try {
48
- for (let pageNumber = 1; pageNumber <= pdfDocument.numPages; pageNumber += 1) {
60
+ for (let pageNumber = 1; pageNumber <= pageLimit; pageNumber += 1) {
49
61
  const page = await pdfDocument.getPage(pageNumber);
50
62
  try {
51
63
  const textContent = await page.getTextContent();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/attachments/lib/textExtraction.ts"],
4
- "sourcesContent": ["import fs from 'fs/promises'\nimport path from 'path'\nimport { createRequire } from 'module'\n\n// NOTE: child_process is intentionally NOT imported here.\n// This module MUST NOT shell out to any external binary for content extraction.\n// All extraction must use pure-JS libraries. See HUNT-PARSER-01.\n\nconst moduleRequire = createRequire(path.join(process.cwd(), 'package.json'))\nconst pdfJsPackageRoot = path.dirname(moduleRequire.resolve('pdfjs-dist/package.json'))\nconst PDF_CMAP_URL = `${path.join(pdfJsPackageRoot, 'cmaps')}${path.sep}`\nconst PDF_STANDARD_FONT_DATA_URL = `${path.join(pdfJsPackageRoot, 'standard_fonts')}${path.sep}`\n\ntype ExtractParams = {\n filePath: string\n mimeType?: string | null\n}\n\nfunction isImage(mimeType?: string | null, filePath?: string | null): boolean {\n const normalized = (mimeType || '').toLowerCase()\n if (normalized.startsWith('image/')) return true\n if (filePath) {\n const ext = path.extname(filePath).toLowerCase()\n return ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.tiff'].includes(ext)\n }\n return false\n}\n\nfunction isPlainText(mimeType: string, ext: string): boolean {\n return mimeType.startsWith('text/')\n || ext === '.txt'\n || ext === '.md'\n || ext === '.csv'\n || ext === '.log'\n}\n\nfunction isPdf(mimeType: string, ext: string): boolean {\n return mimeType === 'application/pdf' || ext === '.pdf'\n}\n\nfunction isDocx(mimeType: string, ext: string): boolean {\n // mammoth supports only Open XML .docx, not legacy binary .doc files.\n return (\n mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'\n || ext === '.docx'\n )\n}\n\nasync function extractPlainText(filePath: string): Promise<string | null> {\n try {\n const text = await fs.readFile(filePath, 'utf8')\n const trimmed = text.trim()\n return trimmed.length > 0 ? trimmed : null\n } catch {\n return null\n }\n}\n\nasync function extractPdfText(filePath: string): Promise<string | null> {\n try {\n const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs')\n const data = new Uint8Array(await fs.readFile(filePath))\n const loadingTask = getDocument({\n data,\n cMapUrl: PDF_CMAP_URL,\n cMapPacked: true,\n standardFontDataUrl: PDF_STANDARD_FONT_DATA_URL,\n })\n const pdfDocument = await loadingTask.promise\n const textParts: string[] = []\n try {\n for (let pageNumber = 1; pageNumber <= pdfDocument.numPages; pageNumber += 1) {\n const page = await pdfDocument.getPage(pageNumber)\n try {\n const textContent = await page.getTextContent()\n const items = (textContent as any).items as Array<{ str?: string }> | undefined\n if (Array.isArray(items)) {\n const pageText = items\n .map((item) => (typeof item?.str === 'string' ? item.str : ''))\n .filter((s) => s.length > 0)\n .join(' ')\n if (pageText.trim()) textParts.push(pageText.trim())\n }\n } finally {\n page.cleanup()\n }\n }\n } finally {\n await loadingTask.destroy()\n }\n const result = textParts.join('\\n').trim()\n return result.length > 0 ? result : null\n } catch {\n return null\n }\n}\n\nasync function extractDocxText(filePath: string): Promise<string | null> {\n try {\n const mammoth = await import('mammoth')\n const result = await mammoth.extractRawText({ path: filePath })\n const trimmed = result.value.trim()\n return trimmed.length > 0 ? trimmed : null\n } catch {\n return null\n }\n}\n\nexport async function extractAttachmentContent(params: ExtractParams): Promise<string | null> {\n const { filePath, mimeType } = params\n if (!filePath) return null\n if (isImage(mimeType, filePath)) return null\n\n const normalized = (mimeType || '').toLowerCase()\n const ext = path.extname(filePath).toLowerCase()\n\n if (isPlainText(normalized, ext)) {\n return extractPlainText(filePath)\n }\n\n if (isPdf(normalized, ext)) {\n return extractPdfText(filePath)\n }\n\n if (isDocx(normalized, ext)) {\n return extractDocxText(filePath)\n }\n\n // XLSX, PPTX, MSG and other Office formats: no safe pure-JS extractor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AAS,IAAI;AAC/B,MAAI,CAAC,SAAU,QAAO;AACtB,MAAI,QAAQ,UAAU,QAAQ,EAAG,QAAO;AAExC,QAAM,cAAc,YAAY,IAAI,YAAY;AAChD,QAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAE/C,MAAI,YAAY,YAAY,GAAG,GAAG;AAChC,WAAO,iBAAiB,QAAQ;AAAA,EAClC;AAEA,MAAI,MAAM,YAAY,GAAG,GAAG;AAC1B,WAAO,eAAe,QAAQ;AAAA,EAChC;AAEA,MAAI,OAAO,YAAY,GAAG,GAAG;AAC3B,WAAO,gBAAgB,QAAQ;AAAA,EACjC;AAIA,SAAO;AACT;",
4
+ "sourcesContent": ["import fs from 'fs/promises'\nimport path from 'path'\nimport { createRequire } from 'module'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { resolveMaxOcrPages, resolvePdfPageIterationLimit } from './ocrLimits'\n\nconst logger = createLogger('attachments').child({ component: 'text-extraction' })\n\n// NOTE: child_process is intentionally NOT imported here.\n// This module MUST NOT shell out to any external binary for content extraction.\n// All extraction must use pure-JS libraries. See HUNT-PARSER-01.\n\nconst moduleRequire = createRequire(path.join(process.cwd(), 'package.json'))\nconst pdfJsPackageRoot = path.dirname(moduleRequire.resolve('pdfjs-dist/package.json'))\nconst PDF_CMAP_URL = `${path.join(pdfJsPackageRoot, 'cmaps')}${path.sep}`\nconst PDF_STANDARD_FONT_DATA_URL = `${path.join(pdfJsPackageRoot, 'standard_fonts')}${path.sep}`\n\ntype ExtractParams = {\n filePath: string\n mimeType?: string | null\n}\n\nfunction isImage(mimeType?: string | null, filePath?: string | null): boolean {\n const normalized = (mimeType || '').toLowerCase()\n if (normalized.startsWith('image/')) return true\n if (filePath) {\n const ext = path.extname(filePath).toLowerCase()\n return ['.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.tiff'].includes(ext)\n }\n return false\n}\n\nfunction isPlainText(mimeType: string, ext: string): boolean {\n return mimeType.startsWith('text/')\n || ext === '.txt'\n || ext === '.md'\n || ext === '.csv'\n || ext === '.log'\n}\n\nfunction isPdf(mimeType: string, ext: string): boolean {\n return mimeType === 'application/pdf' || ext === '.pdf'\n}\n\nfunction isDocx(mimeType: string, ext: string): boolean {\n // mammoth supports only Open XML .docx, not legacy binary .doc files.\n return (\n mimeType === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'\n || ext === '.docx'\n )\n}\n\nasync function extractPlainText(filePath: string): Promise<string | null> {\n try {\n const text = await fs.readFile(filePath, 'utf8')\n const trimmed = text.trim()\n return trimmed.length > 0 ? trimmed : null\n } catch {\n return null\n }\n}\n\nasync function extractPdfText(filePath: string): Promise<string | null> {\n try {\n const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs')\n const data = new Uint8Array(await fs.readFile(filePath))\n const loadingTask = getDocument({\n data,\n cMapUrl: PDF_CMAP_URL,\n cMapPacked: true,\n standardFontDataUrl: PDF_STANDARD_FONT_DATA_URL,\n })\n const pdfDocument = await loadingTask.promise\n const textParts: string[] = []\n const maxPages = resolveMaxOcrPages()\n const pageLimit = resolvePdfPageIterationLimit(pdfDocument.numPages, maxPages)\n if (pdfDocument.numPages > pageLimit) {\n logger.warn('PDF page count exceeds text-extraction cap; truncating', {\n numPages: pdfDocument.numPages,\n maxPages: pageLimit,\n filePath,\n })\n }\n try {\n for (let pageNumber = 1; pageNumber <= pageLimit; pageNumber += 1) {\n const page = await pdfDocument.getPage(pageNumber)\n try {\n const textContent = await page.getTextContent()\n const items = (textContent as any).items as Array<{ str?: string }> | undefined\n if (Array.isArray(items)) {\n const pageText = items\n .map((item) => (typeof item?.str === 'string' ? item.str : ''))\n .filter((s) => s.length > 0)\n .join(' ')\n if (pageText.trim()) textParts.push(pageText.trim())\n }\n } finally {\n page.cleanup()\n }\n }\n } finally {\n await loadingTask.destroy()\n }\n const result = textParts.join('\\n').trim()\n return result.length > 0 ? result : null\n } catch {\n return null\n }\n}\n\nasync function extractDocxText(filePath: string): Promise<string | null> {\n try {\n const mammoth = await import('mammoth')\n const result = await mammoth.extractRawText({ path: filePath })\n const trimmed = result.value.trim()\n return trimmed.length > 0 ? trimmed : null\n } catch {\n return null\n }\n}\n\nexport async function extractAttachmentContent(params: ExtractParams): Promise<string | null> {\n const { filePath, mimeType } = params\n if (!filePath) return null\n if (isImage(mimeType, filePath)) return null\n\n const normalized = (mimeType || '').toLowerCase()\n const ext = path.extname(filePath).toLowerCase()\n\n if (isPlainText(normalized, ext)) {\n return extractPlainText(filePath)\n }\n\n if (isPdf(normalized, ext)) {\n return extractPdfText(filePath)\n }\n\n if (isDocx(normalized, ext)) {\n return extractDocxText(filePath)\n }\n\n // XLSX, PPTX, MSG and other Office formats: no safe pure-JS extractor available yet.\n // Return null rather than shelling out to an external binary.\n return null\n}\n"],
5
+ "mappings": "AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB,oCAAoC;AAEjE,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAMjF,MAAM,gBAAgB,cAAc,KAAK,KAAK,QAAQ,IAAI,GAAG,cAAc,CAAC;AAC5E,MAAM,mBAAmB,KAAK,QAAQ,cAAc,QAAQ,yBAAyB,CAAC;AACtF,MAAM,eAAe,GAAG,KAAK,KAAK,kBAAkB,OAAO,CAAC,GAAG,KAAK,GAAG;AACvE,MAAM,6BAA6B,GAAG,KAAK,KAAK,kBAAkB,gBAAgB,CAAC,GAAG,KAAK,GAAG;AAO9F,SAAS,QAAQ,UAA0B,UAAmC;AAC5E,QAAM,cAAc,YAAY,IAAI,YAAY;AAChD,MAAI,WAAW,WAAW,QAAQ,EAAG,QAAO;AAC5C,MAAI,UAAU;AACZ,UAAM,MAAM,KAAK,QAAQ,QAAQ,EAAE,YAAY;AAC/C,WAAO,CAAC,QAAQ,QAAQ,SAAS,QAAQ,QAAQ,SAAS,OAAO,EAAE,SAAS,G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 const updateCategoryCommand = {
403
403
  ],
404
404
  { transaction: true }
405
405
  );
406
- const resetValues = buildCustomFieldResetMap(payload?.after?.custom ?? void 0, before.custom ?? void 0);
406
+ const resetValues = buildCustomFieldResetMap(before.custom ?? void 0, payload?.after?.custom ?? void 0);
407
407
  if (Object.keys(resetValues).length) {
408
408
  await setCustomFieldsIfAny({
409
409
  dataEngine: ctx.container.resolve("dataEngine"),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/catalog/commands/categories.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { buildChanges, requireId, parseWithCustomFields, setCustomFieldsIfAny, emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { loadCustomFieldSnapshot, buildCustomFieldResetMap } from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CatalogProductCategory } from '../data/entities'\nimport {\n categoryCreateSchema,\n categoryUpdateSchema,\n type CategoryCreateInput,\n type CategoryUpdateInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { rebuildCategoryHierarchyForOrganization } from '../lib/categoryHierarchy'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { E } from '#generated/entities.ids.generated'\n\nconst categoryCrudEvents: CrudEventsConfig = {\n module: 'catalog',\n entity: 'category',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype CategorySnapshot = {\n id: string\n organizationId: string\n tenantId: string\n name: string\n slug: string | null\n description: string | null\n parentId: string | null\n rootId: string | null\n treePath: string | null\n depth: number\n ancestorIds: string[]\n childIds: string[]\n descendantIds: string[]\n isActive: boolean\n createdAt: string\n updatedAt: string\n custom?: Record<string, unknown> | null\n}\n\ntype CategoryUndoPayload = {\n before?: CategorySnapshot | null\n after?: CategorySnapshot | null\n}\n\nconst CATEGORY_CHANGE_KEYS = [\n 'name',\n 'slug',\n 'description',\n 'parentId',\n 'rootId',\n 'treePath',\n 'isActive',\n] as const satisfies readonly string[]\n\nasync function loadCategorySnapshot(em: EntityManager, id: string): Promise<CategorySnapshot | null> {\n const record = await em.findOne(CatalogProductCategory, { id })\n if (!record) return null\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n return {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n name: record.name,\n slug: record.slug ?? null,\n description: record.description ?? null,\n parentId: record.parentId ?? null,\n rootId: record.rootId ?? null,\n treePath: record.treePath ?? null,\n depth: record.depth ?? 0,\n ancestorIds: Array.isArray(record.ancestorIds) ? [...record.ancestorIds] : [],\n childIds: Array.isArray(record.childIds) ? [...record.childIds] : [],\n descendantIds: Array.isArray(record.descendantIds) ? [...record.descendantIds] : [],\n isActive: !!record.isActive,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n custom: custom && Object.keys(custom).length ? custom : null,\n }\n}\n\nasync function assertParentScope(\n em: EntityManager,\n parentId: string | null,\n organizationId: string,\n tenantId: string\n): Promise<string | null> {\n if (!parentId) return null\n const parent = await em.findOne(CatalogProductCategory, {\n id: parentId,\n organizationId,\n tenantId,\n deletedAt: null,\n })\n if (!parent) {\n throw new CrudHttpError(400, { error: 'Parent category not found or inaccessible.' })\n }\n if (parent.id === parentId) return parent.id\n return String(parent.id)\n}\n\nfunction normalizeSlug(slug?: string | null): string | null {\n if (typeof slug !== 'string') return null\n const trimmed = slug.trim().toLowerCase()\n return trimmed.length ? trimmed : null\n}\n\nfunction categorySeedFromSnapshot(snapshot: CategorySnapshot): Record<string, unknown> {\n return {\n id: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n name: snapshot.name,\n slug: snapshot.slug,\n description: snapshot.description,\n parentId: snapshot.parentId,\n rootId: snapshot.rootId,\n treePath: snapshot.treePath,\n depth: snapshot.depth,\n ancestorIds: snapshot.ancestorIds,\n childIds: snapshot.childIds,\n descendantIds: snapshot.descendantIds,\n isActive: snapshot.isActive,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n }\n}\n\nconst createCategoryCommand: CommandHandler<CategoryCreateInput, { categoryId: string }> = {\n id: 'catalog.categories.create',\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryCreateSchema, input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists for this organization.' })\n }\n }\n const parentId = parsed.parentId ? String(parsed.parentId) : null\n const resolvedParent = await assertParentScope(em, parentId, parsed.organizationId, parsed.tenantId)\n\n const now = new Date()\n const record = em.create(CatalogProductCategory, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n name: parsed.name,\n slug,\n description: parsed.description?.trim()?.length ? parsed.description.trim() : null,\n parentId: resolvedParent,\n depth: 0,\n ancestorIds: [],\n childIds: [],\n descendantIds: [],\n isActive: parsed.isActive !== false,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (ctx.bulkImport?.skipDerivedRebuild) return\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const after = snapshots.after as CategorySnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.create', 'Create catalog category'),\n resourceKind: 'catalog.category',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: after.id })\n if (!record) return\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(undefined, after.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n values: resetValues,\n })\n }\n },\n redo: makeCreateRedo<CatalogProductCategory, CategorySnapshot, CategoryCreateInput, { categoryId: string }>({\n entityClass: CatalogProductCategory,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: categorySeedFromSnapshot,\n buildResult: (entity) => ({ categoryId: entity.id }),\n events: categoryCrudEvents,\n afterRestore: async ({ em, ctx, entity, snapshot }) => {\n await rebuildCategoryHierarchyForOrganization(em, entity.organizationId, entity.tenantId)\n if (snapshot.custom && Object.keys(snapshot.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: entity.id,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n values: snapshot.custom,\n })\n }\n },\n }),\n}\n\nconst updateCategoryCommand: CommandHandler<CategoryUpdateInput, { categoryId: string }> = {\n id: 'catalog.categories.update',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryUpdateSchema, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: parsed.id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n if (parsed.name !== undefined) {\n record.name = parsed.name\n }\n\n if (parsed.slug !== undefined) {\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug !== record.slug) {\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n deletedAt: null,\n id: { $ne: record.id },\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists.' })\n }\n }\n record.slug = slug\n }\n }\n\n if (parsed.description !== undefined) {\n record.description = parsed.description?.trim()?.length ? parsed.description.trim() : null\n }\n\n if (parsed.parentId !== undefined) {\n const requestedParent = parsed.parentId ? String(parsed.parentId) : null\n const safeParent = requestedParent && requestedParent !== record.id ? requestedParent : null\n record.parentId = await assertParentScope(em, safeParent, record.organizationId, record.tenantId)\n }\n\n if (parsed.isActive !== undefined) {\n record.isActive = parsed.isActive\n }\n\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n const after = snapshots.after as CategorySnapshot | undefined\n if (!before || !after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.update', 'Update catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: buildChanges(before as Record<string, unknown>, after as Record<string, unknown>, CATEGORY_CHANGE_KEYS),\n payload: {\n undo: { before, after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n record.isActive = before.isActive\n record.deletedAt = null\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(payload?.after?.custom ?? undefined, before.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: resetValues,\n })\n }\n },\n}\n\nconst deleteCategoryCommand: CommandHandler<{ id?: string }, { categoryId: string }> = {\n id: 'catalog.categories.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n const baseEm = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(baseEm, id)\n\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const resetValues = buildCustomFieldResetMap(snapshot.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: resetValues,\n })\n }\n }\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n buildLog: async ({ ctx, snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.delete', 'Delete catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.deletedAt = null\n record.isActive = before.isActive\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n if (before.custom && Object.keys(before.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: before.custom,\n })\n }\n },\n}\n\nregisterCommand(createCategoryCommand)\nregisterCommand(updateCategoryCommand)\nregisterCommand(deleteCategoryCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,cAAc,WAAW,uBAAuB,sBAAsB,2BAA2B;AAC1G,SAAS,yBAAyB,gCAAgC;AAClE,SAAS,uBAAuB;AAEhC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B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C9C,UAAU,EAAE,QAAQ;AAAA,QACpB,UAAU,OAAO;AAAA,QACjB,gBAAgB,OAAO;AAAA,QACvB,UAAU,OAAO;AAAA,QACjB,QAAQ,OAAO;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { buildChanges, requireId, parseWithCustomFields, setCustomFieldsIfAny, emitCrudSideEffects } from '@open-mercato/shared/lib/commands/helpers'\nimport { loadCustomFieldSnapshot, buildCustomFieldResetMap } from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CatalogProductCategory } from '../data/entities'\nimport {\n categoryCreateSchema,\n categoryUpdateSchema,\n type CategoryCreateInput,\n type CategoryUpdateInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope, extractUndoPayload } from './shared'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { rebuildCategoryHierarchyForOrganization } from '../lib/categoryHierarchy'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport { E } from '#generated/entities.ids.generated'\n\nconst categoryCrudEvents: CrudEventsConfig = {\n module: 'catalog',\n entity: 'category',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype CategorySnapshot = {\n id: string\n organizationId: string\n tenantId: string\n name: string\n slug: string | null\n description: string | null\n parentId: string | null\n rootId: string | null\n treePath: string | null\n depth: number\n ancestorIds: string[]\n childIds: string[]\n descendantIds: string[]\n isActive: boolean\n createdAt: string\n updatedAt: string\n custom?: Record<string, unknown> | null\n}\n\ntype CategoryUndoPayload = {\n before?: CategorySnapshot | null\n after?: CategorySnapshot | null\n}\n\nconst CATEGORY_CHANGE_KEYS = [\n 'name',\n 'slug',\n 'description',\n 'parentId',\n 'rootId',\n 'treePath',\n 'isActive',\n] as const satisfies readonly string[]\n\nasync function loadCategorySnapshot(em: EntityManager, id: string): Promise<CategorySnapshot | null> {\n const record = await em.findOne(CatalogProductCategory, { id })\n if (!record) return null\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n })\n return {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n name: record.name,\n slug: record.slug ?? null,\n description: record.description ?? null,\n parentId: record.parentId ?? null,\n rootId: record.rootId ?? null,\n treePath: record.treePath ?? null,\n depth: record.depth ?? 0,\n ancestorIds: Array.isArray(record.ancestorIds) ? [...record.ancestorIds] : [],\n childIds: Array.isArray(record.childIds) ? [...record.childIds] : [],\n descendantIds: Array.isArray(record.descendantIds) ? [...record.descendantIds] : [],\n isActive: !!record.isActive,\n createdAt: record.createdAt.toISOString(),\n updatedAt: record.updatedAt.toISOString(),\n custom: custom && Object.keys(custom).length ? custom : null,\n }\n}\n\nasync function assertParentScope(\n em: EntityManager,\n parentId: string | null,\n organizationId: string,\n tenantId: string\n): Promise<string | null> {\n if (!parentId) return null\n const parent = await em.findOne(CatalogProductCategory, {\n id: parentId,\n organizationId,\n tenantId,\n deletedAt: null,\n })\n if (!parent) {\n throw new CrudHttpError(400, { error: 'Parent category not found or inaccessible.' })\n }\n if (parent.id === parentId) return parent.id\n return String(parent.id)\n}\n\nfunction normalizeSlug(slug?: string | null): string | null {\n if (typeof slug !== 'string') return null\n const trimmed = slug.trim().toLowerCase()\n return trimmed.length ? trimmed : null\n}\n\nfunction categorySeedFromSnapshot(snapshot: CategorySnapshot): Record<string, unknown> {\n return {\n id: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n name: snapshot.name,\n slug: snapshot.slug,\n description: snapshot.description,\n parentId: snapshot.parentId,\n rootId: snapshot.rootId,\n treePath: snapshot.treePath,\n depth: snapshot.depth,\n ancestorIds: snapshot.ancestorIds,\n childIds: snapshot.childIds,\n descendantIds: snapshot.descendantIds,\n isActive: snapshot.isActive,\n createdAt: new Date(snapshot.createdAt),\n updatedAt: new Date(snapshot.updatedAt),\n }\n}\n\nconst createCategoryCommand: CommandHandler<CategoryCreateInput, { categoryId: string }> = {\n id: 'catalog.categories.create',\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryCreateSchema, input)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n deletedAt: null,\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists for this organization.' })\n }\n }\n const parentId = parsed.parentId ? String(parsed.parentId) : null\n const resolvedParent = await assertParentScope(em, parentId, parsed.organizationId, parsed.tenantId)\n\n const now = new Date()\n const record = em.create(CatalogProductCategory, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n name: parsed.name,\n slug,\n description: parsed.description?.trim()?.length ? parsed.description.trim() : null,\n parentId: resolvedParent,\n depth: 0,\n ancestorIds: [],\n childIds: [],\n descendantIds: [],\n isActive: parsed.isActive !== false,\n createdAt: now,\n updatedAt: now,\n })\n em.persist(record)\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n if (ctx.bulkImport?.skipDerivedRebuild) return\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const after = snapshots.after as CategorySnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.create', 'Create catalog category'),\n resourceKind: 'catalog.category',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: after.id })\n if (!record) return\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(undefined, after.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n values: resetValues,\n })\n }\n },\n redo: makeCreateRedo<CatalogProductCategory, CategorySnapshot, CategoryCreateInput, { categoryId: string }>({\n entityClass: CatalogProductCategory,\n getSnapshotId: (snapshot) => snapshot.id,\n seedFromSnapshot: categorySeedFromSnapshot,\n buildResult: (entity) => ({ categoryId: entity.id }),\n events: categoryCrudEvents,\n afterRestore: async ({ em, ctx, entity, snapshot }) => {\n await rebuildCategoryHierarchyForOrganization(em, entity.organizationId, entity.tenantId)\n if (snapshot.custom && Object.keys(snapshot.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: entity.id,\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n values: snapshot.custom,\n })\n }\n },\n }),\n}\n\nconst updateCategoryCommand: CommandHandler<CategoryUpdateInput, { categoryId: string }> = {\n id: 'catalog.categories.update',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const { parsed, custom } = parseWithCustomFields(categoryUpdateSchema, input)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id: parsed.id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n if (parsed.name !== undefined) {\n record.name = parsed.name\n }\n\n if (parsed.slug !== undefined) {\n const slug = normalizeSlug(parsed.slug ?? null)\n if (slug !== record.slug) {\n if (slug) {\n const conflict = await em.findOne(CatalogProductCategory, {\n slug,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n deletedAt: null,\n id: { $ne: record.id },\n })\n if (conflict) {\n throw new CrudHttpError(400, { error: 'Category slug already exists.' })\n }\n }\n record.slug = slug\n }\n }\n\n if (parsed.description !== undefined) {\n record.description = parsed.description?.trim()?.length ? parsed.description.trim() : null\n }\n\n if (parsed.parentId !== undefined) {\n const requestedParent = parsed.parentId ? String(parsed.parentId) : null\n const safeParent = requestedParent && requestedParent !== record.id ? requestedParent : null\n record.parentId = await assertParentScope(em, safeParent, record.organizationId, record.tenantId)\n }\n\n if (parsed.isActive !== undefined) {\n record.isActive = parsed.isActive\n }\n\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n values: custom,\n })\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadCategorySnapshot(em, result.categoryId)\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n const after = snapshots.after as CategorySnapshot | undefined\n if (!before || !after) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.update', 'Update catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes: buildChanges(before as Record<string, unknown>, after as Record<string, unknown>, CATEGORY_CHANGE_KEYS),\n payload: {\n undo: { before, after } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n record.isActive = before.isActive\n record.deletedAt = null\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n const resetValues = buildCustomFieldResetMap(before.custom ?? undefined, payload?.after?.custom ?? undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: resetValues,\n })\n }\n },\n}\n\nconst deleteCategoryCommand: CommandHandler<{ id?: string }, { categoryId: string }> = {\n id: 'catalog.categories.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(em, id)\n if (snapshot) {\n ensureTenantScope(ctx, snapshot.tenantId)\n ensureOrganizationScope(ctx, snapshot.organizationId)\n }\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Category id is required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const record = await em.findOne(CatalogProductCategory, { id, deletedAt: null })\n if (!record) throw new CrudHttpError(404, { error: 'Catalog category not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n const baseEm = ctx.container.resolve('em') as EntityManager\n const snapshot = await loadCategorySnapshot(baseEm, id)\n\n record.deletedAt = new Date()\n record.isActive = false\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, record.organizationId, record.tenantId)\n },\n ],\n { transaction: true }\n )\n if (snapshot?.custom && Object.keys(snapshot.custom).length) {\n const resetValues = buildCustomFieldResetMap(snapshot.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n values: resetValues,\n })\n }\n }\n const de = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n events: categoryCrudEvents,\n })\n return { categoryId: record.id }\n },\n buildLog: async ({ ctx, snapshots }) => {\n const before = snapshots.before as CategorySnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('catalog.audit.categories.delete', 'Delete catalog category'),\n resourceKind: 'catalog.category',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CategoryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CategoryUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let record = await em.findOne(CatalogProductCategory, { id: before.id })\n if (!record) {\n record = em.create(CatalogProductCategory, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n name: before.name,\n slug: before.slug,\n description: before.description,\n parentId: before.parentId,\n rootId: before.rootId,\n treePath: before.treePath,\n depth: before.depth,\n ancestorIds: before.ancestorIds,\n childIds: before.childIds,\n descendantIds: before.descendantIds,\n isActive: before.isActive,\n createdAt: new Date(before.createdAt),\n updatedAt: new Date(before.updatedAt),\n })\n em.persist(record)\n } else {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n record.deletedAt = null\n record.isActive = before.isActive\n record.name = before.name\n record.slug = before.slug\n record.description = before.description\n record.parentId = before.parentId\n record.rootId = before.rootId\n record.treePath = before.treePath\n record.depth = before.depth\n record.ancestorIds = before.ancestorIds\n record.childIds = before.childIds\n record.descendantIds = before.descendantIds\n }\n await withAtomicFlush(\n em,\n [\n () => em.flush(),\n async () => {\n await rebuildCategoryHierarchyForOrganization(em, before.organizationId, before.tenantId)\n },\n ],\n { transaction: true }\n )\n if (before.custom && Object.keys(before.custom).length) {\n await setCustomFieldsIfAny({\n dataEngine: ctx.container.resolve('dataEngine'),\n entityId: E.catalog.catalog_product_category,\n recordId: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n values: before.custom,\n })\n }\n },\n}\n\nregisterCommand(createCategoryCommand)\nregisterCommand(updateCategoryCommand)\nregisterCommand(deleteCategoryCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,cAAc,WAAW,uBAAuB,sBAAsB,2BAA2B;AAC1G,SAAS,yBAAyB,gCAAgC;AAClE,SAAS,uBAAuB;AAEhC,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,yBAAyB,mBAAmB,0BAA0B;AA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