@open-mercato/cli 0.11.1-develop.8589.1.db1a76ea60 → 0.11.1-develop.8665.1.2455b2503c

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 (285) hide show
  1. package/.turbo/turbo-build.log +4 -2
  2. package/AGENTS.md +3 -0
  3. package/dist/agentic/guides/architecture.md +2 -2
  4. package/dist/agentic/guides/extensions.md +7 -2
  5. package/dist/agentic/guides/framework-extension-points.md +1 -0
  6. package/dist/agentic/guides/infrastructure-providers.md +20 -0
  7. package/dist/agentic/guides/integrations.md +2 -2
  8. package/dist/agentic/guides/module-facts.json +2564 -265
  9. package/dist/agentic/guides/module-facts.v2.json +2580 -265
  10. package/dist/agentic/guides/modules/agent_orchestrator/index.md +1 -1
  11. package/dist/agentic/guides/modules/ai_assistant/index.md +1 -1
  12. package/dist/agentic/guides/modules/api_docs/index.md +1 -1
  13. package/dist/agentic/guides/modules/api_keys/index.md +1 -1
  14. package/dist/agentic/guides/modules/assisted_selling/acl-features.md +16 -0
  15. package/dist/agentic/guides/modules/assisted_selling/contribution-resolutions.md +21 -0
  16. package/dist/agentic/guides/modules/assisted_selling/domain-commands.md +11 -0
  17. package/dist/agentic/guides/modules/assisted_selling/entities.md +11 -0
  18. package/dist/agentic/guides/modules/assisted_selling/events.md +22 -0
  19. package/dist/agentic/guides/modules/assisted_selling/exact-override-targets.md +17 -0
  20. package/dist/agentic/guides/modules/assisted_selling/index.md +21 -0
  21. package/dist/agentic/guides/modules/assisted_selling/owned-contract-module-metadata.md +11 -0
  22. package/dist/agentic/guides/modules/assisted_selling/setup.md +11 -0
  23. package/dist/agentic/guides/modules/assisted_selling/umes-contributions.md +21 -0
  24. package/dist/agentic/guides/modules/assisted_selling/umes-hosts.md +23 -0
  25. package/dist/agentic/guides/modules/attachments/exact-override-targets.md +1 -1
  26. package/dist/agentic/guides/modules/attachments/index.md +1 -1
  27. package/dist/agentic/guides/modules/attachments/workers.md +1 -1
  28. package/dist/agentic/guides/modules/audit_logs/index.md +1 -1
  29. package/dist/agentic/guides/modules/auth/index.md +1 -1
  30. package/dist/agentic/guides/modules/availability/index.md +1 -1
  31. package/dist/agentic/guides/modules/backups/di-registrations-rich.md +11 -0
  32. package/dist/agentic/guides/modules/backups/di-service-tokens.md +11 -0
  33. package/dist/agentic/guides/modules/backups/exact-override-targets.md +11 -0
  34. package/dist/agentic/guides/modules/backups/index.md +5 -2
  35. package/dist/agentic/guides/modules/business_rules/index.md +1 -1
  36. package/dist/agentic/guides/modules/carrier_inpost/index.md +1 -1
  37. package/dist/agentic/guides/modules/cart/index.md +1 -1
  38. package/dist/agentic/guides/modules/catalog/acl-features.md +2 -1
  39. package/dist/agentic/guides/modules/catalog/active-extension-bindings.md +2 -0
  40. package/dist/agentic/guides/modules/catalog/backend-pages.md +1 -0
  41. package/dist/agentic/guides/modules/catalog/contribution-resolutions.md +5 -0
  42. package/dist/agentic/guides/modules/catalog/di-registrations-rich.md +8 -7
  43. package/dist/agentic/guides/modules/catalog/di-service-tokens.md +5 -4
  44. package/dist/agentic/guides/modules/catalog/domain-commands.md +2 -0
  45. package/dist/agentic/guides/modules/catalog/entities.md +1 -0
  46. package/dist/agentic/guides/modules/catalog/events.md +4 -1
  47. package/dist/agentic/guides/modules/catalog/exact-override-targets.md +13 -7
  48. package/dist/agentic/guides/modules/catalog/index.md +9 -9
  49. package/dist/agentic/guides/modules/catalog/umes-contributions.md +5 -0
  50. package/dist/agentic/guides/modules/catalog/umes-hosts.md +4 -0
  51. package/dist/agentic/guides/modules/catalog/workers.md +1 -0
  52. package/dist/agentic/guides/modules/channel_apns/index.md +1 -1
  53. package/dist/agentic/guides/modules/channel_discord/index.md +1 -1
  54. package/dist/agentic/guides/modules/channel_expo/index.md +1 -1
  55. package/dist/agentic/guides/modules/channel_fcm/index.md +1 -1
  56. package/dist/agentic/guides/modules/channel_gmail/index.md +1 -1
  57. package/dist/agentic/guides/modules/channel_imap/index.md +1 -1
  58. package/dist/agentic/guides/modules/channel_resend/index.md +1 -1
  59. package/dist/agentic/guides/modules/channel_ses/index.md +1 -1
  60. package/dist/agentic/guides/modules/channel_smtp/index.md +1 -1
  61. package/dist/agentic/guides/modules/checkout/index.md +1 -1
  62. package/dist/agentic/guides/modules/communication_channels/index.md +1 -1
  63. package/dist/agentic/guides/modules/configs/index.md +1 -1
  64. package/dist/agentic/guides/modules/content/index.md +1 -1
  65. package/dist/agentic/guides/modules/currencies/index.md +1 -1
  66. package/dist/agentic/guides/modules/customer_accounts/active-extension-bindings.md +1 -1
  67. package/dist/agentic/guides/modules/customer_accounts/exact-override-targets.md +2 -0
  68. package/dist/agentic/guides/modules/customer_accounts/index.md +2 -2
  69. package/dist/agentic/guides/modules/customer_accounts/workers.md +2 -0
  70. package/dist/agentic/guides/modules/customer_groups/index.md +1 -1
  71. package/dist/agentic/guides/modules/customers/active-extension-bindings.md +2 -1
  72. package/dist/agentic/guides/modules/customers/incoming-installed-contributions.md +1 -0
  73. package/dist/agentic/guides/modules/customers/index.md +3 -3
  74. package/dist/agentic/guides/modules/customers/umes-hosts.md +1 -0
  75. package/dist/agentic/guides/modules/dashboards/active-extension-bindings.md +0 -1
  76. package/dist/agentic/guides/modules/dashboards/cli-commands.md +1 -0
  77. package/dist/agentic/guides/modules/dashboards/exact-override-targets.md +1 -0
  78. package/dist/agentic/guides/modules/dashboards/index.md +2 -3
  79. package/dist/agentic/guides/modules/data_sync/index.md +1 -1
  80. package/dist/agentic/guides/modules/design_system/index.md +1 -1
  81. package/dist/agentic/guides/modules/devices/index.md +1 -1
  82. package/dist/agentic/guides/modules/dictionaries/index.md +1 -1
  83. package/dist/agentic/guides/modules/directory/index.md +1 -1
  84. package/dist/agentic/guides/modules/documents/index.md +1 -1
  85. package/dist/agentic/guides/modules/ecommerce/index.md +1 -1
  86. package/dist/agentic/guides/modules/entities/index.md +1 -1
  87. package/dist/agentic/guides/modules/eudr/index.md +1 -1
  88. package/dist/agentic/guides/modules/events/index.md +1 -1
  89. package/dist/agentic/guides/modules/feature_toggles/index.md +1 -1
  90. package/dist/agentic/guides/modules/forms/index.md +1 -1
  91. package/dist/agentic/guides/modules/gateway_autopay/index.md +1 -1
  92. package/dist/agentic/guides/modules/gateway_stripe/index.md +1 -1
  93. package/dist/agentic/guides/modules/gateway_tpay/index.md +1 -1
  94. package/dist/agentic/guides/modules/generators/index.md +1 -1
  95. package/dist/agentic/guides/modules/inbox_ops/index.md +1 -1
  96. package/dist/agentic/guides/modules/integrations/di-registrations-rich.md +8 -8
  97. package/dist/agentic/guides/modules/integrations/di-service-tokens.md +4 -4
  98. package/dist/agentic/guides/modules/integrations/exact-override-targets.md +14 -12
  99. package/dist/agentic/guides/modules/integrations/index.md +2 -2
  100. package/dist/agentic/guides/modules/integrations/setup.md +1 -1
  101. package/dist/agentic/guides/modules/integrations/workers.md +3 -1
  102. package/dist/agentic/guides/modules/messages/index.md +1 -1
  103. package/dist/agentic/guides/modules/notifications/index.md +1 -1
  104. package/dist/agentic/guides/modules/onboarding/index.md +1 -1
  105. package/dist/agentic/guides/modules/payment_gateways/index.md +1 -1
  106. package/dist/agentic/guides/modules/perspectives/index.md +1 -1
  107. package/dist/agentic/guides/modules/phone_calls/index.md +1 -1
  108. package/dist/agentic/guides/modules/planner/index.md +1 -1
  109. package/dist/agentic/guides/modules/portal/index.md +1 -1
  110. package/dist/agentic/guides/modules/progress/index.md +1 -1
  111. package/dist/agentic/guides/modules/promotions/index.md +1 -1
  112. package/dist/agentic/guides/modules/push_notifications/index.md +1 -1
  113. package/dist/agentic/guides/modules/query_index/index.md +1 -1
  114. package/dist/agentic/guides/modules/record_locks/index.md +1 -1
  115. package/dist/agentic/guides/modules/resources/exact-override-targets.md +3 -3
  116. package/dist/agentic/guides/modules/resources/index.md +1 -1
  117. package/dist/agentic/guides/modules/resources/owned-contract-module-metadata.md +1 -1
  118. package/dist/agentic/guides/modules/resources/setup.md +1 -1
  119. package/dist/agentic/guides/modules/sales/contribution-resolutions.md +1 -0
  120. package/dist/agentic/guides/modules/sales/exact-override-targets.md +1 -0
  121. package/dist/agentic/guides/modules/sales/index.md +3 -3
  122. package/dist/agentic/guides/modules/sales/umes-contributions.md +1 -0
  123. package/dist/agentic/guides/modules/scheduler/index.md +1 -1
  124. package/dist/agentic/guides/modules/search/index.md +1 -1
  125. package/dist/agentic/guides/modules/security/index.md +1 -1
  126. package/dist/agentic/guides/modules/seeds/index.md +1 -1
  127. package/dist/agentic/guides/modules/shipping_carriers/index.md +1 -1
  128. package/dist/agentic/guides/modules/sso/index.md +1 -1
  129. package/dist/agentic/guides/modules/staff/contribution-resolutions.md +1 -1
  130. package/dist/agentic/guides/modules/staff/exact-override-targets.md +1 -1
  131. package/dist/agentic/guides/modules/staff/index.md +1 -1
  132. package/dist/agentic/guides/modules/staff/workers.md +1 -1
  133. package/dist/agentic/guides/modules/storage_s3/index.md +1 -1
  134. package/dist/agentic/guides/modules/sync_akeneo/index.md +1 -1
  135. package/dist/agentic/guides/modules/sync_excel/index.md +1 -1
  136. package/dist/agentic/guides/modules/system_status_overlays/index.md +1 -1
  137. package/dist/agentic/guides/modules/telemetry/index.md +1 -1
  138. package/dist/agentic/guides/modules/tillio/index.md +1 -1
  139. package/dist/agentic/guides/modules/translations/index.md +1 -1
  140. package/dist/agentic/guides/modules/warranty_claims/index.md +1 -1
  141. package/dist/agentic/guides/modules/webhooks/index.md +1 -1
  142. package/dist/agentic/guides/modules/wms/index.md +1 -1
  143. package/dist/agentic/guides/modules/workflows/index.md +1 -1
  144. package/dist/agentic/guides/reference-module-facts.json +811 -21
  145. package/dist/agentic/guides/reference-modules/example/active-extension-bindings.md +1 -0
  146. package/dist/agentic/guides/reference-modules/example/backend-pages.md +2 -0
  147. package/dist/agentic/guides/reference-modules/example/contribution-resolutions.md +3 -1
  148. package/dist/agentic/guides/reference-modules/example/di-registrations-rich.md +3 -3
  149. package/dist/agentic/guides/reference-modules/example/di-service-tokens.md +1 -1
  150. package/dist/agentic/guides/reference-modules/example/entities.md +2 -0
  151. package/dist/agentic/guides/reference-modules/example/events.md +2 -1
  152. package/dist/agentic/guides/reference-modules/example/exact-override-targets.md +25 -8
  153. package/dist/agentic/guides/reference-modules/example/index.md +7 -7
  154. package/dist/agentic/guides/reference-modules/example/notifications.md +1 -0
  155. package/dist/agentic/guides/reference-modules/example/setup.md +1 -1
  156. package/dist/agentic/guides/reference-modules/example/umes-contributions.md +3 -1
  157. package/dist/agentic/guides/reference-modules/example/umes-hosts.md +4 -0
  158. package/dist/agentic/guides/upstream/AGENTS.md +5 -4
  159. package/dist/agentic/guides/upstream/BACKWARD_COMPATIBILITY.md +37 -20
  160. package/dist/agentic/guides/upstream/manifest.json +3 -3
  161. package/dist/agentic/shared/AGENTS.md.template +11 -15
  162. package/dist/agentic/shared/ai/harness/README.md +4 -2
  163. package/dist/agentic/shared/ai/harness/RELEASE.md +4 -4
  164. package/dist/agentic/shared/ai/harness/cases.json +1420 -41
  165. package/dist/agentic/shared/ai/harness/cases.schema.json +4 -4
  166. package/dist/agentic/shared/ai/harness/design-system-inventory.json +640 -142
  167. package/dist/agentic/shared/ai/harness/source-link-inventory.json +223 -16
  168. package/dist/agentic/shared/ai/harness/validators.json +1 -1
  169. package/dist/agentic/shared/ai/skills/om-system-extension/SKILL.md +1 -1
  170. package/dist/agentic/shared/ai/skills/om-system-extension/references/extension-branches.md +25 -0
  171. package/dist/agentic/shared/ai/skills/om-system-extension/references/mechanism-selector.md +1 -0
  172. package/dist/agentic/shared/ai/skills/om-system-extension/references/unified-overrides.md +2 -0
  173. package/dist/agentic/shared/scripts/run-agent-harness-release.mjs +21 -1
  174. package/dist/lib/cache-provider-manifest.js +9 -0
  175. package/dist/lib/cache-provider-manifest.js.map +7 -0
  176. package/dist/lib/generate-child-process.js +21 -3
  177. package/dist/lib/generate-child-process.js.map +2 -2
  178. package/dist/lib/generate-watch-events.js +135 -19
  179. package/dist/lib/generate-watch-events.js.map +2 -2
  180. package/dist/lib/generate-watch-plan.js +170 -0
  181. package/dist/lib/generate-watch-plan.js.map +7 -0
  182. package/dist/lib/generate-watch-runner.js +54 -0
  183. package/dist/lib/generate-watch-runner.js.map +7 -0
  184. package/dist/lib/generate-watch-structure.js +578 -203
  185. package/dist/lib/generate-watch-structure.js.map +3 -3
  186. package/dist/lib/generators/ast/writers.js +5 -1
  187. package/dist/lib/generators/ast/writers.js.map +2 -2
  188. package/dist/lib/generators/cache-providers.js +80 -0
  189. package/dist/lib/generators/cache-providers.js.map +7 -0
  190. package/dist/lib/generators/extensions/agent-files.js +1 -0
  191. package/dist/lib/generators/extensions/agent-files.js.map +2 -2
  192. package/dist/lib/generators/form-section-ast.js +156 -0
  193. package/dist/lib/generators/form-section-ast.js.map +7 -0
  194. package/dist/lib/generators/form-section-extension-compiler.js +568 -0
  195. package/dist/lib/generators/form-section-extension-compiler.js.map +7 -0
  196. package/dist/lib/generators/form-section-extension-source.js +245 -0
  197. package/dist/lib/generators/form-section-extension-source.js.map +7 -0
  198. package/dist/lib/generators/form-section-runtime-revisions.js +184 -0
  199. package/dist/lib/generators/form-section-runtime-revisions.js.map +7 -0
  200. package/dist/lib/generators/form-sections.js +773 -0
  201. package/dist/lib/generators/form-sections.js.map +7 -0
  202. package/dist/lib/generators/index.js +2 -0
  203. package/dist/lib/generators/index.js.map +2 -2
  204. package/dist/lib/generators/module-entities.js +21 -2
  205. package/dist/lib/generators/module-entities.js.map +2 -2
  206. package/dist/lib/generators/module-extension-facts.js +2 -1
  207. package/dist/lib/generators/module-extension-facts.js.map +2 -2
  208. package/dist/lib/generators/module-facts.js +30 -1
  209. package/dist/lib/generators/module-facts.js.map +2 -2
  210. package/dist/lib/generators/module-override-targets.js +24 -2
  211. package/dist/lib/generators/module-override-targets.js.map +2 -2
  212. package/dist/lib/generators/module-registry.js +223 -194
  213. package/dist/lib/generators/module-registry.js.map +3 -3
  214. package/dist/lib/generators/openapi.js +51 -18
  215. package/dist/lib/generators/openapi.js.map +2 -2
  216. package/dist/lib/generators/web-research-adapters.js +54 -22
  217. package/dist/lib/generators/web-research-adapters.js.map +2 -2
  218. package/dist/lib/in-process-generate-watcher.js +98 -75
  219. package/dist/lib/in-process-generate-watcher.js.map +2 -2
  220. package/dist/lib/post-generate-invalidation.js +20 -1
  221. package/dist/lib/post-generate-invalidation.js.map +2 -2
  222. package/dist/lib/resolver.js +195 -1
  223. package/dist/lib/resolver.js.map +3 -3
  224. package/dist/lib/single-instance-strategy-guard.js +26 -3
  225. package/dist/lib/single-instance-strategy-guard.js.map +2 -2
  226. package/dist/mercato.js +106 -50
  227. package/dist/mercato.js.map +2 -2
  228. package/jest.config.cjs +2 -0
  229. package/package.json +7 -7
  230. package/src/__tests__/mercato.test.ts +18 -0
  231. package/src/__tests__/rotation-json-output.test.ts +52 -0
  232. package/src/lib/__tests__/cache-provider-manifest.test.ts +76 -0
  233. package/src/lib/__tests__/generate-child-process.test.ts +30 -0
  234. package/src/lib/__tests__/generate-watch-events.test.ts +377 -8
  235. package/src/lib/__tests__/generate-watch-plan.test.ts +99 -0
  236. package/src/lib/__tests__/generate-watch-runner.test.ts +138 -0
  237. package/src/lib/__tests__/generate-watch-structure.test.ts +556 -1
  238. package/src/lib/__tests__/in-process-generate-watcher.test.ts +393 -6
  239. package/src/lib/__tests__/module-inspection.test.ts +17 -11
  240. package/src/lib/__tests__/post-generate-invalidation.test.ts +108 -0
  241. package/src/lib/__tests__/resolver.form-section-gates.test.ts +82 -0
  242. package/src/lib/__tests__/single-instance-strategy-guard.test.ts +129 -0
  243. package/src/lib/cache-provider-manifest.ts +8 -0
  244. package/src/lib/generate-child-process.ts +26 -3
  245. package/src/lib/generate-watch-events.ts +189 -17
  246. package/src/lib/generate-watch-plan.ts +180 -0
  247. package/src/lib/generate-watch-runner.ts +63 -0
  248. package/src/lib/generate-watch-structure.ts +670 -227
  249. package/src/lib/generators/__tests__/cache-providers.test.ts +102 -0
  250. package/src/lib/generators/__tests__/derived-crud-route-collisions.test.ts +85 -0
  251. package/src/lib/generators/__tests__/form-section-outbox.test.ts +53 -0
  252. package/src/lib/generators/__tests__/form-sections.test.ts +896 -0
  253. package/src/lib/generators/__tests__/incremental-registry.test.ts +262 -0
  254. package/src/lib/generators/__tests__/module-extension-facts.test.ts +1 -0
  255. package/src/lib/generators/__tests__/module-facts.bc-guard.test.ts +8 -6
  256. package/src/lib/generators/__tests__/module-facts.example-fact-coverage.test.ts +37 -13
  257. package/src/lib/generators/__tests__/module-facts.local-reference.test.ts +13 -0
  258. package/src/lib/generators/__tests__/module-override-targets.test.ts +2 -3
  259. package/src/lib/generators/__tests__/module-subset.test.ts +1 -1
  260. package/src/lib/generators/__tests__/openapi.test.ts +147 -10
  261. package/src/lib/generators/__tests__/structural-contracts.test.ts +2 -2
  262. package/src/lib/generators/__tests__/web-research-adapters.test.ts +298 -87
  263. package/src/lib/generators/ast/writers.ts +6 -1
  264. package/src/lib/generators/cache-providers.ts +111 -0
  265. package/src/lib/generators/extension.ts +2 -0
  266. package/src/lib/generators/extensions/agent-files.ts +1 -0
  267. package/src/lib/generators/form-section-ast.ts +166 -0
  268. package/src/lib/generators/form-section-extension-compiler.ts +632 -0
  269. package/src/lib/generators/form-section-extension-source.ts +308 -0
  270. package/src/lib/generators/form-section-runtime-revisions.ts +211 -0
  271. package/src/lib/generators/form-sections.ts +896 -0
  272. package/src/lib/generators/index.ts +1 -0
  273. package/src/lib/generators/module-entities.ts +22 -4
  274. package/src/lib/generators/module-extension-facts.ts +1 -0
  275. package/src/lib/generators/module-facts.ts +40 -0
  276. package/src/lib/generators/module-override-targets.ts +19 -0
  277. package/src/lib/generators/module-registry.ts +246 -202
  278. package/src/lib/generators/openapi.ts +65 -20
  279. package/src/lib/generators/web-research-adapters.ts +76 -21
  280. package/src/lib/in-process-generate-watcher.ts +151 -96
  281. package/src/lib/post-generate-invalidation.ts +28 -1
  282. package/src/lib/resolver.ts +218 -0
  283. package/src/lib/single-instance-strategy-guard.ts +51 -1
  284. package/src/mercato.ts +117 -57
  285. package/dist/agentic/guides/modules/dashboards/incoming-installed-contributions.md +0 -11
