@open-mercato/shared 0.6.7 → 0.6.8-canary.320.1.bf889f49e4

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 (224) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +62 -6
  3. package/build.mjs +2 -4
  4. package/dist/lib/ai/safety-identifier.js +32 -0
  5. package/dist/lib/ai/safety-identifier.js.map +7 -0
  6. package/dist/lib/auth/organizationScope.js +34 -0
  7. package/dist/lib/auth/organizationScope.js.map +7 -0
  8. package/dist/lib/auth/server.js +15 -2
  9. package/dist/lib/auth/server.js.map +2 -2
  10. package/dist/lib/bootstrap/clientOnlyModules.js +55 -0
  11. package/dist/lib/bootstrap/clientOnlyModules.js.map +7 -0
  12. package/dist/lib/bootstrap/dynamicLoader.js +190 -70
  13. package/dist/lib/bootstrap/dynamicLoader.js.map +2 -2
  14. package/dist/lib/bootstrap/factory.js +18 -13
  15. package/dist/lib/bootstrap/factory.js.map +2 -2
  16. package/dist/lib/commands/command-bus.js +9 -3
  17. package/dist/lib/commands/command-bus.js.map +2 -2
  18. package/dist/lib/commands/command-interceptor-runner.js +9 -4
  19. package/dist/lib/commands/command-interceptor-runner.js.map +2 -2
  20. package/dist/lib/commands/errors.js +25 -4
  21. package/dist/lib/commands/errors.js.map +2 -2
  22. package/dist/lib/commands/index.js +7 -1
  23. package/dist/lib/commands/index.js.map +2 -2
  24. package/dist/lib/crud/enricher-runner.js +2 -11
  25. package/dist/lib/crud/enricher-runner.js.map +2 -2
  26. package/dist/lib/crud/factory.js +104 -23
  27. package/dist/lib/crud/factory.js.map +2 -2
  28. package/dist/lib/crud/interceptor-runner.js +2 -2
  29. package/dist/lib/crud/interceptor-runner.js.map +2 -2
  30. package/dist/lib/crud/mutation-guard-registry.js +2 -2
  31. package/dist/lib/crud/mutation-guard-registry.js.map +2 -2
  32. package/dist/lib/crud/types.js +4 -0
  33. package/dist/lib/crud/types.js.map +3 -3
  34. package/dist/lib/data/consistency.js +19 -0
  35. package/dist/lib/data/consistency.js.map +7 -0
  36. package/dist/lib/data/engine.js +37 -11
  37. package/dist/lib/data/engine.js.map +2 -2
  38. package/dist/lib/db/entityMetadata.js +26 -0
  39. package/dist/lib/db/entityMetadata.js.map +7 -0
  40. package/dist/lib/db/pg-errors.js +42 -0
  41. package/dist/lib/db/pg-errors.js.map +2 -2
  42. package/dist/lib/di/container.js +48 -6
  43. package/dist/lib/di/container.js.map +2 -2
  44. package/dist/lib/email/send.js +56 -0
  45. package/dist/lib/email/send.js.map +2 -2
  46. package/dist/lib/encryption/find.js +22 -0
  47. package/dist/lib/encryption/find.js.map +2 -2
  48. package/dist/lib/encryption/likeFilterWarning.js +66 -0
  49. package/dist/lib/encryption/likeFilterWarning.js.map +7 -0
  50. package/dist/lib/encryption/subscriber.js +2 -10
  51. package/dist/lib/encryption/subscriber.js.map +2 -2
  52. package/dist/lib/encryption/tenantDataEncryptionService.js +52 -17
  53. package/dist/lib/encryption/tenantDataEncryptionService.js.map +2 -2
  54. package/dist/lib/i18n/config.js +1 -1
  55. package/dist/lib/i18n/config.js.map +2 -2
  56. package/dist/lib/i18n/dictionary-cache.js +5 -0
  57. package/dist/lib/i18n/dictionary-cache.js.map +2 -2
  58. package/dist/lib/i18n/server.js +4 -4
  59. package/dist/lib/i18n/server.js.map +3 -3
  60. package/dist/lib/logger/extension.js +29 -0
  61. package/dist/lib/logger/extension.js.map +7 -0
  62. package/dist/lib/logger/index.js +47 -3
  63. package/dist/lib/logger/index.js.map +3 -3
  64. package/dist/lib/modules/registry.js +36 -6
  65. package/dist/lib/modules/registry.js.map +2 -2
  66. package/dist/lib/modules/surfaceFingerprint.js +47 -0
  67. package/dist/lib/modules/surfaceFingerprint.js.map +7 -0
  68. package/dist/lib/query/ciphertext-search-warning.js +51 -0
  69. package/dist/lib/query/ciphertext-search-warning.js.map +7 -0
  70. package/dist/lib/query/engine.js +60 -43
  71. package/dist/lib/query/engine.js.map +2 -2
  72. package/dist/lib/query/types.js.map +1 -1
  73. package/dist/lib/redis/connection.js +7 -2
  74. package/dist/lib/redis/connection.js.map +2 -2
  75. package/dist/lib/search/auto-indexing.js +14 -0
  76. package/dist/lib/search/auto-indexing.js.map +7 -0
  77. package/dist/lib/search/availability.js +107 -0
  78. package/dist/lib/search/availability.js.map +7 -0
  79. package/dist/lib/search/config.js +61 -2
  80. package/dist/lib/search/config.js.map +2 -2
  81. package/dist/lib/search/tokenLookup.js +46 -0
  82. package/dist/lib/search/tokenLookup.js.map +7 -0
  83. package/dist/lib/search/tokenize.js +23 -11
  84. package/dist/lib/search/tokenize.js.map +2 -2
  85. package/dist/lib/telemetry/runtime.js +35 -0
  86. package/dist/lib/telemetry/runtime.js.map +7 -0
  87. package/dist/lib/version.js +1 -1
  88. package/dist/lib/version.js.map +1 -1
  89. package/dist/lib/webhooks/body.js +57 -0
  90. package/dist/lib/webhooks/body.js.map +7 -0
  91. package/dist/lib/webhooks/inbound-types.js +1 -0
  92. package/dist/lib/webhooks/inbound-types.js.map +7 -0
  93. package/dist/lib/webhooks/index.js +13 -1
  94. package/dist/lib/webhooks/index.js.map +2 -2
  95. package/dist/lib/webhooks/verify.js +12 -7
  96. package/dist/lib/webhooks/verify.js.map +2 -2
  97. package/dist/modules/analytics.js.map +2 -2
  98. package/dist/modules/overrides.js +50 -1
  99. package/dist/modules/overrides.js.map +2 -2
  100. package/dist/modules/payment_gateways/types.js +8 -1
  101. package/dist/modules/payment_gateways/types.js.map +2 -2
  102. package/dist/modules/registry.js +1 -0
  103. package/dist/modules/registry.js.map +2 -2
  104. package/dist/modules/widgets/extension-points.js +96 -0
  105. package/dist/modules/widgets/extension-points.js.map +7 -0
  106. package/dist/security/enabledModulesRegistry.js +56 -11
  107. package/dist/security/enabledModulesRegistry.js.map +2 -2
  108. package/dist/security/featurePolicy.js +62 -0
  109. package/dist/security/featurePolicy.js.map +7 -0
  110. package/jest.config.cjs +20 -10
  111. package/package.json +19 -9
  112. package/scripts/versionSource.cjs +65 -0
  113. package/src/lib/__tests__/versionSource.test.ts +64 -0
  114. package/src/lib/ai/__tests__/llm-provider-contract.test.ts +59 -0
  115. package/src/lib/ai/__tests__/safety-identifier.test.ts +71 -0
  116. package/src/lib/ai/llm-provider.ts +33 -0
  117. package/src/lib/ai/safety-identifier.ts +73 -0
  118. package/src/lib/auth/__tests__/organizationScope.test.ts +107 -0
  119. package/src/lib/auth/__tests__/server.test.ts +23 -0
  120. package/src/lib/auth/organizationScope.ts +65 -0
  121. package/src/lib/auth/server.ts +23 -2
  122. package/src/lib/bootstrap/__tests__/clientOnlyModules.test.ts +189 -0
  123. package/src/lib/bootstrap/__tests__/dynamicLoader.aliasResolver.test.ts +98 -0
  124. package/src/lib/bootstrap/__tests__/dynamicLoader.appDi.test.ts +211 -0
  125. package/src/lib/bootstrap/__tests__/dynamicLoader.commandInterceptors.test.ts +63 -8
  126. package/src/lib/bootstrap/__tests__/dynamicLoader.generatedCacheRecovery.test.ts +256 -0
  127. package/src/lib/bootstrap/__tests__/dynamicLoader.test.ts +126 -0
  128. package/src/lib/bootstrap/__tests__/dynamicLoader.tsconfig.test.ts +21 -1
  129. package/src/lib/bootstrap/__tests__/factory.test.ts +78 -0
  130. package/src/lib/bootstrap/clientOnlyModules.ts +85 -0
  131. package/src/lib/bootstrap/dynamicLoader.ts +346 -96
  132. package/src/lib/bootstrap/factory.ts +21 -15
  133. package/src/lib/bootstrap/types.ts +6 -0
  134. package/src/lib/commands/__tests__/command-bus.test.ts +63 -0
  135. package/src/lib/commands/__tests__/command-interceptor-error.test.ts +91 -1
  136. package/src/lib/commands/__tests__/command-interceptor-runner.test.ts +101 -0
  137. package/src/lib/commands/command-bus.ts +9 -3
  138. package/src/lib/commands/command-interceptor-runner.ts +27 -6
  139. package/src/lib/commands/command-interceptor.ts +8 -0
  140. package/src/lib/commands/errors.ts +67 -2
  141. package/src/lib/commands/index.ts +7 -1
  142. package/src/lib/crud/__tests__/crud-factory.cache-user-scope.test.ts +171 -0
  143. package/src/lib/crud/__tests__/crud-factory.test.ts +564 -0
  144. package/src/lib/crud/__tests__/mutation-guard-registry.test.ts +26 -0
  145. package/src/lib/crud/enricher-runner.ts +2 -11
  146. package/src/lib/crud/factory.ts +157 -22
  147. package/src/lib/crud/interceptor-runner.ts +2 -2
  148. package/src/lib/crud/mutation-guard-registry.ts +2 -2
  149. package/src/lib/crud/types.ts +3 -0
  150. package/src/lib/data/__tests__/consistency.test.ts +38 -0
  151. package/src/lib/data/__tests__/engine.bulk-suppress.test.ts +18 -3
  152. package/src/lib/data/consistency.ts +17 -0
  153. package/src/lib/data/engine.ts +50 -16
  154. package/src/lib/db/__tests__/entityMetadata.test.ts +38 -0
  155. package/src/lib/db/__tests__/pg-errors.test.ts +48 -0
  156. package/src/lib/db/entityMetadata.ts +43 -0
  157. package/src/lib/db/pg-errors.ts +58 -0
  158. package/src/lib/di/__tests__/container-app-di-absent.test.ts +155 -0
  159. package/src/lib/di/__tests__/container-app-di.test.ts +173 -0
  160. package/src/lib/di/__tests__/registrar-error-log.test.ts +154 -0
  161. package/src/lib/di/container.ts +72 -8
  162. package/src/lib/email/__tests__/send.test.ts +37 -1
  163. package/src/lib/email/send.ts +79 -0
  164. package/src/lib/encryption/__tests__/likeFilterWarning.test.ts +167 -0
  165. package/src/lib/encryption/__tests__/subscriber.test.ts +54 -2
  166. package/src/lib/encryption/__tests__/tenantDataEncryptionService.test.ts +58 -0
  167. package/src/lib/encryption/find.ts +22 -0
  168. package/src/lib/encryption/likeFilterWarning.ts +102 -0
  169. package/src/lib/encryption/subscriber.ts +2 -14
  170. package/src/lib/encryption/tenantDataEncryptionService.ts +64 -18
  171. package/src/lib/i18n/__tests__/config.test.ts +8 -0
  172. package/src/lib/i18n/__tests__/dictionary-cache.test.ts +23 -0
  173. package/src/lib/i18n/__tests__/server-dictionary-cache.test.ts +30 -0
  174. package/src/lib/i18n/__tests__/server-unbootstrapped.test.ts +29 -0
  175. package/src/lib/i18n/config.ts +2 -2
  176. package/src/lib/i18n/dictionary-cache.ts +5 -0
  177. package/src/lib/i18n/server.ts +6 -2
  178. package/src/lib/logger/__tests__/logger.test.ts +77 -0
  179. package/src/lib/logger/extension.ts +59 -0
  180. package/src/lib/logger/index.ts +59 -1
  181. package/src/lib/modules/__tests__/registry.test.ts +26 -0
  182. package/src/lib/modules/__tests__/surfaceFingerprint.test.ts +122 -0
  183. package/src/lib/modules/registry.ts +46 -7
  184. package/src/lib/modules/surfaceFingerprint.ts +87 -0
  185. package/src/lib/query/__tests__/ciphertext-search-warning.test.ts +178 -0
  186. package/src/lib/query/__tests__/engine.scope-and-or.test.ts +67 -0
  187. package/src/lib/query/__tests__/engine.test.ts +213 -13
  188. package/src/lib/query/ciphertext-search-warning.ts +106 -0
  189. package/src/lib/query/engine.ts +102 -61
  190. package/src/lib/query/types.ts +4 -5
  191. package/src/lib/redis/__tests__/connection.test.ts +16 -0
  192. package/src/lib/redis/connection.ts +10 -7
  193. package/src/lib/search/__tests__/availability.test.ts +211 -0
  194. package/src/lib/search/__tests__/config.test.ts +177 -0
  195. package/src/lib/search/__tests__/tokenLookup.test.ts +206 -0
  196. package/src/lib/search/__tests__/tokenize.test.ts +49 -0
  197. package/src/lib/search/auto-indexing.ts +22 -0
  198. package/src/lib/search/availability.ts +232 -0
  199. package/src/lib/search/config.ts +106 -8
  200. package/src/lib/search/tokenLookup.ts +133 -0
  201. package/src/lib/search/tokenize.ts +33 -11
  202. package/src/lib/telemetry/runtime.ts +72 -0
  203. package/src/lib/webhooks/__tests__/body.test.ts +95 -0
  204. package/src/lib/webhooks/__tests__/verify.test.ts +20 -1
  205. package/src/lib/webhooks/body.ts +70 -0
  206. package/src/lib/webhooks/inbound-types.ts +125 -0
  207. package/src/lib/webhooks/index.ts +19 -1
  208. package/src/lib/webhooks/verify.ts +17 -9
  209. package/src/modules/__tests__/nav-group-order-override.test.ts +183 -0
  210. package/src/modules/__tests__/registry.test.ts +10 -2
  211. package/src/modules/analytics.ts +7 -0
  212. package/src/modules/customer-auth.ts +1 -0
  213. package/src/modules/encryption.ts +3 -0
  214. package/src/modules/entities.ts +15 -0
  215. package/src/modules/navigation/backendChrome.ts +15 -0
  216. package/src/modules/overrides.ts +103 -0
  217. package/src/modules/payment_gateways/__tests__/types.test.ts +37 -0
  218. package/src/modules/payment_gateways/types.ts +41 -0
  219. package/src/modules/registry.ts +3 -0
  220. package/src/modules/widgets/__tests__/extension-points.test.ts +101 -0
  221. package/src/modules/widgets/extension-points.ts +524 -0
  222. package/src/security/__tests__/featurePolicy.test.ts +166 -0
  223. package/src/security/enabledModulesRegistry.ts +64 -12
  224. package/src/security/featurePolicy.ts +89 -0
