@open-mercato/core 0.9.1-develop.7473.1.de5b22888f → 0.9.1-develop.7475.1.28ca93ed97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (597) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/dist/generated/entities/catalog_price_history_entry/index.js +53 -0
  3. package/dist/generated/entities/catalog_price_history_entry/index.js.map +7 -0
  4. package/dist/generated/entities/customer_group_terms/index.js +2 -0
  5. package/dist/generated/entities/customer_group_terms/index.js.map +2 -2
  6. package/dist/generated/entities/ecommerce_store/index.js +33 -0
  7. package/dist/generated/entities/ecommerce_store/index.js.map +7 -0
  8. package/dist/generated/entities/ecommerce_store_channel_binding/index.js +29 -0
  9. package/dist/generated/entities/ecommerce_store_channel_binding/index.js.map +7 -0
  10. package/dist/generated/entities/ecommerce_store_domain_binding/index.js +23 -0
  11. package/dist/generated/entities/ecommerce_store_domain_binding/index.js.map +7 -0
  12. package/dist/generated/entities.ids.generated.js +8 -1
  13. package/dist/generated/entities.ids.generated.js.map +2 -2
  14. package/dist/generated/entity-fields-registry.js +72 -0
  15. package/dist/generated/entity-fields-registry.js.map +2 -2
  16. package/dist/helpers/integration/customerGroupsFixtures.js.map +2 -2
  17. package/dist/modules/catalog/acl.js +8 -1
  18. package/dist/modules/catalog/acl.js.map +2 -2
  19. package/dist/modules/catalog/api/config/omnibus/route.js +184 -0
  20. package/dist/modules/catalog/api/config/omnibus/route.js.map +7 -0
  21. package/dist/modules/catalog/api/prices/history/route.js +131 -0
  22. package/dist/modules/catalog/api/prices/history/route.js.map +7 -0
  23. package/dist/modules/catalog/api/prices/omnibus-preview/route.js +184 -0
  24. package/dist/modules/catalog/api/prices/omnibus-preview/route.js.map +7 -0
  25. package/dist/modules/catalog/api/products/route.js +54 -245
  26. package/dist/modules/catalog/api/products/route.js.map +3 -3
  27. package/dist/modules/catalog/api/tags/route.js +6 -0
  28. package/dist/modules/catalog/api/tags/route.js.map +2 -2
  29. package/dist/modules/catalog/backend/config/catalog/page.js +3 -1
  30. package/dist/modules/catalog/backend/config/catalog/page.js.map +2 -2
  31. package/dist/modules/catalog/cli.js +80 -2
  32. package/dist/modules/catalog/cli.js.map +2 -2
  33. package/dist/modules/catalog/commands/categories.js +51 -2
  34. package/dist/modules/catalog/commands/categories.js.map +2 -2
  35. package/dist/modules/catalog/commands/prices.js +43 -1
  36. package/dist/modules/catalog/commands/prices.js.map +2 -2
  37. package/dist/modules/catalog/commands/products.js +71 -0
  38. package/dist/modules/catalog/commands/products.js.map +2 -2
  39. package/dist/modules/catalog/commands/variants.js +7 -0
  40. package/dist/modules/catalog/commands/variants.js.map +2 -2
  41. package/dist/modules/catalog/components/OmnibusSettings.js +703 -0
  42. package/dist/modules/catalog/components/OmnibusSettings.js.map +7 -0
  43. package/dist/modules/catalog/components/PriceEditorOmnibusRow.js +152 -0
  44. package/dist/modules/catalog/components/PriceEditorOmnibusRow.js.map +7 -0
  45. package/dist/modules/catalog/components/lookupSources.js +31 -0
  46. package/dist/modules/catalog/components/lookupSources.js.map +7 -0
  47. package/dist/modules/catalog/components/prices/PriceScopeSelectors.js +8 -2
  48. package/dist/modules/catalog/components/prices/PriceScopeSelectors.js.map +2 -2
  49. package/dist/modules/catalog/components/products/VariantBuilder.js +11 -1
  50. package/dist/modules/catalog/components/products/VariantBuilder.js.map +2 -2
  51. package/dist/modules/catalog/data/entities.js +122 -1
  52. package/dist/modules/catalog/data/entities.js.map +2 -2
  53. package/dist/modules/catalog/data/validators.js +78 -0
  54. package/dist/modules/catalog/data/validators.js.map +2 -2
  55. package/dist/modules/catalog/di.js +18 -0
  56. package/dist/modules/catalog/di.js.map +2 -2
  57. package/dist/modules/catalog/lib/omnibus.js +285 -0
  58. package/dist/modules/catalog/lib/omnibus.js.map +7 -0
  59. package/dist/modules/catalog/lib/omnibusBackfill.js +146 -0
  60. package/dist/modules/catalog/lib/omnibusBackfill.js.map +7 -0
  61. package/dist/modules/catalog/lib/omnibusCache.js +89 -0
  62. package/dist/modules/catalog/lib/omnibusCache.js.map +7 -0
  63. package/dist/modules/catalog/lib/omnibusConfig.js +64 -0
  64. package/dist/modules/catalog/lib/omnibusConfig.js.map +7 -0
  65. package/dist/modules/catalog/lib/omnibusHistoryQueries.js +191 -0
  66. package/dist/modules/catalog/lib/omnibusHistoryQueries.js.map +7 -0
  67. package/dist/modules/catalog/lib/omnibusPresentedEntry.js +73 -0
  68. package/dist/modules/catalog/lib/omnibusPresentedEntry.js.map +7 -0
  69. package/dist/modules/catalog/lib/omnibusProductListEnrichment.js +94 -0
  70. package/dist/modules/catalog/lib/omnibusProductListEnrichment.js.map +7 -0
  71. package/dist/modules/catalog/lib/omnibusTypes.js +115 -0
  72. package/dist/modules/catalog/lib/omnibusTypes.js.map +7 -0
  73. package/dist/modules/catalog/lib/optionSchemaTranslations.js +55 -0
  74. package/dist/modules/catalog/lib/optionSchemaTranslations.js.map +7 -0
  75. package/dist/modules/catalog/lib/priceHistoryQuery.js +103 -0
  76. package/dist/modules/catalog/lib/priceHistoryQuery.js.map +7 -0
  77. package/dist/modules/catalog/lib/pricing.js +26 -2
  78. package/dist/modules/catalog/lib/pricing.js.map +2 -2
  79. package/dist/modules/catalog/lib/productFilters.js +273 -0
  80. package/dist/modules/catalog/lib/productFilters.js.map +7 -0
  81. package/dist/modules/catalog/lib/productScopeKeys.js +105 -0
  82. package/dist/modules/catalog/lib/productScopeKeys.js.map +7 -0
  83. package/dist/modules/catalog/lib/productScopeReindex.js +73 -0
  84. package/dist/modules/catalog/lib/productScopeReindex.js.map +7 -0
  85. package/dist/modules/catalog/migrations/Migration20261005105352_catalog.js +39 -0
  86. package/dist/modules/catalog/migrations/Migration20261005105352_catalog.js.map +7 -0
  87. package/dist/modules/catalog/migrations/Migration20261005150824_catalog.js +39 -0
  88. package/dist/modules/catalog/migrations/Migration20261005150824_catalog.js.map +7 -0
  89. package/dist/modules/catalog/services/catalogOmnibusService.js +480 -0
  90. package/dist/modules/catalog/services/catalogOmnibusService.js.map +7 -0
  91. package/dist/modules/catalog/setup.js +3 -1
  92. package/dist/modules/catalog/setup.js.map +2 -2
  93. package/dist/modules/catalog/subscribers/product-scope-keys-category-deleted.js +16 -0
  94. package/dist/modules/catalog/subscribers/product-scope-keys-category-deleted.js.map +7 -0
  95. package/dist/modules/catalog/subscribers/product-scope-keys-category-updated.js +17 -0
  96. package/dist/modules/catalog/subscribers/product-scope-keys-category-updated.js.map +7 -0
  97. package/dist/modules/catalog/translations.js +10 -0
  98. package/dist/modules/catalog/translations.js.map +2 -2
  99. package/dist/modules/configs/lib/upgrade-actions.js +28 -0
  100. package/dist/modules/configs/lib/upgrade-actions.js.map +2 -2
  101. package/dist/modules/customer_groups/api/customer-groups/[id]/terms/route.js +5 -0
  102. package/dist/modules/customer_groups/api/customer-groups/[id]/terms/route.js.map +2 -2
  103. package/dist/modules/customer_groups/components/CustomerGroupTermsSection.js +111 -3
  104. package/dist/modules/customer_groups/components/CustomerGroupTermsSection.js.map +2 -2
  105. package/dist/modules/customer_groups/components/customerGroupAssortmentScope.js +43 -0
  106. package/dist/modules/customer_groups/components/customerGroupAssortmentScope.js.map +7 -0
  107. package/dist/modules/customer_groups/data/entities.js +3 -0
  108. package/dist/modules/customer_groups/data/entities.js.map +2 -2
  109. package/dist/modules/customer_groups/data/validators.js +9 -0
  110. package/dist/modules/customer_groups/data/validators.js.map +2 -2
  111. package/dist/modules/customer_groups/migrations/Migration20261005110250_customer_groups.js +17 -0
  112. package/dist/modules/customer_groups/migrations/Migration20261005110250_customer_groups.js.map +7 -0
  113. package/dist/modules/customer_groups/services/customerGroupsService.js +62 -15
  114. package/dist/modules/customer_groups/services/customerGroupsService.js.map +2 -2
  115. package/dist/modules/ecommerce/acl.js +13 -0
  116. package/dist/modules/ecommerce/acl.js.map +7 -0
  117. package/dist/modules/ecommerce/api/domain-mappings/route.js +72 -0
  118. package/dist/modules/ecommerce/api/domain-mappings/route.js.map +7 -0
  119. package/dist/modules/ecommerce/api/openapi.js +27 -0
  120. package/dist/modules/ecommerce/api/openapi.js.map +7 -0
  121. package/dist/modules/ecommerce/api/store-channel-bindings/[id]/assortment-count/route.js +109 -0
  122. package/dist/modules/ecommerce/api/store-channel-bindings/[id]/assortment-count/route.js.map +7 -0
  123. package/dist/modules/ecommerce/api/store-channel-bindings/crud.js +265 -0
  124. package/dist/modules/ecommerce/api/store-channel-bindings/crud.js.map +7 -0
  125. package/dist/modules/ecommerce/api/store-channel-bindings/route.js +67 -0
  126. package/dist/modules/ecommerce/api/store-channel-bindings/route.js.map +7 -0
  127. package/dist/modules/ecommerce/api/store-domain-bindings/crud.js +296 -0
  128. package/dist/modules/ecommerce/api/store-domain-bindings/crud.js.map +7 -0
  129. package/dist/modules/ecommerce/api/store-domain-bindings/route.js +73 -0
  130. package/dist/modules/ecommerce/api/store-domain-bindings/route.js.map +7 -0
  131. package/dist/modules/ecommerce/api/storefront/categories/[slug]/route.js +87 -0
  132. package/dist/modules/ecommerce/api/storefront/categories/[slug]/route.js.map +7 -0
  133. package/dist/modules/ecommerce/api/storefront/categories/openapiSchemas.js +50 -0
  134. package/dist/modules/ecommerce/api/storefront/categories/openapiSchemas.js.map +7 -0
  135. package/dist/modules/ecommerce/api/storefront/categories/route.js +75 -0
  136. package/dist/modules/ecommerce/api/storefront/categories/route.js.map +7 -0
  137. package/dist/modules/ecommerce/api/storefront/context/route.js +163 -0
  138. package/dist/modules/ecommerce/api/storefront/context/route.js.map +7 -0
  139. package/dist/modules/ecommerce/api/storefront/products/[idOrHandle]/route.js +87 -0
  140. package/dist/modules/ecommerce/api/storefront/products/[idOrHandle]/route.js.map +7 -0
  141. package/dist/modules/ecommerce/api/storefront/products/openapiSchemas.js +177 -0
  142. package/dist/modules/ecommerce/api/storefront/products/openapiSchemas.js.map +7 -0
  143. package/dist/modules/ecommerce/api/storefront/products/route.js +78 -0
  144. package/dist/modules/ecommerce/api/storefront/products/route.js.map +7 -0
  145. package/dist/modules/ecommerce/api/storefront/search/suggest/openapiSchemas.js +25 -0
  146. package/dist/modules/ecommerce/api/storefront/search/suggest/openapiSchemas.js.map +7 -0
  147. package/dist/modules/ecommerce/api/storefront/search/suggest/route.js +75 -0
  148. package/dist/modules/ecommerce/api/storefront/search/suggest/route.js.map +7 -0
  149. package/dist/modules/ecommerce/api/storefront/storefrontRouteSupport.js +58 -0
  150. package/dist/modules/ecommerce/api/storefront/storefrontRouteSupport.js.map +7 -0
  151. package/dist/modules/ecommerce/api/stores/[id]/branding/route.js +183 -0
  152. package/dist/modules/ecommerce/api/stores/[id]/branding/route.js.map +7 -0
  153. package/dist/modules/ecommerce/api/stores/[id]/preview-branding/route.js +92 -0
  154. package/dist/modules/ecommerce/api/stores/[id]/preview-branding/route.js.map +7 -0
  155. package/dist/modules/ecommerce/api/stores/crud.js +401 -0
  156. package/dist/modules/ecommerce/api/stores/crud.js.map +7 -0
  157. package/dist/modules/ecommerce/api/stores/route.js +64 -0
  158. package/dist/modules/ecommerce/api/stores/route.js.map +7 -0
  159. package/dist/modules/ecommerce/backend/config/ecommerce/[id]/page.js +9 -0
  160. package/dist/modules/ecommerce/backend/config/ecommerce/[id]/page.js.map +7 -0
  161. package/dist/modules/ecommerce/backend/config/ecommerce/[id]/page.meta.js +16 -0
  162. package/dist/modules/ecommerce/backend/config/ecommerce/[id]/page.meta.js.map +7 -0
  163. package/dist/modules/ecommerce/backend/config/ecommerce/page.js +9 -0
  164. package/dist/modules/ecommerce/backend/config/ecommerce/page.js.map +7 -0
  165. package/dist/modules/ecommerce/backend/config/ecommerce/page.meta.js +16 -0
  166. package/dist/modules/ecommerce/backend/config/ecommerce/page.meta.js.map +7 -0
  167. package/dist/modules/ecommerce/commands/stores.js +110 -0
  168. package/dist/modules/ecommerce/commands/stores.js.map +7 -0
  169. package/dist/modules/ecommerce/components/ChannelAssortmentCount.js +90 -0
  170. package/dist/modules/ecommerce/components/ChannelAssortmentCount.js.map +7 -0
  171. package/dist/modules/ecommerce/components/ChannelBindingFormSections.js +33 -0
  172. package/dist/modules/ecommerce/components/ChannelBindingFormSections.js.map +7 -0
  173. package/dist/modules/ecommerce/components/ChannelLookupPicker.js +11 -0
  174. package/dist/modules/ecommerce/components/ChannelLookupPicker.js.map +7 -0
  175. package/dist/modules/ecommerce/components/DomainStatusWarning.js +24 -0
  176. package/dist/modules/ecommerce/components/DomainStatusWarning.js.map +7 -0
  177. package/dist/modules/ecommerce/components/StoreAvailabilityDefaultsSection.js +190 -0
  178. package/dist/modules/ecommerce/components/StoreAvailabilityDefaultsSection.js.map +7 -0
  179. package/dist/modules/ecommerce/components/StoreBrandingControls.js +67 -0
  180. package/dist/modules/ecommerce/components/StoreBrandingControls.js.map +7 -0
  181. package/dist/modules/ecommerce/components/StoreBrandingPreview.js +69 -0
  182. package/dist/modules/ecommerce/components/StoreBrandingPreview.js.map +7 -0
  183. package/dist/modules/ecommerce/components/StoreBrandingTab.js +218 -0
  184. package/dist/modules/ecommerce/components/StoreBrandingTab.js.map +7 -0
  185. package/dist/modules/ecommerce/components/StoreChannelBindingDialog.js +270 -0
  186. package/dist/modules/ecommerce/components/StoreChannelBindingDialog.js.map +7 -0
  187. package/dist/modules/ecommerce/components/StoreChannelsTab.js +313 -0
  188. package/dist/modules/ecommerce/components/StoreChannelsTab.js.map +7 -0
  189. package/dist/modules/ecommerce/components/StoreCreateDialog.js +164 -0
  190. package/dist/modules/ecommerce/components/StoreCreateDialog.js.map +7 -0
  191. package/dist/modules/ecommerce/components/StoreDomainBindingDialog.js +162 -0
  192. package/dist/modules/ecommerce/components/StoreDomainBindingDialog.js.map +7 -0
  193. package/dist/modules/ecommerce/components/StoreDomainsTab.js +357 -0
  194. package/dist/modules/ecommerce/components/StoreDomainsTab.js.map +7 -0
  195. package/dist/modules/ecommerce/components/StoreEditPage.js +155 -0
  196. package/dist/modules/ecommerce/components/StoreEditPage.js.map +7 -0
  197. package/dist/modules/ecommerce/components/StoreGeneralTab.js +167 -0
  198. package/dist/modules/ecommerce/components/StoreGeneralTab.js.map +7 -0
  199. package/dist/modules/ecommerce/components/StoreListPage.js +290 -0
  200. package/dist/modules/ecommerce/components/StoreListPage.js.map +7 -0
  201. package/dist/modules/ecommerce/components/StoreSeoTab.js +132 -0
  202. package/dist/modules/ecommerce/components/StoreSeoTab.js.map +7 -0
  203. package/dist/modules/ecommerce/components/StoreStatusBadge.js +20 -0
  204. package/dist/modules/ecommerce/components/StoreStatusBadge.js.map +7 -0
  205. package/dist/modules/ecommerce/components/channelLookups.js +28 -0
  206. package/dist/modules/ecommerce/components/channelLookups.js.map +7 -0
  207. package/dist/modules/ecommerce/components/storeAdmin.js +41 -0
  208. package/dist/modules/ecommerce/components/storeAdmin.js.map +7 -0
  209. package/dist/modules/ecommerce/components/storeBrandingForm.js +197 -0
  210. package/dist/modules/ecommerce/components/storeBrandingForm.js.map +7 -0
  211. package/dist/modules/ecommerce/components/storeChannels.js +140 -0
  212. package/dist/modules/ecommerce/components/storeChannels.js.map +7 -0
  213. package/dist/modules/ecommerce/components/storeDomains.js +167 -0
  214. package/dist/modules/ecommerce/components/storeDomains.js.map +7 -0
  215. package/dist/modules/ecommerce/components/storeEditTabs.js +62 -0
  216. package/dist/modules/ecommerce/components/storeEditTabs.js.map +7 -0
  217. package/dist/modules/ecommerce/components/storeGeneral.js +95 -0
  218. package/dist/modules/ecommerce/components/storeGeneral.js.map +7 -0
  219. package/dist/modules/ecommerce/components/storeSeo.js +69 -0
  220. package/dist/modules/ecommerce/components/storeSeo.js.map +7 -0
  221. package/dist/modules/ecommerce/components/useChannelAssortmentCount.js +45 -0
  222. package/dist/modules/ecommerce/components/useChannelAssortmentCount.js.map +7 -0
  223. package/dist/modules/ecommerce/components/useStoreAccess.js +28 -0
  224. package/dist/modules/ecommerce/components/useStoreAccess.js.map +7 -0
  225. package/dist/modules/ecommerce/data/enrichers.js +157 -0
  226. package/dist/modules/ecommerce/data/enrichers.js.map +7 -0
  227. package/dist/modules/ecommerce/data/entities.js +197 -0
  228. package/dist/modules/ecommerce/data/entities.js.map +7 -0
  229. package/dist/modules/ecommerce/data/validators.js +406 -0
  230. package/dist/modules/ecommerce/data/validators.js.map +7 -0
  231. package/dist/modules/ecommerce/di.js +11 -0
  232. package/dist/modules/ecommerce/di.js.map +7 -0
  233. package/dist/modules/ecommerce/events.js +27 -0
  234. package/dist/modules/ecommerce/events.js.map +7 -0
  235. package/dist/modules/ecommerce/index.js +16 -0
  236. package/dist/modules/ecommerce/index.js.map +7 -0
  237. package/dist/modules/ecommerce/lib/assortmentCount.js +112 -0
  238. package/dist/modules/ecommerce/lib/assortmentCount.js.map +7 -0
  239. package/dist/modules/ecommerce/lib/brandingStyles.js +184 -0
  240. package/dist/modules/ecommerce/lib/brandingStyles.js.map +7 -0
  241. package/dist/modules/ecommerce/lib/buyerContext.js +284 -0
  242. package/dist/modules/ecommerce/lib/buyerContext.js.map +7 -0
  243. package/dist/modules/ecommerce/lib/cacheInvalidation.js +186 -0
  244. package/dist/modules/ecommerce/lib/cacheInvalidation.js.map +7 -0
  245. package/dist/modules/ecommerce/lib/cacheKeys.js +236 -0
  246. package/dist/modules/ecommerce/lib/cacheKeys.js.map +7 -0
  247. package/dist/modules/ecommerce/lib/createConflictRecheck.js +29 -0
  248. package/dist/modules/ecommerce/lib/createConflictRecheck.js.map +7 -0
  249. package/dist/modules/ecommerce/lib/crudEvents.js +94 -0
  250. package/dist/modules/ecommerce/lib/crudEvents.js.map +7 -0
  251. package/dist/modules/ecommerce/lib/crudSupport.js +64 -0
  252. package/dist/modules/ecommerce/lib/crudSupport.js.map +7 -0
  253. package/dist/modules/ecommerce/lib/domainBindingRebind.js +99 -0
  254. package/dist/modules/ecommerce/lib/domainBindingRebind.js.map +7 -0
  255. package/dist/modules/ecommerce/lib/domainMappingSummaries.js +39 -0
  256. package/dist/modules/ecommerce/lib/domainMappingSummaries.js.map +7 -0
  257. package/dist/modules/ecommerce/lib/exclusiveFlag.js +57 -0
  258. package/dist/modules/ecommerce/lib/exclusiveFlag.js.map +7 -0
  259. package/dist/modules/ecommerce/lib/references.js +70 -0
  260. package/dist/modules/ecommerce/lib/references.js.map +7 -0
  261. package/dist/modules/ecommerce/lib/seedDraftStore.js +99 -0
  262. package/dist/modules/ecommerce/lib/seedDraftStore.js.map +7 -0
  263. package/dist/modules/ecommerce/lib/storeBindingCascade.js +109 -0
  264. package/dist/modules/ecommerce/lib/storeBindingCascade.js.map +7 -0
  265. package/dist/modules/ecommerce/lib/storeBranding.js +40 -0
  266. package/dist/modules/ecommerce/lib/storeBranding.js.map +7 -0
  267. package/dist/modules/ecommerce/lib/storeBrandingRoute.js +76 -0
  268. package/dist/modules/ecommerce/lib/storeBrandingRoute.js.map +7 -0
  269. package/dist/modules/ecommerce/lib/storeContext.js +393 -0
  270. package/dist/modules/ecommerce/lib/storeContext.js.map +7 -0
  271. package/dist/modules/ecommerce/lib/storeContextService.js +43 -0
  272. package/dist/modules/ecommerce/lib/storeContextService.js.map +7 -0
  273. package/dist/modules/ecommerce/lib/storeLocale.js +60 -0
  274. package/dist/modules/ecommerce/lib/storeLocale.js.map +7 -0
  275. package/dist/modules/ecommerce/lib/storeNotifications.js +41 -0
  276. package/dist/modules/ecommerce/lib/storeNotifications.js.map +7 -0
  277. package/dist/modules/ecommerce/lib/storefrontCatalogSupport.js +248 -0
  278. package/dist/modules/ecommerce/lib/storefrontCatalogSupport.js.map +7 -0
  279. package/dist/modules/ecommerce/lib/storefrontCategories.js +241 -0
  280. package/dist/modules/ecommerce/lib/storefrontCategories.js.map +7 -0
  281. package/dist/modules/ecommerce/lib/storefrontCategoryCache.js +71 -0
  282. package/dist/modules/ecommerce/lib/storefrontCategoryCache.js.map +7 -0
  283. package/dist/modules/ecommerce/lib/storefrontDetail.js +447 -0
  284. package/dist/modules/ecommerce/lib/storefrontDetail.js.map +7 -0
  285. package/dist/modules/ecommerce/lib/storefrontFacets.js +441 -0
  286. package/dist/modules/ecommerce/lib/storefrontFacets.js.map +7 -0
  287. package/dist/modules/ecommerce/lib/storefrontOptionFilter.js +15 -0
  288. package/dist/modules/ecommerce/lib/storefrontOptionFilter.js.map +7 -0
  289. package/dist/modules/ecommerce/lib/storefrontPricing.js +393 -0
  290. package/dist/modules/ecommerce/lib/storefrontPricing.js.map +7 -0
  291. package/dist/modules/ecommerce/lib/storefrontProductCache.js +90 -0
  292. package/dist/modules/ecommerce/lib/storefrontProductCache.js.map +7 -0
  293. package/dist/modules/ecommerce/lib/storefrontProductScope.js +107 -0
  294. package/dist/modules/ecommerce/lib/storefrontProductScope.js.map +7 -0
  295. package/dist/modules/ecommerce/lib/storefrontProducts.js +670 -0
  296. package/dist/modules/ecommerce/lib/storefrontProducts.js.map +7 -0
  297. package/dist/modules/ecommerce/lib/storefrontQuery.js +156 -0
  298. package/dist/modules/ecommerce/lib/storefrontQuery.js.map +7 -0
  299. package/dist/modules/ecommerce/lib/storefrontRateLimit.js +99 -0
  300. package/dist/modules/ecommerce/lib/storefrontRateLimit.js.map +7 -0
  301. package/dist/modules/ecommerce/lib/storefrontSearch.js +303 -0
  302. package/dist/modules/ecommerce/lib/storefrontSearch.js.map +7 -0
  303. package/dist/modules/ecommerce/lib/storefrontSearchCache.js +35 -0
  304. package/dist/modules/ecommerce/lib/storefrontSearchCache.js.map +7 -0
  305. package/dist/modules/ecommerce/lib/subscriberSupport.js +33 -0
  306. package/dist/modules/ecommerce/lib/subscriberSupport.js.map +7 -0
  307. package/dist/modules/ecommerce/lib/types.js +1 -0
  308. package/dist/modules/ecommerce/lib/types.js.map +7 -0
  309. package/dist/modules/ecommerce/migrations/Migration20261005113233_ecommerce.js +32 -0
  310. package/dist/modules/ecommerce/migrations/Migration20261005113233_ecommerce.js.map +7 -0
  311. package/dist/modules/ecommerce/migrations/Migration20261006112733_ecommerce.js +17 -0
  312. package/dist/modules/ecommerce/migrations/Migration20261006112733_ecommerce.js.map +7 -0
  313. package/dist/modules/ecommerce/notifications.client.js +47 -0
  314. package/dist/modules/ecommerce/notifications.client.js.map +7 -0
  315. package/dist/modules/ecommerce/notifications.js +48 -0
  316. package/dist/modules/ecommerce/notifications.js.map +7 -0
  317. package/dist/modules/ecommerce/search.js +83 -0
  318. package/dist/modules/ecommerce/search.js.map +7 -0
  319. package/dist/modules/ecommerce/setup.js +17 -0
  320. package/dist/modules/ecommerce/setup.js.map +7 -0
  321. package/dist/modules/ecommerce/subscribers/assortment-empty-notifications.js +14 -0
  322. package/dist/modules/ecommerce/subscribers/assortment-empty-notifications.js.map +7 -0
  323. package/dist/modules/ecommerce/subscribers/availability-policy-cache-invalidation.js +14 -0
  324. package/dist/modules/ecommerce/subscribers/availability-policy-cache-invalidation.js.map +7 -0
  325. package/dist/modules/ecommerce/subscribers/catalog-category-cache-invalidation.js +14 -0
  326. package/dist/modules/ecommerce/subscribers/catalog-category-cache-invalidation.js.map +7 -0
  327. package/dist/modules/ecommerce/subscribers/catalog-price-cache-invalidation.js +14 -0
  328. package/dist/modules/ecommerce/subscribers/catalog-price-cache-invalidation.js.map +7 -0
  329. package/dist/modules/ecommerce/subscribers/catalog-product-cache-invalidation.js +14 -0
  330. package/dist/modules/ecommerce/subscribers/catalog-product-cache-invalidation.js.map +7 -0
  331. package/dist/modules/ecommerce/subscribers/catalog-variant-cache-invalidation.js +14 -0
  332. package/dist/modules/ecommerce/subscribers/catalog-variant-cache-invalidation.js.map +7 -0
  333. package/dist/modules/ecommerce/subscribers/customer-group-cache-invalidation.js +14 -0
  334. package/dist/modules/ecommerce/subscribers/customer-group-cache-invalidation.js.map +7 -0
  335. package/dist/modules/ecommerce/subscribers/customer-group-membership-cache-invalidation.js +14 -0
  336. package/dist/modules/ecommerce/subscribers/customer-group-membership-cache-invalidation.js.map +7 -0
  337. package/dist/modules/ecommerce/subscribers/customer-group-terms-cache-invalidation.js +14 -0
  338. package/dist/modules/ecommerce/subscribers/customer-group-terms-cache-invalidation.js.map +7 -0
  339. package/dist/modules/ecommerce/subscribers/customer-user-deleted-cache-invalidation.js +14 -0
  340. package/dist/modules/ecommerce/subscribers/customer-user-deleted-cache-invalidation.js.map +7 -0
  341. package/dist/modules/ecommerce/subscribers/customer-user-updated-cache-invalidation.js +14 -0
  342. package/dist/modules/ecommerce/subscribers/customer-user-updated-cache-invalidation.js.map +7 -0
  343. package/dist/modules/ecommerce/subscribers/domain-binding-rebind.js +16 -0
  344. package/dist/modules/ecommerce/subscribers/domain-binding-rebind.js.map +7 -0
  345. package/dist/modules/ecommerce/subscribers/domain-mapping-cache-invalidation.js +14 -0
  346. package/dist/modules/ecommerce/subscribers/domain-mapping-cache-invalidation.js.map +7 -0
  347. package/dist/modules/ecommerce/subscribers/store-cache-invalidation.js +14 -0
  348. package/dist/modules/ecommerce/subscribers/store-cache-invalidation.js.map +7 -0
  349. package/dist/modules/ecommerce/subscribers/store-channel-binding-cache-invalidation.js +14 -0
  350. package/dist/modules/ecommerce/subscribers/store-channel-binding-cache-invalidation.js.map +7 -0
  351. package/dist/modules/ecommerce/subscribers/store-domain-binding-cache-invalidation.js +14 -0
  352. package/dist/modules/ecommerce/subscribers/store-domain-binding-cache-invalidation.js.map +7 -0
  353. package/dist/modules/ecommerce/subscribers/store-notifications.js +14 -0
  354. package/dist/modules/ecommerce/subscribers/store-notifications.js.map +7 -0
  355. package/dist/modules/query_index/lib/batch.js +23 -9
  356. package/dist/modules/query_index/lib/batch.js.map +2 -2
  357. package/dist/modules/query_index/lib/doc-enrichers.js +212 -0
  358. package/dist/modules/query_index/lib/doc-enrichers.js.map +7 -0
  359. package/dist/modules/query_index/lib/document.js +2 -0
  360. package/dist/modules/query_index/lib/document.js.map +2 -2
  361. package/dist/modules/query_index/lib/engine.js +68 -1
  362. package/dist/modules/query_index/lib/engine.js.map +2 -2
  363. package/dist/modules/query_index/lib/indexer.js +7 -0
  364. package/dist/modules/query_index/lib/indexer.js.map +2 -2
  365. package/dist/modules/query_index/lib/search-tokens.js +2 -0
  366. package/dist/modules/query_index/lib/search-tokens.js.map +2 -2
  367. package/dist/modules/query_index/migrations/Migration20261005201500_query_index.js +17 -0
  368. package/dist/modules/query_index/migrations/Migration20261005201500_query_index.js.map +7 -0
  369. package/dist/modules/translations/components/TranslationManager.js +3 -3
  370. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  371. package/dist/modules/translations/data/validators.js +1 -1
  372. package/dist/modules/translations/data/validators.js.map +1 -1
  373. package/dist/modules/translations/lib/batch.js +21 -1
  374. package/dist/modules/translations/lib/batch.js.map +2 -2
  375. package/dist/modules/translations/lib/helpers.js +3 -0
  376. package/dist/modules/translations/lib/helpers.js.map +2 -2
  377. package/dist/modules/translations/lib/resolve-field-list.js +14 -2
  378. package/dist/modules/translations/lib/resolve-field-list.js.map +2 -2
  379. package/generated/entities/catalog_price_history_entry/index.ts +25 -0
  380. package/generated/entities/customer_group_terms/index.ts +1 -0
  381. package/generated/entities/ecommerce_store/index.ts +15 -0
  382. package/generated/entities/ecommerce_store_channel_binding/index.ts +13 -0
  383. package/generated/entities/ecommerce_store_domain_binding/index.ts +10 -0
  384. package/generated/entities.ids.generated.ts +8 -1
  385. package/generated/entity-fields-registry.ts +72 -0
  386. package/package.json +7 -7
  387. package/src/helpers/integration/customerGroupsFixtures.ts +2 -0
  388. package/src/modules/auth/i18n/de.json +8 -0
  389. package/src/modules/auth/i18n/en.json +8 -0
  390. package/src/modules/auth/i18n/es.json +8 -0
  391. package/src/modules/auth/i18n/ko.json +8 -0
  392. package/src/modules/auth/i18n/pl.json +8 -0
  393. package/src/modules/catalog/AGENTS.md +5 -2
  394. package/src/modules/catalog/acl.ts +7 -0
  395. package/src/modules/catalog/api/config/omnibus/route.ts +204 -0
  396. package/src/modules/catalog/api/prices/history/route.ts +139 -0
  397. package/src/modules/catalog/api/prices/omnibus-preview/route.ts +202 -0
  398. package/src/modules/catalog/api/products/route.ts +53 -308
  399. package/src/modules/catalog/api/tags/route.ts +6 -0
  400. package/src/modules/catalog/backend/config/catalog/page.tsx +2 -0
  401. package/src/modules/catalog/cli.ts +84 -1
  402. package/src/modules/catalog/commands/categories.ts +54 -2
  403. package/src/modules/catalog/commands/prices.ts +43 -1
  404. package/src/modules/catalog/commands/products.ts +84 -1
  405. package/src/modules/catalog/commands/variants.ts +7 -0
  406. package/src/modules/catalog/components/OmnibusSettings.tsx +832 -0
  407. package/src/modules/catalog/components/PriceEditorOmnibusRow.tsx +219 -0
  408. package/src/modules/catalog/components/lookupSources.ts +29 -0
  409. package/src/modules/catalog/components/prices/PriceScopeSelectors.tsx +9 -0
  410. package/src/modules/catalog/components/products/VariantBuilder.tsx +9 -0
  411. package/src/modules/catalog/data/entities.ts +123 -1
  412. package/src/modules/catalog/data/validators.ts +118 -0
  413. package/src/modules/catalog/di.ts +23 -0
  414. package/src/modules/catalog/i18n/de.json +77 -0
  415. package/src/modules/catalog/i18n/en.json +77 -0
  416. package/src/modules/catalog/i18n/es.json +77 -0
  417. package/src/modules/catalog/i18n/ko.json +77 -0
  418. package/src/modules/catalog/i18n/pl.json +77 -0
  419. package/src/modules/catalog/lib/omnibus.ts +406 -0
  420. package/src/modules/catalog/lib/omnibusBackfill.ts +198 -0
  421. package/src/modules/catalog/lib/omnibusCache.ts +111 -0
  422. package/src/modules/catalog/lib/omnibusConfig.ts +73 -0
  423. package/src/modules/catalog/lib/omnibusHistoryQueries.ts +248 -0
  424. package/src/modules/catalog/lib/omnibusPresentedEntry.ts +76 -0
  425. package/src/modules/catalog/lib/omnibusProductListEnrichment.ts +125 -0
  426. package/src/modules/catalog/lib/omnibusTypes.ts +202 -0
  427. package/src/modules/catalog/lib/optionSchemaTranslations.ts +55 -0
  428. package/src/modules/catalog/lib/priceHistoryQuery.ts +155 -0
  429. package/src/modules/catalog/lib/pricing.ts +42 -4
  430. package/src/modules/catalog/lib/productFilters.ts +349 -0
  431. package/src/modules/catalog/lib/productScopeKeys.ts +162 -0
  432. package/src/modules/catalog/lib/productScopeReindex.ts +139 -0
  433. package/src/modules/catalog/migrations/.snapshot-open-mercato.json +572 -0
  434. package/src/modules/catalog/migrations/Migration20261005105352_catalog.ts +39 -0
  435. package/src/modules/catalog/migrations/Migration20261005150824_catalog.ts +39 -0
  436. package/src/modules/catalog/services/catalogOmnibusService.ts +642 -0
  437. package/src/modules/catalog/setup.ts +2 -0
  438. package/src/modules/catalog/subscribers/product-scope-keys-category-deleted.ts +18 -0
  439. package/src/modules/catalog/subscribers/product-scope-keys-category-updated.ts +19 -0
  440. package/src/modules/catalog/translations.ts +12 -0
  441. package/src/modules/configs/i18n/de.json +5 -1
  442. package/src/modules/configs/i18n/en.json +5 -1
  443. package/src/modules/configs/i18n/es.json +5 -1
  444. package/src/modules/configs/i18n/ko.json +5 -1
  445. package/src/modules/configs/i18n/pl.json +5 -1
  446. package/src/modules/configs/lib/upgrade-actions.ts +35 -0
  447. package/src/modules/customer_groups/api/customer-groups/[id]/terms/route.ts +7 -0
  448. package/src/modules/customer_groups/components/CustomerGroupTermsSection.tsx +124 -2
  449. package/src/modules/customer_groups/components/customerGroupAssortmentScope.ts +46 -0
  450. package/src/modules/customer_groups/data/entities.ts +4 -0
  451. package/src/modules/customer_groups/data/validators.ts +14 -0
  452. package/src/modules/customer_groups/i18n/de.json +12 -0
  453. package/src/modules/customer_groups/i18n/en.json +12 -0
  454. package/src/modules/customer_groups/i18n/es.json +12 -0
  455. package/src/modules/customer_groups/i18n/ko.json +12 -0
  456. package/src/modules/customer_groups/i18n/pl.json +12 -0
  457. package/src/modules/customer_groups/migrations/.snapshot-open-mercato.json +17 -0
  458. package/src/modules/customer_groups/migrations/Migration20261005110250_customer_groups.ts +15 -0
  459. package/src/modules/customer_groups/services/customerGroupsService.ts +74 -23
  460. package/src/modules/ecommerce/acl.ts +9 -0
  461. package/src/modules/ecommerce/api/domain-mappings/route.ts +76 -0
  462. package/src/modules/ecommerce/api/openapi.ts +28 -0
  463. package/src/modules/ecommerce/api/store-channel-bindings/[id]/assortment-count/route.ts +141 -0
  464. package/src/modules/ecommerce/api/store-channel-bindings/crud.ts +283 -0
  465. package/src/modules/ecommerce/api/store-channel-bindings/route.ts +67 -0
  466. package/src/modules/ecommerce/api/store-domain-bindings/crud.ts +324 -0
  467. package/src/modules/ecommerce/api/store-domain-bindings/route.ts +73 -0
  468. package/src/modules/ecommerce/api/storefront/categories/[slug]/route.ts +94 -0
  469. package/src/modules/ecommerce/api/storefront/categories/openapiSchemas.ts +63 -0
  470. package/src/modules/ecommerce/api/storefront/categories/route.ts +78 -0
  471. package/src/modules/ecommerce/api/storefront/context/route.ts +203 -0
  472. package/src/modules/ecommerce/api/storefront/products/[idOrHandle]/route.ts +94 -0
  473. package/src/modules/ecommerce/api/storefront/products/openapiSchemas.ts +193 -0
  474. package/src/modules/ecommerce/api/storefront/products/route.ts +81 -0
  475. package/src/modules/ecommerce/api/storefront/search/suggest/openapiSchemas.ts +25 -0
  476. package/src/modules/ecommerce/api/storefront/search/suggest/route.ts +78 -0
  477. package/src/modules/ecommerce/api/storefront/storefrontRouteSupport.ts +68 -0
  478. package/src/modules/ecommerce/api/stores/[id]/branding/route.ts +205 -0
  479. package/src/modules/ecommerce/api/stores/[id]/preview-branding/route.ts +99 -0
  480. package/src/modules/ecommerce/api/stores/crud.ts +457 -0
  481. package/src/modules/ecommerce/api/stores/route.ts +66 -0
  482. package/src/modules/ecommerce/backend/config/ecommerce/[id]/page.meta.ts +12 -0
  483. package/src/modules/ecommerce/backend/config/ecommerce/[id]/page.tsx +5 -0
  484. package/src/modules/ecommerce/backend/config/ecommerce/page.meta.ts +12 -0
  485. package/src/modules/ecommerce/backend/config/ecommerce/page.tsx +5 -0
  486. package/src/modules/ecommerce/commands/stores.ts +154 -0
  487. package/src/modules/ecommerce/components/ChannelAssortmentCount.tsx +138 -0
  488. package/src/modules/ecommerce/components/ChannelBindingFormSections.tsx +40 -0
  489. package/src/modules/ecommerce/components/ChannelLookupPicker.tsx +5 -0
  490. package/src/modules/ecommerce/components/DomainStatusWarning.tsx +32 -0
  491. package/src/modules/ecommerce/components/StoreAvailabilityDefaultsSection.tsx +219 -0
  492. package/src/modules/ecommerce/components/StoreBrandingControls.tsx +73 -0
  493. package/src/modules/ecommerce/components/StoreBrandingPreview.tsx +77 -0
  494. package/src/modules/ecommerce/components/StoreBrandingTab.tsx +242 -0
  495. package/src/modules/ecommerce/components/StoreChannelBindingDialog.tsx +306 -0
  496. package/src/modules/ecommerce/components/StoreChannelsTab.tsx +375 -0
  497. package/src/modules/ecommerce/components/StoreCreateDialog.tsx +204 -0
  498. package/src/modules/ecommerce/components/StoreDomainBindingDialog.tsx +198 -0
  499. package/src/modules/ecommerce/components/StoreDomainsTab.tsx +426 -0
  500. package/src/modules/ecommerce/components/StoreEditPage.tsx +193 -0
  501. package/src/modules/ecommerce/components/StoreGeneralTab.tsx +189 -0
  502. package/src/modules/ecommerce/components/StoreListPage.tsx +326 -0
  503. package/src/modules/ecommerce/components/StoreSeoTab.tsx +152 -0
  504. package/src/modules/ecommerce/components/StoreStatusBadge.tsx +22 -0
  505. package/src/modules/ecommerce/components/channelLookups.ts +24 -0
  506. package/src/modules/ecommerce/components/storeAdmin.ts +56 -0
  507. package/src/modules/ecommerce/components/storeBrandingForm.ts +230 -0
  508. package/src/modules/ecommerce/components/storeChannels.ts +210 -0
  509. package/src/modules/ecommerce/components/storeDomains.ts +221 -0
  510. package/src/modules/ecommerce/components/storeEditTabs.tsx +76 -0
  511. package/src/modules/ecommerce/components/storeGeneral.ts +155 -0
  512. package/src/modules/ecommerce/components/storeSeo.ts +78 -0
  513. package/src/modules/ecommerce/components/useChannelAssortmentCount.ts +67 -0
  514. package/src/modules/ecommerce/components/useStoreAccess.ts +36 -0
  515. package/src/modules/ecommerce/data/enrichers.ts +213 -0
  516. package/src/modules/ecommerce/data/entities.ts +168 -0
  517. package/src/modules/ecommerce/data/validators.ts +587 -0
  518. package/src/modules/ecommerce/di.ts +9 -0
  519. package/src/modules/ecommerce/events.ts +27 -0
  520. package/src/modules/ecommerce/i18n/de.json +341 -0
  521. package/src/modules/ecommerce/i18n/en.json +341 -0
  522. package/src/modules/ecommerce/i18n/es.json +341 -0
  523. package/src/modules/ecommerce/i18n/ko.json +341 -0
  524. package/src/modules/ecommerce/i18n/pl.json +341 -0
  525. package/src/modules/ecommerce/index.ts +14 -0
  526. package/src/modules/ecommerce/lib/assortmentCount.ts +175 -0
  527. package/src/modules/ecommerce/lib/brandingStyles.ts +215 -0
  528. package/src/modules/ecommerce/lib/buyerContext.ts +401 -0
  529. package/src/modules/ecommerce/lib/cacheInvalidation.ts +302 -0
  530. package/src/modules/ecommerce/lib/cacheKeys.ts +340 -0
  531. package/src/modules/ecommerce/lib/createConflictRecheck.ts +31 -0
  532. package/src/modules/ecommerce/lib/crudEvents.ts +128 -0
  533. package/src/modules/ecommerce/lib/crudSupport.ts +85 -0
  534. package/src/modules/ecommerce/lib/domainBindingRebind.ts +138 -0
  535. package/src/modules/ecommerce/lib/domainMappingSummaries.ts +71 -0
  536. package/src/modules/ecommerce/lib/exclusiveFlag.ts +90 -0
  537. package/src/modules/ecommerce/lib/references.ts +93 -0
  538. package/src/modules/ecommerce/lib/seedDraftStore.ts +125 -0
  539. package/src/modules/ecommerce/lib/storeBindingCascade.ts +138 -0
  540. package/src/modules/ecommerce/lib/storeBranding.ts +48 -0
  541. package/src/modules/ecommerce/lib/storeBrandingRoute.ts +91 -0
  542. package/src/modules/ecommerce/lib/storeContext.ts +669 -0
  543. package/src/modules/ecommerce/lib/storeContextService.ts +71 -0
  544. package/src/modules/ecommerce/lib/storeLocale.ts +88 -0
  545. package/src/modules/ecommerce/lib/storeNotifications.ts +55 -0
  546. package/src/modules/ecommerce/lib/storefrontCatalogSupport.ts +427 -0
  547. package/src/modules/ecommerce/lib/storefrontCategories.ts +419 -0
  548. package/src/modules/ecommerce/lib/storefrontCategoryCache.ts +113 -0
  549. package/src/modules/ecommerce/lib/storefrontDetail.ts +654 -0
  550. package/src/modules/ecommerce/lib/storefrontFacets.ts +697 -0
  551. package/src/modules/ecommerce/lib/storefrontOptionFilter.ts +44 -0
  552. package/src/modules/ecommerce/lib/storefrontPricing.ts +583 -0
  553. package/src/modules/ecommerce/lib/storefrontProductCache.ts +126 -0
  554. package/src/modules/ecommerce/lib/storefrontProductScope.ts +181 -0
  555. package/src/modules/ecommerce/lib/storefrontProducts.ts +963 -0
  556. package/src/modules/ecommerce/lib/storefrontQuery.ts +215 -0
  557. package/src/modules/ecommerce/lib/storefrontRateLimit.ts +126 -0
  558. package/src/modules/ecommerce/lib/storefrontSearch.ts +454 -0
  559. package/src/modules/ecommerce/lib/storefrontSearchCache.ts +49 -0
  560. package/src/modules/ecommerce/lib/subscriberSupport.ts +41 -0
  561. package/src/modules/ecommerce/lib/types.ts +69 -0
  562. package/src/modules/ecommerce/migrations/.snapshot-open-mercato.json +829 -0
  563. package/src/modules/ecommerce/migrations/Migration20261005113233_ecommerce.ts +32 -0
  564. package/src/modules/ecommerce/migrations/Migration20261006112733_ecommerce.ts +15 -0
  565. package/src/modules/ecommerce/notifications.client.ts +46 -0
  566. package/src/modules/ecommerce/notifications.ts +46 -0
  567. package/src/modules/ecommerce/search.ts +93 -0
  568. package/src/modules/ecommerce/setup.ts +15 -0
  569. package/src/modules/ecommerce/subscribers/assortment-empty-notifications.ts +12 -0
  570. package/src/modules/ecommerce/subscribers/availability-policy-cache-invalidation.ts +12 -0
  571. package/src/modules/ecommerce/subscribers/catalog-category-cache-invalidation.ts +12 -0
  572. package/src/modules/ecommerce/subscribers/catalog-price-cache-invalidation.ts +12 -0
  573. package/src/modules/ecommerce/subscribers/catalog-product-cache-invalidation.ts +12 -0
  574. package/src/modules/ecommerce/subscribers/catalog-variant-cache-invalidation.ts +12 -0
  575. package/src/modules/ecommerce/subscribers/customer-group-cache-invalidation.ts +12 -0
  576. package/src/modules/ecommerce/subscribers/customer-group-membership-cache-invalidation.ts +12 -0
  577. package/src/modules/ecommerce/subscribers/customer-group-terms-cache-invalidation.ts +12 -0
  578. package/src/modules/ecommerce/subscribers/customer-user-deleted-cache-invalidation.ts +12 -0
  579. package/src/modules/ecommerce/subscribers/customer-user-updated-cache-invalidation.ts +12 -0
  580. package/src/modules/ecommerce/subscribers/domain-binding-rebind.ts +14 -0
  581. package/src/modules/ecommerce/subscribers/domain-mapping-cache-invalidation.ts +12 -0
  582. package/src/modules/ecommerce/subscribers/store-cache-invalidation.ts +12 -0
  583. package/src/modules/ecommerce/subscribers/store-channel-binding-cache-invalidation.ts +12 -0
  584. package/src/modules/ecommerce/subscribers/store-domain-binding-cache-invalidation.ts +12 -0
  585. package/src/modules/ecommerce/subscribers/store-notifications.ts +12 -0
  586. package/src/modules/query_index/lib/batch.ts +25 -9
  587. package/src/modules/query_index/lib/doc-enrichers.ts +306 -0
  588. package/src/modules/query_index/lib/document.ts +2 -0
  589. package/src/modules/query_index/lib/engine.ts +58 -1
  590. package/src/modules/query_index/lib/indexer.ts +8 -0
  591. package/src/modules/query_index/lib/search-tokens.ts +2 -0
  592. package/src/modules/query_index/migrations/Migration20261005201500_query_index.ts +42 -0
  593. package/src/modules/translations/components/TranslationManager.tsx +3 -3
  594. package/src/modules/translations/data/validators.ts +1 -1
  595. package/src/modules/translations/lib/batch.ts +47 -0
  596. package/src/modules/translations/lib/helpers.ts +4 -0
  597. package/src/modules/translations/lib/resolve-field-list.ts +16 -2
