@open-mercato/cli 0.11.1-develop.8784.1.e9d95a72f5 → 0.11.1-develop.8843.1.b02f9b125d

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 (210) hide show
  1. package/.turbo/turbo-build.log +8 -2
  2. package/AGENTS.md +2 -0
  3. package/dist/agentic/guides/architecture.md +1 -0
  4. package/dist/agentic/guides/module-facts.json +2453 -1146
  5. package/dist/agentic/guides/module-facts.v2.json +2453 -1146
  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 +2 -2
  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 +2 -2
  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/entities.md +0 -1
  46. package/dist/agentic/guides/modules/configs/exact-override-targets.md +2 -0
  47. package/dist/agentic/guides/modules/configs/host-extension-points.md +10 -0
  48. package/dist/agentic/guides/modules/configs/index.md +5 -3
  49. package/dist/agentic/guides/modules/configs/owned-contract-module-metadata.md +1 -1
  50. package/dist/agentic/guides/modules/configs/setup.md +1 -1
  51. package/dist/agentic/guides/modules/configs/umes-diagnostics.md +9 -0
  52. package/dist/agentic/guides/modules/configs/umes-hosts.md +9 -1
  53. package/dist/agentic/guides/modules/content/index.md +1 -1
  54. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  55. package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
  56. package/dist/agentic/guides/modules/customer_accounts/index.md +1 -1
  57. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  58. package/dist/agentic/guides/modules/customers/acl-features.md +2 -1
  59. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -0
  60. package/dist/agentic/guides/modules/customers/contribution-resolutions.md +2 -0
  61. package/dist/agentic/guides/modules/customers/di-registrations-rich.md +8 -5
  62. package/dist/agentic/guides/modules/customers/domain-commands.md +1 -1
  63. package/dist/agentic/guides/modules/customers/exact-override-targets.md +11 -5
  64. package/dist/agentic/guides/modules/customers/index.md +5 -5
  65. package/dist/agentic/guides/modules/customers/owned-contract-module-metadata.md +1 -1
  66. package/dist/agentic/guides/modules/customers/umes-contributions.md +2 -0
  67. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -10
  68. package/dist/agentic/guides/modules/dashboards/contribution-resolutions.md +0 -10
  69. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +0 -10
  70. package/dist/agentic/guides/modules/dashboards/index.md +5 -5
  71. package/dist/agentic/guides/modules/dashboards/umes-contributions.md +0 -10
  72. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  73. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  74. package/dist/agentic/guides/modules/devices/index.md +1 -1
  75. package/dist/agentic/guides/modules/devices/owned-contract-module-metadata.md +1 -1
  76. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  77. package/dist/agentic/guides/modules/directory/index.md +1 -1
  78. package/dist/agentic/guides/modules/documents/index.md +1 -1
  79. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  80. package/dist/agentic/guides/modules/ecommerce/owned-contract-module-metadata.md +1 -1
  81. package/dist/agentic/guides/modules/entities/index.md +1 -1
  82. package/dist/agentic/guides/modules/entities/owned-contract-module-metadata.md +1 -1
  83. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  84. package/dist/agentic/guides/modules/events/index.md +1 -1
  85. package/dist/agentic/guides/modules/events/owned-contract-module-metadata.md +1 -1
  86. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  87. package/dist/agentic/guides/modules/forms/index.md +1 -1
  88. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  89. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  90. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  91. package/dist/agentic/guides/modules/generators/index.md +1 -1
  92. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  93. package/dist/agentic/guides/modules/integrations/index.md +1 -1
  94. package/dist/agentic/guides/modules/integrations/owned-contract-module-metadata.md +1 -1
  95. package/dist/agentic/guides/modules/ledger/index.md +1 -1
  96. package/dist/agentic/guides/modules/maintenance/contribution-resolutions.md +11 -0
  97. package/dist/agentic/guides/modules/maintenance/events.md +14 -0
  98. package/dist/agentic/guides/modules/maintenance/exact-override-targets.md +11 -0
  99. package/dist/agentic/guides/modules/maintenance/index.md +17 -0
  100. package/dist/agentic/guides/modules/maintenance/owned-contract-module-metadata.md +11 -0
  101. package/dist/agentic/guides/modules/maintenance/umes-contributions.md +11 -0
  102. package/dist/agentic/guides/modules/maintenance/umes-hosts.md +14 -0
  103. package/dist/agentic/guides/modules/messages/index.md +1 -1
  104. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  105. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  106. package/dist/agentic/guides/modules/payment_gateways/exact-override-targets.md +3 -3
  107. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  108. package/dist/agentic/guides/modules/payment_gateways/setup.md +1 -1
  109. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  110. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  111. package/dist/agentic/guides/modules/phone_calls/owned-contract-module-metadata.md +1 -1
  112. package/dist/agentic/guides/modules/planner/index.md +1 -1
  113. package/dist/agentic/guides/modules/portal/index.md +1 -1
  114. package/dist/agentic/guides/modules/progress/index.md +1 -1
  115. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  116. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  117. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  118. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  119. package/dist/agentic/guides/modules/resources/index.md +1 -1
  120. package/dist/agentic/guides/modules/sales/active-extension-bindings.md +8 -0
  121. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +8 -0
  122. package/dist/agentic/guides/modules/sales/di-registrations-rich.md +31 -30
  123. package/dist/agentic/guides/modules/sales/di-service-tokens.md +5 -5
  124. package/dist/agentic/guides/modules/sales/exact-override-targets.md +39 -30
  125. package/dist/agentic/guides/modules/sales/index.md +5 -5
  126. package/dist/agentic/guides/modules/sales/owned-contract-module-metadata.md +1 -1
  127. package/dist/agentic/guides/modules/sales/umes-contributions.md +8 -0
  128. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  129. package/dist/agentic/guides/modules/search/index.md +1 -1
  130. package/dist/agentic/guides/modules/search/owned-contract-module-metadata.md +1 -1
  131. package/dist/agentic/guides/modules/security/index.md +1 -1
  132. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  133. package/dist/agentic/guides/modules/shipping_carriers/active-extension-bindings.md +1 -1
  134. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  135. package/dist/agentic/guides/modules/sso/index.md +1 -1
  136. package/dist/agentic/guides/modules/staff/active-extension-bindings.md +2 -1
  137. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -0
  138. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -0
  139. package/dist/agentic/guides/modules/staff/index.md +8 -8
  140. package/dist/agentic/guides/modules/staff/umes-contributions.md +1 -0
  141. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  142. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  143. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  144. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  145. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  146. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  147. package/dist/agentic/guides/modules/translations/index.md +1 -1
  148. package/dist/agentic/guides/modules/upgrade_actions/cli-commands.md +11 -0
  149. package/dist/agentic/guides/modules/upgrade_actions/contribution-resolutions.md +12 -0
  150. package/dist/agentic/guides/modules/upgrade_actions/entities.md +11 -0
  151. package/dist/agentic/guides/modules/upgrade_actions/exact-override-targets.md +12 -0
  152. package/dist/agentic/guides/modules/upgrade_actions/index.md +18 -0
  153. package/dist/agentic/guides/modules/upgrade_actions/owned-contract-module-metadata.md +11 -0
  154. package/dist/agentic/guides/modules/upgrade_actions/umes-contributions.md +12 -0
  155. package/dist/agentic/guides/modules/upgrade_actions/umes-hosts.md +11 -0
  156. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  157. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  158. package/dist/agentic/guides/modules/wms/index.md +1 -1
  159. package/dist/agentic/guides/modules/workflows/domain-commands.md +3 -0
  160. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  161. package/dist/agentic/guides/production-deployment.md +6 -0
  162. package/dist/agentic/guides/reference-module-facts.json +1 -1
  163. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +17 -9
  164. package/dist/agentic/guides/upstream/manifest.json +2 -2
  165. package/dist/agentic/shared/AGENTS.md.template +1 -1
  166. package/dist/agentic/shared/ai/harness/cases.json +7 -7
  167. package/dist/lib/generators/extensions/dashboard-widgets.js +46 -4
  168. package/dist/lib/generators/extensions/dashboard-widgets.js.map +2 -2
  169. package/dist/lib/generators/extensions/workflows.js +25 -2
  170. package/dist/lib/generators/extensions/workflows.js.map +2 -2
  171. package/dist/lib/generators/module-facts.js +2 -0
  172. package/dist/lib/generators/module-facts.js.map +2 -2
  173. package/dist/lib/generators/module-registry.js +35 -6
  174. package/dist/lib/generators/module-registry.js.map +2 -2
  175. package/dist/lib/module-coupling/analyze.js +391 -0
  176. package/dist/lib/module-coupling/analyze.js.map +7 -0
  177. package/dist/lib/module-diagnostics.js +160 -0
  178. package/dist/lib/module-diagnostics.js.map +7 -0
  179. package/dist/lib/module-index.js +103 -0
  180. package/dist/lib/module-index.js.map +7 -0
  181. package/dist/lib/testing/ephemeral-database-guard.js +89 -0
  182. package/dist/lib/testing/ephemeral-database-guard.js.map +7 -0
  183. package/dist/lib/testing/integration-discovery.js +20 -15
  184. package/dist/lib/testing/integration-discovery.js.map +3 -3
  185. package/dist/mercato.js +45 -5
  186. package/dist/mercato.js.map +2 -2
  187. package/package.json +7 -7
  188. package/src/__tests__/init-ephemeral-database.test.ts +112 -0
  189. package/src/__tests__/mercato.test.ts +15 -0
  190. package/src/__tests__/rotation-json-output.test.ts +13 -0
  191. package/src/lib/__tests__/module-diagnostics.test.ts +207 -0
  192. package/src/lib/__tests__/modules-config.test.ts +1 -0
  193. package/src/lib/generators/__tests__/module-facts.customers.fixture.test.ts +2 -1
  194. package/src/lib/generators/__tests__/module-facts.owned-contracts.test.ts +2 -2
  195. package/src/lib/generators/__tests__/module-registry-requires-enforcement.test.ts +18 -0
  196. package/src/lib/generators/__tests__/output-snapshots.test.ts +19 -0
  197. package/src/lib/generators/__tests__/registry-variant-parity.test.ts +95 -19
  198. package/src/lib/generators/__tests__/structural-contracts.test.ts +18 -0
  199. package/src/lib/generators/extensions/dashboard-widgets.ts +49 -3
  200. package/src/lib/generators/extensions/workflows.ts +26 -2
  201. package/src/lib/generators/module-facts.ts +2 -0
  202. package/src/lib/generators/module-registry.ts +55 -7
  203. package/src/lib/module-coupling/analyze.ts +464 -0
  204. package/src/lib/module-diagnostics.ts +182 -0
  205. package/src/lib/module-index.ts +133 -0
  206. package/src/lib/testing/__tests__/ephemeral-database-guard.test.ts +88 -0
  207. package/src/lib/testing/__tests__/integration-discovery.test.ts +26 -2
  208. package/src/lib/testing/ephemeral-database-guard.ts +105 -0
  209. package/src/lib/testing/integration-discovery.ts +19 -11
  210. package/src/mercato.ts +47 -5