@@ -0,0 +1,59 @@
1
+ import type { LogLevel } from './level'
2
+
3
+ export type LoggerExtensionRecord = {
4
+ level: LogLevel
5
+ namespace: string
6
+ message: string
7
+ fields: Record<string, unknown>
8
+ time: number
9
+ }
10
+
11
+ export type LoggerExtension = {
12
+ /**
13
+ * Add process-local context (for example trace/span ids) to both the local
14
+ * line and the optional remote sink.
15
+ */
16
+ enrich?(): Record<string, unknown> | undefined
17
+ /**
18
+ * Observe a record after the local transport writes it. Implementations must
19
+ * never throw into application code.
20
+ */
21
+ emit?(record: LoggerExtensionRecord): void
22
+ }
23
+
24
+ const GLOBAL_KEY = Symbol.for('@open-mercato/shared.loggerExtension')
25
+
26
+ type LoggerExtensionStore = {
27
+ active?: LoggerExtension
28
+ }
29
+
30
+ function store(): LoggerExtensionStore {
31
+ const globalStore = globalThis as unknown as Record<symbol, LoggerExtensionStore | undefined>
32
+ let current = globalStore[GLOBAL_KEY]
33
+ if (!current) {
34
+ current = {}
35
+ globalStore[GLOBAL_KEY] = current
36
+ }
37
+ return current
38
+ }
39
+
40
+ /**
41
+ * Register the single process-wide logger extension. The returned disposer only
42
+ * clears the extension when it is still the active registration.
43
+ */
44
+ export function registerLoggerExtension(extension: LoggerExtension): () => void {
45
+ store().active = extension
46
+ return () => {
47
+ const current = store()
48
+ if (current.active === extension) current.active = undefined
49
+ }
50
+ }
51
+
52
+ export function getLoggerExtension(): LoggerExtension | undefined {
53
+ return store().active
54
+ }
55
+
56
+ /** Test-only: clear the process-wide extension. */
57
+ export function resetLoggerExtension(): void {
58
+ store().active = undefined
59
+ }
@@ -1,9 +1,17 @@
1
1
  import { selectTransport } from './transport'
