@open-mercato/cli 0.11.1-develop.8784.1.e9d95a72f5 → 0.11.1-develop.8805.1.6357054d1a

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 (175) hide show
  1. package/.turbo/turbo-build.log +4 -2
  2. package/AGENTS.md +2 -0
  3. package/dist/agentic/guides/architecture.md +1 -0
  4. package/dist/agentic/guides/module-facts.json +2014 -1099
  5. package/dist/agentic/guides/module-facts.v2.json +2014 -1099
  6. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  7. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  8. package/dist/agentic/guides/modules/ai_assistant/owned-contract-module-metadata.md +1 -1
  9. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  10. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  11. package/dist/agentic/guides/modules/assisted_selling/index.md +1 -1
  12. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  13. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  14. package/dist/agentic/guides/modules/auth/index.md +1 -1
  15. package/dist/agentic/guides/modules/auth/owned-contract-module-metadata.md +1 -1
  16. package/dist/agentic/guides/modules/availability/index.md +1 -1
  17. package/dist/agentic/guides/modules/backups/index.md +1 -1
  18. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  19. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  20. package/dist/agentic/guides/modules/cart/index.md +1 -1
  21. package/dist/agentic/guides/modules/cart/owned-contract-module-metadata.md +1 -1
  22. package/dist/agentic/guides/modules/catalog/di-registrations-rich.md +11 -8
  23. package/dist/agentic/guides/modules/catalog/di-service-tokens.md +5 -5
  24. package/dist/agentic/guides/modules/catalog/exact-override-targets.md +11 -8
  25. package/dist/agentic/guides/modules/catalog/index.md +2 -2
  26. package/dist/agentic/guides/modules/catalog/owned-contract-module-metadata.md +1 -1
  27. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  28. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  29. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  30. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  31. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  32. package/dist/agentic/guides/modules/channel_gmail/owned-contract-module-metadata.md +1 -1
  33. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  34. package/dist/agentic/guides/modules/channel_imap/owned-contract-module-metadata.md +1 -1
  35. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  36. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  37. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  38. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  39. package/dist/agentic/guides/modules/communication_channels/exact-override-targets.md +1 -1
  40. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  41. package/dist/agentic/guides/modules/communication_channels/owned-contract-module-metadata.md +1 -1
  42. package/dist/agentic/guides/modules/communication_channels/workers.md +1 -1
  43. package/dist/agentic/guides/modules/configs/acl-features.md +2 -1
  44. package/dist/agentic/guides/modules/configs/backend-pages.md +1 -0
  45. package/dist/agentic/guides/modules/configs/exact-override-targets.md +2 -0
  46. package/dist/agentic/guides/modules/configs/host-extension-points.md +10 -0
  47. package/dist/agentic/guides/modules/configs/index.md +5 -3
  48. package/dist/agentic/guides/modules/configs/owned-contract-module-metadata.md +1 -1
  49. package/dist/agentic/guides/modules/configs/setup.md +1 -1
  50. package/dist/agentic/guides/modules/configs/umes-diagnostics.md +9 -0
  51. package/dist/agentic/guides/modules/configs/umes-hosts.md +9 -0
  52. package/dist/agentic/guides/modules/content/index.md +1 -1
  53. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  54. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  55. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  56. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -0
  57. package/dist/agentic/guides/modules/customers/contribution-resolutions.md +2 -0
  58. package/dist/agentic/guides/modules/customers/di-registrations-rich.md +8 -5
  59. package/dist/agentic/guides/modules/customers/exact-override-targets.md +10 -5
  60. package/dist/agentic/guides/modules/customers/index.md +5 -5
  61. package/dist/agentic/guides/modules/customers/owned-contract-module-metadata.md +1 -1
  62. package/dist/agentic/guides/modules/customers/umes-contributions.md +2 -0
  63. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -10
  64. package/dist/agentic/guides/modules/dashboards/contribution-resolutions.md +0 -10
  65. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +0 -10
  66. package/dist/agentic/guides/modules/dashboards/index.md +5 -5
  67. package/dist/agentic/guides/modules/dashboards/umes-contributions.md +0 -10
  68. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  69. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  70. package/dist/agentic/guides/modules/devices/index.md +1 -1
  71. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  72. package/dist/agentic/guides/modules/directory/index.md +1 -1
  73. package/dist/agentic/guides/modules/documents/index.md +1 -1
  74. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  75. package/dist/agentic/guides/modules/entities/index.md +1 -1
  76. package/dist/agentic/guides/modules/entities/owned-contract-module-metadata.md +1 -1
  77. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  78. package/dist/agentic/guides/modules/events/index.md +1 -1
  79. package/dist/agentic/guides/modules/events/owned-contract-module-metadata.md +1 -1
  80. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  81. package/dist/agentic/guides/modules/forms/index.md +1 -1
  82. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  83. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  84. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  85. package/dist/agentic/guides/modules/generators/index.md +1 -1
  86. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  87. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  88. package/dist/agentic/guides/modules/integrations/owned-contract-module-metadata.md +1 -1
  89. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  90. package/dist/agentic/guides/modules/messages/index.md +1 -1
  91. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  92. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  93. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  94. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  95. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  96. package/dist/agentic/guides/modules/planner/index.md +1 -1
  97. package/dist/agentic/guides/modules/portal/index.md +1 -1
  98. package/dist/agentic/guides/modules/progress/index.md +1 -1
  99. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  100. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  101. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  102. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  103. package/dist/agentic/guides/modules/resources/index.md +1 -1
  104. package/dist/agentic/guides/modules/sales/active-extension-bindings.md +8 -0
  105. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +8 -0
  106. package/dist/agentic/guides/modules/sales/di-registrations-rich.md +31 -30
  107. package/dist/agentic/guides/modules/sales/di-service-tokens.md +5 -5
  108. package/dist/agentic/guides/modules/sales/exact-override-targets.md +39 -30
  109. package/dist/agentic/guides/modules/sales/index.md +5 -5
  110. package/dist/agentic/guides/modules/sales/owned-contract-module-metadata.md +1 -1
  111. package/dist/agentic/guides/modules/sales/umes-contributions.md +8 -0
  112. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  113. package/dist/agentic/guides/modules/search/index.md +1 -1
  114. package/dist/agentic/guides/modules/search/owned-contract-module-metadata.md +1 -1
  115. package/dist/agentic/guides/modules/security/index.md +1 -1
  116. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  117. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  118. package/dist/agentic/guides/modules/sso/index.md +1 -1
  119. package/dist/agentic/guides/modules/staff/active-extension-bindings.md +2 -1
  120. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -0
  121. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -0
  122. package/dist/agentic/guides/modules/staff/index.md +8 -8
  123. package/dist/agentic/guides/modules/staff/umes-contributions.md +1 -0
  124. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  125. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  126. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  127. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  128. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  129. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  130. package/dist/agentic/guides/modules/translations/index.md +1 -1
  131. package/dist/agentic/guides/modules/upgrade_actions/contribution-resolutions.md +12 -0
  132. package/dist/agentic/guides/modules/upgrade_actions/exact-override-targets.md +11 -0
  133. package/dist/agentic/guides/modules/upgrade_actions/index.md +15 -0
  134. package/dist/agentic/guides/modules/upgrade_actions/owned-contract-module-metadata.md +11 -0
  135. package/dist/agentic/guides/modules/upgrade_actions/umes-contributions.md +12 -0
  136. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  137. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  138. package/dist/agentic/guides/modules/wms/index.md +1 -1
  139. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  140. package/dist/agentic/guides/reference-module-facts.json +1 -1
  141. package/dist/agentic/guides/upstream/manifest.json +1 -1
  142. package/dist/lib/generators/extensions/dashboard-widgets.js +46 -4
  143. package/dist/lib/generators/extensions/dashboard-widgets.js.map +2 -2
  144. package/dist/lib/generators/extensions/workflows.js +25 -2
  145. package/dist/lib/generators/extensions/workflows.js.map +2 -2
  146. package/dist/lib/generators/module-facts.js +2 -0
  147. package/dist/lib/generators/module-facts.js.map +2 -2
  148. package/dist/lib/generators/module-registry.js +7 -6
  149. package/dist/lib/generators/module-registry.js.map +2 -2
  150. package/dist/lib/module-coupling/analyze.js +391 -0
  151. package/dist/lib/module-coupling/analyze.js.map +7 -0
  152. package/dist/lib/module-diagnostics.js +160 -0
  153. package/dist/lib/module-diagnostics.js.map +7 -0
  154. package/dist/lib/module-index.js +103 -0
  155. package/dist/lib/module-index.js.map +7 -0
  156. package/dist/lib/testing/integration-discovery.js +20 -15
  157. package/dist/lib/testing/integration-discovery.js.map +3 -3
  158. package/dist/mercato.js +19 -2
  159. package/dist/mercato.js.map +2 -2
  160. package/package.json +7 -7
  161. package/src/__tests__/rotation-json-output.test.ts +13 -0
  162. package/src/lib/__tests__/module-diagnostics.test.ts +207 -0
  163. package/src/lib/generators/__tests__/module-facts.owned-contracts.test.ts +2 -2
  164. package/src/lib/generators/__tests__/output-snapshots.test.ts +19 -0
  165. package/src/lib/generators/__tests__/structural-contracts.test.ts +18 -0
  166. package/src/lib/generators/extensions/dashboard-widgets.ts +49 -3
  167. package/src/lib/generators/extensions/workflows.ts +26 -2
  168. package/src/lib/generators/module-facts.ts +2 -0
  169. package/src/lib/generators/module-registry.ts +11 -7
  170. package/src/lib/module-coupling/analyze.ts +464 -0
  171. package/src/lib/module-diagnostics.ts +182 -0
  172. package/src/lib/module-index.ts +133 -0
  173. package/src/lib/testing/__tests__/integration-discovery.test.ts +26 -2
  174. package/src/lib/testing/integration-discovery.ts +19 -11
  175. package/src/mercato.ts +21 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/cli",