@@ -1,6 +1,7 @@
1
1
  import crypto from 'node:crypto'
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
+ import ts from 'typescript-js'
4
5
  import {
5
6
  MODULE_CODE_EXTENSIONS,
6
7
  SCAN_CONFIGS,
@@ -8,279 +9,721 @@ import {
8
9
  scanModuleDir,
9
10
  stripModuleCodeExtension,
10
11
  type ModuleRoots,
12
+ type ScanConfig,
13
+ type ScannedFile,
11
14
  } from './generators/scanner'
15
+ import type {
16
+ GenerateWatchCategory, GenerateWatchChange, GenerateWatchRecord, GenerateWatchSnapshot,
17
+ } from './generate-watch-plan'
12
18
 
13
- const STRUCTURAL_CONVENTION_FILES = [
14
- 'index.ts',
15
- 'cli.ts',
16
- 'di.ts',
17
- 'acl.ts',
18
- 'setup.ts',
19
- 'runtime.ts',
20
- 'encryption.ts',
21
- 'ce.ts',
22
- 'search.ts',
23
- 'events.ts',
24
- 'notifications.ts',
25
- 'notifications.client.ts',
26
- 'notifications.handlers.ts',
27
- 'translations.ts',
28
- 'generators.ts',
29
- 'ai-tools.ts',
30
- 'ai-agents.ts',
31
- 'analytics.ts',
32
- 'workflows.ts',
33
- 'inbox-actions.ts',
34
- 'message-types.ts',
35
- 'message-objects.ts',
36
- 'integration.ts',
37
- 'security.mfa-providers.ts',
38
- 'security.sudo.ts',
39
- 'data/entities.ts',
40
- 'data/extensions.ts',
41
- 'data/fields.ts',
42
- 'data/enrichers.ts',
43
- 'data/guards.ts',
44
- 'api/interceptors.ts',
45
- 'commands/interceptors.ts',
46
- 'widgets/components.ts',
47
- 'widgets/injection-table.ts',
48
- 'frontend/middleware.ts',
49
- 'backend/middleware.ts',
50
- ] as const
51
-
52
- const CONTENT_SENSITIVE_SCAN_CONFIGS = [
53
- SCAN_CONFIGS.apiRoutes,
54
- SCAN_CONFIGS.apiPlainFiles,
55
- SCAN_CONFIGS.subscribers,
56
- SCAN_CONFIGS.workers,
57
- SCAN_CONFIGS.dashboardWidgets,
58
- SCAN_CONFIGS.injectionWidgets,
59
- ] as const
60
-
61
- const ROUTE_SHAPE_SCAN_CONFIGS = [
62
- SCAN_CONFIGS.frontendPages,
63
- SCAN_CONFIGS.backendPages,
64
- ] as const
19
+ type InputKind = { category: GenerateWatchCategory; extensionId?: string }
20
+ type WatchRoots = ModuleRoots & { moduleId?: string; from?: string }
21
+ export type GenerateWatchStructureOptions = {
22
+ modulesFile: string
23
+ moduleRoots: WatchRoots[]
24
+ /** Dependency/configuration inputs whose changes require a conservative full generation. */
25
+ additionalInputs?: string[]
26
+ /** Inputs consumed specifically by OpenAPI generation. */
27
+ openapiInputs?: string[]
28
+ cacheProviderInputs?: string[]
29
+ /** Candidate package manifests consumed specifically by web-research adapter discovery. */
30
+ webResearchAdapterInputs?: string[]
31
+ /** Adapter discovery failures that make this capture non-authoritative. */
32
+ webResearchAdapterFullReasons?: readonly string[]
33
+ }
34
+
35
+ /**
36
+ * Facts derived from one stat identity of a tracked file. Source text and parsed
37
+ * ASTs are capture-local; only these small extracted values outlive a capture.
38
+ */
39
+ type CachedStructureFile = {
40
+ identity: string
41
+ fingerprint: string
42
+ parseFailed?: true
43
+ pageFingerprint?: string | null
44
+ imports?: { specifiers: string[]; uncertain: boolean }
45
+ pluginConventions?: string[] | null
46
+ supervisorOverride?: boolean
47
+ }
48
+
49
+ type GenerateWatchStructureCacheState = {
50
+ files: Map<string, CachedStructureFile>
51
+ }
52
+
53
+ declare const generateWatchStructureCacheBrand: unique symbol
54
+ export type GenerateWatchStructureCache = {
55
+ readonly [generateWatchStructureCacheBrand]: true
56
+ }
57
+
58
+ const cacheStates = new WeakMap<GenerateWatchStructureCache, GenerateWatchStructureCacheState>()
59
+
60
+ export function createGenerateWatchStructureCache(): GenerateWatchStructureCache {
61
+ const cache = {} as GenerateWatchStructureCache
62
+ cacheStates.set(cache, { files: new Map() })
63
+ return cache
64
+ }
65
+
66
+ const REGISTRY_CONVENTIONS = [
67
+ 'index', 'acl', 'setup', 'runtime', 'encryption', 'ce', 'integration', 'vector',
68
+ 'data/extensions', 'data/fields',
69
+ ]
70
+ const EXTENSION_CONVENTIONS: Readonly<Record<string, string>> = {
71
+ notifications: 'registry.notifications',
72
+ 'notifications.client': 'registry.notifications',
73
+ 'notifications.handlers': 'registry.notifications',
74
+ 'message-types': 'registry.messages',
75
+ 'message-objects': 'registry.messages',
76
+ 'ai-tools': 'registry.ai-tools',
77
+ 'ai-agents': 'registry.ai-agents',
78
+ analytics: 'registry.analytics',
79
+ translations: 'registry.translatable-fields',
80
+ workflows: 'registry.workflows',
81
+ 'inbox-actions': 'registry.inbox-actions',
82
+ 'data/enrichers': 'registry.enrichers',
83
+ 'data/guards': 'registry.guards',
84
+ 'api/interceptors': 'registry.interceptors',
85
+ 'commands/interceptors': 'registry.command-interceptors',
86
+ 'widgets/components': 'registry.component-overrides',
87
+ 'frontend/middleware': 'registry.page-middleware',
88
+ 'backend/middleware': 'registry.page-middleware',
89
+ }
90
+
91
+ // These two policies mirror the registry's command/legacy-API scans; all other
92
+ // directory discovery is shared with the generator through SCAN_CONFIGS.
93
+ const COMMAND_SCAN_CONFIG: ScanConfig = {
94
+ folder: 'commands',
95
+ include: (name) => MODULE_CODE_EXTENSIONS.some((extension) => name.endsWith(extension))
96
+ && !name.endsWith('.d.ts') && !/\.(test|spec)\.[jt]sx?$/.test(name)
97
+ && !['index', 'shared', 'factory'].includes(stripModuleCodeExtension(name)),
98
+ }
99
+ const LEGACY_API_SCAN_CONFIGS: ScanConfig[] = ['get', 'post', 'put', 'patch', 'delete'].map((method) => ({
100
+ folder: `api/${method}`,
101
+ include: (name) => /\.[jt]s$/.test(name) && !/\.(test|spec)\.[jt]s$/.test(name),
102
+ }))
65
103
 
66
104
  function checksum(value: string): string {
67
105
  return crypto.createHash('md5').update(value).digest('hex')
68
106
  }
69
107
 
70
- function moduleRootIdentity(roots: ModuleRoots): string {
71
- return JSON.stringify([
72
- roots.pkgBase.replace(/\\/g, '/'),
73
- roots.appBase.replace(/\\/g, '/'),
74
- ])
108
+ function isMissing(error: unknown): boolean {
109
+ return typeof error === 'object' && error !== null && 'code' in error
110
+ && (error.code === 'ENOENT' || error.code === 'ENOTDIR')
75
111
  }
76
112
 
77
- function fileRecord(filePath: string, base: string, mode: 'content' | 'shape'): string | null {
78
- if (!fs.existsSync(filePath)) return null
79
- let stat: fs.Stats
80
- try {
81
- stat = fs.statSync(filePath)
82
- } catch {
83
- return null
113
+ function unwrap(node: ts.Expression): ts.Expression {
114
+ while (ts.isParenthesizedExpression(node) || ts.isAsExpression(node)
115
+ || ts.isTypeAssertionExpression(node) || ts.isSatisfiesExpression(node)) node = node.expression
116
+ return node
117
+ }
118
+
119
+ /** Read only static declaration data; never execute a plugin to watch it. */
120
+ function pluginConventions(file: ts.SourceFile): string[] | null {
121
+ const declarations = new Map<string, ts.Expression>()
122
+ let exported: ts.Expression | undefined
123
+ for (const statement of file.statements) {
124
+ if (ts.isVariableStatement(statement)) {
125
+ for (const declaration of statement.declarationList.declarations) {
126
+ if (ts.isIdentifier(declaration.name) && declaration.initializer) {
127
+ declarations.set(declaration.name.text, declaration.initializer)
128
+ if (declaration.name.text === 'generatorPlugins'
129
+ && statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) {
130
+ exported = declaration.initializer
131
+ }
132
+ }
133
+ }
134
+ } else if (ts.isExportAssignment(statement)) {
135
+ exported ??= statement.expression
136
+ } else if (ts.isImportDeclaration(statement)) {
137
+ if (!statement.importClause?.isTypeOnly) return null
138
+ } else if (!ts.isFunctionDeclaration(statement) && !ts.isInterfaceDeclaration(statement)
139
+ && !ts.isTypeAliasDeclaration(statement) && !ts.isEmptyStatement(statement)) return null
84
140
  }
85
- if (!stat.isFile()) return null
86
- const rel = path.relative(base, filePath).replace(/\\/g, '/')
87
- if (mode === 'shape') {
88
- return `file:${rel}`
141
+ if (!exported) return null
142
+ const resolve = (expression: ts.Expression, seen = new Set<string>()): ts.Expression | null => {
143
+ const node = unwrap(expression)
144
+ if (!ts.isIdentifier(node)) return node
145
+ if (seen.has(node.text)) return null
146
+ seen.add(node.text)
147
+ const value = declarations.get(node.text)
148
+ return value ? resolve(value, seen) : null
89
149
  }
90
- try {
91
- return `file:${rel}:${stat.size}:${checksum(fs.readFileSync(filePath, 'utf8'))}`
92
- } catch {
93
- return `file:${rel}:unreadable`
150
+ const plugins = resolve(exported)
151
+ if (!plugins || !ts.isArrayLiteralExpression(plugins)) return null
152
+ const conventions: string[] = []
153
+ for (const element of plugins.elements) {
154
+ const plugin = resolve(element)
155
+ if (!plugin || !ts.isObjectLiteralExpression(plugin)) return null
156
+ let convention: string | undefined
157
+ for (const property of plugin.properties) {
158
+ if (ts.isSpreadAssignment(property) || ts.isComputedPropertyName(property.name)) return null
159
+ if (property.name.getText(file).replace(/^['"]|['"]$/g, '') !== 'conventionFile') continue
160
+ const value = ts.isPropertyAssignment(property) ? resolve(property.initializer) : null
161
+ if (!value || !ts.isStringLiteralLike(value)) return null
162
+ convention = value.text
163
+ }
164
+ if (!convention) return null
165
+ conventions.push(convention)
94
166
  }
167
+ return conventions
95
168
  }
96
169
 
97
- function addFileRecord(
98
- records: string[],
99
- prefix: string,
100
- filePath: string,
101
- base: string,
102
- mode: 'content' | 'shape',
103
- ): void {
104
- const record = fileRecord(filePath, base, mode)
105
- if (record) records.push(`${prefix}:${record}`)
170
+ /** `null` when the page exports metadata (content fingerprint applies); otherwise its default-export marker. */
171
+ function pageFingerprint(parsed: ts.SourceFile): string | null {
172
+ const metadata = parsed.statements.some((statement) => {
173
+ if (ts.isExportDeclaration(statement)) {
174
+ return !statement.exportClause || (ts.isNamedExports(statement.exportClause)
175
+ && statement.exportClause.elements.some((element) => element.name.text === 'metadata'))
176
+ }
177
+ if (!ts.canHaveModifiers(statement)
178
+ || !ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)) return false
179
+ if (ts.isVariableStatement(statement)) {
180
+ return statement.declarationList.declarations.some((declaration) => /\bmetadata\b/.test(declaration.name.getText(parsed)))
181
+ }
182
+ return (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name?.text === 'metadata'
183
+ })
184
+ if (metadata) return null
185
+ const hasDefault = parsed.statements.some((statement) =>
186
+ (ts.isExportAssignment(statement) && !statement.isExportEquals)
187
+ || (ts.canHaveModifiers(statement) && ts.getModifiers(statement)?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword))
188
+ || (ts.isExportDeclaration(statement) && statement.exportClause && ts.isNamedExports(statement.exportClause)
189
+ && statement.exportClause.elements.some((element) => element.name.text === 'default')),
190
+ )
191
+ return `page:default:${hasDefault}`
106
192
  }
107
193
 
108
- function resolveCodeFile(base: string, relativePath: string): string | null {
109
- const stripped = stripModuleCodeExtension(relativePath)
110
- const candidates = MODULE_CODE_EXTENSIONS.map((extension) => `${stripped}${extension}`)
111
- for (const candidate of candidates) {
112
- const filePath = path.join(base, ...candidate.split('/'))
113
- if (fs.existsSync(filePath)) return filePath
194
+ const SUPERVISOR_OVERRIDE_CALLS = ['applyWorkerOverrides', 'applyCliOverrides']
195
+
196
+ function declaresSupervisorOverride(parsed: ts.SourceFile): boolean {
197
+ const direct = new Set<string>()
198
+ const namespaces = new Set<string>()
199
+ for (const statement of parsed.statements) {
200
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier)
201
+ || statement.moduleSpecifier.text !== '@open-mercato/shared/modules/overrides') continue
202
+ const bindings = statement.importClause?.namedBindings
203
+ if (bindings && ts.isNamespaceImport(bindings)) namespaces.add(bindings.name.text)
204
+ if (bindings && ts.isNamedImports(bindings)) {
205
+ for (const element of bindings.elements) {
206
+ if (SUPERVISOR_OVERRIDE_CALLS.includes(element.propertyName?.text ?? element.name.text)) direct.add(element.name.text)
207
+ }
208
+ }
209
+ }
210
+ let found = false
211
+ const visit = (node: ts.Node): void => {
212
+ if (ts.isCallExpression(node)) {
213
+ const expression = node.expression
214
+ if (ts.isIdentifier(expression) && direct.has(expression.text)) found = true
215
+ if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression)
216
+ && namespaces.has(expression.expression.text)
217
+ && SUPERVISOR_OVERRIDE_CALLS.includes(expression.name.text)) found = true
218
+ }
219
+ if (!found) ts.forEachChild(node, visit)
114
220
  }
115
- return null
221
+ visit(parsed)
222
+ return found
116
223
  }
117
224
 
118
- function resolveRuntimeCounterpart(
119
- pkgBase: string,
120
- sourceBase: string,
121
- sourceFile: string,
122
- ): string | null {
123
- if (sourceBase === pkgBase) return null
124
- const relativePath = path.relative(sourceBase, sourceFile).replace(/\\/g, '/')
125
- return resolveCodeFile(pkgBase, relativePath)
225
+ /** Module specifiers evaluated at load time; `uncertain` marks a non-literal import()/require(). */
226
+ function staticImports(parsed: ts.SourceFile): { specifiers: string[]; uncertain: boolean } {
227
+ const specifiers: string[] = []
228
+ let uncertain = false
229
+ const visit = (node: ts.Node): void => {
230
+ // Handler/component bodies are not evaluated to discover registrations.
231
+ // Static imports are still tracked, including imports used by metadata.
232
+ if (ts.isFunctionLike(node)) return
233
+ if (ts.isImportDeclaration(node)) {
234
+ if (node.importClause?.isTypeOnly) return
235
+ const bindings = node.importClause?.namedBindings
236
+ if (!node.importClause?.name && bindings && ts.isNamedImports(bindings)
237
+ && bindings.elements.length > 0 && bindings.elements.every((element) => element.isTypeOnly)) return
238
+ if (ts.isStringLiteralLike(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text)
239
+ return
240
+ }
241
+ if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier
242
+ && ts.isStringLiteralLike(node.moduleSpecifier)) specifiers.push(node.moduleSpecifier.text)
243
+ if (ts.isCallExpression(node) && (node.expression.kind === ts.SyntaxKind.ImportKeyword
244
+ || (ts.isIdentifier(node.expression) && node.expression.text === 'require'))) {
245
+ const argument = node.arguments[0]
246
+ if (argument && ts.isStringLiteralLike(argument)) specifiers.push(argument.text)
247
+ else uncertain = true
248
+ }
249
+ ts.forEachChild(node, visit)
250
+ }
251
+ visit(parsed)
252
+ return { specifiers, uncertain }
126
253
  }
127
254
 
128
- function hasInlinePageMetadata(filePath: string): boolean {
129
- try {
130
- const source = fs.readFileSync(filePath, 'utf8')
131
- return /\bexport\s+(?:const|let|var|function|class)\s+metadata\b/.test(source)
132
- || /\bexport\s+\{[^}]*\bmetadata\b[^}]*\}/.test(source)
133
- } catch {
134
- return false
255
+ class SnapshotCollector {
256
+ readonly records = new Map<string, GenerateWatchRecord>()
257
+ readonly fullReasons = new Set<string>()
258
+ private readonly stats = new Map<string, fs.Stats | null>()
259
+ private readonly identities = new Map<string, string | null>()
260
+ readonly uncertainDependencies = new Set<string>()
261
+ readonly uncertainPluginDescriptors = new Set<string>()
262
+ private readonly dependencySeeds = new Map<string, Map<string, InputKind>>()
263
+ readonly inspectedCachePaths = new Set<string>()
264
+ private readonly sources = new Map<string, string>()
265
+ private readonly parsedFiles = new Map<string, ts.SourceFile>()
266
+
267
+ constructor(private readonly cache: GenerateWatchStructureCacheState) {}
268
+
269
+ private identity(file: string): string | null {
270
+ if (!this.identities.has(file)) this.stat(file)
271
+ return this.identities.get(file) ?? null
135
272
  }
136
- }
137
273
 
138
- function addConventionRecords(records: string[], roots: ModuleRoots): void {
139
- const packageSourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
140
- for (const base of [roots.pkgBase, roots.appBase]) {
141
- records.push(`module-root:${base}:${fs.existsSync(base) ? 'present' : 'missing'}`)
142
- }
143
- if (packageSourceBase !== roots.pkgBase) {
144
- records.push(
145
- `module-root:${packageSourceBase}:${fs.existsSync(packageSourceBase) ? 'present' : 'missing'}`,
146
- )
147
- }
148
-
149
- for (const relativePath of STRUCTURAL_CONVENTION_FILES) {
150
- const appFile = resolveCodeFile(roots.appBase, relativePath)
151
- if (appFile) {
152
- addFileRecord(records, 'convention:app', appFile, roots.appBase, 'content')
153
- continue
154
- }
155
-
156
- const sourceFile = resolveCodeFile(packageSourceBase, relativePath)
157
- if (!sourceFile) {
158
- const runtimeFile = packageSourceBase === roots.pkgBase
159
- ? null
160
- : resolveCodeFile(roots.pkgBase, relativePath)
161
- if (runtimeFile) {
162
- addFileRecord(records, 'convention:package-runtime', runtimeFile, roots.pkgBase, 'content')
163
- } else {
164
- records.push(`convention:missing:${relativePath}`)
165
- }
166
- continue
274
+ private seedDependency(file: string, kind: InputKind): void {
275
+ const identity = `${kind.category}:${kind.extensionId ?? ''}`
276
+ const kinds = this.dependencySeeds.get(file) ?? new Map<string, InputKind>()
277
+ kinds.set(identity, kind)
278
+ this.dependencySeeds.set(file, kinds)
279
+ }
280
+
281
+ stat(file: string): fs.Stats | null {
282
+ if (this.stats.has(file)) return this.stats.get(file) ?? null
283
+ try {
284
+ const stat = fs.statSync(file)
285
+ const identity = [stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs].join(':')
286
+ this.stats.set(file, stat)
287
+ this.identities.set(file, identity)
288
+ return stat
289
+ } catch (error) {
290
+ if (!isMissing(error)) this.fullReasons.add(`Cannot inspect generator input: ${file}`)
291
+ this.stats.set(file, null)
292
+ this.identities.set(file, null)
293
+ return null
167
294
  }
295
+ }
168
296
 
169
- const packagePrefix = packageSourceBase === roots.pkgBase ? 'package' : 'package-source'
170
- addFileRecord(records, `convention:${packagePrefix}`, sourceFile, packageSourceBase, 'content')
171
- const runtimeFile = resolveRuntimeCounterpart(roots.pkgBase, packageSourceBase, sourceFile)
172
- if (runtimeFile) {
173
- addFileRecord(records, 'convention:package-runtime', runtimeFile, roots.pkgBase, 'content')
174
- } else if (packageSourceBase !== roots.pkgBase) {
175
- records.push(`convention:package-runtime:missing:${relativePath}`)
297
+ /** Stat-keyed cache entry for a readable file; unchanged identities are never re-read. */
298
+ entry(file: string): CachedStructureFile | null {
299
+ const stat = this.stat(file)
300
+ const identity = this.identity(file)
301
+ if (!stat?.isFile() || !identity) {
302
+ this.fullReasons.add(`Cannot read generator input: ${file}`)
303
+ return null
176
304
  }
305
+ this.inspectedCachePaths.add(file)
306
+ const cached = this.cache.files.get(file)
307
+ if (cached?.identity === identity) return cached
308
+ const source = this.readSource(file)
309
+ if (source === null) return null
310
+ const entry: CachedStructureFile = { identity, fingerprint: checksum(source) }
311
+ this.cache.files.set(file, entry)
312
+ return entry
177
313
  }
178
- }
179
314
 
180
- function addScannedRecords(records: string[], roots: ModuleRoots): void {
181
- const packageSourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
182
- for (const config of CONTENT_SENSITIVE_SCAN_CONFIGS) {
183
- for (const scanned of scanModuleDir(roots, config)) {
184
- const base = scanned.fromApp ? roots.appBase : packageSourceBase
185
- const filePath = path.join(base, ...config.folder.split('/'), ...scanned.relPath.split('/'))
186
- let sourceOrigin = 'app'
187
- if (!scanned.fromApp) {
188
- sourceOrigin = packageSourceBase === roots.pkgBase ? 'package' : 'package-source'
315
+ private readSource(file: string): string | null {
316
+ const known = this.sources.get(file)
317
+ if (known !== undefined) return known
318
+ try {
319
+ const source = fs.readFileSync(file, 'utf8')
320
+ this.sources.set(file, source)
321
+ return source
322
+ } catch {
323
+ this.fullReasons.add(`Cannot read generator input: ${file}`)
324
+ return null
325
+ }
326
+ }
327
+
328
+ /** Capture-local AST for a file whose cached facts are missing; parse failures are cached per identity. */
329
+ parsed(file: string, entry: CachedStructureFile): ts.SourceFile | null {
330
+ if (entry.parseFailed) {
331
+ this.fullReasons.add(`Cannot parse generator input: ${file}`)
332
+ return null
333
+ }
334
+ const known = this.parsedFiles.get(file)
335
+ if (known) return known
336
+ const source = this.readSource(file)
337
+ if (source === null) return null
338
+ let parsed: ts.SourceFile
339
+ try {
340
+ parsed = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true)
341
+ } catch {
342
+ this.fullReasons.add(`Cannot parse generator input: ${file}`)
343
+ return null
344
+ }
345
+ const diagnostics = (parsed as ts.SourceFile & { parseDiagnostics?: readonly ts.Diagnostic[] }).parseDiagnostics
346
+ if (diagnostics?.length) {
347
+ entry.parseFailed = true
348
+ this.fullReasons.add(`Cannot parse generator input: ${file}`)
349
+ return null
350
+ }
351
+ this.parsedFiles.set(file, parsed)
352
+ return parsed
353
+ }
354
+
355
+ record(key: string, file: string, kind: InputKind, fingerprint: string): void {
356
+ this.records.set(key, { key, path: file, ...kind, fingerprint })
357
+ }
358
+
359
+ file(key: string, file: string, kind: InputKind, mode: 'content' | 'page' | 'membership' | 'stat' = 'content'): void {
360
+ if (!this.stat(file)?.isFile()) return
361
+ if (mode === 'membership') {
362
+ this.record(key, file, kind, 'present')
363
+ return
364
+ }
365
+ if (mode === 'stat') {
366
+ this.record(key, file, kind, this.identity(file) ?? 'present')
367
+ return
368
+ }
369
+ const entry = this.entry(file)
370
+ if (!entry) {
371
+ this.record(key, file, kind, 'unreadable')
372
+ return
373
+ }
374
+ if (mode === 'page') {
375
+ if (entry.pageFingerprint === undefined) {
376
+ const parsed = this.parsed(file, entry)
377
+ if (!parsed) {
378
+ this.record(key, file, kind, 'unparseable')
379
+ return
380
+ }
381
+ entry.pageFingerprint = pageFingerprint(parsed)
382
+ }
383
+ if (entry.pageFingerprint !== null) {
384
+ this.record(key, file, kind, entry.pageFingerprint)
385
+ return
189
386
  }
190
- addFileRecord(records, `${config.folder}:${sourceOrigin}`, filePath, base, 'content')
191
-
192
- if (!scanned.fromApp && packageSourceBase !== roots.pkgBase) {
193
- const runtimeFile = resolveRuntimeCounterpart(roots.pkgBase, packageSourceBase, filePath)
194
- if (runtimeFile) {
195
- addFileRecord(
196
- records,
197
- `${config.folder}:package-runtime`,
198
- runtimeFile,
199
- roots.pkgBase,
200
- 'content',
201
- )
202
- } else {
203
- records.push(`${config.folder}:package-runtime:missing:${scanned.relPath}`)
387
+ }
388
+ this.record(key, file, kind, entry.fingerprint)
389
+ if (/\.[cm]?[jt]sx?$/.test(file)) this.seedDependency(file, kind)
390
+ }
391
+
392
+ codeFile(base: string, relativePath: string): string | null {
393
+ const stripped = stripModuleCodeExtension(relativePath)
394
+ const candidates = [relativePath, ...MODULE_CODE_EXTENSIONS.map((extension) => `${stripped}${extension}`)]
395
+ for (const candidate of candidates) {
396
+ const file = path.join(base, candidate)
397
+ if (this.stat(file)?.isFile()) return file
398
+ }
399
+ return null
400
+ }
401
+
402
+ scan(roots: ModuleRoots, config: ScanConfig): ScannedFile[] {
403
+ try {
404
+ return scanModuleDir(roots, config)
405
+ } catch {
406
+ this.fullReasons.add(`Cannot scan generator inputs: ${roots.appBase}, ${roots.pkgBase}/${config.folder}`)
407
+ return []
408
+ }
409
+ }
410
+
411
+ entries(directory: string): fs.Dirent[] {
412
+ if (!this.stat(directory)?.isDirectory()) return []
413
+ try {
414
+ return fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))
415
+ } catch {
416
+ this.fullReasons.add(`Cannot scan generator inputs: ${directory}`)
417
+ return []
418
+ }
419
+ }
420
+
421
+ pair(identity: string, roots: ModuleRoots, relativePath: string, kind: InputKind, mode: 'content' | 'page' = 'content'): string[] {
422
+ const sourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
423
+ const app = this.codeFile(roots.appBase, relativePath)
424
+ const source = app ?? this.codeFile(sourceBase, relativePath)
425
+ // Conventions retain stale compiled inputs after source deletion. Directory
426
+ // scans still enumerate only the authoritative source mirror before pairing.
427
+ const runtime = !app && sourceBase !== roots.pkgBase
428
+ ? this.codeFile(roots.pkgBase, stripModuleCodeExtension(relativePath))
429
+ : source
430
+ const primary = source ?? runtime
431
+ if (!primary) return []
432
+ const logical = stripModuleCodeExtension(relativePath).replace(/\\/g, '/')
433
+ const key = `${identity}:${kind.category}:${kind.extensionId ?? ''}:${logical}`
434
+ if (source) this.file(`${key}:source`, source, kind, mode)
435
+ if (runtime && runtime !== source) this.file(`${key}:runtime`, runtime, kind, mode)
436
+ // Physical ownership is part of the fingerprint even for identical bytes.
437
+ this.record(`${key}:authority`, primary, kind, JSON.stringify([source, runtime]))
438
+ return source && runtime && runtime !== source ? [source, runtime] : [primary]
439
+ }
440
+
441
+ tree(identity: string, directory: string, kind: InputKind, skipTests = true): void {
442
+ for (const entry of this.entries(directory)) {
443
+ if (skipTests && (entry.name === '__tests__' || entry.name === '__mocks__')) continue
444
+ const file = path.join(directory, entry.name)
445
+ if (entry.isDirectory()) this.tree(identity, file, kind, skipTests)
446
+ else if (entry.isFile()) this.file(`${identity}:${file}`, file, kind)
447
+ }
448
+ }
449
+
450
+ supervisor(appSource: string): void {
451
+ const pending = [appSource]
452
+ let found = false
453
+ while (pending.length > 0 && !found) {
454
+ const directory = pending.pop()!
455
+ for (const entry of this.entries(directory)) {
456
+ const file = path.join(directory, entry.name)
457
+ if (entry.isDirectory()) {
458
+ if (entry.name !== '__tests__' && entry.name !== 'node_modules') pending.push(file)
459
+ continue
460
+ }
461
+ if (!/\.[cm]?tsx?$/.test(entry.name) || /(?:^|\.)test\.[cm]?tsx?$/.test(entry.name)) continue
462
+ const cached = this.entry(file)
463
+ if (!cached) continue
464
+ if (cached.supervisorOverride === undefined) {
465
+ if (!this.readSource(file)?.includes('@open-mercato/shared/modules/overrides')) {
466
+ cached.supervisorOverride = false
467
+ continue
468
+ }
469
+ const parsed = this.parsed(file, cached)
470
+ if (!parsed) continue
471
+ cached.supervisorOverride = declaresSupervisorOverride(parsed)
472
+ }
473
+ if (cached.supervisorOverride) {
474
+ found = true
475
+ break
204
476
  }
205
477
  }
206
478
  }
479
+ this.record('supervisor-overrides', appSource, { category: 'registry-convention', extensionId: 'supervisor' }, String(found))
207
480
  }
208
481
 
209
- for (const config of ROUTE_SHAPE_SCAN_CONFIGS) {
210
- for (const scanned of scanModuleDir(roots, config)) {
211
- const base = scanned.fromApp ? roots.appBase : packageSourceBase
212
- const folderPath = path.join(base, ...config.folder.split('/'))
213
- const filePath = path.join(folderPath, ...scanned.relPath.split('/'))
214
- let sourceOrigin = 'app'
215
- if (!scanned.fromApp) {
216
- sourceOrigin = packageSourceBase === roots.pkgBase ? 'package' : 'package-source'
482
+ dependencies(appSource: string): void {
483
+ const visited = new Set<string>()
484
+ const pending = [...this.dependencySeeds]
485
+ .flatMap(([file, kinds]) => [...kinds.entries()].map(([identity, kind]) => ({ file, identity, kind })))
486
+ .sort((left, right) => right.file.localeCompare(left.file) || right.identity.localeCompare(left.identity))
487
+ while (pending.length > 0) {
488
+ const { file, identity, kind } = pending.pop()!
489
+ const visitKey = `${identity}:${file}`
490
+ if (visited.has(visitKey)) continue
491
+ visited.add(visitKey)
492
+ const cached = this.entry(file)
493
+ if (!cached) continue
494
+ if (!cached.imports) {
495
+ const parsed = this.parsed(file, cached)
496
+ if (!parsed) continue
497
+ cached.imports = staticImports(parsed)
217
498
  }
218
- addFileRecord(
219
- records,
220
- `${config.folder}:${sourceOrigin}`,
221
- filePath,
222
- base,
223
- hasInlinePageMetadata(filePath) ? 'content' : 'shape',
224
- )
225
-
226
- let runtimeFile: string | null = null
227
- if (!scanned.fromApp && packageSourceBase !== roots.pkgBase) {
228
- runtimeFile = resolveRuntimeCounterpart(roots.pkgBase, packageSourceBase, filePath)
229
- if (runtimeFile) {
230
- addFileRecord(
231
- records,
232
- `${config.folder}:package-runtime`,
233
- runtimeFile,
234
- roots.pkgBase,
235
- hasInlinePageMetadata(runtimeFile) ? 'content' : 'shape',
236
- )
237
- } else {
238
- records.push(`${config.folder}:package-runtime:missing:${scanned.relPath}`)
499
+ if (cached.imports.uncertain) this.uncertainDependencies.add(file)
500
+ const imports = cached.imports.specifiers
501
+ for (const specifier of imports) {
502
+ if (!specifier.startsWith('.') && !specifier.startsWith('@/')) continue
503
+ const target = specifier.startsWith('@/')
504
+ ? path.join(appSource, specifier.slice(2)) : path.resolve(path.dirname(file), specifier)
505
+ const resolved = this.codeFile(path.dirname(target), path.basename(target))
506
+ ?? this.codeFile(target, 'index')
507
+ const dependencyKey = `dependency:${identity}:${file}:${target}`
508
+ if (!resolved) {
509
+ // Keep an absence record so a newly supplied helper invalidates the plan.
510
+ this.record(dependencyKey, target, kind, 'missing')
511
+ continue
239
512
  }
513
+ // A generator's own outputs must not feed back into its watcher baseline.
514
+ if (resolved.includes(`${path.sep}.mercato${path.sep}`) || resolved.includes(`${path.sep}generated${path.sep}`)) continue
515
+ const fingerprint = this.entry(resolved)?.fingerprint ?? 'unreadable'
516
+ this.record(dependencyKey, resolved, kind, `${resolved}:${fingerprint}`)
517
+ if (/\.[cm]?[jt]sx?$/.test(resolved)) pending.push({ file: resolved, identity, kind })
240
518
  }
519
+ }
520
+ }
521
+ }
241
522
 
242
- const stem = stripModuleCodeExtension(path.basename(filePath))
243
- const metaCandidates = stem === 'page'
244
- ? ['page.meta', 'meta']
245
- : [`${stem}.meta`, 'meta']
246
- for (const candidate of metaCandidates) {
247
- const metaPath = resolveCodeFile(path.dirname(filePath), candidate)
248
- if (!metaPath) continue
249
- addFileRecord(records, `${config.folder}:meta:${sourceOrigin}`, metaPath, base, 'content')
250
- }
523
+ function addModule(collector: SnapshotCollector, roots: WatchRoots, index: number, plugins: Set<string>): void {
524
+ const distMarker = `${path.sep}dist${path.sep}modules${path.sep}`
525
+ const distIndex = roots.pkgBase.lastIndexOf(distMarker)
526
+ if (distIndex >= 0) {
527
+ const packageRoot = roots.pkgBase.slice(0, distIndex)
528
+ collector.stat(path.join(packageRoot, 'src', 'modules', roots.pkgBase.slice(distIndex + distMarker.length)))
529
+ }
530
+ const sourceBase = resolveStandaloneSourceMirrorBase(roots.pkgBase) ?? roots.pkgBase
531
+ const identity = `module:${index}:${roots.moduleId ?? path.basename(roots.appBase)}:${roots.appBase}:${roots.pkgBase}`
532
+ collector.record(`${identity}:roots`, roots.appBase, { category: 'configuration' }, JSON.stringify([
533
+ Object.entries(roots).sort(([left], [right]) => left.localeCompare(right)), sourceBase,
534
+ collector.stat(roots.appBase)?.isDirectory() ?? false, collector.stat(roots.pkgBase)?.isDirectory() ?? false,
535
+ ]))
536
+ const convention = (relativePath: string, kind: InputKind) => collector.pair(identity, roots, `${relativePath}.ts`, kind)
537
+ for (const relativePath of REGISTRY_CONVENTIONS) convention(relativePath, { category: 'registry-convention' })
538
+ // Section definitions can change shared field sets, route manifests, and OpenAPI together.
539
+ convention('form-sections', { category: 'configuration' })
540
+ for (const [relativePath, extensionId] of Object.entries(EXTENSION_CONVENTIONS)) {
541
+ convention(relativePath, { category: 'extension', extensionId })
542
+ }
543
+ collector.pair(identity, roots, 'widgets/payments/client.tsx', { category: 'extension', extensionId: 'registry.notifications' })
544
+ for (const category of ['cli', 'di', 'search', 'events'] as const) convention(category, { category })
545
+ convention('widgets/injection-table', { category: 'injection-widgets' })
546
+ for (const descriptor of convention('generators', { category: 'generator-plugin' })) {
547
+ const cached = collector.entry(descriptor)
548
+ if (cached && cached.pluginConventions === undefined) {
549
+ const parsed = collector.parsed(descriptor, cached)
550
+ if (parsed) cached.pluginConventions = pluginConventions(parsed)
551
+ }
552
+ const discovered = cached?.pluginConventions ?? null
553
+ if (discovered === null) collector.uncertainPluginDescriptors.add(descriptor)
554
+ else for (const file of discovered) plugins.add(file)
555
+ }
251
556
 
252
- if (runtimeFile) {
253
- for (const candidate of metaCandidates) {
254
- const runtimeMetaPath = resolveCodeFile(path.dirname(runtimeFile), candidate)
255
- if (!runtimeMetaPath) continue
256
- addFileRecord(
257
- records,
258
- `${config.folder}:meta:package-runtime`,
259
- runtimeMetaPath,
260
- roots.pkgBase,
261
- 'content',
262
- )
557
+ // Entity generators use direct app/package candidates, including legacy db and
558
+ // override/schema fallbacks, rather than resolveModuleFile's source authority.
559
+ for (const base of new Set([roots.appBase, roots.pkgBase, sourceBase])) {
560
+ for (const directory of ['data', 'db']) {
561
+ for (const stem of ['entities.override', 'entities', 'schema']) {
562
+ for (const extension of MODULE_CODE_EXTENSIONS) {
563
+ const file = path.join(base, directory, `${stem}${extension}`)
564
+ collector.file(`${identity}:entities:${file}`, file, { category: 'entities' })
263
565
  }
264
566
  }
265
567
  }
266
568
  }
569
+ if (distIndex >= 0) {
570
+ const packageRoot = roots.pkgBase.slice(0, distIndex)
571
+ const direct = path.join(packageRoot, 'generated')
572
+ collector.record(`${identity}:package-entities-direct-root`, direct, { category: 'entities' },
573
+ collector.stat(direct)?.isDirectory() ? 'directory' : 'missing')
574
+ const generated = collector.stat(direct)?.isDirectory() ? direct : path.join(packageRoot, 'dist', 'generated')
575
+ collector.record(`${identity}:package-entities-root`, generated, { category: 'entities' }, generated)
576
+ for (const extension of ['.ts', '.js']) {
577
+ const ids = path.join(generated, `entities.ids.generated${extension}`)
578
+ collector.file(`${identity}:package-entities:${ids}`, ids, { category: 'entities' })
579
+ for (const entry of collector.entries(path.join(generated, 'entities'))) {
580
+ if (!entry.isDirectory()) continue
581
+ const fields = path.join(generated, 'entities', entry.name, `index${extension}`)
582
+ collector.file(`${identity}:package-entities:${fields}`, fields, { category: 'entities' })
583
+ }
584
+ }
585
+ }
586
+ const scans: Array<[ScanConfig, GenerateWatchCategory]> = [
587
+ [SCAN_CONFIGS.apiRoutes, 'api-route'], [SCAN_CONFIGS.apiPlainFiles, 'api-route'],
588
+ ...LEGACY_API_SCAN_CONFIGS.map((config): [ScanConfig, GenerateWatchCategory] => [config, 'api-route']),
589
+ [COMMAND_SCAN_CONFIG, 'commands'], [SCAN_CONFIGS.subscribers, 'subscribers'],
590
+ [SCAN_CONFIGS.workers, 'workers'], [SCAN_CONFIGS.dashboardWidgets, 'dashboard-widgets'],
591
+ [SCAN_CONFIGS.injectionWidgets, 'injection-widgets'],
592
+ [SCAN_CONFIGS.frontendPages, 'frontend-page'], [SCAN_CONFIGS.backendPages, 'backend-page'],
593
+ ]
594
+ for (const [config, category] of scans) {
595
+ for (const scanned of collector.scan(roots, config)) {
596
+ const relativePath = `${config.folder}/${scanned.relPath}`
597
+ // Exact conventions in route/page directories are not route registrations.
598
+ if (EXTENSION_CONVENTIONS[stripModuleCodeExtension(relativePath)]) continue
599
+ const page = category === 'frontend-page' || category === 'backend-page'
600
+ const files = collector.pair(identity, roots, relativePath, { category }, page ? 'page' : 'content')
601
+ if (!page) continue
602
+ for (const file of files) {
603
+ const stem = stripModuleCodeExtension(path.basename(file))
604
+ for (const candidate of [stem === 'page' ? 'page.meta' : `${stem}.meta`, 'meta']) {
605
+ const metadata = collector.codeFile(path.dirname(file), candidate)
606
+ if (metadata) collector.file(`${identity}:${category}:metadata:${metadata}`, metadata, { category })
607
+ }
608
+ }
609
+ }
610
+ }
611
+ for (const base of new Set([sourceBase, roots.appBase])) {
612
+ const directory = path.join(base, 'i18n')
613
+ for (const entry of collector.entries(directory)) {
614
+ if (!entry.isFile() || !/^[a-zA-Z0-9][a-zA-Z0-9_-]*\.json$/.test(entry.name)) continue
615
+ const file = path.join(directory, entry.name)
616
+ collector.file(`${identity}:i18n:${file}`, file, { category: 'i18n' }, 'membership')
617
+ if (base === sourceBase && sourceBase !== roots.pkgBase) {
618
+ const runtime = path.join(roots.pkgBase, 'i18n', entry.name)
619
+ collector.file(`${identity}:i18n:runtime:${runtime}`, runtime, { category: 'i18n' }, 'membership')
620
+ }
621
+ }
622
+ collector.tree(`${identity}:agents`, path.join(base, 'agents'), { category: 'extension', extensionId: 'registry.agent-files' })
623
+ }
267
624
  }
268
625
 
269
- export function calculateGenerateWatchStructureChecksum(options: {
270
- modulesFile: string
271
- moduleRoots: ModuleRoots[]
272
- }): string {
273
- const records: string[] = []
274
- const modulesRecord = fileRecord(options.modulesFile, path.dirname(options.modulesFile), 'content')
275
- records.push(modulesRecord ?? `missing:${options.modulesFile}`)
626
+ export function collectGenerateWatchStructureSnapshot(
627
+ options: GenerateWatchStructureOptions,
628
+ cache?: GenerateWatchStructureCache,
629
+ ): GenerateWatchSnapshot {
630
+ const cacheState = cache ? cacheStates.get(cache) : { files: new Map<string, CachedStructureFile>() }
631
+ if (!cacheState) throw new TypeError('Invalid generate watch structure cache')
632
+ const collector = new SnapshotCollector(cacheState)
633
+ for (const reason of options.webResearchAdapterFullReasons ?? []) collector.fullReasons.add(reason)
634
+ collector.file(`configuration:${options.modulesFile}`, options.modulesFile, { category: 'configuration' })
635
+ const plugins = new Set<string>()
636
+ options.moduleRoots.forEach((roots, index) => addModule(collector, roots, index, plugins))
637
+ options.moduleRoots.forEach((roots, index) => {
638
+ const identity = `module:${index}:${roots.moduleId ?? path.basename(roots.appBase)}:${roots.appBase}:${roots.pkgBase}`
639
+ for (const relativePath of plugins) collector.pair(identity, roots, relativePath, { category: 'generator-plugin' })
640
+ })
641
+ const knownInputs = new Map<string, GenerateWatchRecord>()
642
+ for (const record of collector.records.values()) {
643
+ if (record.category !== 'configuration') knownInputs.set(record.path, record)
644
+ }
645
+ const ordered = (inputs: readonly string[] | undefined) =>
646
+ [...new Set(inputs ?? [])].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)
647
+ for (const input of ordered(options.additionalInputs)) {
648
+ if (knownInputs.has(input)) continue
649
+ const stat = collector.stat(input)
650
+ if (stat?.isFile()) collector.file(`configuration:${input}`, input, { category: 'configuration' })
651
+ else collector.record(`configuration:${input}`, input, { category: 'configuration' }, stat?.isDirectory() ? 'directory' : 'missing')
652
+ }
653
+ const addSpecializedInputs = (
654
+ inputs: readonly string[] | undefined,
655
+ kind: InputKind,
656
+ keyPrefix: string,
657
+ mode: 'content' | 'stat' | 'membership' = 'content',
658
+ ) => {
659
+ for (const input of ordered(inputs)) {
660
+ const stat = collector.stat(input)
661
+ if (stat?.isFile()) collector.file(`${keyPrefix}:${input}`, input, kind, mode)
662
+ else collector.record(`${keyPrefix}:${input}`, input, kind, stat?.isDirectory() ? 'directory' : 'missing')
663
+ }
664
+ }
665
+ addSpecializedInputs(options.openapiInputs, { category: 'openapi' }, 'openapi-input')
666
+ addSpecializedInputs(
667
+ options.webResearchAdapterInputs,
668
+ { category: 'web-research-adapters' },
669
+ 'web-research-adapter-input',
670
+ 'stat',
671
+ )
672
+ addSpecializedInputs(options.cacheProviderInputs, { category: 'cache-providers' }, 'cache-provider-input', 'membership')
673
+ collector.supervisor(path.dirname(options.modulesFile))
674
+ collector.dependencies(path.dirname(options.modulesFile))
675
+ // A dynamic descriptor is valid source, not a transient failed capture. Until
676
+ // its dependencies can be proven, watch all potential module contributions.
677
+ // Changes require a full suite, but an unchanged successful baseline is clean.
678
+ if (collector.uncertainPluginDescriptors.size > 0 || collector.uncertainDependencies.size > 0) {
679
+ const category = collector.uncertainPluginDescriptors.size > 0 ? 'generator-plugin' : 'unknown'
680
+ for (const roots of options.moduleRoots) {
681
+ for (const base of new Set([roots.appBase, roots.pkgBase, resolveStandaloneSourceMirrorBase(roots.pkgBase)])) {
682
+ if (base) collector.tree(`uncertain-dependencies:${base}`, base, { category }, false)
683
+ }
684
+ }
685
+ for (const descriptor of collector.uncertainPluginDescriptors) {
686
+ collector.record(`uncertain-plugin:${descriptor}`, descriptor, { category: 'generator-plugin' }, 'unresolved-conventions')
687
+ }
688
+ for (const dependency of collector.uncertainDependencies) {
689
+ collector.record(`uncertain-dependency:${dependency}`, dependency, { category: 'unknown' }, 'unresolved-import')
690
+ }
691
+ }
692
+ const records = new Map([...collector.records].sort(([left], [right]) => left.localeCompare(right)))
693
+ const fullReasons = [...collector.fullReasons].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)
694
+ if (fullReasons.length === 0) {
695
+ for (const cachedPath of cacheState.files.keys()) {
696
+ if (!collector.inspectedCachePaths.has(cachedPath)) cacheState.files.delete(cachedPath)
697
+ }
698
+ }
699
+ return {
700
+ checksum: checksum(JSON.stringify([[...records.values()], fullReasons])),
701
+ records,
702
+ fullReasons,
703
+ }
704
+ }
276
705
 
277
- for (const roots of options.moduleRoots) {
278
- const moduleRecords: string[] = []
279
- addConventionRecords(moduleRecords, roots)
280
- addScannedRecords(moduleRecords, roots)
281
- const rootIdentity = moduleRootIdentity(roots)
282
- records.push(...moduleRecords.map((record) => `${rootIdentity}:${record}`))
706
+ export function diffGenerateWatchStructureSnapshots(
707
+ previous: GenerateWatchSnapshot,
708
+ next: GenerateWatchSnapshot,
709
+ ): GenerateWatchChange[] {
710
+ const changes: GenerateWatchChange[] = []
711
+ for (const key of [...new Set([...previous.records.keys(), ...next.records.keys()])].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)) {
712
+ const before = previous.records.get(key)
713
+ const after = next.records.get(key)
714
+ if (before && after && before.fingerprint === after.fingerprint && before.path === after.path
715
+ && before.category === after.category && before.extensionId === after.extensionId) continue
716
+ const record = after ?? before!
717
+ changes.push({
718
+ key, kind: !before ? 'add' : !after ? 'delete' : 'change',
719
+ category: record.category, path: record.path,
720
+ ...(record.extensionId ? { extensionId: record.extensionId } : {}),
721
+ })
283
722
  }
723
+ return changes
724
+ }
284
725
 
285
- return checksum(records.sort((a, b) => a.localeCompare(b)).join('\n'))
726
+ /** Legacy callers intentionally receive only the opaque snapshot checksum. */
727
+ export function calculateGenerateWatchStructureChecksum(options: GenerateWatchStructureOptions): string {
728
+ return collectGenerateWatchStructureSnapshot(options).checksum
286
729
  }