2
+ import { getLoggerExtension } from './extension'
3
+ import { isLevelEnabled, type LogLevel } from './level'
2
4
 
3
5
  export type { LogLevel } from './level'
4
6
  export { getLogLevel, isLevelEnabled, resetLogLevelCache, OM_LOG_LEVEL_ENV } from './level'
5
7
  export { resetServerLoggerCache, OM_LOG_DESTINATION_ENV } from './transport.server'
6
8
  export { resetLogPrettyCache, OM_LOG_PRETTY_ENV } from './transport.pretty'
9
+ export {
10
+ getLoggerExtension,
11
+ registerLoggerExtension,
12
+ resetLoggerExtension,
13
+ } from './extension'
14
+ export type { LoggerExtension, LoggerExtensionRecord } from './extension'
7
15
 
8
16
  export type LogBindings = Record<string, unknown>
9
17
 
@@ -18,11 +26,61 @@ export interface Logger {
18
26
 
19
27
  const loggerRegistry = new Map<string, Logger>()
20
28
 
29
+ function createExtendedLogger(
30
+ namespace: string,
31
+ transport: Logger,
32
+ bindings: LogBindings = {},
33
+ ): Logger {
34
+ const emit = (
35
+ level: LogLevel,
36
+ msg: string,
37
+ fields?: LogBindings,
38
+ ): void => {
39
+ if (!isLevelEnabled(level)) return
40
+
41
+ const extension = getLoggerExtension()
42
+ let context: LogBindings = {}
43
+ try {
44
+ context = extension?.enrich?.() ?? {}
45
+ } catch {
46
+ // Observability must never alter application behavior.
47
+ }
48
+
49
+ const mergedFields = { ...fields, ...context }
50
+ transport[level](msg, mergedFields)
51
+
52
+ try {
53
+ extension?.emit?.({
54
+ level,
55
+ namespace,
56
+ message: msg,
57
+ fields: { ...bindings, ...mergedFields },
58
+ time: Date.now(),
59
+ })
60
+ } catch {
61
+ // Remote logging is best-effort; the local line has already been written.
62
+ }
63
+ }
64
+
65
+ return {
66
+ debug: (msg, fields) => emit('debug', msg, fields),
67
+ info: (msg, fields) => emit('info', msg, fields),
68
+ warn: (msg, fields) => emit('warn', msg, fields),
69
+ error: (msg, fields) => emit('error', msg, fields),
70
+ child: (childBindings) =>
71
+ createExtendedLogger(
72
+ namespace,
73
+ transport.child(childBindings),
74
+ { ...bindings, ...childBindings },
75
+ ),
76
+ }
77
+ }
78
+
21
79
  /** Create (or reuse) a namespaced logger. `namespace` is attached as `name`. */
22
80
  export function createLogger(namespace: string): Logger {
23
81
  const existing = loggerRegistry.get(namespace)
24
82
  if (existing) return existing
25
- const created = selectTransport(namespace)
83
+ const created = createExtendedLogger(namespace, selectTransport(namespace))
26
84
  loggerRegistry.set(namespace, created)
27
85
  return created
28
86
  }
@@ -145,4 +145,30 @@ describe('shared modules registry', () => {
145
145
  }),
146
146
  ])