3
- "version": "0.11.1-develop.8784.1.e9d95a72f5",
3
+ "version": "0.11.1-develop.8805.1.6357054d1a",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -60,10 +60,10 @@
60
60
  "@mikro-orm/decorators": "^7.1.14",
61
61
  "@mikro-orm/migrations": "^7.1.14",
62
62
  "@mikro-orm/postgresql": "^7.1.14",
63
- "@open-mercato/events": "0.11.1-develop.8784.1.e9d95a72f5",
64
- "@open-mercato/queue": "0.11.1-develop.8784.1.e9d95a72f5",
65
- "@open-mercato/shared": "0.11.1-develop.8784.1.e9d95a72f5",
66
- "@open-mercato/telemetry": "0.11.1-develop.8784.1.e9d95a72f5",
63
+ "@open-mercato/events": "0.11.1-develop.8805.1.6357054d1a",
64
+ "@open-mercato/queue": "0.11.1-develop.8805.1.6357054d1a",
65
+ "@open-mercato/shared": "0.11.1-develop.8805.1.6357054d1a",
66
+ "@open-mercato/telemetry": "0.11.1-develop.8805.1.6357054d1a",
67
67
  "cross-spawn": "^7.0.6",
68
68
  "minisearch": "7.2.0",
69
69
  "pg": "8.23.0",