@@ -3,6 +3,7 @@ import { recordIndexerError } from "@open-mercato/shared/lib/indexers/error-log"
3
3
  import { isUniqueViolation } from "@open-mercato/shared/lib/db/pg-errors";
4
4
  import { buildIndexDocument, rebuildAggregateSearchField } from "./document.js";
5
5
  import { replaceSearchTokensForBatch, isSearchDebugEnabled } from "./search-tokens.js";
6
+ import { applyIndexDocEnrichers } from "./doc-enrichers.js";
6
7
  import { createLogger } from "@open-mercato/shared/lib/logger";
7
8
  import { resolveSearchConfig } from "@open-mercato/shared/lib/search/config";
8
9
  const logger = createLogger("query_index").child({ component: "reindex-batch" });
@@ -112,6 +113,7 @@ async function upsertIndexBatch(db, entityType, rows, scope, options = {}) {
112
113
  const basePayloads = [];
113
114
  const debugEnabled = isSearchDebugEnabled();
114
115
  const searchConfig = resolveSearchConfig();
116
+ const builtDocs = [];
115
117
  for (const row of rows) {
116
118
  const recordId = normalizeId(row.id);
117
119
  const baseOrg = normalizeScopedValue(row.organization_id);
@@ -134,15 +136,27 @@ async function upsertIndexBatch(db, entityType, rows, scope, options = {}) {
134
136
  if (!entityRow) return row;
135
137
  return { ...entityRow, ...row };
136
138
  })();
137
- let doc = buildIndexDocument(
138
- mergedRow,
139
- values,
140
- {
141
- organizationId: scopeOrg ?? null,
142
- tenantId: scopeTenant ?? null
143
- },
144
- { entityType, config: searchConfig }
145
- );
139
+ builtDocs.push({
140
+ recordId,
141
+ doc: buildIndexDocument(
142
+ mergedRow,
143
+ values,
144
+ {
145
+ organizationId: scopeOrg ?? null,
146
+ tenantId: scopeTenant ?? null
147
+ },
148
+ { entityType, config: searchConfig }
149
+ ),
150
+ tenantId: scopeTenant ?? null,
151
+ organizationId: scopeOrg ?? null
152
+ });
153
+ }
154
+ await applyIndexDocEnrichers(db, entityType, builtDocs);
155
+ for (const built of builtDocs) {
156
+ const recordId = built.recordId;
157
+ const scopeOrg = built.organizationId;
158
+ const scopeTenant = built.tenantId;
159
+ let doc = built.doc;
146
160
  let tokenDoc = doc;
147
161
  if (typeof options.encryptDoc === "function") {
148
162
  try {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/query_index/lib/batch.ts"],
4
- "sourcesContent": ["import { type Kysely, sql } from 'kysely'\nimport { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'\nimport { isUniqueViolation } from '@open-mercato/shared/lib/db/pg-errors'\nimport { buildIndexDocument, rebuildAggregateSearchField, type IndexCustomFieldValue } from './document'\nimport { replaceSearchTokensForBatch, isSearchDebugEnabled } from './search-tokens'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { resolveSearchConfig } from '@open-mercato/shared/lib/search/config'\n\nconst logger = createLogger('query_index').child({ component: 'reindex-batch' })\n\n/**\n * Cap on how many per-row failures a single batch persists to `indexer_error_logs`.\n * Under a systemic failure (pool exhausted, disk full, KMS down) every row fails, and\n * writing one error row per record would hammer the database that is already failing.\n * The count of suppressed failures still reaches the caller via `failedRecordIds`.\n */\nconst MAX_RECORDED_ROW_ERRORS_PER_BATCH = 50\n\nexport type AnyRow = Record<string, any> & { id: string | number }\n\nexport type ScopeOverrides = {\n orgId?: string\n tenantId?: string\n}\n\n/**\n * What a batch actually wrote, as opposed to what it was asked to write. Callers MUST\n * reconcile `written` against `attempted` \u2014 a batch that loses rows and reports success\n * is how records go permanently missing from the index (issue GSM-266).\n */\nexport type UpsertIndexBatchResult = {\n attempted: number\n written: number\n failedRecordIds: string[]\n searchTokenFailures: number\n}\n\nexport class QueryIndexBatchWriteError extends Error {\n readonly entityType: string\n readonly attempted: number\n readonly written: number\n readonly failedRecordIds: string[]\n\n constructor(entityType: string, result: UpsertIndexBatchResult) {\n const preview = result.failedRecordIds.slice(0, 10)\n const suffix = result.failedRecordIds.length > preview.length ? ', ...' : ''\n super(\n `[internal] Query index write incomplete for ${entityType}: wrote ${result.written} of ${result.attempted} records` +\n (preview.length ? ` (failed: ${preview.join(', ')}${suffix})` : ''),\n )\n this.name = 'QueryIndexBatchWriteError'\n this.entityType = entityType\n this.attempted = result.attempted\n this.written = result.written\n this.failedRecordIds = result.failedRecordIds\n }\n}\n\nexport function assertIndexBatchWritesLanded(entityType: string, result: UpsertIndexBatchResult): void {\n if (result.written >= result.attempted && result.failedRecordIds.length === 0) return\n throw new QueryIndexBatchWriteError(entityType, result)\n}\n\nexport function createEmptyUpsertIndexBatchResult(): UpsertIndexBatchResult {\n return { attempted: 0, written: 0, failedRecordIds: [], searchTokenFailures: 0 }\n}\n\nexport function mergeUpsertIndexBatchResults(\n target: UpsertIndexBatchResult,\n addition: UpsertIndexBatchResult,\n): UpsertIndexBatchResult {\n target.attempted += addition.attempted\n target.written += addition.written\n target.searchTokenFailures += addition.searchTokenFailures\n target.failedRecordIds.push(...addition.failedRecordIds)\n return target\n}\n\ntype CustomFieldRow = {\n record_id: string\n field_key: string\n value_text: string | null\n value_multiline: string | null\n value_int: number | null\n value_float: number | null\n value_bool: boolean | null\n organization_id: string | null\n tenant_id: string | null\n}\n\nexport type IndexBatchOptions = {\n deriveOrganizationId?: (row: AnyRow) => string | null | undefined\n encryptDoc?: (\n entityType: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => Promise<Record<string, unknown> | null | undefined>\n decryptDoc?: (\n entityType: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => Promise<Record<string, unknown> | null | undefined>\n}\n\nfunction normalizeId(value: unknown): string {\n return String(value)\n}\n\nfunction normalizeScopedValue(value: unknown): string | null {\n if (value === undefined || value === null || value === '') return null\n return String(value)\n}\n\ntype IndexRowPayload = {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n doc: Record<string, unknown>\n tokenDoc: Record<string, unknown>\n index_version: number\n}\n\nasync function updateIndexRow(db: Kysely<any>, payload: IndexRowPayload): Promise<number> {\n let updateQuery = db\n .updateTable('entity_indexes' as any)\n .set({\n doc: sql`${JSON.stringify(payload.doc)}::jsonb`,\n index_version: payload.index_version,\n organization_id: payload.organization_id ?? null,\n tenant_id: payload.tenant_id ?? null,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any)\n .where('entity_type' as any, '=', payload.entity_type)\n .where('entity_id' as any, '=', payload.entity_id)\n updateQuery = payload.organization_id == null\n ? updateQuery.where('organization_id' as any, 'is', null as any)\n : updateQuery.where('organization_id' as any, '=', payload.organization_id)\n const result = await updateQuery.executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n return Number(result?.numUpdatedRows ?? 0)\n}\n\nexport async function upsertIndexBatch(\n db: Kysely<any>,\n entityType: string,\n rows: AnyRow[],\n scope: ScopeOverrides,\n options: IndexBatchOptions = {},\n): Promise<UpsertIndexBatchResult> {\n if (!rows.length) return createEmptyUpsertIndexBatchResult()\n const recordIds = rows.map((row) => normalizeId(row.id))\n\n const failedRecordIds: string[] = []\n let searchTokenFailures = 0\n let recordedRowErrors = 0\n\n const recordRowFailure = async (\n recordId: string,\n error: unknown,\n handler: string,\n rowScope: { organizationId: string | null; tenantId: string | null },\n ): Promise<void> => {\n failedRecordIds.push(recordId)\n if (recordedRowErrors >= MAX_RECORDED_ROW_ERRORS_PER_BATCH) return\n recordedRowErrors += 1\n await recordIndexerError(\n { db },\n {\n source: 'query_index',\n handler,\n error,\n entityType,\n recordId,\n tenantId: rowScope.tenantId,\n organizationId: rowScope.organizationId,\n },\n ).catch(() => undefined)\n }\n\n const shouldMergeCustomerEntity =\n entityType === 'customers:customer_person_profile' || entityType === 'customers:customer_company_profile'\n\n let customerEntitiesById: Map<string, AnyRow> | null = null\n if (shouldMergeCustomerEntity) {\n const entityIds = Array.from(\n new Set(\n rows\n .map((row) => (row as AnyRow).entity_id || (row as AnyRow).entityId)\n .filter((value): value is string | number => value !== undefined && value !== null && `${value}` !== '')\n .map((value) => normalizeId(value)),\n ),\n )\n if (entityIds.length) {\n const entityRows = await db\n .selectFrom('customer_entities' as any)\n .selectAll()\n .where('id' as any, 'in', entityIds)\n .execute() as AnyRow[]\n customerEntitiesById = new Map(entityRows.map((row) => [normalizeId(row.id), row]))\n }\n }\n\n const customFieldRows = await db\n .selectFrom('custom_field_values' as any)\n .select([\n 'record_id' as any,\n 'field_key' as any,\n 'value_text' as any,\n 'value_multiline' as any,\n 'value_int' as any,\n 'value_float' as any,\n 'value_bool' as any,\n 'organization_id' as any,\n 'tenant_id' as any,\n ])\n .where('entity_id' as any, '=', entityType)\n .where('record_id' as any, 'in', recordIds)\n .execute() as CustomFieldRow[]\n\n const customFieldMap = new Map<string, CustomFieldRow[]>()\n for (const fieldRow of customFieldRows) {\n const key = normalizeId(fieldRow.record_id)\n const bucket = customFieldMap.get(key)\n if (bucket) bucket.push(fieldRow)\n else customFieldMap.set(key, [fieldRow])\n }\n\n const basePayloads: IndexRowPayload[] = []\n\n const debugEnabled = isSearchDebugEnabled()\n const searchConfig = resolveSearchConfig()\n\n for (const row of rows) {\n const recordId = normalizeId(row.id)\n const baseOrg = normalizeScopedValue((row as AnyRow).organization_id)\n const baseTenant = normalizeScopedValue((row as AnyRow).tenant_id)\n const derivedOrg = options?.deriveOrganizationId\n ? normalizeScopedValue(options.deriveOrganizationId(row))\n : undefined\n const scopeOrg =\n scope.orgId !== undefined\n ? scope.orgId\n : derivedOrg !== undefined\n ? derivedOrg\n : baseOrg\n const scopeTenant = scope.tenantId !== undefined ? scope.tenantId : baseTenant\n const inputRows = customFieldMap.get(recordId) ?? []\n const values: IndexCustomFieldValue[] = inputRows.map((fieldRow) => ({\n key: fieldRow.field_key,\n value:\n fieldRow.value_bool ??\n fieldRow.value_int ??\n fieldRow.value_float ??\n fieldRow.value_text ??\n fieldRow.value_multiline ??\n null,\n organizationId: normalizeScopedValue(fieldRow.organization_id),\n tenantId: normalizeScopedValue(fieldRow.tenant_id),\n }))\n const mergedRow = (() => {\n if (!shouldMergeCustomerEntity || !customerEntitiesById) return row\n const entityId = (row as AnyRow).entity_id || (row as AnyRow).entityId\n if (!entityId) return row\n const entityRow = customerEntitiesById.get(normalizeId(entityId))\n if (!entityRow) return row\n return { ...entityRow, ...row }\n })()\n let doc = buildIndexDocument(\n mergedRow,\n values,\n {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n },\n { entityType, config: searchConfig },\n )\n let tokenDoc: Record<string, unknown> = doc\n if (typeof options.encryptDoc === 'function') {\n try {\n const encrypted = await options.encryptDoc(entityType, doc, {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n })\n if (encrypted && typeof encrypted === 'object') {\n doc = encrypted\n tokenDoc = encrypted\n }\n } catch (encryptError) {\n // Falling through would write the plaintext document into entity_indexes,\n // which must stay encrypted at rest. Skip the row instead so the previously\n // encrypted row survives, and let the caller fail the run.\n await recordRowFailure(recordId, encryptError, 'query_index:reindex-batch:encrypt', {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n })\n continue\n }\n }\n if (typeof options.decryptDoc === 'function') {\n try {\n const decrypted = await options.decryptDoc(entityType, doc, {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n })\n if (decrypted && typeof decrypted === 'object') {\n // Rebuilt on the decrypted copy: `search_text` is on no encryption map, so the\n // aggregate composed at document-build time still concatenates the ciphertext\n // values the row carries at rest and tokenizes into rows nothing matches (#5625).\n // The copy keeps `doc` \u2014 the encrypted row written to `entity_indexes` \u2014 untouched.\n // A caller that passes no `decryptDoc` keeps the build-time aggregate by design:\n // without a decryption step there is no plaintext to recompose it from.\n tokenDoc = rebuildAggregateSearchField(decrypted, { entityType, config: searchConfig })\n }\n } catch (decryptError) {\n // Only affects the search tokens built below; the indexed document itself is\n // unharmed, so the row still counts as written.\n logger.warn('Failed to decrypt index document for search tokens', { entityType, recordId })\n await recordIndexerError(\n { db },\n {\n source: 'fulltext',\n handler: 'query_index:reindex-batch:decrypt',\n error: decryptError,\n entityType,\n recordId,\n tenantId: scopeTenant ?? null,\n organizationId: scopeOrg ?? null,\n },\n ).catch(() => undefined)\n }\n }\n basePayloads.push({\n entity_type: entityType,\n entity_id: recordId,\n organization_id: scopeOrg ?? null,\n tenant_id: scopeTenant ?? null,\n doc,\n tokenDoc,\n index_version: 1,\n })\n if (debugEnabled) {\n const sample = {\n display_name: (tokenDoc as any).display_name,\n first_name: (tokenDoc as any).first_name,\n last_name: (tokenDoc as any).last_name,\n brand_name: (tokenDoc as any).brand_name,\n legal_name: (tokenDoc as any).legal_name,\n }\n logger.debug('Reindex batch document', {\n entityType,\n recordId,\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n sample,\n })\n }\n }\n\n const insertRows = basePayloads.map((payload) => ({\n entity_type: payload.entity_type,\n entity_id: payload.entity_id,\n organization_id: payload.organization_id,\n tenant_id: payload.tenant_id,\n doc: sql`${JSON.stringify(payload.doc)}::jsonb`,\n index_version: payload.index_version,\n created_at: sql`now()`,\n updated_at: sql`now()`,\n deleted_at: null,\n }))\n\n const tokenPayloads = basePayloads.map((payload) => ({\n entityType: payload.entity_type,\n recordId: payload.entity_id,\n organizationId: payload.organization_id,\n tenantId: payload.tenant_id,\n doc: payload.tokenDoc,\n }))\n\n const writeSearchTokens = async (payloads = tokenPayloads): Promise<void> => {\n if (!payloads.length) return\n try {\n await replaceSearchTokensForBatch(db, payloads)\n } catch (searchTokenError) {\n // Record instead of swallowing: a failed token write leaves fulltext search stale.\n // Not counted as a write failure \u2014 replaceSearchTokensForBatch is transactional, so\n // tokens end up stale rather than missing, and the record's next write rebuilds them.\n searchTokenFailures += 1\n await recordIndexerError(\n { db },\n { source: 'fulltext', handler: 'query_index:reindex-batch', error: searchTokenError, entityType, tenantId: scope.tenantId ?? null, organizationId: scope.orgId ?? null },\n ).catch(() => undefined)\n }\n }\n\n const buildResult = (written: number): UpsertIndexBatchResult => ({\n attempted: rows.length,\n written,\n failedRecordIds,\n searchTokenFailures,\n })\n\n if (!basePayloads.length) return buildResult(0)\n\n let bulkWriteFailed = false\n try {\n // One statement, so it is atomic on its own. Note the arbiter is\n // (entity_type, entity_id, organization_id_coalesced): two payloads sharing a\n // conflict key in the same batch would raise 21000 for the whole statement and\n // fall through to the per-row path below.\n await db\n .insertInto('entity_indexes' as any)\n .values(insertRows as any)\n .onConflict((oc: any) => oc\n .columns(['entity_type', 'entity_id', 'organization_id_coalesced'])\n .doUpdateSet({\n doc: sql`excluded.doc`,\n index_version: sql`excluded.index_version`,\n organization_id: sql`excluded.organization_id`,\n tenant_id: sql`excluded.tenant_id`,\n deleted_at: sql`excluded.deleted_at`,\n updated_at: sql`now()`,\n } as any))\n .execute()\n } catch (bulkError) {\n bulkWriteFailed = true\n logger.warn('Bulk index upsert failed; falling back to per-row writes', {\n entityType,\n records: basePayloads.length,\n })\n await recordIndexerError(\n { db },\n {\n source: 'query_index',\n handler: 'query_index:reindex-batch:bulk',\n error: bulkError,\n entityType,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.orgId ?? null,\n },\n ).catch(() => undefined)\n }\n\n if (!bulkWriteFailed) {\n await writeSearchTokens()\n if (debugEnabled) {\n logger.debug('Reindex batch tokens', {\n entityType,\n records: basePayloads.length,\n scopeOrg: scope.orgId ?? null,\n scopeTenant: scope.tenantId ?? null,\n })\n }\n return buildResult(basePayloads.length)\n }\n\n // Deliberately NOT wrapped in a transaction. In Postgres a single failing statement\n // aborts the surrounding transaction, and COMMIT on an aborted transaction answers\n // with a ROLLBACK tag instead of raising \u2014 so one bad row used to discard the entire\n // batch while this function reported success (issue GSM-266). Each row here is an\n // independent, idempotent upsert; they share no invariant worth a transaction.\n let written = 0\n for (const payload of basePayloads) {\n try {\n if (await updateIndexRow(db, payload) > 0) {\n written += 1\n continue\n }\n try {\n await db\n .insertInto('entity_indexes' as any)\n .values({\n entity_type: payload.entity_type,\n entity_id: payload.entity_id,\n organization_id: payload.organization_id,\n tenant_id: payload.tenant_id,\n doc: sql`${JSON.stringify(payload.doc)}::jsonb`,\n index_version: payload.index_version,\n created_at: sql`now()`,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any)\n .execute()\n written += 1\n } catch (insertError) {\n // A concurrent worker may have inserted the row between our UPDATE and INSERT.\n // Only a successful retry of the UPDATE proves the row is actually there.\n if (isUniqueViolation(insertError) && await updateIndexRow(db, payload) > 0) {\n written += 1\n continue\n }\n await recordRowFailure(payload.entity_id, insertError, 'query_index:reindex-batch:row', {\n organizationId: payload.organization_id,\n tenantId: payload.tenant_id,\n })\n }\n } catch (rowError) {\n await recordRowFailure(payload.entity_id, rowError, 'query_index:reindex-batch:row', {\n organizationId: payload.organization_id,\n tenantId: payload.tenant_id,\n })\n }\n }\n\n const failedRecordIdSet = new Set(failedRecordIds)\n await writeSearchTokens(tokenPayloads.filter((payload) => !failedRecordIdSet.has(payload.recordId)))\n return buildResult(written)\n}\n"],
5
- "mappings": "AAAA,SAAsB,WAAW;AACjC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC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,QAAQ;AAAA,UACxB,UAAU,QAAQ;AAAA,QACpB,CAAC;AAAA,MACH;AAAA,IACF,SAAS,UAAU;AACjB,YAAM,iBAAiB,QAAQ,WAAW,UAAU,iCAAiC;AAAA,QACnF,gBAAgB,QAAQ;AAAA,QACxB,UAAU,QAAQ;AAAA,MACpB,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,oBAAoB,IAAI,IAAI,eAAe;AACjD,QAAM,kBAAkB,cAAc,OAAO,CAAC,YAAY,CAAC,kBAAkB,IAAI,QAAQ,QAAQ,CAAC,CAAC;AACnG,SAAO,YAAY,OAAO;AAC5B;",
4
+ "sourcesContent": ["import { type Kysely, sql } from 'kysely'\nimport { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'\nimport { isUniqueViolation } from '@open-mercato/shared/lib/db/pg-errors'\nimport { buildIndexDocument, rebuildAggregateSearchField, type IndexCustomFieldValue } from './document'\nimport { replaceSearchTokensForBatch, isSearchDebugEnabled } from './search-tokens'\nimport { applyIndexDocEnrichers, type IndexDocEnrichmentTarget } from './doc-enrichers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { resolveSearchConfig } from '@open-mercato/shared/lib/search/config'\n\nconst logger = createLogger('query_index').child({ component: 'reindex-batch' })\n\n/**\n * Cap on how many per-row failures a single batch persists to `indexer_error_logs`.\n * Under a systemic failure (pool exhausted, disk full, KMS down) every row fails, and\n * writing one error row per record would hammer the database that is already failing.\n * The count of suppressed failures still reaches the caller via `failedRecordIds`.\n */\nconst MAX_RECORDED_ROW_ERRORS_PER_BATCH = 50\n\nexport type AnyRow = Record<string, any> & { id: string | number }\n\nexport type ScopeOverrides = {\n orgId?: string\n tenantId?: string\n}\n\n/**\n * What a batch actually wrote, as opposed to what it was asked to write. Callers MUST\n * reconcile `written` against `attempted` \u2014 a batch that loses rows and reports success\n * is how records go permanently missing from the index (issue GSM-266).\n */\nexport type UpsertIndexBatchResult = {\n attempted: number\n written: number\n failedRecordIds: string[]\n searchTokenFailures: number\n}\n\nexport class QueryIndexBatchWriteError extends Error {\n readonly entityType: string\n readonly attempted: number\n readonly written: number\n readonly failedRecordIds: string[]\n\n constructor(entityType: string, result: UpsertIndexBatchResult) {\n const preview = result.failedRecordIds.slice(0, 10)\n const suffix = result.failedRecordIds.length > preview.length ? ', ...' : ''\n super(\n `[internal] Query index write incomplete for ${entityType}: wrote ${result.written} of ${result.attempted} records` +\n (preview.length ? ` (failed: ${preview.join(', ')}${suffix})` : ''),\n )\n this.name = 'QueryIndexBatchWriteError'\n this.entityType = entityType\n this.attempted = result.attempted\n this.written = result.written\n this.failedRecordIds = result.failedRecordIds\n }\n}\n\nexport function assertIndexBatchWritesLanded(entityType: string, result: UpsertIndexBatchResult): void {\n if (result.written >= result.attempted && result.failedRecordIds.length === 0) return\n throw new QueryIndexBatchWriteError(entityType, result)\n}\n\nexport function createEmptyUpsertIndexBatchResult(): UpsertIndexBatchResult {\n return { attempted: 0, written: 0, failedRecordIds: [], searchTokenFailures: 0 }\n}\n\nexport function mergeUpsertIndexBatchResults(\n target: UpsertIndexBatchResult,\n addition: UpsertIndexBatchResult,\n): UpsertIndexBatchResult {\n target.attempted += addition.attempted\n target.written += addition.written\n target.searchTokenFailures += addition.searchTokenFailures\n target.failedRecordIds.push(...addition.failedRecordIds)\n return target\n}\n\ntype CustomFieldRow = {\n record_id: string\n field_key: string\n value_text: string | null\n value_multiline: string | null\n value_int: number | null\n value_float: number | null\n value_bool: boolean | null\n organization_id: string | null\n tenant_id: string | null\n}\n\nexport type IndexBatchOptions = {\n deriveOrganizationId?: (row: AnyRow) => string | null | undefined\n encryptDoc?: (\n entityType: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => Promise<Record<string, unknown> | null | undefined>\n decryptDoc?: (\n entityType: string,\n doc: Record<string, unknown>,\n scope: { organizationId: string | null; tenantId: string | null },\n ) => Promise<Record<string, unknown> | null | undefined>\n}\n\nfunction normalizeId(value: unknown): string {\n return String(value)\n}\n\nfunction normalizeScopedValue(value: unknown): string | null {\n if (value === undefined || value === null || value === '') return null\n return String(value)\n}\n\ntype IndexRowPayload = {\n entity_type: string\n entity_id: string\n organization_id: string | null\n tenant_id: string | null\n doc: Record<string, unknown>\n tokenDoc: Record<string, unknown>\n index_version: number\n}\n\nasync function updateIndexRow(db: Kysely<any>, payload: IndexRowPayload): Promise<number> {\n let updateQuery = db\n .updateTable('entity_indexes' as any)\n .set({\n doc: sql`${JSON.stringify(payload.doc)}::jsonb`,\n index_version: payload.index_version,\n organization_id: payload.organization_id ?? null,\n tenant_id: payload.tenant_id ?? null,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any)\n .where('entity_type' as any, '=', payload.entity_type)\n .where('entity_id' as any, '=', payload.entity_id)\n updateQuery = payload.organization_id == null\n ? updateQuery.where('organization_id' as any, 'is', null as any)\n : updateQuery.where('organization_id' as any, '=', payload.organization_id)\n const result = await updateQuery.executeTakeFirst() as { numUpdatedRows?: bigint | number } | undefined\n return Number(result?.numUpdatedRows ?? 0)\n}\n\nexport async function upsertIndexBatch(\n db: Kysely<any>,\n entityType: string,\n rows: AnyRow[],\n scope: ScopeOverrides,\n options: IndexBatchOptions = {},\n): Promise<UpsertIndexBatchResult> {\n if (!rows.length) return createEmptyUpsertIndexBatchResult()\n const recordIds = rows.map((row) => normalizeId(row.id))\n\n const failedRecordIds: string[] = []\n let searchTokenFailures = 0\n let recordedRowErrors = 0\n\n const recordRowFailure = async (\n recordId: string,\n error: unknown,\n handler: string,\n rowScope: { organizationId: string | null; tenantId: string | null },\n ): Promise<void> => {\n failedRecordIds.push(recordId)\n if (recordedRowErrors >= MAX_RECORDED_ROW_ERRORS_PER_BATCH) return\n recordedRowErrors += 1\n await recordIndexerError(\n { db },\n {\n source: 'query_index',\n handler,\n error,\n entityType,\n recordId,\n tenantId: rowScope.tenantId,\n organizationId: rowScope.organizationId,\n },\n ).catch(() => undefined)\n }\n\n const shouldMergeCustomerEntity =\n entityType === 'customers:customer_person_profile' || entityType === 'customers:customer_company_profile'\n\n let customerEntitiesById: Map<string, AnyRow> | null = null\n if (shouldMergeCustomerEntity) {\n const entityIds = Array.from(\n new Set(\n rows\n .map((row) => (row as AnyRow).entity_id || (row as AnyRow).entityId)\n .filter((value): value is string | number => value !== undefined && value !== null && `${value}` !== '')\n .map((value) => normalizeId(value)),\n ),\n )\n if (entityIds.length) {\n const entityRows = await db\n .selectFrom('customer_entities' as any)\n .selectAll()\n .where('id' as any, 'in', entityIds)\n .execute() as AnyRow[]\n customerEntitiesById = new Map(entityRows.map((row) => [normalizeId(row.id), row]))\n }\n }\n\n const customFieldRows = await db\n .selectFrom('custom_field_values' as any)\n .select([\n 'record_id' as any,\n 'field_key' as any,\n 'value_text' as any,\n 'value_multiline' as any,\n 'value_int' as any,\n 'value_float' as any,\n 'value_bool' as any,\n 'organization_id' as any,\n 'tenant_id' as any,\n ])\n .where('entity_id' as any, '=', entityType)\n .where('record_id' as any, 'in', recordIds)\n .execute() as CustomFieldRow[]\n\n const customFieldMap = new Map<string, CustomFieldRow[]>()\n for (const fieldRow of customFieldRows) {\n const key = normalizeId(fieldRow.record_id)\n const bucket = customFieldMap.get(key)\n if (bucket) bucket.push(fieldRow)\n else customFieldMap.set(key, [fieldRow])\n }\n\n const basePayloads: IndexRowPayload[] = []\n\n const debugEnabled = isSearchDebugEnabled()\n const searchConfig = resolveSearchConfig()\n\n const builtDocs: IndexDocEnrichmentTarget[] = []\n for (const row of rows) {\n const recordId = normalizeId(row.id)\n const baseOrg = normalizeScopedValue((row as AnyRow).organization_id)\n const baseTenant = normalizeScopedValue((row as AnyRow).tenant_id)\n const derivedOrg = options?.deriveOrganizationId\n ? normalizeScopedValue(options.deriveOrganizationId(row))\n : undefined\n const scopeOrg =\n scope.orgId !== undefined\n ? scope.orgId\n : derivedOrg !== undefined\n ? derivedOrg\n : baseOrg\n const scopeTenant = scope.tenantId !== undefined ? scope.tenantId : baseTenant\n const inputRows = customFieldMap.get(recordId) ?? []\n const values: IndexCustomFieldValue[] = inputRows.map((fieldRow) => ({\n key: fieldRow.field_key,\n value:\n fieldRow.value_bool ??\n fieldRow.value_int ??\n fieldRow.value_float ??\n fieldRow.value_text ??\n fieldRow.value_multiline ??\n null,\n organizationId: normalizeScopedValue(fieldRow.organization_id),\n tenantId: normalizeScopedValue(fieldRow.tenant_id),\n }))\n const mergedRow = (() => {\n if (!shouldMergeCustomerEntity || !customerEntitiesById) return row\n const entityId = (row as AnyRow).entity_id || (row as AnyRow).entityId\n if (!entityId) return row\n const entityRow = customerEntitiesById.get(normalizeId(entityId))\n if (!entityRow) return row\n return { ...entityRow, ...row }\n })()\n builtDocs.push({\n recordId,\n doc: buildIndexDocument(\n mergedRow,\n values,\n {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n },\n { entityType, config: searchConfig },\n ),\n tenantId: scopeTenant ?? null,\n organizationId: scopeOrg ?? null,\n })\n }\n\n await applyIndexDocEnrichers(db, entityType, builtDocs)\n\n for (const built of builtDocs) {\n const recordId = built.recordId\n const scopeOrg = built.organizationId\n const scopeTenant = built.tenantId\n let doc = built.doc\n let tokenDoc: Record<string, unknown> = doc\n if (typeof options.encryptDoc === 'function') {\n try {\n const encrypted = await options.encryptDoc(entityType, doc, {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n })\n if (encrypted && typeof encrypted === 'object') {\n doc = encrypted\n tokenDoc = encrypted\n }\n } catch (encryptError) {\n // Falling through would write the plaintext document into entity_indexes,\n // which must stay encrypted at rest. Skip the row instead so the previously\n // encrypted row survives, and let the caller fail the run.\n await recordRowFailure(recordId, encryptError, 'query_index:reindex-batch:encrypt', {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n })\n continue\n }\n }\n if (typeof options.decryptDoc === 'function') {\n try {\n const decrypted = await options.decryptDoc(entityType, doc, {\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n })\n if (decrypted && typeof decrypted === 'object') {\n // Rebuilt on the decrypted copy: `search_text` is on no encryption map, so the\n // aggregate composed at document-build time still concatenates the ciphertext\n // values the row carries at rest and tokenizes into rows nothing matches (#5625).\n // The copy keeps `doc` \u2014 the encrypted row written to `entity_indexes` \u2014 untouched.\n // A caller that passes no `decryptDoc` keeps the build-time aggregate by design:\n // without a decryption step there is no plaintext to recompose it from.\n tokenDoc = rebuildAggregateSearchField(decrypted, { entityType, config: searchConfig })\n }\n } catch (decryptError) {\n // Only affects the search tokens built below; the indexed document itself is\n // unharmed, so the row still counts as written.\n logger.warn('Failed to decrypt index document for search tokens', { entityType, recordId })\n await recordIndexerError(\n { db },\n {\n source: 'fulltext',\n handler: 'query_index:reindex-batch:decrypt',\n error: decryptError,\n entityType,\n recordId,\n tenantId: scopeTenant ?? null,\n organizationId: scopeOrg ?? null,\n },\n ).catch(() => undefined)\n }\n }\n basePayloads.push({\n entity_type: entityType,\n entity_id: recordId,\n organization_id: scopeOrg ?? null,\n tenant_id: scopeTenant ?? null,\n doc,\n tokenDoc,\n index_version: 1,\n })\n if (debugEnabled) {\n const sample = {\n display_name: (tokenDoc as any).display_name,\n first_name: (tokenDoc as any).first_name,\n last_name: (tokenDoc as any).last_name,\n brand_name: (tokenDoc as any).brand_name,\n legal_name: (tokenDoc as any).legal_name,\n }\n logger.debug('Reindex batch document', {\n entityType,\n recordId,\n organizationId: scopeOrg ?? null,\n tenantId: scopeTenant ?? null,\n sample,\n })\n }\n }\n\n const insertRows = basePayloads.map((payload) => ({\n entity_type: payload.entity_type,\n entity_id: payload.entity_id,\n organization_id: payload.organization_id,\n tenant_id: payload.tenant_id,\n doc: sql`${JSON.stringify(payload.doc)}::jsonb`,\n index_version: payload.index_version,\n created_at: sql`now()`,\n updated_at: sql`now()`,\n deleted_at: null,\n }))\n\n const tokenPayloads = basePayloads.map((payload) => ({\n entityType: payload.entity_type,\n recordId: payload.entity_id,\n organizationId: payload.organization_id,\n tenantId: payload.tenant_id,\n doc: payload.tokenDoc,\n }))\n\n const writeSearchTokens = async (payloads = tokenPayloads): Promise<void> => {\n if (!payloads.length) return\n try {\n await replaceSearchTokensForBatch(db, payloads)\n } catch (searchTokenError) {\n // Record instead of swallowing: a failed token write leaves fulltext search stale.\n // Not counted as a write failure \u2014 replaceSearchTokensForBatch is transactional, so\n // tokens end up stale rather than missing, and the record's next write rebuilds them.\n searchTokenFailures += 1\n await recordIndexerError(\n { db },\n { source: 'fulltext', handler: 'query_index:reindex-batch', error: searchTokenError, entityType, tenantId: scope.tenantId ?? null, organizationId: scope.orgId ?? null },\n ).catch(() => undefined)\n }\n }\n\n const buildResult = (written: number): UpsertIndexBatchResult => ({\n attempted: rows.length,\n written,\n failedRecordIds,\n searchTokenFailures,\n })\n\n if (!basePayloads.length) return buildResult(0)\n\n let bulkWriteFailed = false\n try {\n // One statement, so it is atomic on its own. Note the arbiter is\n // (entity_type, entity_id, organization_id_coalesced): two payloads sharing a\n // conflict key in the same batch would raise 21000 for the whole statement and\n // fall through to the per-row path below.\n await db\n .insertInto('entity_indexes' as any)\n .values(insertRows as any)\n .onConflict((oc: any) => oc\n .columns(['entity_type', 'entity_id', 'organization_id_coalesced'])\n .doUpdateSet({\n doc: sql`excluded.doc`,\n index_version: sql`excluded.index_version`,\n organization_id: sql`excluded.organization_id`,\n tenant_id: sql`excluded.tenant_id`,\n deleted_at: sql`excluded.deleted_at`,\n updated_at: sql`now()`,\n } as any))\n .execute()\n } catch (bulkError) {\n bulkWriteFailed = true\n logger.warn('Bulk index upsert failed; falling back to per-row writes', {\n entityType,\n records: basePayloads.length,\n })\n await recordIndexerError(\n { db },\n {\n source: 'query_index',\n handler: 'query_index:reindex-batch:bulk',\n error: bulkError,\n entityType,\n tenantId: scope.tenantId ?? null,\n organizationId: scope.orgId ?? null,\n },\n ).catch(() => undefined)\n }\n\n if (!bulkWriteFailed) {\n await writeSearchTokens()\n if (debugEnabled) {\n logger.debug('Reindex batch tokens', {\n entityType,\n records: basePayloads.length,\n scopeOrg: scope.orgId ?? null,\n scopeTenant: scope.tenantId ?? null,\n })\n }\n return buildResult(basePayloads.length)\n }\n\n // Deliberately NOT wrapped in a transaction. In Postgres a single failing statement\n // aborts the surrounding transaction, and COMMIT on an aborted transaction answers\n // with a ROLLBACK tag instead of raising \u2014 so one bad row used to discard the entire\n // batch while this function reported success (issue GSM-266). Each row here is an\n // independent, idempotent upsert; they share no invariant worth a transaction.\n let written = 0\n for (const payload of basePayloads) {\n try {\n if (await updateIndexRow(db, payload) > 0) {\n written += 1\n continue\n }\n try {\n await db\n .insertInto('entity_indexes' as any)\n .values({\n entity_type: payload.entity_type,\n entity_id: payload.entity_id,\n organization_id: payload.organization_id,\n tenant_id: payload.tenant_id,\n doc: sql`${JSON.stringify(payload.doc)}::jsonb`,\n index_version: payload.index_version,\n created_at: sql`now()`,\n updated_at: sql`now()`,\n deleted_at: null,\n } as any)\n .execute()\n written += 1\n } catch (insertError) {\n // A concurrent worker may have inserted the row between our UPDATE and INSERT.\n // Only a successful retry of the UPDATE proves the row is actually there.\n if (isUniqueViolation(insertError) && await updateIndexRow(db, payload) > 0) {\n written += 1\n continue\n }\n await recordRowFailure(payload.entity_id, insertError, 'query_index:reindex-batch:row', {\n organizationId: payload.organization_id,\n tenantId: payload.tenant_id,\n })\n }\n } catch (rowError) {\n await recordRowFailure(payload.entity_id, rowError, 'query_index:reindex-batch:row', {\n organizationId: payload.organization_id,\n tenantId: payload.tenant_id,\n })\n }\n }\n\n const failedRecordIdSet = new Set(failedRecordIds)\n await writeSearchTokens(tokenPayloads.filter((payload) => !failedRecordIdSet.has(payload.recordId)))\n return buildResult(written)\n}\n"],
5
+ "mappings": "AAAA,SAAsB,WAAW;AACjC,SAAS,0BAA0B;AACnC,SAAS,yBAAyB;AAClC,SAAS,oBAAoB,mCAA+D;AAC5F,SAAS,6BAA6B,4BAA4B;AAClE,SAAS,8BAA6D;AACtE,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,E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AI,kBAAkB,WAAW,KAAK,MAAM,eAAe,IAAI,OAAO,IAAI,GAAG;AAC3E,qBAAW;AACX;AAAA,QACF;AACA,cAAM,iBAAiB,QAAQ,WAAW,aAAa,iCAAiC;AAAA,UACtF,gBAAgB,QAAQ;AAAA,UACxB,UAAU,QAAQ;AAAA,QACpB,CAAC;AAAA,MACH;AAAA,IACF,SAAS,UAAU;AACjB,YAAM,iBAAiB,QAAQ,WAAW,UAAU,iCAAiC;AAAA,QACnF,gBAAgB,QAAQ;AAAA,QACxB,UAAU,QAAQ;AAAA,MACpB,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,oBAAoB,IAAI,IAAI,eAAe;AACjD,QAAM,kBAAkB,cAAc,OAAO,CAAC,YAAY,CAAC,kBAAkB,IAAI,QAAQ,QAAQ,CAAC,CAAC;AACnG,SAAO,YAAY,OAAO;AAC5B;",
6
6
  "names": ["written"]
7
7
  }
@@ -0,0 +1,212 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ import { recordIndexerError } from "@open-mercato/shared/lib/indexers/error-log";
3
+ import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
4
+ const logger = createLogger("query_index").child({ component: "doc-enrichers" });
5
+ const INDEX_DOC_ENRICHER_KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
6
+ const RESERVED_INDEX_DOC_KEYS = /* @__PURE__ */ new Set([
7
+ "id",
8
+ "tenant_id",
9
+ "organization_id",
10
+ "created_at",
11
+ "updated_at",
12
+ "deleted_at",
13
+ "search_text"
14
+ ]);
15
+ const GLOBAL_ENRICHER_REGISTRY_KEY = "__openMercatoQueryIndexDocEnrichers__";
16
+ function getRegistryState() {
17
+ const globalRegistry = globalThis;
18
+ if (!globalRegistry[GLOBAL_ENRICHER_REGISTRY_KEY]) {
19
+ globalRegistry[GLOBAL_ENRICHER_REGISTRY_KEY] = { byEntityType: /* @__PURE__ */ new Map() };
20
+ }
21
+ return globalRegistry[GLOBAL_ENRICHER_REGISTRY_KEY];
22
+ }
23
+ function validateEnricher(enricher, existing) {
24
+ if (typeof enricher.id !== "string" || !enricher.id.trim()) {
25
+ throw new Error("[internal] Index doc enricher requires a non-empty id");
26
+ }
27
+ if (typeof enricher.entityType !== "string" || !enricher.entityType.includes(":")) {
28
+ throw new Error(`[internal] Index doc enricher "${enricher.id}" requires an entityType in '<module>:<entity>' form`);
29
+ }
30
+ if (typeof enricher.enrich !== "function") {
31
+ throw new Error(`[internal] Index doc enricher "${enricher.id}" requires an enrich function`);
32
+ }
33
+ const keys = Array.from(new Set(enricher.keys ?? []));
34
+ if (!keys.length) {
35
+ throw new Error(`[internal] Index doc enricher "${enricher.id}" must declare at least one key`);
36
+ }
37
+ for (const key of keys) {
38
+ if (!INDEX_DOC_ENRICHER_KEY_PATTERN.test(key)) {
39
+ throw new Error(`[internal] Index doc enricher "${enricher.id}" key "${key}" must match ${INDEX_DOC_ENRICHER_KEY_PATTERN}`);
40
+ }
41
+ if (RESERVED_INDEX_DOC_KEYS.has(key)) {
42
+ throw new Error(`[internal] Index doc enricher "${enricher.id}" key "${key}" is reserved`);
43
+ }
44
+ const owner = existing.find((entry) => entry.id !== enricher.id && entry.keys.includes(key));
45
+ if (owner) {
46
+ throw new Error(`[internal] Index doc enricher "${enricher.id}" key "${key}" is already contributed by "${owner.id}" for ${enricher.entityType}`);
47
+ }
48
+ }
49
+ return keys;
50
+ }
51
+ function registerIndexDocEnricher(enricher) {
52
+ const state = getRegistryState();
53
+ const existing = state.byEntityType.get(enricher.entityType) ?? [];
54
+ const keys = validateEnricher(enricher, existing);
55
+ const registered = { ...enricher, keys };
56
+ const next = existing.filter((entry) => entry.id !== enricher.id);
57
+ next.push(registered);
58
+ state.byEntityType.set(enricher.entityType, next);
59
+ return () => {
60
+ const current = state.byEntityType.get(enricher.entityType) ?? [];
61
+ const remaining = current.filter((entry) => entry !== registered);
62
+ if (remaining.length) state.byEntityType.set(enricher.entityType, remaining);
63
+ else state.byEntityType.delete(enricher.entityType);
64
+ };
65
+ }
66
+ function getIndexDocEnrichers(entityType) {
67
+ return getRegistryState().byEntityType.get(entityType) ?? [];
68
+ }
69
+ function hasIndexDocEnrichers(entityType) {
70
+ return (getRegistryState().byEntityType.get(entityType)?.length ?? 0) > 0;
71
+ }
72
+ function isIndexDocEnrichedKey(entityType, field) {
73
+ if (!entityType) return false;
74
+ const enrichers = getRegistryState().byEntityType.get(entityType);
75
+ if (!enrichers) return false;
76
+ return enrichers.some((entry) => entry.keys.includes(field));
77
+ }
78
+ function resetIndexDocEnrichers() {
79
+ getRegistryState().byEntityType.clear();
80
+ }
81
+ function scopeGroupKey(target) {
82
+ return `${target.tenantId ?? ""}|${target.organizationId ?? ""}`;
83
+ }
84
+ async function reportEnricherFailure(db, input) {
85
+ logger.error("Index doc enricher failed; contributed keys written as null", {
86
+ enricherId: input.enricher.id,
87
+ entityType: input.entityType,
88
+ tenantId: input.tenantId,
89
+ organizationId: input.organizationId,
90
+ recordId: input.recordId ?? null,
91
+ ...input.details,
92
+ err: input.error
93
+ });
94
+ getTelemetryRuntime()?.reportError(input.error, {
95
+ module: "query_index",
96
+ code: "query_index.doc_enricher_failed"
97
+ });
98
+ await recordIndexerError(
99
+ { db },
100
+ {
101
+ source: "query_index",
102
+ handler: input.handler,
103
+ error: input.error,
104
+ entityType: input.entityType,
105
+ recordId: input.recordId ?? null,
106
+ tenantId: input.tenantId,
107
+ organizationId: input.organizationId,
108
+ payload: { enricherId: input.enricher.id, ...input.details }
109
+ }
110
+ ).catch(() => void 0);
111
+ }
112
+ const COLLISION_SAMPLE_SIZE = 10;
113
+ function nullOut(targets, keys, baseKeys) {
114
+ for (const target of targets) {
115
+ const ownKeys = baseKeys.get(target.recordId);
116
+ for (const key of keys) {
117
+ if (ownKeys?.has(key)) continue;
118
+ target.doc[key] = null;
119
+ }
120
+ }
121
+ }
122
+ async function applyIndexDocEnrichers(db, entityType, targets) {
123
+ const enrichers = getRegistryState().byEntityType.get(entityType);
124
+ if (!enrichers?.length || !targets.length) return;
125
+ const baseKeys = /* @__PURE__ */ new Map();
126
+ for (const target of targets) baseKeys.set(target.recordId, new Set(Object.keys(target.doc)));
127
+ const groups = /* @__PURE__ */ new Map();
128
+ for (const target of targets) {
129
+ const key = scopeGroupKey(target);
130
+ const bucket = groups.get(key);
131
+ if (bucket) bucket.push(target);
132
+ else groups.set(key, [target]);
133
+ }
134
+ for (const enricher of [...enrichers]) {
135
+ for (const group of groups.values()) {
136
+ const { tenantId, organizationId } = group[0];
137
+ let result;
138
+ try {
139
+ const records = group.map((target) => ({ recordId: target.recordId, doc: target.doc }));
140
+ const returned = await enricher.enrich(records, { db, entityType, tenantId, organizationId });
141
+ if (!(returned instanceof Map)) {
142
+ throw new Error(`[internal] Index doc enricher "${enricher.id}" must return a Map keyed by record id`);
143
+ }
144
+ result = returned;
145
+ } catch (error) {
146
+ nullOut(group, enricher.keys, baseKeys);
147
+ await reportEnricherFailure(db, {
148
+ enricher,
149
+ entityType,
150
+ tenantId,
151
+ organizationId,
152
+ error,
153
+ handler: "query_index:doc-enricher"
154
+ });
155
+ continue;
156
+ }
157
+ const collidingRecordIdsByKey = /* @__PURE__ */ new Map();
158
+ for (const target of group) {
159
+ const contribution = result.get(target.recordId);
160
+ const ownKeys = baseKeys.get(target.recordId);
161
+ for (const key of enricher.keys) {
162
+ if (ownKeys?.has(key)) {
163
+ const colliding = collidingRecordIdsByKey.get(key);
164
+ if (colliding) colliding.push(target.recordId);
165
+ else collidingRecordIdsByKey.set(key, [target.recordId]);
166
+ continue;
167
+ }
168
+ const value = contribution && Object.prototype.hasOwnProperty.call(contribution, key) ? contribution[key] : null;
169
+ target.doc[key] = value === void 0 ? null : value;
170
+ }
171
+ if (contribution) {
172
+ const undeclared = Object.keys(contribution).filter((key) => !enricher.keys.includes(key));
173
+ if (undeclared.length) {
174
+ logger.warn("Index doc enricher returned undeclared keys; ignored", {
175
+ enricherId: enricher.id,
176
+ entityType,
177
+ recordId: target.recordId,
178
+ keys: undeclared
179
+ });
180
+ }
181
+ }
182
+ }
183
+ for (const [key, recordIds] of collidingRecordIdsByKey) {
184
+ await reportEnricherFailure(db, {
185
+ enricher,
186
+ entityType,
187
+ tenantId,
188
+ organizationId,
189
+ recordId: recordIds.length === 1 ? recordIds[0] : void 0,
190
+ error: new Error(`[internal] Index doc enricher "${enricher.id}" key "${key}" collides with a base document key of ${entityType} on ${recordIds.length} record(s)`),
191
+ handler: "query_index:doc-enricher:collision",
192
+ details: {
193
+ collidingKey: key,
194
+ collidingRecordCount: recordIds.length,
195
+ sampleRecordIds: recordIds.slice(0, COLLISION_SAMPLE_SIZE)
196
+ }
197
+ });
198
+ }
199
+ }
200
+ }
201
+ }
202
+ export {
203
+ INDEX_DOC_ENRICHER_KEY_PATTERN,
204
+ RESERVED_INDEX_DOC_KEYS,
205
+ applyIndexDocEnrichers,
206
+ getIndexDocEnrichers,
207
+ hasIndexDocEnrichers,
208
+ isIndexDocEnrichedKey,
209
+ registerIndexDocEnricher,
210
+ resetIndexDocEnrichers
211
+ };
212
+ //# sourceMappingURL=doc-enrichers.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/query_index/lib/doc-enrichers.ts"],
4
+ "sourcesContent": ["import type { Kysely } from 'kysely'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { recordIndexerError } from '@open-mercato/shared/lib/indexers/error-log'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\n\nconst logger = createLogger('query_index').child({ component: 'doc-enrichers' })\n\n/**\n * Index-document enrichment \u2014 lets the module that owns an entity contribute computed keys to\n * that entity's `entity_indexes.doc` at index time (Storefront Public API \u00A73.3, decision D9).\n *\n * Registration is programmatic (call `registerIndexDocEnricher` from the owning module's `di.ts`);\n * there is no auto-discovered module file for it.\n *\n * Key namespace: every enricher declares the exact keys it writes. A key MUST be a lowercase\n * snake_case identifier (`^[a-z][a-z0-9_]*$`), so it can never collide with `cf:*` custom-field\n * keys or `l10n:*` translation keys, MUST NOT be one of the reserved document keys, and MUST NOT be\n * declared by another enricher of the same entity type. A key that turns out to be a base column\n * of the indexed row is a collision detected at index time: the base value is kept, the\n * contribution is discarded and the error is recorded.\n *\n * Failure semantics (fail closed, detectable): when an enricher throws, or returns nothing for a\n * record, every key it declares is written as JSON `null` on the affected documents. Consumers\n * MUST treat `null` (and an absent key) as \"not indexed\" \u2014 never as \"empty\". Indexing itself\n * never fails because of an enricher.\n *\n * Enriched keys are filter/projection data: they are excluded from the `search_text` aggregate\n * and from `search_tokens`.\n */\nexport type IndexDocEnricherContext = {\n db: Kysely<any>\n entityType: string\n tenantId: string | null\n organizationId: string | null\n}\n\nexport type IndexDocEnricherRecord = {\n recordId: string\n doc: Readonly<Record<string, unknown>>\n}\n\nexport type IndexDocEnrichment = Record<string, unknown>\n\nexport type IndexDocEnricher = {\n id: string\n entityType: string\n keys: readonly string[]\n enrich: (\n records: readonly IndexDocEnricherRecord[],\n ctx: IndexDocEnricherContext,\n ) => Promise<Map<string, IndexDocEnrichment>>\n}\n\nexport type IndexDocEnrichmentTarget = {\n recordId: string\n doc: Record<string, unknown>\n tenantId: string | null\n organizationId: string | null\n}\n\nexport const INDEX_DOC_ENRICHER_KEY_PATTERN = /^[a-z][a-z0-9_]*$/\n\nexport const RESERVED_INDEX_DOC_KEYS: ReadonlySet<string> = new Set([\n 'id',\n 'tenant_id',\n 'organization_id',\n 'created_at',\n 'updated_at',\n 'deleted_at',\n 'search_text',\n])\n\ntype RegisteredEnricher = IndexDocEnricher & { keys: string[] }\n\ntype EnricherRegistryState = {\n byEntityType: Map<string, RegisteredEnricher[]>\n}\n\nconst GLOBAL_ENRICHER_REGISTRY_KEY = '__openMercatoQueryIndexDocEnrichers__' as const\n\ntype GlobalEnricherRegistry = typeof globalThis & {\n [GLOBAL_ENRICHER_REGISTRY_KEY]?: EnricherRegistryState\n}\n\nfunction getRegistryState(): EnricherRegistryState {\n const globalRegistry = globalThis as GlobalEnricherRegistry\n if (!globalRegistry[GLOBAL_ENRICHER_REGISTRY_KEY]) {\n globalRegistry[GLOBAL_ENRICHER_REGISTRY_KEY] = { byEntityType: new Map() }\n }\n return globalRegistry[GLOBAL_ENRICHER_REGISTRY_KEY]\n}\n\nfunction validateEnricher(enricher: IndexDocEnricher, existing: readonly RegisteredEnricher[]): string[] {\n if (typeof enricher.id !== 'string' || !enricher.id.trim()) {\n throw new Error('[internal] Index doc enricher requires a non-empty id')\n }\n if (typeof enricher.entityType !== 'string' || !enricher.entityType.includes(':')) {\n throw new Error(`[internal] Index doc enricher \"${enricher.id}\" requires an entityType in '<module>:<entity>' form`)\n }\n if (typeof enricher.enrich !== 'function') {\n throw new Error(`[internal] Index doc enricher \"${enricher.id}\" requires an enrich function`)\n }\n const keys = Array.from(new Set(enricher.keys ?? []))\n if (!keys.length) {\n throw new Error(`[internal] Index doc enricher \"${enricher.id}\" must declare at least one key`)\n }\n for (const key of keys) {\n if (!INDEX_DOC_ENRICHER_KEY_PATTERN.test(key)) {\n throw new Error(`[internal] Index doc enricher \"${enricher.id}\" key \"${key}\" must match ${INDEX_DOC_ENRICHER_KEY_PATTERN}`)\n }\n if (RESERVED_INDEX_DOC_KEYS.has(key)) {\n throw new Error(`[internal] Index doc enricher \"${enricher.id}\" key \"${key}\" is reserved`)\n }\n const owner = existing.find((entry) => entry.id !== enricher.id && entry.keys.includes(key))\n if (owner) {\n throw new Error(`[internal] Index doc enricher \"${enricher.id}\" key \"${key}\" is already contributed by \"${owner.id}\" for ${enricher.entityType}`)\n }\n }\n return keys\n}\n\n/**\n * Registers an enricher. Re-registering the same `id` for the same entity type replaces the\n * previous registration (HMR-safe). Throws on an invalid or colliding key declaration.\n * Returns a function that removes the registration.\n */\nexport function registerIndexDocEnricher(enricher: IndexDocEnricher): () => void {\n const state = getRegistryState()\n const existing = state.byEntityType.get(enricher.entityType) ?? []\n const keys = validateEnricher(enricher, existing)\n const registered: RegisteredEnricher = { ...enricher, keys }\n const next = existing.filter((entry) => entry.id !== enricher.id)\n next.push(registered)\n state.byEntityType.set(enricher.entityType, next)\n return () => {\n const current = state.byEntityType.get(enricher.entityType) ?? []\n const remaining = current.filter((entry) => entry !== registered)\n if (remaining.length) state.byEntityType.set(enricher.entityType, remaining)\n else state.byEntityType.delete(enricher.entityType)\n }\n}\n\nexport function getIndexDocEnrichers(entityType: string): readonly IndexDocEnricher[] {\n return getRegistryState().byEntityType.get(entityType) ?? []\n}\n\nexport function hasIndexDocEnrichers(entityType: string): boolean {\n return (getRegistryState().byEntityType.get(entityType)?.length ?? 0) > 0\n}\n\nexport function isIndexDocEnrichedKey(entityType: string | null | undefined, field: string): boolean {\n if (!entityType) return false\n const enrichers = getRegistryState().byEntityType.get(entityType)\n if (!enrichers) return false\n return enrichers.some((entry) => entry.keys.includes(field))\n}\n\nexport function resetIndexDocEnrichers(): void {\n getRegistryState().byEntityType.clear()\n}\n\nfunction scopeGroupKey(target: IndexDocEnrichmentTarget): string {\n return `${target.tenantId ?? ''}|${target.organizationId ?? ''}`\n}\n\nasync function reportEnricherFailure(\n db: Kysely<any>,\n input: {\n enricher: RegisteredEnricher\n entityType: string\n tenantId: string | null\n organizationId: string | null\n recordId?: string\n error: unknown\n handler: string\n details?: Record<string, unknown>\n },\n): Promise<void> {\n logger.error('Index doc enricher failed; contributed keys written as null', {\n enricherId: input.enricher.id,\n entityType: input.entityType,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n recordId: input.recordId ?? null,\n ...input.details,\n err: input.error,\n })\n getTelemetryRuntime()?.reportError(input.error, {\n module: 'query_index',\n code: 'query_index.doc_enricher_failed',\n })\n await recordIndexerError(\n { db },\n {\n source: 'query_index',\n handler: input.handler,\n error: input.error,\n entityType: input.entityType,\n recordId: input.recordId ?? null,\n tenantId: input.tenantId,\n organizationId: input.organizationId,\n payload: { enricherId: input.enricher.id, ...input.details },\n },\n ).catch(() => undefined)\n}\n\nconst COLLISION_SAMPLE_SIZE = 10\n\nfunction nullOut(targets: readonly IndexDocEnrichmentTarget[], keys: readonly string[], baseKeys: Map<string, Set<string>>): void {\n for (const target of targets) {\n const ownKeys = baseKeys.get(target.recordId)\n for (const key of keys) {\n if (ownKeys?.has(key)) continue\n target.doc[key] = null\n }\n }\n}\n\n/**\n * Runs every enricher registered for `entityType` over a batch of freshly built documents and\n * merges the contributed keys into them in place. One `enrich` call per enricher per\n * tenant/organization scope present in the batch \u2014 never per record.\n */\nexport async function applyIndexDocEnrichers(\n db: Kysely<any>,\n entityType: string,\n targets: readonly IndexDocEnrichmentTarget[],\n): Promise<void> {\n const enrichers = getRegistryState().byEntityType.get(entityType)\n if (!enrichers?.length || !targets.length) return\n\n const baseKeys = new Map<string, Set<string>>()\n for (const target of targets) baseKeys.set(target.recordId, new Set(Object.keys(target.doc)))\n\n const groups = new Map<string, IndexDocEnrichmentTarget[]>()\n for (const target of targets) {\n const key = scopeGroupKey(target)\n const bucket = groups.get(key)\n if (bucket) bucket.push(target)\n else groups.set(key, [target])\n }\n\n for (const enricher of [...enrichers]) {\n for (const group of groups.values()) {\n const { tenantId, organizationId } = group[0]\n let result: Map<string, IndexDocEnrichment>\n try {\n const records = group.map((target) => ({ recordId: target.recordId, doc: target.doc }))\n const returned = await enricher.enrich(records, { db, entityType, tenantId, organizationId })\n if (!(returned instanceof Map)) {\n throw new Error(`[internal] Index doc enricher \"${enricher.id}\" must return a Map keyed by record id`)\n }\n result = returned\n } catch (error) {\n nullOut(group, enricher.keys, baseKeys)\n await reportEnricherFailure(db, {\n enricher, entityType, tenantId, organizationId, error,\n handler: 'query_index:doc-enricher',\n })\n continue\n }\n\n const collidingRecordIdsByKey = new Map<string, string[]>()\n for (const target of group) {\n const contribution = result.get(target.recordId)\n const ownKeys = baseKeys.get(target.recordId)\n for (const key of enricher.keys) {\n if (ownKeys?.has(key)) {\n const colliding = collidingRecordIdsByKey.get(key)\n if (colliding) colliding.push(target.recordId)\n else collidingRecordIdsByKey.set(key, [target.recordId])\n continue\n }\n const value = contribution && Object.prototype.hasOwnProperty.call(contribution, key)\n ? contribution[key]\n : null\n target.doc[key] = value === undefined ? null : value\n }\n if (contribution) {\n const undeclared = Object.keys(contribution).filter((key) => !enricher.keys.includes(key))\n if (undeclared.length) {\n logger.warn('Index doc enricher returned undeclared keys; ignored', {\n enricherId: enricher.id,\n entityType,\n recordId: target.recordId,\n keys: undeclared,\n })\n }\n }\n }\n for (const [key, recordIds] of collidingRecordIdsByKey) {\n await reportEnricherFailure(db, {\n enricher, entityType, tenantId, organizationId,\n recordId: recordIds.length === 1 ? recordIds[0] : undefined,\n error: new Error(`[internal] Index doc enricher \"${enricher.id}\" key \"${key}\" collides with a base document key of ${entityType} on ${recordIds.length} record(s)`),\n handler: 'query_index:doc-enricher:collision',\n details: {\n collidingKey: key,\n collidingRecordCount: recordIds.length,\n sampleRecordIds: recordIds.slice(0, COLLISION_SAMPLE_SIZE),\n },\n })\n }\n }\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AAEpC,MAAM,SAAS,aAAa,aAAa,EAAE,MAAM,EAAE,WAAW,gBAAgB,CAAC;AAuDxE,MAAM,iCAAiC;AAEvC,MAAM,0BAA+C,oBAAI,IAAI;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAQD,MAAM,+BAA+B;AAMrC,SAAS,mBAA0C;AACjD,QAAM,iBAAiB;AACvB,MAAI,CAAC,eAAe,4BAA4B,GAAG;AACjD,mBAAe,4BAA4B,IAAI,EAAE,cAAc,oBAAI,IAAI,EAAE;AAAA,EAC3E;AACA,SAAO,eAAe,4BAA4B;AACpD;AAEA,SAAS,iBAAiB,UAA4B,UAAmD;AACvG,MAAI,OAAO,SAAS,OAAO,YAAY,CAAC,SAAS,GAAG,KAAK,GAAG;AAC1D,UAAM,IAAI,MAAM,uDAAuD;AAAA,EACzE;AACA,MAAI,OAAO,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H;AAAA,QACF;AAAA,MACF;AACA,iBAAW,CAAC,KAAK,SAAS,KAAK,yBAAyB;AACtD,cAAM,sBAAsB,IAAI;AAAA,UAC9B;AAAA,UAAU;AAAA,UAAY;AAAA,UAAU;AAAA,UAChC,UAAU,UAAU,WAAW,IAAI,UAAU,CAAC,IAAI;AAAA,UAClD,OAAO,IAAI,MAAM,kCAAkC,SAAS,EAAE,UAAU,GAAG,0CAA0C,UAAU,OAAO,UAAU,MAAM,YAAY;AAAA,UAClK,SAAS;AAAA,UACT,SAAS;AAAA,YACP,cAAc;AAAA,YACd,sBAAsB,UAAU;AAAA,YAChC,iBAAiB,UAAU,MAAM,GAAG,qBAAqB;AAAA,UAC3D;AAAA,QACF,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -2,6 +2,7 @@ import {
2
2
  isSearchFieldBlocklisted,
3
3
  resolveSearchConfig
4
4
  } from "@open-mercato/shared/lib/search/config";
5
+ import { isIndexDocEnrichedKey } from "./doc-enrichers.js";
5
6
  const AGGREGATE_SEARCH_FIELD = "search_text";
6
7
  function normalizeScopeValue(value) {
7
8
  if (value === void 0 || value === null || value === "") return null;
@@ -21,6 +22,7 @@ function collectAggregateSearchValues(field, value, entityType, config) {
21
22
  return [];
22
23
  }
23
24
  if (isSearchFieldBlocklisted(field, entityType, config)) return [];
25
+ if (isIndexDocEnrichedKey(entityType, field)) return [];
24
26
  if (typeof value === "string") {
25
27
  const trimmed = value.trim();
26
28
  return trimmed.length > 0 ? [trimmed] : [];
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/query_index/lib/document.ts"],
4
- "sourcesContent": ["import {\n isSearchFieldBlocklisted,\n resolveSearchConfig,\n type SearchConfig,\n} from '@open-mercato/shared/lib/search/config'\n\nexport type IndexDocumentScope = {\n organizationId?: string | null\n tenantId?: string | null\n}\n\nexport type IndexCustomFieldValue = {\n key: string\n value: unknown\n organizationId?: string | null\n tenantId?: string | null\n}\n\nexport const AGGREGATE_SEARCH_FIELD = 'search_text'\n\n/**\n * Controls which fields may contribute text to the `search_text` aggregate.\n *\n * Both properties are optional so existing callers keep working unchanged: an\n * omitted `config` is resolved from the environment, and an omitted `entityType`\n * means only the global blocklist entries apply.\n */\nexport type AggregateSearchOptions = {\n entityType?: string | null\n config?: SearchConfig\n}\n\nfunction normalizeScopeValue(value: string | null | undefined): string | null {\n if (value === undefined || value === null || value === '') return null\n return value\n}\n\nfunction isScopedValueVisible(\n scopeValue: string | null,\n fieldValue: string | null,\n): boolean {\n if (scopeValue === null) return fieldValue === null\n return fieldValue === null || fieldValue === scopeValue\n}\n\nfunction normalizeValue(value: unknown): unknown {\n if (value === undefined) return null\n return value\n}\n\nfunction collectAggregateSearchValues(\n field: string,\n value: unknown,\n entityType: string | null,\n config: SearchConfig,\n): string[] {\n const lower = field.toLowerCase()\n if (\n lower === AGGREGATE_SEARCH_FIELD\n || lower === 'id'\n || lower.endsWith('_id')\n || lower.endsWith('.id')\n || lower.endsWith('_at')\n || ['created_at', 'updated_at', 'deleted_at', 'tenant_id', 'organization_id'].includes(lower)\n ) {\n return []\n }\n\n if (isSearchFieldBlocklisted(field, entityType, config)) return []\n\n if (typeof value === 'string') {\n const trimmed = value.trim()\n return trimmed.length > 0 ? [trimmed] : []\n }\n\n if (Array.isArray(value)) {\n return value\n .filter((entry): entry is string => typeof entry === 'string')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n }\n\n return []\n}\n\nexport function attachAggregateSearchField(\n doc: Record<string, unknown>,\n options: AggregateSearchOptions = {},\n): Record<string, unknown> {\n const config = options.config ?? resolveSearchConfig()\n const entityType = options.entityType ?? null\n const parts: string[] = []\n const seen = new Set<string>()\n\n for (const [field, value] of Object.entries(doc)) {\n const values = collectAggregateSearchValues(field, value, entityType, config)\n for (const entry of values) {\n const key = entry.toLowerCase()\n if (seen.has(key)) continue\n seen.add(key)\n parts.push(entry)\n }\n }\n\n if (parts.length > 0) {\n doc[AGGREGATE_SEARCH_FIELD] = parts.join('\\n')\n }\n\n return doc\n}\n\n/**\n * Recomputes the aggregate on a shallow copy of `doc`.\n *\n * Search tokens are built from the *decrypted* index document, while the document\n * persisted in `entity_indexes` stays encrypted at rest. The aggregate composed during\n * document build therefore concatenates ciphertext for every field an encryption map\n * covers, and `decryptIndexDocForSearch` cannot repair it because `search_text` is on no\n * map (#5625). Token writers call this on the decrypted document so the aggregate is\n * tokenized from the same plaintext a user actually searches for; the copy keeps the\n * caller's stored document untouched.\n *\n * A pre-existing aggregate is blanked before recomposition rather than deleted: an empty\n * string yields no tokens, but it keeps the key on the document, and\n * `replaceSearchTokensForRecord` scopes its DELETE to the document's own field names. A\n * deleted key would drop `search_text` out of that scope and strand the ciphertext-derived\n * rows with no writer left to remove them.\n */\nexport function rebuildAggregateSearchField(\n doc: Record<string, unknown>,\n options: AggregateSearchOptions = {},\n): Record<string, unknown> {\n const copy = { ...doc }\n // `collectAggregateSearchValues` skips the aggregate's own key, so this blank is\n // overwritten whenever anything survives the blocklist and stays blank otherwise.\n if (AGGREGATE_SEARCH_FIELD in copy) copy[AGGREGATE_SEARCH_FIELD] = ''\n return attachAggregateSearchField(copy, options)\n}\n\nexport function buildIndexDocument(\n baseRow: Record<string, unknown>,\n customFieldValues: Iterable<IndexCustomFieldValue> = [],\n scope: IndexDocumentScope = {},\n options: AggregateSearchOptions = {},\n): Record<string, unknown> {\n const doc: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(baseRow)) {\n doc[key] = value\n }\n\n const scopeOrg = normalizeScopeValue(scope.organizationId ?? null)\n const scopeTenant = normalizeScopeValue(scope.tenantId ?? null)\n\n const grouped = new Map<string, unknown[]>()\n for (const field of customFieldValues) {\n const org = normalizeScopeValue(field.organizationId ?? null)\n const tenant = normalizeScopeValue(field.tenantId ?? null)\n\n if (!isScopedValueVisible(scopeOrg, org)) continue\n if (!isScopedValueVisible(scopeTenant, tenant)) continue\n\n const bucketKey = `cf:${field.key}`\n let bucket = grouped.get(bucketKey)\n if (!bucket) {\n bucket = []\n grouped.set(bucketKey, bucket)\n }\n\n const { value } = field\n if (Array.isArray(value)) {\n for (const entry of value) bucket.push(normalizeValue(entry))\n } else {\n bucket.push(normalizeValue(value))\n }\n }\n\n for (const [key, values] of grouped.entries()) {\n if (values.length === 1) {\n doc[key] = values[0]\n } else if (values.length > 1) {\n doc[key] = values\n }\n }\n\n return attachAggregateSearchField(doc, options)\n}\n"],
5
- "mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AAcA,MAAM,yBAAyB;AActC,SAAS,oBAAoB,OAAiD;AAC5E,MAAI,UAAU,UAAa,UAAU,QAAQ,UAAU,GAAI,QAAO;AAClE,SAAO;AACT;AAEA,SAAS,qBACP,YACA,YACS;AACT,MAAI,eAAe,KAAM,QAAO,eAAe;AAC/C,SAAO,eAAe,QAAQ,eAAe;AAC/C;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO;AACT;AAEA,SAAS,6BACP,OACA,OACA,YACA,QACU;AACV,QAAM,QAAQ,MAAM,YAAY;AAChC,MACE,UAAU,0BACP,UAAU,QACV,MAAM,SAAS,KAAK,KACpB,MAAM,SAAS,KAAK,KACpB,MAAM,SAAS,KAAK,KACpB,CAAC,cAAc,cAAc,cAAc,aAAa,iBAAiB,EAAE,SAAS,KAAK,GAC5F;AACA,WAAO,CAAC;AAAA,EACV;AAEA,MAAI,yBAAyB,OAAO,YAAY,MAAM,EAAG,QAAO,CAAC;AAEjE,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,UAAU,MAAM,KAAK;AAC3B,WAAO,QAAQ,SAAS,IAAI,CAAC,OAAO,IAAI,CAAC;AAAA,EAC3C;AAEA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,MACJ,OAAO,CAAC,UAA2B,OAAO,UAAU,QAAQ,EAC5D,IAAI,CAAC,UAAU,MAAM,KAAK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,MAAM,YAAY,IAAI;AAEzD,QAAI,CAAC,qBAAqB,UAAU,GAAG,EAAG;AAC1C,QAAI,CAAC,qBAAqB,aAAa,MAAM,EAAG;AAEhD,UAAM,YAAY,MAAM,MAAM,GAAG;AACjC,QAAI,SAAS,QAAQ,IAAI,SAAS;AAClC,QAAI,CAAC,QAAQ;AACX,eAAS,CAAC;AACV,cAAQ,IAAI,WAAW,MAAM;AAAA,IAC/B;AAEA,UAAM,EAAE,MAAM,IAAI;AAClB,QAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,iBAAW,SAAS,MAAO,QAAO,KAAK,eAAe,KAAK,CAAC;AAAA,IAC9D,OAAO;AACL,aAAO,KAAK,eAAe,KAAK,CAAC;AAAA,IACnC;AAAA,EACF;AAEA,aAAW,CAAC,KAAK,MAAM,KAAK,QAAQ,QAAQ,GAAG;AAC7C,QAAI,OAAO,WAAW,GAAG;AACvB,UAAI,GAAG,IAAI,OAAO,CAAC;AAAA,IACrB,WAAW,OAAO,SAAS,GAAG;AAC5B,UAAI,GAAG,IAAI;AAAA,IACb;AAAA,EACF;AAEA,SAAO,2BAA2B,KAAK,OAAO;AAChD;",
4
+ "sourcesContent": ["import {\n isSearchFieldBlocklisted,\n resolveSearchConfig,\n type SearchConfig,\n} from '@open-mercato/shared/lib/search/config'\nimport { isIndexDocEnrichedKey } from './doc-enrichers'\n\nexport type IndexDocumentScope = {\n organizationId?: string | null\n tenantId?: string | null\n}\n\nexport type IndexCustomFieldValue = {\n key: string\n value: unknown\n organizationId?: string | null\n tenantId?: string | null\n}\n\nexport const AGGREGATE_SEARCH_FIELD = 'search_text'\n\n/**\n * Controls which fields may contribute text to the `search_text` aggregate.\n *\n * Both properties are optional so existing callers keep working unchanged: an\n * omitted `config` is resolved from the environment, and an omitted `entityType`\n * means only the global blocklist entries apply.\n */\nexport type AggregateSearchOptions = {\n entityType?: string | null\n config?: SearchConfig\n}\n\nfunction normalizeScopeValue(value: string | null | undefined): string | null {\n if (value === undefined || value === null || value === '') return null\n return value\n}\n\nfunction isScopedValueVisible(\n scopeValue: string | null,\n fieldValue: string | null,\n): boolean {\n if (scopeValue === null) return fieldValue === null\n return fieldValue === null || fieldValue === scopeValue\n}\n\nfunction normalizeValue(value: unknown): unknown {\n if (value === undefined) return null\n return value\n}\n\nfunction collectAggregateSearchValues(\n field: string,\n value: unknown,\n entityType: string | null,\n config: SearchConfig,\n): string[] {\n const lower = field.toLowerCase()\n if (\n lower === AGGREGATE_SEARCH_FIELD\n || lower === 'id'\n || lower.endsWith('_id')\n || lower.endsWith('.id')\n || lower.endsWith('_at')\n || ['created_at', 'updated_at', 'deleted_at', 'tenant_id', 'organization_id'].includes(lower)\n ) {\n return []\n }\n\n if (isSearchFieldBlocklisted(field, entityType, config)) return []\n if (isIndexDocEnrichedKey(entityType, field)) return []\n\n if (typeof value === 'string') {\n const trimmed = value.trim()\n return trimmed.length > 0 ? [trimmed] : []\n }\n\n if (Array.isArray(value)) {\n return value\n .filter((entry): entry is string => typeof entry === 'string')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n }\n\n return []\n}\n\nexport function attachAggregateSearchField(\n doc: Record<string, unknown>,\n options: AggregateSearchOptions = {},\n): Record<string, unknown> {\n const config = options.config ?? resolveSearchConfig()\n const entityType = options.entityType ?? null\n const parts: string[] = []\n const seen = new Set<string>()\n\n for (const [field, value] of Object.entries(doc)) {\n const values = collectAggregateSearchValues(field, value, entityType, config)\n for (const entry of values) {\n const key = entry.toLowerCase()\n if (seen.has(key)) continue\n seen.add(key)\n parts.push(entry)\n }\n }\n\n if (parts.length > 0) {\n doc[AGGREGATE_SEARCH_FIELD] = parts.join('\\n')\n }\n\n return doc\n}\n\n/**\n * Recomputes the aggregate on a shallow copy of `doc`.\n *\n * Search tokens are built from the *decrypted* index document, while the document\n * persisted in `entity_indexes` stays encrypted at rest. The aggregate composed during\n * document build therefore concatenates ciphertext for every field an encryption map\n * covers, and `decryptIndexDocForSearch` cannot repair it because `search_text` is on no\n * map (#5625). Token writers call this on the decrypted document so the aggregate is\n * tokenized from the same plaintext a user actually searches for; the copy keeps the\n * caller's stored document untouched.\n *\n * A pre-existing aggregate is blanked before recomposition rather than deleted: an empty\n * string yields no tokens, but it keeps the key on the document, and\n * `replaceSearchTokensForRecord` scopes its DELETE to the document's own field names. A\n * deleted key would drop `search_text` out of that scope and strand the ciphertext-derived\n * rows with no writer left to remove them.\n */\nexport function rebuildAggregateSearchField(\n doc: Record<string, unknown>,\n options: AggregateSearchOptions = {},\n): Record<string, unknown> {\n const copy = { ...doc }\n // `collectAggregateSearchValues` skips the aggregate's own key, so this blank is\n // overwritten whenever anything survives the blocklist and stays blank otherwise.\n if (AGGREGATE_SEARCH_FIELD in copy) copy[AGGREGATE_SEARCH_FIELD] = ''\n return attachAggregateSearchField(copy, options)\n}\n\nexport function buildIndexDocument(\n baseRow: Record<string, unknown>,\n customFieldValues: Iterable<IndexCustomFieldValue> = [],\n scope: IndexDocumentScope = {},\n options: AggregateSearchOptions = {},\n): Record<string, unknown> {\n const doc: Record<string, unknown> = {}\n for (const [key, value] of Object.entries(baseRow)) {\n doc[key] = value\n }\n\n const scopeOrg = normalizeScopeValue(scope.organizationId ?? null)\n const scopeTenant = normalizeScopeValue(scope.tenantId ?? null)\n\n const grouped = new Map<string, unknown[]>()\n for (const field of customFieldValues) {\n const org = normalizeScopeValue(field.organizationId ?? null)\n const tenant = normalizeScopeValue(field.tenantId ?? null)\n\n if (!isScopedValueVisible(scopeOrg, org)) continue\n if (!isScopedValueVisible(scopeTenant, tenant)) continue\n\n const bucketKey = `cf:${field.key}`\n let bucket = grouped.get(bucketKey)\n if (!bucket) {\n bucket = []\n grouped.set(bucketKey, bucket)\n }\n\n const { value } = field\n if (Array.isArray(value)) {\n for (const entry of value) bucket.push(normalizeValue(entry))\n } else {\n bucket.push(normalizeValue(value))\n }\n }\n\n for (const [key, values] of grouped.entries()) {\n if (values.length === 1) {\n doc[key] = values[0]\n } else if (values.length > 1) {\n doc[key] =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