@@ -0,0 +1,464 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import ts from 'typescript-js'
4
+ import { resolveModuleRequirement } from '@open-mercato/shared/modules/module-locators'
5
+ import { extractModuleFacts } from '../generators/module-facts'
6
+ import { resolveIndexedModule, type IndexedModule } from '../module-index'
7
+ import { resolveModuleDependenciesForSpec } from '../testing/integration-discovery'
8
+
9
+ export const PLATFORM_KERNEL = ['auth', 'directory', 'api_keys'] as const
10
+ const kernel = new Set<string>(PLATFORM_KERNEL)
11
+ const excludedDirectories = new Set(['__tests__', '__mocks__', '__benchmarks__', 'migrations', 'i18n', 'node_modules'])
12
+ const testsOrGenerated = /(?:\.(?:test|generated|d)\.[cm]?[jt]sx?)$/
13
+
14
+ export type CouplingRule = 'R1' | 'R2' | 'R4' | 'R5'
15
+ type ReferenceKind = 'import' | 'api-path' | 'page-path' | 'feature' | 'di-token'
16
+ type Reference = { kind: ReferenceKind; value: string; file: string; line: number; partial: boolean }
17
+ export type CouplingFinding = {
18
+ rule: CouplingRule
19
+ module: string
20
+ target: string
21
+ message: string
22
+ kind?: ReferenceKind
23
+ file: string
24
+ line?: number
25
+ }
26
+ export type DanglingReference = Reference & { module: string }
27
+ export type MissingContribution = { module: string; spotId: string; minimum: number; count: number; file: string; line: number }
28
+ export type CouplingReport = {
29
+ findings: CouplingFinding[]
30
+ dangling: DanglingReference[]
31
+ contributions: MissingContribution[]
32
+ }
33
+
34
+ type ParsedFile = { relative: string; absolute: string; source: ts.SourceFile }
35
+ type AnalyzedModule = {
36
+ entry: IndexedModule
37
+ files: ParsedFile[]
38
+ features: Set<string>
39
+ tokens: Set<string>
40
+ api: Set<string>
41
+ pages: Set<string>
42
+ contributions: ReturnType<typeof extractModuleFacts>['extensionSurfaces']
43
+ }
44
+ type RouteOwner = { route: string; owner: string; exact: boolean; pattern: RegExp }
45
+
46
+ function walkFiles(directory: string): string[] {
47
+ if (!fs.existsSync(directory)) return []
48
+ const files: string[] = []
49
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
50
+ if (excludedDirectories.has(entry.name) || entry.name.startsWith('.')) continue
51
+ const fullPath = path.join(directory, entry.name)
52
+ if (entry.isDirectory()) files.push(...walkFiles(fullPath))
53
+ else if (/\.[cm]?[jt]sx?$/.test(entry.name) && !testsOrGenerated.test(entry.name)) files.push(fullPath)
54
+ }
55
+ return files
56
+ }
57
+
58
+ function literalValue(node: ts.Node | undefined): string | undefined {
59
+ return node && ts.isStringLiteralLike(node) ? node.text : undefined
60
+ }
61
+
62
+ function fileName(root: string, file: string): string {
63
+ return path.relative(root, file).split(path.sep).join('/')
64
+ }
65
+
66
+ function readFiles(roots: string[]): ParsedFile[] {
67
+ const files = new Map<string, ParsedFile>()
68
+ for (const root of roots) {
69
+ for (const absolute of walkFiles(root)) {
70
+ const relative = fileName(root, absolute)
71
+ const identity = relative.replace(/\.[cm]?[jt]sx?$/, '')
72
+ if (files.has(identity)) continue
73
+ const text = fs.readFileSync(absolute, 'utf8')
74
+ files.set(identity, { relative, absolute, source: ts.createSourceFile(absolute, text, ts.ScriptTarget.Latest, true) })
75
+ }
76
+ }
77
+ return [...files.values()].sort((left, right) => left.relative.localeCompare(right.relative))
78
+ }
79
+
80
+ function asApiPath(route: string): string {
81
+ const pathname = route.startsWith('/') ? route : `/${route}`
82
+ return pathname.startsWith('/api/') ? pathname : `/api${pathname}`
83
+ }
84
+
85
+ function staticApiRoute(file: ParsedFile, moduleId: string): string | undefined {
86
+ if (!file.relative.startsWith('api/') || file.relative.includes('/__integration__/')) return undefined
87
+ const handlers = new Set(['get', 'post', 'put', 'patch', 'delete', 'head', 'options'])
88
+ const segments = file.relative.replace(/\.[cm]?[jt]sx?$/, '').split('/').slice(1)
89
+ const first = segments[0]
90
+ const isConventionalRoute = segments.at(-1) === 'route'
91
+ if (isConventionalRoute) segments.pop()
92
+ else if (first && handlers.has(first.toLowerCase())) segments.shift()
93
+ else return undefined
94
+ for (const statement of file.source.statements) {
95
+ if (!ts.isVariableStatement(statement)) continue
96
+ for (const declaration of statement.declarationList.declarations) {
97
+ if (!ts.isIdentifier(declaration.name) || declaration.name.text !== 'metadata' || !declaration.initializer
98
+ || !ts.isObjectLiteralExpression(declaration.initializer)) continue
99
+ for (const property of declaration.initializer.properties) {
100
+ if (!ts.isPropertyAssignment(property)) continue
101
+ const name = propertyText(property.name)
102
+ const value = literalValue(property.initializer)
103
+ if (name === 'path' && value) return asApiPath(value)
104
+ }
105
+ }
106
+ }
107
+ return asApiPath([moduleId, ...segments].join('/'))
108
+ }
109
+
110
+ function analyzeModule(entry: IndexedModule): AnalyzedModule {
111
+ const files = readFiles(entry.roots)
112
+ const features = new Set<string>()
113
+ const tokens = new Set<string>()
114
+ const api = new Set<string>()
115
+ const pages = new Set<string>()
116
+ let contributions: AnalyzedModule['contributions']
117
+ for (const moduleRoot of entry.roots) {
118
+ const facts = extractModuleFacts({ moduleId: entry.id, moduleRoot, sourcePackage: entry.packageName === '@app' ? null : entry.packageName })
119
+ facts.aclFeatures.forEach((feature) => features.add(feature))
120
+ facts.diTokens.forEach((token) => tokens.add(token))
121
+ facts.apiRoutes.forEach((route) => api.add(asApiPath(route.path)))
122
+ facts.backendPages.forEach((page) => pages.add(page.path))
123
+ if (!contributions) contributions = facts.extensionSurfaces
124
+ else if (facts.extensionSurfaces) {
125
+ contributions = {
126
+ hosts: [...contributions.hosts, ...facts.extensionSurfaces.hosts],
127
+ contributions: [...contributions.contributions, ...facts.extensionSurfaces.contributions],
128
+ unresolved: [...contributions.unresolved, ...facts.extensionSurfaces.unresolved],
129
+ }
130
+ }
131
+ }
132
+ for (const file of files) {
133
+ const route = staticApiRoute(file, entry.id)
134
+ if (route) api.add(route)
135
+ }
136
+ return { entry, files, features, tokens, api, pages, contributions }
137
+ }
138
+
139
+ function propertyText(name: ts.PropertyName): string | undefined {
140
+ return ts.isIdentifier(name) ? name.text : literalValue(name)
141
+ }
142
+
143
+ function callName(expression: ts.Expression): string | undefined {
144
+ return ts.isIdentifier(expression) ? expression.text : ts.isPropertyAccessExpression(expression) ? expression.name.text : undefined
145
+ }
146
+
147
+ function lineOf(file: ParsedFile, node: ts.Node): number {
148
+ return file.source.getLineAndCharacterOfPosition(node.getStart(file.source)).line + 1
149
+ }
150
+
151
+ function isValueImport(node: ts.ImportDeclaration): boolean {
152
+ if (!node.importClause) return true
153
+ const { isTypeOnly, name, namedBindings } = node.importClause
154
+ if (isTypeOnly) return false
155
+ return !!name || !namedBindings || !ts.isNamedImports(namedBindings) || namedBindings.elements.some((item) => !item.isTypeOnly)
156
+ }
157
+
158
+ function parseFileReferences(file: ParsedFile): Reference[] {
159
+ const results: Reference[] = []
160
+ const featureProperties = new Set(['requireFeatures', 'requireCustomerFeatures', 'features', 'requiredFeatures'])
161
+ function add(kind: ReferenceKind, node: ts.Node | undefined, value: string | undefined, partial = false): void {
162
+ if (node && value) results.push({ kind, value, file: file.absolute, line: lineOf(file, node), partial })
163
+ }
164
+ function visit(node: ts.Node): void {
165
+ if (ts.isImportDeclaration(node) && isValueImport(node)) {
166
+ add('import', node.moduleSpecifier, literalValue(node.moduleSpecifier))
167
+ } else if (ts.isExportDeclaration(node) && !node.isTypeOnly
168
+ && !(node.exportClause && ts.isNamedExports(node.exportClause) && node.exportClause.elements.every((item) => item.isTypeOnly))) {
169
+ add('import', node.moduleSpecifier, literalValue(node.moduleSpecifier))
170
+ } else if (ts.isCallExpression(node)) {
171
+ const name = callName(node.expression)
172
+ const arg = node.arguments[0]
173
+ if (node.expression.kind === ts.SyntaxKind.ImportKeyword || name === 'require') {
174
+ add('import', arg, literalValue(arg))
175
+ } else if (name === 'resolve' || name === 'hasRegistration') {
176
+ add('di-token', arg, literalValue(arg))
177
+ } else if (name === 'hasFeature') {
178
+ const feature = node.arguments[1]
179
+ add('feature', feature, literalValue(feature))
180
+ }
181
+ } else if (ts.isPropertyAssignment(node) && featureProperties.has(propertyText(node.name) ?? '')
182
+ && ts.isArrayLiteralExpression(node.initializer)) {
183
+ for (const value of node.initializer.elements) add('feature', value, literalValue(value))
184
+ } else if (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) {
185
+ const value = ts.isTemplateExpression(node) ? node.head.text : node.text
186
+ const kind = value.startsWith('/api/') ? 'api-path' : value.startsWith('/backend/') ? 'page-path' : undefined
187
+ if (kind) add(kind, node, value, ts.isTemplateExpression(node))
188
+ }
189
+ ts.forEachChild(node, visit)
190
+ }
191
+ visit(file.source)
192
+ return results
193
+ }
194
+
195
+ function escapeRegExp(value: string): string {
196
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
197
+ }
198
+
199
+ function routeOwner(route: string, owner: string): RouteOwner {
200
+ const segments = route.split('/').filter(Boolean)
201
+ const dynamic = (segment: string): boolean => segment.startsWith('[') || segment.startsWith(':') || segment.startsWith('{')
202
+ const pattern = segments.map((segment) => segment.includes('...') || segment.startsWith('[[...') ? '.+' : dynamic(segment) ? '[^/]+' : escapeRegExp(segment))
203
+ return { route, owner, exact: !segments.some(dynamic), pattern: new RegExp(`^/${pattern.join('/')}/?$`) }
204
+ }
205
+
206
+ function routeModule(reference: Reference, routes: RouteOwner[]): string | undefined {
207
+ const requestPath = reference.value.split(/[?#]/)[0]
208
+ if (!reference.partial) {
209
+ return routes.find((route) => route.exact && route.route === requestPath)?.owner
210
+ ?? routes.find((route) => route.pattern.test(requestPath))?.owner
211
+ }
212
+ const prefix = requestPath.endsWith('/') ? requestPath : `${requestPath}/`
213
+ const owners = new Set(routes.filter((route) => route.route.startsWith(prefix)).map((route) => route.owner))
214
+ return owners.size === 1 ? [...owners][0] : undefined
215
+ }
216
+
217
+ function importModule(reference: Reference, roots: Map<string, string>, sourcePackage: string): string | undefined {
218
+ if (reference.value.startsWith('@open-mercato/shared/modules/')) return undefined
219
+ const direct = reference.value.match(/^(?:@[^/]+\/[^/]+\/modules|@\/modules)\/([a-z0-9_]+)(?:\/|$)/)
220
+ if (direct) return direct[1]
221
+ const samePackage = reference.value.startsWith(`${sourcePackage}/modules/`)
222
+ ? reference.value.slice(sourcePackage.length + '/modules/'.length).split('/')[0]
223
+ : undefined
224
+ if (samePackage) return samePackage
225
+ if (!reference.value.startsWith('.')) return undefined
226
+ let current = path.resolve(path.dirname(reference.file), reference.value)
227
+ while (current !== path.dirname(current)) {
228
+ const owner = roots.get(current)
229
+ if (owner) return owner
230
+ current = path.dirname(current)
231
+ }
232
+ return undefined
233
+ }
234
+
235
+ function closure(entry: IndexedModule, modules: IndexedModule[], includeOptional: boolean): Set<string> {
236
+ const reached = new Set<string>()
237
+ const visited = new Set([entry.id])
238
+ const pending = [entry]
239
+ while (pending.length > 0) {
240
+ const source = pending.pop()
241
+ if (!source) continue
242
+ const requirements = includeOptional ? [...source.requires, ...source.optionalRequires] : source.requires
243
+ for (const requirement of requirements) {
244
+ const target = resolveIndexedModule(requirement, modules)
245
+ reached.add(target?.id ?? requirement)
246
+ if (!target || visited.has(target.id)) continue
247
+ visited.add(target.id)
248
+ pending.push(target)
249
+ }
250
+ }
251
+ return reached
252
+ }
253
+
254
+ function guardEvidence(file: ParsedFile, target: string, features: Set<string>, tokens: Set<string>, reference: Reference): boolean {
255
+ const client = file.source.statements.some((statement) =>
256
+ ts.isExpressionStatement(statement) && literalValue(statement.expression) === 'use client')
257
+ let evidence = false
258
+ function visit(node: ts.Node): void {
259
+ if (evidence) return
260
+ if (ts.isCallExpression(node)) {
261
+ const name = callName(node.expression)
262
+ const argument = literalValue(node.arguments[0])
263
+ const moduleGuard = name === 'isClientModuleEnabled'
264
+ || (client ? name === 'useModuleEnabled' : name === 'isModuleEnabled')
265
+ if (moduleGuard && argument === target) evidence = true
266
+ if (name === 'hasRegistration' && argument && tokens.has(argument)) evidence = true
267
+ const feature = literalValue(node.arguments[1])
268
+ if (name === 'hasFeature' && feature && features.has(feature)) evidence = true
269
+ if (name === 'resolve' && reference.kind === 'di-token' && argument === reference.value) {
270
+ const options = node.arguments[1]
271
+ if (options && ts.isObjectLiteralExpression(options) && options.properties.some((property) =>
272
+ ts.isPropertyAssignment(property) && propertyText(property.name) === 'allowUnregistered'
273
+ && property.initializer.kind === ts.SyntaxKind.TrueKeyword)) evidence = true
274
+ for (let parent: ts.Node | undefined = node; parent; parent = parent.parent) {
275
+ if (ts.isTryStatement(parent) && parent.catchClause && node.getStart(file.source) < parent.tryBlock.end) evidence = true
276
+ }
277
+ }
278
+ }
279
+ if (ts.isPropertyAssignment(node) && ts.isArrayLiteralExpression(node.initializer)) {
280
+ const key = propertyText(node.name)
281
+ for (const entry of node.initializer.elements) {
282
+ const value = literalValue(entry)
283
+ if (key === 'requiredModules' && value === target) evidence = true
284
+ if ((key === 'requiredFeatures' || key === 'requireFeatures' || key === 'features') && value && features.has(value)) evidence = true
285
+ }
286
+ }
287
+ ts.forEachChild(node, visit)
288
+ }
289
+ visit(file.source)
290
+ return evidence
291
+ }
292
+
293
+ export function optionalCapabilityLabel(entry: IndexedModule, target: string): string | undefined {
294
+ const key = `optionalRequires.${target}`
295
+ for (const root of entry.roots) {
296
+ const english = path.join(root, 'i18n', 'en.json')
297
+ try {
298
+ const text: Record<string, unknown> = JSON.parse(fs.readFileSync(english, 'utf8'))
299
+ const value = text[`${entry.id}.${key}`] ?? text[key]
300
+ if (typeof value === 'string' && value.trim()) return value
301
+ } catch {
302
+ // Missing capability labels are reported as declaration findings.
303
+ }
304
+ }
305
+ return undefined
306
+ }
307
+
308
+ function readWidgetModuleRequirements(files: ParsedFile[]): Map<string, string[]> {
309
+ const requirements = new Map<string, string[]>()
310
+ for (const file of files) {
311
+ if (!file.relative.startsWith('widgets/injection/')) continue
312
+ function visit(node: ts.Node): void {
313
+ if (ts.isPropertyAssignment(node) && propertyText(node.name) === 'metadata' && ts.isObjectLiteralExpression(node.initializer)) {
314
+ const metadata = node.initializer.properties.filter(ts.isPropertyAssignment)
315
+ const id = literalValue(metadata.find((entry) => propertyText(entry.name) === 'id')?.initializer)
316
+ const dependencies = metadata.find((entry) => propertyText(entry.name) === 'requiredModules')?.initializer
317
+ if (id && dependencies && ts.isArrayLiteralExpression(dependencies)) {
318
+ requirements.set(id, dependencies.elements.map(literalValue).filter((value): value is string => !!value))
319
+ }
320
+ }
321
+ ts.forEachChild(node, visit)
322
+ }
323
+ visit(file.source)
324
+ }
325
+ return requirements
326
+ }
327
+
328
+ function hostContributions(modules: AnalyzedModule[], enabledIds: Set<string>): MissingContribution[] {
329
+ const result: MissingContribution[] = []
330
+ const candidates = modules.filter((module) => enabledIds.has(module.entry.id)).map((module) => ({
331
+ contributions: module.contributions?.contributions ?? [],
332
+ requirements: readWidgetModuleRequirements(module.files),
333
+ }))
334
+ for (const module of modules) {
335
+ if (!enabledIds.has(module.entry.id)) continue
336
+ const declaration = module.files.find((file) => /^extension-points\.[cm]?[jt]sx?$/.test(file.relative))
337
+ if (!declaration) continue
338
+ const file = declaration
339
+ function visit(node: ts.Node): void {
340
+ if (ts.isCallExpression(node) && callName(node.expression) === 'injectionExtensionHost'
341
+ && node.arguments[0] && ts.isObjectLiteralExpression(node.arguments[0])) {
342
+ const host = node.arguments[0]
343
+ const spot = host.properties.find((item): item is ts.PropertyAssignment => ts.isPropertyAssignment(item) && propertyText(item.name) === 'spotId')
344
+ const min = host.properties.find((item): item is ts.PropertyAssignment => ts.isPropertyAssignment(item) && propertyText(item.name) === 'minContributions')
345
+ const spotId = spot ? literalValue(spot.initializer) : undefined
346
+ if (spotId && min && ts.isNumericLiteral(min.initializer)) {
347
+ const minimum = Number(min.initializer.text)
348
+ const suffix = `@${spotId}`
349
+ const count = candidates.reduce((total, { contributions, requirements }) => total + contributions.filter((contribution) => {
350
+ if (!('targets' in contribution) || !contribution.id.endsWith(suffix)) return false
351
+ const widgetId = contribution.id.slice(0, -suffix.length)
352
+ return requirements.get(widgetId)?.every((id) => enabledIds.has(id)) ?? true
353
+ }).length, 0)
354
+ if (count < minimum) result.push({ module: module.entry.id, spotId, minimum, count, file: file.absolute, line: lineOf(file, node) })
355
+ }
356
+ }
357
+ ts.forEachChild(node, visit)
358
+ }
359
+ visit(declaration.source)
360
+ }
361
+ return result
362
+ }
363
+
364
+ export function findMissingModuleContributions(entries: IndexedModule[]): MissingContribution[] {
365
+ const enabled = entries.filter((entry) => entry.enabled)
366
+ return hostContributions(enabled.map(analyzeModule), new Set(enabled.map((entry) => entry.id)))
367
+ }
368
+
369
+ export function analyzeModuleCoupling(
370
+ entries: IndexedModule[],
371
+ analyzedModuleIds: ReadonlySet<string> = new Set(entries.filter((entry) => entry.enabled).map((entry) => entry.id)),
372
+ ): CouplingReport {
373
+ const modules = new Map<string, AnalyzedModule>()
374
+ const roots = new Map<string, string>()
375
+ const api: RouteOwner[] = []
376
+ const pages: RouteOwner[] = []
377
+ const features = new Map<string, string>()
378
+ const tokens = new Map<string, string>()
379
+ const hostOwners = new Map<string, string>()
380
+ for (const entry of [...entries.filter((item) => item.enabled), ...entries.filter((item) => !item.enabled)]) {
381
+ if (modules.has(entry.id)) continue
382
+ const analyzed = analyzeModule(entry)
383
+ modules.set(entry.id, analyzed)
384
+ entry.roots.forEach((root) => roots.set(root, entry.id))
385
+ analyzed.api.forEach((route) => api.push(routeOwner(route, entry.id)))
386
+ analyzed.pages.forEach((route) => pages.push(routeOwner(route, entry.id)))
387
+ analyzed.contributions?.hosts.forEach((host) => hostOwners.set(host.id, host.ownerModule))
388
+ analyzed.features.forEach((feature) => { if (!features.has(feature)) features.set(feature, entry.id) })
389
+ analyzed.tokens.forEach((token) => { if (!tokens.has(token)) tokens.set(token, entry.id) })
390
+ }
391
+ const hard = new Map([...modules.values()].map(({ entry }) => [entry.id, closure(entry, entries, false)]))
392
+ const dependencies = new Map([...modules.values()].map(({ entry }) => [entry.id, closure(entry, entries, true)]))
393
+ const findings: CouplingFinding[] = []
394
+ const dangling: DanglingReference[] = []
395
+ for (const [module, analyzed] of modules) {
396
+ if (!analyzedModuleIds.has(module)) continue
397
+ const knownHard = hard.get(module)
398
+ const optional = new Set(analyzed.entry.optionalRequires.map((requirement) => resolveModuleRequirement(requirement, entries) ?? requirement))
399
+ for (const target of optional) {
400
+ const index = analyzed.files.find((file) => /^index\.[cm]?[jt]sx?$/.test(file.relative))
401
+ if (index && !optionalCapabilityLabel(analyzed.entry, target)) {
402
+ findings.push({ rule: 'R1', module, target, file: index.absolute, message: `Missing English capability label for optional module '${target}'` })
403
+ }
404
+ }
405
+ for (const file of analyzed.files) {
406
+ const integration = file.relative.split('/').includes('__integration__')
407
+ if (integration && !file.relative.endsWith('.spec.ts')) continue
408
+ const moduleRoot = integration
409
+ ? analyzed.entry.roots.find((root) => path.join(root, file.relative) === file.absolute)
410
+ : undefined
411
+ const testDependencies = moduleRoot
412
+ ? new Set(resolveModuleDependenciesForSpec(moduleRoot, file.relative, { includeOptional: true }))
413
+ : undefined
414
+ const fileContributions = analyzed.contributions?.contributions.filter((item) =>
415
+ 'source' in item && item.source.path.endsWith(`/${file.relative}`)) ?? []
416
+ const structural = new Set(fileContributions.flatMap((item) =>
417
+ 'targets' in item
418
+ ? item.targets.map((target) => hostOwners.get(target.id)).filter((owner): owner is string => !!owner)
419
+ : []))
420
+ const providesDashboardWidget = fileContributions.some((item) =>
421
+ item.kind === 'widget' && item.details.payload === 'dashboard')
422
+ const providesInboxActions = /^inbox-actions\.[cm]?[jt]s$/.test(file.relative)
423
+ && file.source.statements.some((statement) => ts.isExportAssignment(statement))
424
+ for (const reference of parseFileReferences(file)) {
425
+ if (integration && reference.kind === 'import'
426
+ && reference.value.startsWith('@open-mercato/core/modules/core/__integration__/')) continue
427
+ const target = reference.kind === 'import' ? importModule(reference, roots, analyzed.entry.packageName)
428
+ : reference.kind === 'api-path' ? routeModule(reference, api)
429
+ : reference.kind === 'page-path' ? routeModule(reference, pages)
430
+ : reference.kind === 'feature' ? features.get(reference.value) : tokens.get(reference.value)
431
+ if (providesDashboardWidget && target === 'dashboards'
432
+ && reference.kind === 'feature' && reference.value === 'analytics.view') continue
433
+ if (providesInboxActions && target === 'inbox_ops' && reference.kind === 'import') continue
434
+ if (!target) {
435
+ if (!integration && (reference.kind === 'api-path' || reference.kind === 'page-path') && !reference.partial) {
436
+ dangling.push({ ...reference, module })
437
+ }
438
+ continue
439
+ }
440
+ if (target === module || structural.has(target)) continue
441
+ const context = { module, target, file: file.absolute, line: reference.line, kind: reference.kind }
442
+ if (integration) {
443
+ if (!kernel.has(target) && !knownHard?.has(target) && !testDependencies?.has(target)) {
444
+ findings.push({ ...context, rule: 'R4', message: `Integration spec must declare dependsOnModules: ['${target}']` })
445
+ }
446
+ continue
447
+ }
448
+ if (!kernel.has(target) && !knownHard?.has(target) && !optional.has(target)) {
449
+ findings.push({ ...context, rule: 'R1', message: `'${module}' references '${target}' without a dependency declaration` })
450
+ }
451
+ if (optional.has(target)) {
452
+ const peer = modules.get(target)
453
+ if (!guardEvidence(file, target, peer?.features ?? new Set(), peer?.tokens ?? new Set(), reference)) {
454
+ findings.push({ ...context, rule: 'R2', message: `Optional reference to '${target}' has no module guard` })
455
+ }
456
+ }
457
+ if (!(kernel.has(module) && kernel.has(target)) && dependencies.get(target)?.has(module)) {
458
+ findings.push({ ...context, rule: 'R5', message: `'${module}' references its consumer '${target}'` })
459
+ }
460
+ }
461
+ }
462
+ }
463
+ return { findings, dangling, contributions: hostContributions([...modules.values()], new Set(analyzedModuleIds)) }
464
+ }
@@ -0,0 +1,182 @@
1
+ import path from 'node:path'
2
+ import { getModuleRequirementHint } from '@open-mercato/shared/modules/module-locators'
3
+ import { analyzeModuleCoupling, optionalCapabilityLabel, PLATFORM_KERNEL } from './module-coupling/analyze'
4
+ import { buildModuleIndex, inactiveModuleDependencies, missingModuleRequirements, resolveIndexedModule, type IndexedModule } from './module-index'
5
+ import { createResolver, type PackageResolver } from './resolver'
6
+
7
+ const GROUPS = [
8
+ 'missing-kernel',
9
+ 'missing-hard',
10
+ 'inactive-optional',
11
+ 'undeclared-or-upstream',
12
+ 'missing-contributions',
13
+ 'dangling',
14
+ ] as const
15
+
16
+ type Group = typeof GROUPS[number]
17
+ type Finding = {
18
+ group: Group
19
+ module: string
20
+ target?: string
21
+ kind?: string
22
+ file?: string
23
+ line?: number
24
+ message: string
25
+ }
26
+
27
+ function cleanFileName(root: string, file: string): string {
28
+ return path.relative(root, file).split(path.sep).join('/')
29
+ }
30
+
31
+ function printHelp(command: 'list' | 'doctor'): void {
32
+ if (command === 'list') console.log('Usage: yarn mercato module list [--all] [--json]')
33
+ else console.log('Usage: yarn mercato module doctor [--strict] [--json]')
34
+ }
35
+
36
+ function listModules(modules: IndexedModule[], json: boolean, all: boolean): void {
37
+ const enabled = modules.filter((module) => module.enabled)
38
+ const rows = modules.filter((module) => all || module.enabled).map((module) => ({
39
+ id: module.id,
40
+ package: module.packageName,
41
+ version: module.version,
42
+ enabled: module.enabled,
43
+ requires: module.requires,
44
+ optionalRequires: module.optionalRequires,
45
+ requiredBy: enabled.filter((other) => other.requires.some((requirement) => resolveIndexedModule(requirement, modules) === module))
46
+ .map((other) => other.id),
47
+ ...(module.notAnalyzed ? { notAnalyzed: module.notAnalyzed } : {}),
48
+ }))
49
+ if (json) {
50
+ console.log(JSON.stringify({ version: 1, modules: rows }, null, 2))
51
+ return
52
+ }
53
+ for (const row of rows) {
54
+ const status = row.enabled ? 'enabled' : 'installed'
55
+ const version = row.version ? `@${row.version}` : ''
56
+ console.log(`${row.id} ${row.package}${version} (${status})`)
57
+ if (row.requires.length) console.log(` Requires: ${row.requires.join(', ')}`)
58
+ if (row.optionalRequires.length) console.log(` Optional: ${row.optionalRequires.join(', ')}`)
59
+ if (row.requiredBy.length) console.log(` Required by: ${row.requiredBy.join(', ')}`)
60
+ if (row.notAnalyzed) console.log(` Not analyzed: ${row.notAnalyzed}`)
61
+ }
62
+ }
63
+
64
+ function instructionFor(target: string, modules: IndexedModule[]): string {
65
+ const installed = resolveIndexedModule(target, modules)
66
+ if (installed?.packageName === '@app') return `Enable '${installed.id}' in src/modules.ts.`
67
+ if (installed) return `yarn mercato module enable ${installed.packageName} --module ${installed.id}`
68
+ return getModuleRequirementHint(target)
69
+ }
70
+
71
+ function doctorFindings(modules: IndexedModule[], root: string): Finding[] {
72
+ const enabled = modules.filter((module) => module.enabled)
73
+ const enabledIds = new Set(enabled.map((module) => module.id))
74
+ const findings: Finding[] = PLATFORM_KERNEL.filter((id) => !enabledIds.has(id)).map((module) => ({
75
+ group: 'missing-kernel',
76
+ module,
77
+ message: `Enable kernel module '${module}' in src/modules.ts.`,
78
+ }))
79
+ for (const module of enabled) {
80
+ for (const { requirement, path: chain } of missingModuleRequirements(module, modules)) {
81
+ findings.push({
82
+ group: 'missing-hard',
83
+ module: module.id,
84
+ target: requirement,
85
+ message: `${chain.join(' → ')} is required. ${instructionFor(requirement, modules)}`,
86
+ })
87
+ }
88
+ }
89
+ for (const { source, target } of inactiveModuleDependencies(modules)) {
90
+ const label = optionalCapabilityLabel(source, resolveIndexedModule(target, modules)?.id ?? target)
91
+ findings.push({
92
+ group: 'inactive-optional',
93
+ module: source.id,
94
+ target,
95
+ message: `${label ?? `Optional module '${target}'`} is inactive. ${instructionFor(target, modules)}`,
96
+ })
97
+ }
98
+ const coupling = analyzeModuleCoupling(modules)
99
+ for (const finding of coupling.findings) {
100
+ if (finding.rule === 'R4' || (enabledIds.has(finding.target) && finding.rule !== 'R2')) continue
101
+ findings.push({
102
+ group: 'undeclared-or-upstream',
103
+ module: finding.module,
104
+ target: finding.target,
105
+ kind: finding.kind,
106
+ file: cleanFileName(root, finding.file),
107
+ line: finding.line,
108
+ message: finding.message,
109
+ })
110
+ }
111
+ for (const finding of coupling.contributions) {
112
+ findings.push({
113
+ group: 'missing-contributions',
114
+ module: finding.module,
115
+ target: finding.spotId,
116
+ file: cleanFileName(root, finding.file),
117
+ line: finding.line,
118
+ message: `Host '${finding.spotId}' needs ${finding.minimum} enabled contributions, found ${finding.count}.`,
119
+ })
120
+ }
121
+ for (const reference of coupling.dangling) {
122
+ findings.push({
123
+ group: 'dangling',
124
+ module: reference.module,
125
+ target: reference.value,
126
+ kind: reference.kind,
127
+ file: cleanFileName(root, reference.file),
128
+ line: reference.line,
129
+ message: `No installed module owns '${reference.value}'.`,
130
+ })
131
+ }
132
+ const seen = new Set<string>()
133
+ return findings.filter((finding) => {
134
+ const key = JSON.stringify(finding)
135
+ if (seen.has(key)) return false
136
+ seen.add(key)
137
+ return true
138
+ })
139
+ }
140
+
141
+ export function runModuleDiagnostics(
142
+ command: 'list' | 'doctor',
143
+ args: string[],
144
+ resolver: PackageResolver = createResolver(),
145
+ ): number {
146
+ if (args.includes('--help') || args.includes('-h')) {
147
+ printHelp(command)
148
+ return 0
149
+ }
150
+ const commandFlag = command === 'list' ? '--all' : '--strict'
151
+ const invalid = args.find((arg) => arg !== '--json' && arg !== commandFlag)
152
+ if (invalid) {
153
+ console.error(`Unknown module ${command} option '${invalid}'.`)
154
+ return 1
155
+ }
156
+ const json = args.includes('--json')
157
+ const modules = buildModuleIndex(resolver, command === 'doctor' || args.includes('--all'))
158
+ if (command === 'list') {
159
+ listModules(modules, json, args.includes('--all'))
160
+ return 0
161
+ }
162
+ const enabled = modules.filter((module) => module.enabled).map((module) => module.id)
163
+ const notAnalyzed = modules.filter((module) => module.enabled && module.notAnalyzed)
164
+ .map((module) => ({ module: module.id, reason: module.notAnalyzed }))
165
+ const findings = doctorFindings(modules, resolver.getAppDir())
166
+ if (json) console.log(JSON.stringify({ version: 1, enabled, findings, ...(notAnalyzed.length ? { notAnalyzed } : {}) }, null, 2))
167
+ else {
168
+ for (const group of GROUPS) {
169
+ const rows = findings.filter((finding) => finding.group === group)
170
+ console.log(`${group} (${rows.length})`)
171
+ for (const row of rows) {
172
+ const location = row.file ? ` (${row.file}${row.line ? `:${row.line}` : ''})` : ''
173
+ console.log(` ${row.module}: ${row.message}${location}`)
174
+ }
175
+ }
176
+ for (const row of notAnalyzed) console.log(`Not analyzed: ${row.module} (${row.reason})`)
177
+ }
178
+ const strict = args.includes('--strict')
179
+ return findings.some((finding) =>
180
+ finding.group === 'missing-kernel' || finding.group === 'missing-hard'
181
+ || (strict && finding.group !== 'inactive-optional')) ? 1 : 0
182
+ }