147
147
  })
148
+
149
+ it('preserves translations when runtime modules register after locale shards', () => {
150
+ const registry = loadRegistry()
151
+ const handler = jest.fn()
152
+ registry.registerModules([
153
+ {
154
+ id: 'checkout',
155
+ translations: { pl: { title: 'Kasa' } },
156
+ } as Module,
157
+ ])
158
+
159
+ registry.registerModules([
160
+ {
161
+ id: 'checkout',
162
+ subscribers: [{ id: 'checkout-gateway-payment-failed', event: 'payment_gateways.payment.failed', handler }],
163
+ } as Module,
164
+ ])
165
+
166
+ expect(registry.getModules()).toEqual([
167
+ expect.objectContaining({
168
+ id: 'checkout',
169
+ subscribers: [expect.objectContaining({ id: 'checkout-gateway-payment-failed' })],
170
+ translations: { pl: { title: 'Kasa' } },
171
+ }),
172
+ ])
173
+ })
148
174
  })
@@ -0,0 +1,122 @@
1
+ import type { Module, BackendRouteManifestEntry } from '../../../modules/registry'
2
+ import { getBackendRouteManifests } from '../../../modules/registry'
3
+ import { getModules } from '../registry'
4
+ import { getModuleSurfaceFingerprint } from '../surfaceFingerprint'
5
+
6
+ jest.mock('../registry', () => ({
7
+ getModules: jest.fn(),
8
+ }))
9
+
10
+ jest.mock('../../../modules/registry', () => ({
11
+ getBackendRouteManifests: jest.fn(),
12
+ }))
13
+
14
+ const mockGetModules = jest.mocked(getModules)
15
+ const mockGetBackendRouteManifests = jest.mocked(getBackendRouteManifests)
16
+
17
+ function route(pattern: string, overrides: Partial<BackendRouteManifestEntry> = {}): BackendRouteManifestEntry {
18
+ return {
19
+ moduleId: 'auth',
20
+ pattern,
21
+ title: 'Page',
22
+ load: async () => null,
23
+ ...overrides,
24
+ } as BackendRouteManifestEntry
25
+ }
26
+
27
+ type ModuleSurface = string | { id: string; features: Array<{ id: string; module?: string }> }
28
+
29
+ function setSurface(modules: ModuleSurface[], routes: BackendRouteManifestEntry[]): void {
30
+ mockGetModules.mockReturnValue(modules.map((mod) => (typeof mod === 'string' ? { id: mod } : mod) as Module))
31
+ mockGetBackendRouteManifests.mockReturnValue(routes)
32
+ }
33
+
34
+ describe('getModuleSurfaceFingerprint', () => {
35
+ afterEach(() => {
36
+ jest.resetAllMocks()
37
+ })
38
+
39
+ it('is stable for the same enabled modules and route manifest', () => {
40
+ setSurface(['auth', 'search'], [route('/backend/dashboard')])
41
+ const first = getModuleSurfaceFingerprint()
42
+
43
+ setSurface(['auth', 'search'], [route('/backend/dashboard')])
44
+ expect(getModuleSurfaceFingerprint()).toBe(first)
45
+ })
46
+
47
+ it('changes when a module is enabled — the deploy that used to serve a stale nav', () => {
48
+ setSurface(['auth'], [route('/backend/dashboard')])
49
+ const before = getModuleSurfaceFingerprint()
50
+
51
+ setSurface(['auth', 'search'], [route('/backend/dashboard')])
52
+ expect(getModuleSurfaceFingerprint()).not.toBe(before)
53
+ })
54
+
55
+ it('changes when a backend route is added', () => {
56
+ setSurface(['auth'], [route('/backend/dashboard')])
57
+ const before = getModuleSurfaceFingerprint()
58
+
59
+ setSurface(['auth'], [route('/backend/dashboard'), route('/backend/search')])
60
+ expect(getModuleSurfaceFingerprint()).not.toBe(before)
61
+ })
62
+
63
+ it('changes when only a route metadata field changes', () => {
64
+ setSurface(['auth'], [route('/backend/dashboard', { title: 'Dashboard' })])
65
+ const before = getModuleSurfaceFingerprint()
66
+
67
+ setSurface(['auth'], [route('/backend/dashboard', { title: 'Overview' })])
68
+ expect(getModuleSurfaceFingerprint()).not.toBe(before)
69
+ })
70
+
71
+ it('changes when a module declares a new feature and no route moves', () => {
72
+ const routes = [route('/backend/dashboard')]
73
+ setSurface([{ id: 'auth', features: [{ id: 'auth.view' }] }], routes)
74
+ const before = getModuleSurfaceFingerprint()
75
+
76
+ setSurface([{ id: 'auth', features: [{ id: 'auth.view' }, { id: 'auth.manage' }] }], routes)
77
+ expect(getModuleSurfaceFingerprint()).not.toBe(before)
78
+ })
79
+
80
+ it('changes when a feature declares a different owning module', () => {
81
+ const routes = [route('/backend/dashboard')]
82
+ setSurface([{ id: 'auth', features: [{ id: 'analytics.view' }] }], routes)
83
+ const before = getModuleSurfaceFingerprint()
84
+
85
+ setSurface([{ id: 'auth', features: [{ id: 'analytics.view', module: 'reporting' }] }], routes)
86
+ expect(getModuleSurfaceFingerprint()).not.toBe(before)
87
+ })
88
+
89
+ it('ignores feature ordering within a module', () => {
90
+ const routes = [route('/backend/dashboard')]
91
+ setSurface([{ id: 'auth', features: [{ id: 'auth.view' }, { id: 'auth.manage' }] }], routes)
92
+ const forward = getModuleSurfaceFingerprint()
93
+
94
+ setSurface([{ id: 'auth', features: [{ id: 'auth.manage' }, { id: 'auth.view' }] }], routes)
95
+ expect(getModuleSurfaceFingerprint()).toBe(forward)
96
+ })
97
+
98
+ it('ignores route manifest ordering', () => {
99
+ setSurface(['auth'], [route('/backend/a'), route('/backend/b')])
100
+ const forward = getModuleSurfaceFingerprint()
101
+
102
+ setSurface(['auth'], [route('/backend/b'), route('/backend/a')])
103
+ expect(getModuleSurfaceFingerprint()).toBe(forward)
104
+ })
105
+
106
+ it('falls back to the route manifest alone when the module registry is not populated', () => {
107
+ mockGetModules.mockImplementation(() => {
108
+ throw new Error('[Bootstrap] Modules not registered.')
109
+ })
110
+ mockGetBackendRouteManifests.mockReturnValue([route('/backend/dashboard')])
111
+
112
+ expect(getModuleSurfaceFingerprint()).toMatch(/^[0-9a-f]{12}$/)
113
+ })
114
+
115
+ it('degrades to a constant rather than throwing when route metadata cannot be serialized', () => {
116
+ const circular = route('/backend/dashboard') as BackendRouteManifestEntry & { self?: unknown }
117
+ circular.self = circular
118
+ setSurface(['auth'], [circular])
119
+
120
+ expect(getModuleSurfaceFingerprint()).toBe('unknown')
121
+ })
122
+ })
@@ -1,6 +1,7 @@
1
1
  import type { Module } from '@open-mercato/shared/modules/registry'