@@ -75,10 +75,10 @@
75
75
  "typescript-js": "npm:typescript@6.0.3"
76
76
  },
77
77
  "peerDependencies": {
78
- "@open-mercato/shared": "0.11.1-develop.8784.1.e9d95a72f5"
78
+ "@open-mercato/shared": "0.11.1-develop.8805.1.6357054d1a"
79
79
  },
80
80
  "devDependencies": {
81
- "@open-mercato/shared": "0.11.1-develop.8784.1.e9d95a72f5",
81
+ "@open-mercato/shared": "0.11.1-develop.8805.1.6357054d1a",
82
82
  "@types/jest": "^30.0.0",
83
83
  "jest": "^30.4.2",
84
84
  "ts-jest": "^29.4.12"
@@ -32,6 +32,19 @@ describe('rotation dispatcher JSON progress', () => {
32
32
  expect(stdout.mock.calls.flat().join('\n')).toContain('Running entities:rotate-encryption-key')
33
33
  })
34
34
 
35
+ it('prints a readable lock refusal for operators', async () => {
36
+ delete process.env.OM_ROTATION_PROGRESS
37
+ const message = 'ROTATION_RUN_LOCKED:1ca9d863-bee9-4f54-aac8-e8ab42163ccb'
38
+ registerCliModules([{
39
+ id: 'entities',
40
+ cli: [{ command: 'rotate-encryption-key', run: async () => { throw new Error(`[internal] ${message}`) } }],
41
+ } as Module])
42
+ jest.spyOn(console, 'log').mockImplementation()
43
+ const humanError = jest.spyOn(console, 'error').mockImplementation()
44
+ expect(await run(['node', 'mercato', 'entities', 'rotate-encryption-key'])).toBe(1)
45
+ expect(humanError).toHaveBeenCalledWith(`💥 Failed: ${message}`)
46
+ })
47
+
35
48
  it.each([
36
49
  ['entities', 'rotate-encryption-key', undefined],
37
50
  ['entities', 'rotate-encryption-key', 'plain'],
@@ -0,0 +1,207 @@
1
+ import fs from 'node:fs'
2
+ import os from 'node:os'
3
+ import path from 'node:path'
4
+ import { analyzeModuleCoupling } from '../module-coupling/analyze'
5
+ import { runModuleDiagnostics } from '../module-diagnostics'
6
+ import { buildModuleIndex, inactiveModuleDependencies, missingModuleRequirements, resolveIndexedModule, type IndexedModule } from '../module-index'
7
+ import { createResolver } from '../resolver'
8
+
9
+ let root: string
10
+
11
+ function fixture(file: string, contents: string): void {
12
+ const target = path.join(root, file)
13
+ fs.mkdirSync(path.dirname(target), { recursive: true })
14
+ fs.writeFileSync(target, contents)
15
+ }
16
+
17
+ function moduleSource(module: string, suffix: string, contents: string): void {
18
+ fixture(`src/modules/${module}/${suffix}`, contents)
19
+ }
20
+
21
+ function register(...ids: string[]): void {
22
+ fixture('src/modules.ts', `export const enabledModules = [${ids.map((id) => `{ id: '${id}', from: '@app' }`).join(', ')}]`)
23
+ }
24
+
25
+ function descriptor(id: string, other = ''): void {
26
+ moduleSource(id, 'index.ts', `export const metadata = { name: '${id}'${other ? `, ${other}` : ''} }`)
27
+ }
28
+
29
+ beforeEach(() => {
30
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'module-diagnostics-'))
31
+ fixture('package.json', '{"name":"fixture","version":"1.0.0"}')
32
+ })
33
+
34
+ afterEach(() => {
35
+ jest.restoreAllMocks()
36
+ fs.rmSync(root, { recursive: true, force: true })
37
+ })
38
+
39
+ it('indexes local and packaged module declarations and reports transitive inactive hard dependencies', () => {
40
+ register('first')
41
+ descriptor('first', "requires: ['second'], optionalRequires: ['addon']")
42
+ descriptor('second', "requires: ['third']")
43
+ descriptor('third', "requires: ['first']")
44
+ fixture('node_modules/@open-mercato/core/package.json', '{"name":"@open-mercato/core","version":"2.0.0"}')
45
+ fixture('node_modules/@open-mercato/core/dist/modules/addon/index.js',
46
+ "exports.metadata = { name: 'addon', requires: ['third'], optionalRequires: ['first'] }")
47
+
48
+ const index = buildModuleIndex(createResolver(root))
49
+ expect(index.find((module) => module.id === 'addon')).toMatchObject({
50
+ packageName: '@open-mercato/core', version: '2.0.0', enabled: false, requires: ['third'], optionalRequires: ['first'],
51
+ })
52
+ const first = index.find((module) => module.id === 'first')!
53
+ expect(missingModuleRequirements(first, index)).toEqual([
54
+ { requirement: 'second', path: ['first', 'second'] },
55
+ { requirement: 'third', path: ['first', 'second', 'third'] },
56
+ ])
57
+ expect(inactiveModuleDependencies(index)).toEqual([{ source: first, target: 'addon' }])
58
+ })
59
+
60
+ it('checks import, route and DI ownership, optional guards, and integration declarations from source', () => {
61
+ register('core_user', 'provider')
62
+ descriptor('core_user', "optionalRequires: ['provider']")
63
+ descriptor('provider')
64
+ descriptor('unrelated', "requires: ['core_user']")
65
+ moduleSource('core_user', 'i18n/en.json', '{"core_user.optionalRequires.provider":"Provider sync"}')
66
+ moduleSource('provider', 'api/read/route.ts', "export const metadata = { path: '/custom/endpoint' }; export const GET = () => null")
67
+ moduleSource('provider', 'di.ts',
68
+ 'export const register = (container) => container.register({ providerService: asFunction(createService) })')
69
+ moduleSource('core_user', 'service.ts', [
70
+ "import type { PrivateShape } from '../unrelated/contract'",
71
+ "export async function list() { return fetch('/api/custom/endpoint') }",
72
+ "export async function useOther() { return import('../unrelated/runtime') }",
73
+ ].join('\n'))
74
+ moduleSource('core_user', 'guarded.ts',
75
+ "export function guarded(container) { try { return container.resolve('providerService') } catch { return null } }")
76
+ moduleSource('core_user', '__integration__/TC-TEST-001.spec.ts', "test('provider', () => fetch('/api/custom/endpoint'))")
77
+ moduleSource('core_user', '__integration__/TC-TEST-002.spec.ts',
78
+ "export const meta = { dependsOnModules: ['provider'] }; test('provider', () => fetch('/api/custom/endpoint'))")
79
+
80
+ moduleSource('core_user', '__integration__/nested/meta.ts',
81
+ "export const meta = { requiredModules: ['provider'] }")
82
+ moduleSource('core_user', '__integration__/nested/TC-TEST-003.spec.ts',
83
+ "test('provider', () => fetch('/api/custom/endpoint'))")
84
+ moduleSource('core_user', '__integration__/TC-TEST-004.meta.ts',
85
+ "export const meta = { requiresModules: ['provider'] }")
86
+ moduleSource('core_user', '__integration__/TC-TEST-004.spec.ts',
87
+ "test('provider', () => fetch('/api/custom/endpoint'))")
88
+ moduleSource('core_user', '__integration__/helpers/provider.ts',
89
+ "export const read = () => fetch('/api/custom/endpoint')")
90
+ moduleSource('core_user', '__integration__/TC-TEST-005.spec.ts',
91
+ "export const meta = { optionalModules: ['provider'] }; test('provider', () => fetch('/api/custom/endpoint'))")
92
+
93
+ const facts = analyzeModuleCoupling(buildModuleIndex(createResolver(root)))
94
+ expect(facts.findings.map(({ rule, target, kind }) => ({ rule, target, kind }))).toEqual([
95
+ { rule: 'R4', target: 'provider', kind: 'api-path' },
96
+ { rule: 'R2', target: 'provider', kind: 'api-path' },
97
+ { rule: 'R1', target: 'unrelated', kind: 'import' },
98
+ { rule: 'R5', target: 'unrelated', kind: 'import' },
99
+ ])
100
+ })
101
+
102
+ it('exempts kernel references from declaration rules but detects reverse edges from non-kernel modules', () => {
103
+ register('auth', 'directory', 'plugin')
104
+ descriptor('auth', "requires: ['directory', 'plugin']")
105
+ descriptor('directory')
106
+ descriptor('plugin')
107
+ moduleSource('directory', 'runtime.ts', "export const internal = () => import('../auth/index')")
108
+ moduleSource('plugin', 'runtime.ts', "export const internal = () => import('../auth/index')")
109
+ moduleSource('plugin', '__integration__/TC-TEST-003.spec.ts', "test('kernel', () => import('../auth/index'))")
110
+
111
+ const facts = analyzeModuleCoupling(buildModuleIndex(createResolver(root)))
112
+ expect(facts.findings.map(({ rule, module, target }) => ({ rule, module, target }))).toEqual([
113
+ { rule: 'R5', module: 'plugin', target: 'auth' },
114
+ ])
115
+ })
116
+
117
+ it('prints all six doctor groups, supports JSON, and only blocks optional drift in strict mode', () => {
118
+ register('auth', 'directory', 'reader')
119
+ descriptor('auth')
120
+ descriptor('directory')
121
+ descriptor('reader', "requires: ['missing'], optionalRequires: ['addon']")
122
+ descriptor('addon')
123
+ descriptor('peer')
124
+ moduleSource('reader', 'i18n/en.json', '{"reader.optionalRequires.addon":"Optional export"}')
125
+ moduleSource('reader', 'references.ts',
126
+ "export async function peers() { await import('../peer/index'); await fetch('/api/not-found') }")
127
+ moduleSource('reader', 'extension-points.ts',
128
+ "export const extensionPoints = defineModuleExtensionPoints({ moduleId: 'reader', hosts: { index: injectionExtensionHost({ family: 'generic', spotId: 'reader:host', supported: ['render-widget'], source: 'references.ts', minContributions: 1 }) } })")
129
+ const output = jest.spyOn(console, 'log').mockImplementation(() => {})
130
+ const resolver = createResolver(root)
131
+ expect(runModuleDiagnostics('doctor', ['--json'], resolver)).toBe(1)
132
+ const doctor = JSON.parse(output.mock.calls.at(-1)?.[0] ?? '{}')
133
+ expect(doctor).toMatchObject({ version: 1, enabled: ['auth', 'directory', 'reader'] })
134
+ expect(doctor.findings.map((finding: { group: string }) => finding.group)).toEqual([
135
+ 'missing-kernel', 'missing-hard', 'inactive-optional', 'undeclared-or-upstream', 'missing-contributions', 'dangling',
136
+ ])
137
+ expect(doctor.findings[2].message).toContain('Optional export')
138
+
139
+ expect(runModuleDiagnostics('list', ['--all', '--json'], resolver)).toBe(0)
140
+ const modules = JSON.parse(output.mock.calls.at(-1)?.[0] ?? '{}')
141
+ expect(modules.modules).toEqual(expect.arrayContaining([
142
+ expect.objectContaining({ id: 'addon', enabled: false }),
143
+ expect.objectContaining({ id: 'reader', requires: ['missing'], optionalRequires: ['addon'] }),
144
+ ]))
145
+
146
+ register('auth', 'directory', 'api_keys', 'reader')
147
+ descriptor('api_keys')
148
+ descriptor('reader', "optionalRequires: ['addon']")
149
+ expect(runModuleDiagnostics('doctor', [], resolver)).toBe(0)
150
+ expect(runModuleDiagnostics('doctor', ['--strict'], resolver)).toBe(1)
151
+ })
152
+
153
+ it('recognizes an InboxOps action contribution without accepting other module imports', () => {
154
+ register('reader', 'inbox_ops')
155
+ descriptor('reader')
156
+ descriptor('inbox_ops')
157
+ moduleSource('reader', 'inbox-actions.ts', "import { helper } from '../inbox_ops/helpers'; export default [helper]")
158
+ moduleSource('reader', 'runtime.ts', "import '../inbox_ops/helpers'")
159
+ moduleSource('inbox_ops', 'helpers.ts', 'export const helper = {}')
160
+
161
+ const report = analyzeModuleCoupling(buildModuleIndex(createResolver(root)))
162
+ expect(report.findings).toEqual([expect.objectContaining({
163
+ rule: 'R1', module: 'reader', target: 'inbox_ops', file: expect.stringContaining('runtime.ts'),
164
+ })])
165
+ })
166
+
167
+ it('keeps a package-qualified requirement bound to its intended provider', () => {
168
+ const base = { id: 'provider', version: '1.0.0', roots: [], requires: [], optionalRequires: [] }
169
+ const enabled: IndexedModule = { ...base, packageName: '@example/alternate', locators: ['@example/alternate'], enabled: true }
170
+ const installed: IndexedModule = { ...base, packageName: '@example/provider', locators: ['@example/provider'], enabled: false }
171
+ const entries = [enabled, installed]
172
+ expect(resolveIndexedModule('@example/provider', entries)).toBe(installed)
173
+ expect(resolveIndexedModule('provider', entries)).toBe(enabled)
174
+ expect(missingModuleRequirements({ ...enabled, id: 'reader', requires: ['@example/provider'] }, entries))
175
+ .toEqual([{ requirement: '@example/provider', path: ['reader', 'provider'] }])
176
+ })
177
+
178
+ it('reads the feature ID in a hasFeature call', () => {
179
+ register('reader', 'provider')
180
+ descriptor('reader')
181
+ descriptor('provider')
182
+ moduleSource('provider', 'acl.ts', "export const features = [{ id: 'provider.view', title: 'View', module: 'provider' }]")
183
+ moduleSource('reader', 'runtime.ts', "export const canView = (grants) => hasFeature(grants, 'provider.view')")
184
+ const report = analyzeModuleCoupling(buildModuleIndex(createResolver(root)))
185
+ expect(report.findings).toEqual([expect.objectContaining({
186
+ rule: 'R1', module: 'reader', target: 'provider', kind: 'feature',
187
+ })])
188
+ })
189
+
190
+ it('does not count a widget whose required module is absent', () => {
191
+ register('reader', 'provider')
192
+ descriptor('reader')
193
+ descriptor('provider')
194
+ descriptor('addon')
195
+ moduleSource('reader', 'extension-points.ts',
196
+ "export const extensionPoints = defineModuleExtensionPoints({ moduleId: 'reader', hosts: { index: injectionExtensionHost({ family: 'generic', spotId: 'reader:host', supported: ['render-widget'], source: 'references.ts', minContributions: 1 }) } })")
197
+ moduleSource('provider', 'widgets/injection-table.ts',
198
+ "export const injectionTable = { 'reader:host': ['provider.widget'] }")
199
+ moduleSource('provider', 'widgets/injection/example/widget.ts',
200
+ "export default { metadata: { id: 'provider.widget', requiredModules: ['addon'] } }")
201
+ const resolver = createResolver(root)
202
+ expect(analyzeModuleCoupling(buildModuleIndex(resolver)).contributions)
203
+ .toEqual([expect.objectContaining({ count: 0, minimum: 1, spotId: 'reader:host' })])
204
+
205
+ register('reader', 'provider', 'addon')
206
+ expect(analyzeModuleCoupling(buildModuleIndex(resolver)).contributions).toEqual([])
207
+ })
@@ -31,7 +31,7 @@ describe('module-facts owned contracts + provenance (Spec 1)', () => {
31
31
  writeFixture(
32
32
  moduleRoot,
33
33
  'index.ts',
34
- "export const metadata = { name: 'facts', title: 'Facts', version: '1.2.3', requires: ['auth', 'catalog'], ejectable: true }\n",
34
+ "export const metadata = { name: 'facts', title: 'Facts', version: '1.2.3', requires: ['auth', 'catalog'], optionalRequires: ['customers'], ejectable: true }\n",
35
35
  )
36
36
  writeFixture(
37
37
  moduleRoot,
@@ -213,7 +213,7 @@ describe('module-facts owned contracts + provenance (Spec 1)', () => {
213
213
  it('extracts module-metadata owned contract with only safe scalar fields', () => {
214
214
  const fact = ownedById(facts, 'module-metadata', 'facts')
215
215
  expect(fact).toBeDefined()
216
- expect(fact?.metadata).toEqual({ name: 'facts', version: '1.2.3', requires: ['auth', 'catalog'], ejectable: true })
216
+ expect(fact?.metadata).toEqual({ name: 'facts', version: '1.2.3', requires: ['auth', 'catalog'], optionalRequires: ['customers'], ejectable: true })
217
217
  expect(fact?.source.sourcePath).toBe('node_modules/@open-mercato/example/src/modules/facts/index.ts')
218
218
  })
219
219
 
@@ -671,6 +671,25 @@ function captureGeneratedFiles(): Map<string, string> {
671
671
  }
672
672
 
673
673
  describe('generator output compatibility', () => {
674
+ it('only imports the validating workflow registrar when the engine is enabled', async () => {
675
+ const workflowEngine = { id: 'workflows', from: '@open-mercato/core' }
676
+ touchFile(pkgModulePath('workflows', 'index.ts'), "export const metadata = { name: 'workflows' }\n")
677
+ touchFile(
678
+ pkgModulePath('workflows', 'lib', 'code-registry.ts'),
679
+ 'export function registerCodeWorkflows(_workflows: unknown[]) {}\n',
680
+ )
681
+ await generateModuleRegistry({ resolver: createMockResolver([workflowEngine]), quiet: true })
682
+ expect(readGenerated('workflows.generated.ts')).not.toContain('/modules/workflows/lib/code-registry')
683
+ expect(readGenerated('workflow-registrations.generated.ts')).toContain(
684
+ 'import { registerCodeWorkflows } from "@open-mercato/core/modules/workflows/lib/code-registry"',
685
+ )
686
+ expect(readGenerated('workflow-registrations.generated.ts')).toContain('registerCodeWorkflows(allCodeWorkflows)')
687
+
688
+ await generateModuleRegistry({ resolver: createMockResolver([]), quiet: true })
689
+ expect(readGenerated('workflow-registrations.generated.ts')).toContain('export function registerGeneratedCodeWorkflows()')
690
+ expect(readGenerated('workflow-registrations.generated.ts')).not.toContain('/modules/workflows/lib/code-registry')
691
+ })
692
+
674
693
  const registryFiles = [
675
694
  'ai-tools.generated.ts',
676
695
  'ai-agents.generated.ts',
@@ -1084,6 +1084,24 @@ describe('dashboard-widgets.generated.ts', () => {
1084
1084
  expect(content).toContain('source: "app"')
1085
1085
  expect(content).toContain('loader: () =>')
1086
1086
  })
1087
+
1088
+ it.each([
1089
+ "export const dashboardWidgetKey = 'dashboards:revenue:widget'; export default {}",
1090
+ "const key = 'dashboards:revenue:widget'; export { key as dashboardWidgetKey }; export default {}",
1091
+ ])('keeps a relocated dashboard key in both registries with an app override (%s)', async (source) => {
1092
+ const enabled = scaffoldFixture()
1093
+ const resolver = createMockResolver(enabled)
1094
+ touchFile(pkgModulePath('orders', 'widgets', 'dashboard', 'revenue', 'widget.ts'), source)
1095
+ touchFile(appModulePath('orders', 'widgets', 'dashboard', 'revenue', 'widget.ts'), 'export default {}')
1096
+ await generateModuleRegistry({ resolver, quiet: true })
1097
+
1098
+ for (const name of ['dashboard-widgets.generated.ts', 'modules.generated.ts']) {
1099
+ const registry = readGenerated(name)
1100
+ expect(registry).toContain('key: "dashboards:revenue:widget"')
1101
+ expect(registry).not.toContain('key: "orders:revenue:widget"')
1102
+ expect(registry).toContain('@/modules/orders/widgets/dashboard/revenue/widget')
1103
+ }
1104
+ })
1087
1105
  })
1088
1106
 
1089
1107
  describe('injection-widgets.generated.ts', () => {
@@ -1,6 +1,17 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import ts from 'typescript-js'
1
4
  import { VariableDeclarationKind } from 'ts-morph'
2
5
  import type { GeneratorExtension } from '../extension'
3
- import { scanModuleDir, SCAN_CONFIGS } from '../scanner'
6
+ import {
7
+ MODULE_CODE_EXTENSIONS,
8
+ resolveStandaloneSourceMirrorBase,
9
+ scanModuleDir,
10
+ SCAN_CONFIGS,
11
+ stripModuleCodeExtension,
12
+ type ModuleRoots,
13
+ type ScannedFile,
14
+ } from '../scanner'
4
15
  import { arrayLiteral, arrowFunction, identifier, methodCall, nullishCoalesce, objectLiteral, propertyAccess, writeValue } from '../ast'
5
16
  import { dynamicImportExpression, renderGeneratedTsSource } from './shared'
6
17
 
@@ -11,6 +22,41 @@ type DashboardWidgetEntry = {
11
22
  importPath: string
12
23
  }
13
24
 
25
+ function readRegisteredWidgetKey(absolutePath: string): string | undefined {
26
+ if (!fs.existsSync(absolutePath)) return undefined
27
+ const source = ts.createSourceFile(absolutePath, fs.readFileSync(absolutePath, 'utf8'), ts.ScriptTarget.Latest, true)
28
+ const values = new Map<string, string>()
29
+ let exportName: string | undefined
30
+ for (const statement of source.statements) {
31
+ if (ts.isVariableStatement(statement)) {
32
+ const exported = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
33
+ for (const declaration of statement.declarationList.declarations) {
34
+ if (!ts.isIdentifier(declaration.name) || !declaration.initializer) continue
35
+ if (!ts.isStringLiteralLike(declaration.initializer) || !declaration.initializer.text) continue
36
+ values.set(declaration.name.text, declaration.initializer.text)
37
+ if (exported && declaration.name.text === 'dashboardWidgetKey') exportName = declaration.name.text
38
+ }
39
+ } else if (ts.isExportDeclaration(statement) && !statement.moduleSpecifier && statement.exportClause
40
+ && ts.isNamedExports(statement.exportClause)) {
41
+ const key = statement.exportClause.elements.find((item) => item.name.text === 'dashboardWidgetKey')
42
+ if (key) exportName = (key.propertyName ?? key.name).text
43
+ }
44
+ }
45
+ return exportName ? values.get(exportName) : undefined
46
+ }
47
+
48
+ export function resolveDashboardWidgetKey(moduleId: string, roots: ModuleRoots, file: ScannedFile): string {
49
+ const relative = path.join('widgets', 'dashboard', file.relPath)
50
+ const fallback = [moduleId, ...stripModuleCodeExtension(file.relPath).split('/')].join(':')
51
+ const packageBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
52
+ if (!file.fromApp) return readRegisteredWidgetKey(path.join(packageBase, relative)) ?? fallback
53
+ const appKey = readRegisteredWidgetKey(path.join(roots.appBase, relative))
54
+ if (appKey) return appKey
55
+ const packagePath = stripModuleCodeExtension(path.join(packageBase, relative))
56
+ const packageExtension = MODULE_CODE_EXTENSIONS.find((extension) => fs.existsSync(packagePath + extension))
57
+ return (packageExtension && readRegisteredWidgetKey(packagePath + packageExtension)) ?? fallback
58
+ }
59
+
14
60
  export function createDashboardWidgetsExtension(): GeneratorExtension {
15
61
  const widgetEntries = new Map<string, DashboardWidgetEntry>()
16
62
 
@@ -22,11 +68,11 @@ export function createDashboardWidgetsExtension(): GeneratorExtension {
22
68
  for (const { relPath, fromApp } of files) {
23
69
  const segments = relPath.split('/')
24
70
  const file = segments.pop() ?? ''
25
- const base = file.replace(/\.(t|j)sx?$/, '')
71
+ const base = stripModuleCodeExtension(file)
26
72
  const importPath = ctx.sanitizeGeneratedModuleSpecifier(
27
73
  `${fromApp ? ctx.imps.appBase : ctx.imps.pkgBase}/widgets/dashboard/${[...segments, base].join('/')}`
28
74
  )
29
- const key = [ctx.moduleId, ...segments, base].filter(Boolean).join(':')
75
+ const key = resolveDashboardWidgetKey(ctx.moduleId, ctx.roots, { relPath, fromApp })
30
76
  const entry: DashboardWidgetEntry = {
31
77
  moduleId: ctx.moduleId,
32
78
  key,
@@ -20,11 +20,16 @@ import {
20
20
  export function createWorkflowsExtension(): GeneratorExtension {
21
21
  const imports: Array<ReturnType<typeof namespaceImportSpec>> = []
22
22
  const entries: WriterFunction[] = []
23
+ let registrarImport: string | undefined
23
24
 
24
25
  return {
25
26
  id: 'registry.workflows',
26
- outputFiles: ['workflows.generated.ts'],
27
+ outputFiles: ['workflows.generated.ts', 'workflow-registrations.generated.ts'],
27
28
  scanModule(ctx) {
29
+ if (ctx.moduleId === 'workflows') {
30
+ const registrar = ctx.resolveModuleFile(ctx.roots, ctx.imps, 'lib/code-registry.ts')
31
+ if (registrar) registrarImport = ctx.sanitizeGeneratedModuleSpecifier(registrar.importPath)
32
+ }
28
33
  ctx.processStandaloneConfig({
29
34
  roots: ctx.roots,
30
35
  imps: ctx.imps,
@@ -135,7 +140,26 @@ export function createWorkflowsExtension(): GeneratorExtension {
135
140
  },
136
141
  })
137
142
 
138
- return new Map([['workflows.generated.ts', output]])
143
+ const registrationOutput = renderGeneratedTsSource({
144
+ fileName: 'workflow-registrations.generated.ts',
145
+ imports: registrarImport ? [
146
+ { namedImports: [{ name: 'allCodeWorkflows' }], moduleSpecifier: './workflows.generated' },
147
+ { namedImports: [{ name: 'registerCodeWorkflows' }], moduleSpecifier: registrarImport },
148
+ ] : [],
149
+ build(sourceFile) {
150
+ sourceFile.addFunction({
151
+ name: 'registerGeneratedCodeWorkflows',
152
+ isExported: true,
153
+ returnType: 'void',
154
+ statements: registrarImport ? ['registerCodeWorkflows(allCodeWorkflows)'] : [],
155
+ })
156
+ },
157
+ })
158
+
159
+ return new Map([
160
+ ['workflows.generated.ts', output],
161
+ ['workflow-registrations.generated.ts', registrationOutput],
162
+ ])
139
163
  },
140
164
  }
141
165
  }
@@ -1542,6 +1542,8 @@ function extractModuleMetadataContract(
1542
1542
  if (version) facts.version = version
1543
1543
  const requires = readStringArrayPropertyInitializer(metadata, 'requires')
1544
1544
  if (requires && requires.length > 0) facts.requires = requires
1545
+ const optionalRequires = readStringArrayPropertyInitializer(metadata, 'optionalRequires')
1546
+ if (optionalRequires && optionalRequires.length > 0) facts.optionalRequires = optionalRequires
1545
1547
  const ejectable = readBooleanPropertyInitializer(metadata, 'ejectable')
1546
1548
  if (ejectable !== undefined) facts.ejectable = ejectable
1547
1549
  return {
@@ -80,6 +80,7 @@ import {
80
80
  resolveStandaloneSourceMirrorBase,
81
81
  } from './scanner'
82
82
  import { loadGeneratorExtensions } from './extensions'
83
+ import { resolveDashboardWidgetKey } from './extensions/dashboard-widgets'
83
84
  import { prepareCrudFormSectionRegistries, writeCrudFormSectionRegistries, writeDerivedCrudFormSectionRoutes } from './form-sections'
84
85
  import type { ModuleScanContext, StandaloneConfigOptions } from './extension'
85
86
  import {
@@ -321,7 +322,7 @@ function scanDashboardWidgetEntries(options: {
321
322
  const importPath = sanitizeGeneratedModuleSpecifier(
322
323
  `${fromApp ? appImportBase : pkgImportBase}/widgets/dashboard/${[...segs, base].join('/')}`
323
324
  )
324
- const key = [modId, ...segs, base].filter(Boolean).join(':')
325
+ const key = resolveDashboardWidgetKey(modId, roots, { relPath, fromApp })
325
326
  const source = fromApp ? 'app' : 'package'
326
327
  return { moduleId: modId, key, source, importPath }
327
328
  })
@@ -601,12 +602,15 @@ function findExportedMetadataSource(parsed: ts.SourceFile): ExportedMetadataSour
601
602
  }
602
603
 
603
604
  /**
604
- * Reads `metadata.requires` from a module `index` source purely syntactically — the file is parsed,
605
+ * Reads a module dependency declaration from its `index` source; the file is parsed,
605
606
  * never executed, so packaged TypeScript sources and module side effects are both safe. Only the
606
607
  * exported `metadata` object is consulted, and only string-literal entries are accepted: anything
607
608
  * computed is reported as unresolvable instead of being guessed.
608
609
  */
609
- export function extractModuleRequiresFromSource(sourceFile: string): ModuleRequiresExtraction {
610
+ export function extractModuleRequiresFromSource(
611
+ sourceFile: string,
612
+ propertyName: 'requires' | 'optionalRequires' = 'requires',
613
+ ): ModuleRequiresExtraction {
610
614
  let source = ''
611
615
  try {
612
616
  source = fs.readFileSync(sourceFile, 'utf8')
@@ -647,9 +651,9 @@ export function extractModuleRequiresFromSource(sourceFile: string): ModuleRequi
647
651
  return { status: 'unresolvable', reason: 'exported metadata uses a computed key' }
648
652
  }
649
653
  const key = ts.isIdentifier(name) || ts.isStringLiteral(name) ? name.text : null
650
- if (key !== 'requires') continue
654
+ if (key !== propertyName) continue
651
655
  if (!ts.isPropertyAssignment(property)) {
652
- return { status: 'unresolvable', reason: 'metadata.requires is not a property assignment' }
656
+ return { status: 'unresolvable', reason: `metadata.${propertyName} is not a property assignment` }
653
657
  }
654
658
  requiresInitializer = property.initializer
655
659
  }
@@ -657,14 +661,14 @@ export function extractModuleRequiresFromSource(sourceFile: string): ModuleRequi
657
661
 
658
662
  const requiresArray = unwrapExpression(requiresInitializer)
659
663
  if (!ts.isArrayLiteralExpression(requiresArray)) {
660
- return { status: 'unresolvable', reason: 'metadata.requires is not an array literal' }
664
+ return { status: 'unresolvable', reason: `metadata.${propertyName} is not an array literal` }
661
665
  }
662
666
 
663
667
  const requires: string[] = []
664
668
  for (const element of requiresArray.elements) {
665
669
  const value = unwrapExpression(element)
666
670
  if (!ts.isStringLiteral(value) && !ts.isNoSubstitutionTemplateLiteral(value)) {
667
- return { status: 'unresolvable', reason: 'metadata.requires contains a non-literal entry' }
671
+ return { status: 'unresolvable', reason: `metadata.${propertyName} contains a non-literal entry` }
668
672
  }
669
673
  requires.push(value.text)
670
674
  }