2
2
  import { applyModuleOverridesToModules } from '@open-mercato/shared/modules/overrides'
3
- import { invalidateDictionaryCache } from '../i18n/dictionary-cache'
3
+ import type { Locale } from '../i18n/config'
4
+ import { invalidateDictionaryCache, invalidateDictionaryCacheLocales } from '../i18n/dictionary-cache'
4
5
  import { createLogger } from '../logger'
5
6
 
6
7
  const logger = createLogger('shared').child({ component: 'modules-registry' })
@@ -38,7 +39,10 @@ function mergeI18nModules(existing: Module[], incoming: Module[]): Module[] {
38
39
  if (!i18nModule?.translations) return entry
39
40
  return {
40
41
  ...entry,
41
- translations: i18nModule.translations,
42
+ translations: {
43
+ ...(entry.translations ?? {}),
44
+ ...i18nModule.translations,
45
+ },
42
46
  }
43
47
  })
44
48
 
@@ -49,17 +53,42 @@ function mergeI18nModules(existing: Module[], incoming: Module[]): Module[] {
49
53
  return merged
50
54
  }
51
55
 
56
+ function getTranslationLocales(modules: Module[]): Locale[] {
57
+ const locales = new Set<Locale>()
58
+ for (const entry of modules) {
59
+ for (const locale of Object.keys(entry.translations ?? {})) {
60
+ locales.add(locale as Locale)
61
+ }
62
+ }
63
+ return [...locales]
64
+ }
65
+
66
+ function preserveExistingTranslations(existing: Module[], incoming: Module[]): Module[] {
67
+ const existingById = new Map(existing.map((entry) => [entry.id, entry]))
68
+ return incoming.map((entry) => {
69
+ if (entry.translations) return entry
70
+ const translations = existingById.get(entry.id)?.translations
71
+ return translations ? { ...entry, translations } : entry
72
+ })
73
+ }
74
+
52
75
  export function registerModules(modules: Module[]) {
53
76
  const existing = getGlobalModules()
54
77
  if (existing !== null && process.env.NODE_ENV === 'development') {
55
78
  logger.debug('Modules re-registered (this may occur during HMR)')
56
79
  }
57
80
  const nextModules = applyModuleOverridesToModules(modules)
58
- const shouldMergeI18nOnly = existing !== null
59
- && existing.some(hasRuntimeContracts)
60
- && isI18nOnlyRegistration(nextModules)
61
- setGlobalModules(shouldMergeI18nOnly ? mergeI18nModules(existing, nextModules) : nextModules)
62
- invalidateDictionaryCache()
81
+ const i18nOnlyRegistration = isI18nOnlyRegistration(nextModules)
82
+ const shouldMergeI18nOnly = existing !== null && i18nOnlyRegistration
83
+ const registeredModules = shouldMergeI18nOnly
84
+ ? mergeI18nModules(existing, nextModules)
85
+ : preserveExistingTranslations(existing ?? [], nextModules)
86
+ setGlobalModules(registeredModules)
87
+ if (i18nOnlyRegistration) {
88
+ invalidateDictionaryCacheLocales(getTranslationLocales(nextModules))
89
+ } else {
90
+ invalidateDictionaryCache()
91
+ }
63
92
  }
64
93
 
65
94
  export function getModules(): Module[] {
@@ -69,3 +98,13 @@ export function getModules(): Module[] {
69
98
  }
70
99
  return modules
71
100
  }
101
+
102
+ /**
103
+ * Non-throwing counterpart of `getModules()` for call sites that have a
104
+ * meaningful degraded behavior when bootstrap has not run — route unit tests
105
+ * exercise a single handler without `registerModules()`, and a hard throw there
106
+ * turns an unrelated assertion into a bootstrap error.
107
+ */
108
+ export function tryGetModules(): Module[] | null {
109
+ return getGlobalModules()
110
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Deploy-time fingerprint of the registered module surface.
3
+ *
4
+ * Some cached payloads are derived from state that only changes when the app
5
+ * is redeployed — the enabled module set and the backend route manifest. That
6
+ * state has no database write to hang a tag invalidation off, so a cache key
7
+ * that omits it keeps serving the pre-deploy payload to anyone with a warm
8
+ * entry (see `/api/auth/admin/nav`, whose payload embeds
9
+ * `filterGrantsByEnabledModules(...)` computed at write time).
10
+ *
11
+ * Mixing this fingerprint into such keys makes new processes write to new
12
+ * keys, so old and new pods coexist during a rolling deploy without a purge
13
+ * step and without any ordering constraint between purge and rollout.
14
+ *
15
+ * Covered inputs: the enabled module ids, each module's declared `features`
16
+ * (which drive `filterGrantsByEnabledModules`, including the `*` superadmin
17
+ * expansion and off-convention prefixes), and every JSON-serializable field
18
+ * of the backend route manifest.
19
+ *
20
+ * NOT covered: a route's `icon`. It is a React element whose `type` is a
21
+ * function, which `JSON.stringify` drops — two different icon components
22
+ * serialize identically. Swapping an icon heals on the caller's TTL, not on
23
+ * the fingerprint. Callers MUST therefore still pass a `ttl`.
24
+ */
25
+ import { createHash } from 'node:crypto'
26
+ import type { Module } from '../../modules/registry'
27
+ import { getBackendRouteManifests } from '../../modules/registry'
28
+ import { getModules } from './registry'
29
+
30
+ const UNKNOWN_FINGERPRINT = 'unknown'
31
+
32
+ let cachedFingerprint: string | null = null
33
+ let cachedManifestsRef: unknown = null
34
+ let cachedModulesRef: unknown = null
35
+
36
+ function readModulesRef(): readonly Module[] | null {
37
+ try {
38
+ return getModules()
39
+ } catch {
40
+ return null
41
+ }
42
+ }
43
+
44
+ function byCodeUnit(a: string, b: string): number {
45
+ return a < b ? -1 : a > b ? 1 : 0
46
+ }
47
+
48
+ function describeModules(modules: readonly Module[] | null): string[] {
49
+ if (!modules) return []
50
+ return modules
51
+ .map((mod) => {
52
+ const features = (Array.isArray(mod.features) ? mod.features : [])
53
+ .filter((feature) => feature && typeof feature.id === 'string' && feature.id.length > 0)
54
+ .map((feature) => `${feature.id}:${feature.module || mod.id}`)
55
+ .sort(byCodeUnit)
56
+ return JSON.stringify({ id: mod.id, features })
57
+ })
58
+ .sort(byCodeUnit)
59
+ }
60
+
61
+ export function getModuleSurfaceFingerprint(): string {
62
+ const manifests = getBackendRouteManifests()
63
+ const modulesRef = readModulesRef()
64
+ if (cachedFingerprint !== null && cachedManifestsRef === manifests && cachedModulesRef === modulesRef) {
65
+ return cachedFingerprint
66
+ }
67
+ // The manifest carries third-party route metadata and module-scope React
68
+ // elements, so serialization is not fully under this repo's control. Every
69
+ // other fallible step in the nav handler degrades rather than throws, and a
70
+ // throw here would blank the entire admin chrome — fall back to a constant,
71
+ // which is exactly the pre-fingerprint behavior.
72
+ let fingerprint: string
73
+ try {
74
+ const modules = describeModules(modulesRef)
75
+ const routes = manifests.map((route) => JSON.stringify(route)).sort(byCodeUnit)
76
+ fingerprint = createHash('sha1')
77
+ .update(JSON.stringify({ modules, routes }))
78
+ .digest('hex')
79
+ .slice(0, 12)
80
+ } catch {
81
+ fingerprint = UNKNOWN_FINGERPRINT
82
+ }
83
+ cachedManifestsRef = manifests
84
+ cachedModulesRef = modulesRef
85
+ cachedFingerprint = fingerprint
86
+ return fingerprint
87
+ }
@@ -0,0 +1,178 @@
1
+ import {
2
+ normalizeColumnName,
3
+ resetCiphertextLikeWarnCache,
4
+ warnOnCiphertextLikeFallback,
5
+ } from '../ciphertext-search-warning'
6
+ import { createLogger } from '../../logger'
7
+
8
+ jest.mock('../../logger', () => {
9
+ const warn = jest.fn()
10
+ const debug = jest.fn()
11
+ const child = jest.fn(() => ({ warn, debug }))
12
+ return { createLogger: jest.fn(() => ({ child })), __warn: warn, __debug: debug }
13
+ })
14
+
15
+ const loggerModule = jest.requireMock('../../logger') as { __warn: jest.Mock; __debug: jest.Mock }
16
+
17
+ function createService(encryptedFields: string[], overrides: Record<string, unknown> = {}) {
18
+ return {
19
+ isEnabled: () => true,
20
+ getEncryptedFieldNames: jest.fn(async () => encryptedFields),
21
+ ...overrides,
22
+ }
23
+ }
24
+
25
+ describe('warnOnCiphertextLikeFallback', () => {
26
+ beforeEach(() => {
27
+ resetCiphertextLikeWarnCache()
28
+ loggerModule.__warn.mockClear()
29
+ loggerModule.__debug.mockClear()
30
+ })
31
+
32
+ it('warns when the filtered column is covered by an encryption map', async () => {
33
+ const service = createService(['email', 'display_name'])
34
+ await warnOnCiphertextLikeFallback({
35
+ entity: 'customers:customer_entity',
36
+ fields: ['display_name'],
37
+ tenantId: 'tenant-1',
38
+ reason: 'no-search-tokens',
39
+ service,
40
+ })
41
+
42
+ expect(loggerModule.__warn).toHaveBeenCalledTimes(1)
43
+ const [message, payload] = loggerModule.__warn.mock.calls[0]
44
+ expect(message).toBe('Text search filter cannot match an encrypted column')
45
+ expect(payload).toMatchObject({
46
+ entity: 'customers:customer_entity',
47
+ field: 'display_name',
48
+ reason: 'no-search-tokens',
49
+ })
50
+ })
51
+
52
+ it('stays quiet for columns outside the encryption map', async () => {
53
+ await warnOnCiphertextLikeFallback({
54
+ entity: 'currencies:currency',
55
+ fields: ['code', 'symbol'],
56
+ tenantId: 'tenant-1',
57
+ reason: 'no-search-tokens',
58
+ service: createService(['unrelated']),
59
+ })
60
+ expect(loggerModule.__warn).not.toHaveBeenCalled()
61
+ })
62
+
63
+ it('does not cache a non-encrypted lookup as already warned', async () => {
64
+ await warnOnCiphertextLikeFallback({
65
+ entity: 'auth:user', fields: ['email'], tenantId: 'tenant-1', reason: 'no-search-tokens', service: createService([]),
66
+ })
67
+ await warnOnCiphertextLikeFallback({
68
+ entity: 'auth:user', fields: ['email'], tenantId: 'tenant-1', reason: 'no-search-tokens', service: createService(['email']),
69
+ })
70
+ expect(loggerModule.__warn).toHaveBeenCalledTimes(1)
71
+ })
72
+
73
+ it('matches camelCase filter fields against snake_case map entries', async () => {
74
+ await warnOnCiphertextLikeFallback({
75
+ entity: 'checkout:checkout_transaction',
76
+ fields: ['firstName'],
77
+ tenantId: null,
78
+ reason: 'no-search-tokens',
79
+ service: createService(['first_name']),
80
+ })
81
+ expect(loggerModule.__warn).toHaveBeenCalledTimes(1)
82
+ expect(loggerModule.__warn.mock.calls[0][1]).toMatchObject({ field: 'first_name' })
83
+ })
84
+
85
+ it('warns once per entity, tenant and field', async () => {
86
+ const service = createService(['email'])
87
+ const params = {
88
+ entity: 'auth:user',
89
+ fields: ['email'],
90
+ tenantId: 'tenant-1',
91
+ reason: 'no-search-tokens' as const,
92
+ service,
93
+ }
94
+ await warnOnCiphertextLikeFallback(params)
95
+ await warnOnCiphertextLikeFallback(params)
96
+ await warnOnCiphertextLikeFallback(params)
97
+
98
+ expect(loggerModule.__warn).toHaveBeenCalledTimes(1)
99
+ expect(service.getEncryptedFieldNames).toHaveBeenCalledTimes(1)
100
+ })
101
+
102
+ it('warns separately for a different tenant', async () => {
103
+ const service = createService(['email'])
104
+ await warnOnCiphertextLikeFallback({
105
+ entity: 'auth:user', fields: ['email'], tenantId: 'tenant-1', reason: 'no-search-tokens', service,
106
+ })
107
+ await warnOnCiphertextLikeFallback({
108
+ entity: 'auth:user', fields: ['email'], tenantId: 'tenant-2', reason: 'no-search-tokens', service,
109
+ })
110
+ expect(loggerModule.__warn).toHaveBeenCalledTimes(2)
111
+ })
112
+
113
+ it('does nothing when encryption is unavailable or disabled', async () => {
114
+ await warnOnCiphertextLikeFallback({
115
+ entity: 'auth:user', fields: ['email'], tenantId: null, reason: 'no-search-tokens', service: null,
116
+ })
117
+ await warnOnCiphertextLikeFallback({
118
+ entity: 'auth:user',
119
+ fields: ['email'],
120
+ tenantId: null,
121
+ reason: 'no-search-tokens',
122
+ service: createService(['email'], { isEnabled: () => false }),
123
+ })
124
+ expect(loggerModule.__warn).not.toHaveBeenCalled()
125
+ })
126
+
127
+ it('ignores custom-field filters', async () => {
128
+ const service = createService(['cf:secret_note'])
129
+ await warnOnCiphertextLikeFallback({
130
+ entity: 'example:todo', fields: ['cf:secret_note'], tenantId: null, reason: 'no-search-tokens', service,
131
+ })
132
+ expect(service.getEncryptedFieldNames).not.toHaveBeenCalled()
133
+ expect(loggerModule.__warn).not.toHaveBeenCalled()
134
+ })
135
+
136
+ it('reports the disabled-search reason with its own hint', async () => {
137
+ await warnOnCiphertextLikeFallback({
138
+ entity: 'auth:user', fields: ['email'], tenantId: null, reason: 'search-disabled', service: createService(['email']),
139
+ })
140
+ expect(loggerModule.__warn.mock.calls[0][1]).toMatchObject({ reason: 'search-disabled' })
141
+ expect(loggerModule.__warn.mock.calls[0][1].hint).toContain('OM_SEARCH_ENABLED')
142
+ })
143
+
144
+ it('reports values that are too short to tokenize', async () => {
145
+ await warnOnCiphertextLikeFallback({
146
+ entity: 'auth:user', fields: ['email'], tenantId: null, reason: 'no-indexable-tokens', service: createService(['email']),
147
+ })
148
+ expect(loggerModule.__warn.mock.calls[0][1]).toMatchObject({ reason: 'no-indexable-tokens' })
149
+ expect(loggerModule.__warn.mock.calls[0][1].hint).toContain('OM_SEARCH_MIN_LEN')
150
+ })
151
+
152
+ it('never rethrows when the encryption lookup fails', async () => {
153
+ const service = {
154
+ isEnabled: () => true,
155
+ getEncryptedFieldNames: jest.fn(async () => { throw new Error('kms down') }),
156
+ }
157
+ await expect(warnOnCiphertextLikeFallback({
158
+ entity: 'auth:user', fields: ['email'], tenantId: null, reason: 'no-search-tokens', service,
159
+ })).resolves.toBeUndefined()
160
+ expect(loggerModule.__warn).not.toHaveBeenCalled()
161
+ expect(loggerModule.__debug).toHaveBeenCalled()
162
+ })
163
+ })
164
+
165
+ describe('normalizeColumnName', () => {
166
+ it('converts camelCase to snake_case and lowercases', () => {
167
+ expect(normalizeColumnName('firstName')).toBe('first_name')
168
+ expect(normalizeColumnName('primaryEmail')).toBe('primary_email')
169
+ expect(normalizeColumnName('display_name')).toBe('display_name')
170
+ expect(normalizeColumnName('Email')).toBe('email')
171
+ })
172
+ })
173
+
174
+ describe('logger wiring', () => {
175
+ it('uses the shared query logger namespace', () => {
176
+ expect(createLogger).toHaveBeenCalledWith('shared')
177
+ })
178
+ })