@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
@@ -0,0 +1,896 @@
1
+ import fs from 'node:fs'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import path from 'node:path'
4
+ import ts from 'typescript-js'
5
+ import { resolveModuleRequirement, type ModuleIdentity } from '@open-mercato/shared/modules/module-locators'
6
+ import {
7
+ crudFormSectionClientMutationFactSchema, crudSectionOperationMethods as derivedRouteMethods,
8
+ derivedCrudFormSectionClientMutationFact, derivedCrudFormSectionRetryPath, parseCrudFormSectionClientMutationFacts,
9
+ } from '@open-mercato/shared/lib/crud/form-sections/client-mutation-facts'
10
+ import { crudFormSectionOverrideKey } from '@open-mercato/shared/lib/crud/form-sections/composition'
11
+ import type { CrudFormSectionClientHostFact } from '@open-mercato/shared/modules/form-sections'
12
+ import type { FormSectionOverridesMap } from '@open-mercato/shared/modules/overrides'
13
+ import { writeGeneratedFile, type GeneratorResult } from '../utils'
14
+ import { escapeGeneratedJsonLiteral, stringLiteral } from './ast/writers'
15
+ import { compileCrudFormSectionExtensions, type CompilerModule, type CompiledSectionExtensions } from './form-section-extension-compiler'
16
+ import { parseSectionExtensionSources } from './form-section-extension-source'
17
+ import { arrayField, exportedDeclaration, fieldsOf, helperArgument, literalData, literalValue, readIdentity, readSectionRuntimeFields, unwrap } from './form-section-ast'
18
+ import { hashHandwrittenSectionRuntime, planHandwrittenSectionRevisionWrite } from './form-section-runtime-revisions'
19
+ import {
20
+ MODULE_CODE_EXTENSIONS,
21
+ resolveStandaloneSourceMirrorBase,
22
+ stripModuleCodeExtension,
23
+ type ModuleRoots,
24
+ type ResolvedFile,
25
+ } from './scanner'
26
+
27
+ type ModuleSource = {
28
+ modId: string
29
+ roots: ModuleRoots
30
+ resolve: (relativePath: string) => ResolvedFile | null
31
+ formSectionOverrides?: Readonly<FormSectionOverridesMap>
32
+ }
33
+
34
+ const factFields = [
35
+ ['host', 'hostFacts'],
36
+ ['contribution', 'contributionFacts'],
37
+ ] as const
38
+
39
+ type Descriptor = {
40
+ id: string
41
+ roundTripId: string
42
+ kind: (typeof factFields)[number][0]
43
+ field: (typeof factFields)[number][1]
44
+ index: number
45
+ runtimePath: string
46
+ }
47
+
48
+ type ModuleSections = CompilerModule & {
49
+ hasHandwrittenSections: boolean
50
+ sourceFileName: string
51
+ descriptors: Descriptor[]
52
+ leafDefaultProviderIds: readonly string[]
53
+ sinkIds: readonly string[]
54
+ derivedRoutes: readonly DerivedRouteDeclaration[]
55
+ revisionWrite: ReturnType<typeof planHandwrittenSectionRevisionWrite>
56
+ }
57
+
58
+ type DerivedMethod = 'POST' | 'PUT' | 'DELETE'
59
+ type DerivedRouteDeclaration = {
60
+ index: number
61
+ routePath: string
62
+ hostDescriptorId: string
63
+ operations: readonly ('create' | 'update' | 'delete')[]
64
+ versioned: boolean
65
+ outboxRetry: boolean
66
+ }
67
+ export type GeneratedDerivedCrudRoute = {
68
+ moduleId: string
69
+ routePath: string
70
+ fileName: string
71
+ methods: DerivedMethod[]
72
+ }
73
+
74
+ export const generatedDerivedCrudRouteIndex = 'crud-form-section-derived-routes.generated.json'
75
+
76
+
77
+ function compareIds(left: string, right: string): number {
78
+ if (left === right) return 0
79
+ return left < right ? -1 : 1
80
+ }
81
+
82
+ function readRuntimePath(
83
+ initializer: ts.Expression | undefined,
84
+ declaration: ResolvedFile,
85
+ declarationSourcePath: string,
86
+ expected: { id: string; roundTripId: string },
87
+ invalid: (reason: string) => never,
88
+ ): { runtimePath: string; source: ts.SourceFile } {
89
+ if (!initializer) return invalid('missing runtime loader')
90
+ const arrow = unwrap(helperArgument(initializer, 'lazyCrudFormSectionRuntime', invalid))
91
+ if (!ts.isArrowFunction(arrow) || arrow.parameters.length !== 0 || ts.isBlock(arrow.body)) {
92
+ return invalid('expected a zero-argument arrow returning a literal import()')
93
+ }
94
+ const call = unwrap(arrow.body)
95
+ if (!ts.isCallExpression(call) || call.expression.kind !== ts.SyntaxKind.ImportKeyword || call.arguments.length !== 1) {
96
+ return invalid('expected a literal import()')
97
+ }
98
+ const specifier = literalValue(call.arguments[0], 'runtime import specifier', invalid)
99
+ if (!specifier.startsWith('./') || specifier.includes('\\')) return invalid('expected a module-relative runtime import')
100
+ const relative = stripModuleCodeExtension(path.posix.normalize(specifier))
101
+ if (relative.startsWith('../') || !relative.endsWith('.client')) {
102
+ return invalid(`runtime import "${specifier}" must resolve to a .client file inside the owning module`)
103
+ }
104
+ const readRuntime = (declarationPath: string) => {
105
+ const owner = path.dirname(declarationPath)
106
+ const runtimeFile = MODULE_CODE_EXTENSIONS
107
+ .map((extension) => path.join(owner, `${relative}${extension}`))
108
+ .find((candidate) => fs.existsSync(candidate))
109
+ if (!runtimeFile) return invalid(`runtime import "${specifier}" is missing from the owning module`)
110
+ const filename = fs.realpathSync(runtimeFile)
111
+ const fromOwner = path.relative(fs.realpathSync(owner), filename)
112
+ if (fromOwner === '..' || fromOwner.startsWith(`..${path.sep}`) || path.isAbsolute(fromOwner)) {
113
+ return invalid(`runtime import "${specifier}" escapes the owning module`)
114
+ }
115
+ const source = ts.createSourceFile(filename, fs.readFileSync(filename, 'utf8'), ts.ScriptTarget.Latest, true)
116
+ const runtime = exportedDeclaration(source, 'crudFormSectionRuntime')
117
+ if (!runtime) return invalid(`runtime import "${specifier}" must export crudFormSectionRuntime`)
118
+ const runtimeValue = unwrap(runtime)
119
+ const literal = ts.isCallExpression(runtimeValue)
120
+ ? helperArgument(runtimeValue,
121
+ ts.isIdentifier(runtimeValue.expression) && runtimeValue.expression.text === 'defineCrudFormFieldGranularSection'
122
+ ? 'defineCrudFormFieldGranularSection' : 'defineCrudFormSectionRuntime', invalid) : runtimeValue
123
+ const actual = readIdentity(fieldsOf(literal, invalid), invalid)
124
+ if (actual.id !== expected.id || actual.roundTripId !== expected.roundTripId) {
125
+ return invalid(`runtime import "${specifier}" exports "${actual.roundTripId}" but loader declares "${expected.roundTripId}"`)
126
+ }
127
+ return source
128
+ }
129
+ const source = readRuntime(declarationSourcePath)
130
+ if (declarationSourcePath !== declaration.absolutePath) readRuntime(declaration.absolutePath)
131
+ const importBase = declaration.importPath.slice(0, declaration.importPath.lastIndexOf('/'))
132
+ return { runtimePath: `${importBase}/${relative}`, source }
133
+ }
134
+
135
+ function importedNamedBinding(source: ts.SourceFile, localName: string): { specifier: string; exported: string } | null {
136
+ for (const statement of source.statements) {
137
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)
138
+ || statement.importClause?.isTypeOnly) continue
139
+ const names = statement.importClause?.namedBindings
140
+ if (!names || !ts.isNamedImports(names)) continue
141
+ const entry = names.elements.find(({ name, isTypeOnly }) => !isTypeOnly && name.text === localName)
142
+ if (entry) return { specifier: statement.moduleSpecifier.text, exported: (entry.propertyName ?? entry.name).text }
143
+ }
144
+ return null
145
+ }
146
+
147
+ function exportsFactoryBinding(source: ts.SourceFile, factoryName: string, exported: string): boolean {
148
+ const exportedLocals = new Set<string>()
149
+ for (const statement of source.statements) {
150
+ if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier || !statement.exportClause
151
+ || !ts.isNamedExports(statement.exportClause)) continue
152
+ for (const entry of statement.exportClause.elements) {
153
+ if (!entry.isTypeOnly && entry.name.text === exported) exportedLocals.add((entry.propertyName ?? entry.name).text)
154
+ }
155
+ }
156
+ for (const statement of source.statements) {
157
+ if (!ts.isVariableStatement(statement)) continue
158
+ const direct = statement.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword)
159
+ const isBound = (local: string) => Boolean(direct && local === exported) || exportedLocals.has(local)
160
+ for (const declaration of statement.declarationList.declarations) {
161
+ if (!declaration.initializer) continue
162
+ const value = unwrap(declaration.initializer)
163
+ if (ts.isIdentifier(declaration.name) && isBound(declaration.name.text)
164
+ && ts.isPropertyAccessExpression(value) && ts.isIdentifier(value.expression)
165
+ && value.expression.text === factoryName && value.name.text === exported) return true
166
+ if (ts.isObjectBindingPattern(declaration.name) && ts.isIdentifier(value) && value.text === factoryName
167
+ && declaration.name.elements.some((entry) => ts.isIdentifier(entry.name) && isBound(entry.name.text)
168
+ && !entry.initializer && (entry.propertyName ?? entry.name).getText() === exported)) return true
169
+ }
170
+ }
171
+ return false
172
+ }
173
+
174
+ function hasIdentityMapper(input: ts.Expression | undefined): boolean {
175
+ if (!input) return true
176
+ const mapper = unwrap(input)
177
+ if (!ts.isArrowFunction(mapper) || mapper.parameters.length !== 1 || ts.isBlock(mapper.body)) return false
178
+ const binding = mapper.parameters[0].name
179
+ if (!ts.isObjectBindingPattern(binding) || binding.elements.length !== 1) return false
180
+ const [entry] = binding.elements
181
+ const body = unwrap(mapper.body)
182
+ return !entry.dotDotDotToken && !entry.initializer && ts.isIdentifier(entry.name)
183
+ && (entry.propertyName ?? entry.name).getText() === 'parsed' && ts.isIdentifier(body) && body.text === entry.name.text
184
+ }
185
+
186
+ function parseDerivedRoutes(
187
+ fields: ReadonlyMap<string, ts.Expression>,
188
+ module: ModuleSource,
189
+ declaration: ResolvedFile,
190
+ source: ts.SourceFile,
191
+ invalid: (reason: string) => never,
192
+ ): DerivedRouteDeclaration[] {
193
+ return arrayField(fields, 'derivedHosts', invalid).map((entry, index) => {
194
+ const options = fieldsOf(helperArgument(entry, 'defineCrudRouteSectionHost', invalid), invalid)
195
+ const hostDescriptorId = literalValue(options.get('hostDescriptorId'), 'hostDescriptorId', invalid)
196
+ const formOperation = literalValue(options.get('formOperation'), 'formOperation', invalid)
197
+ if (formOperation !== 'create' && formOperation !== 'update') return invalid('derived host requires create or update')
198
+ if (formOperation === 'create' && options.has('delete')) return invalid('derived create host cannot declare delete')
199
+ const groups = arrayField(options, 'sections', invalid)
200
+ if (!groups.length) return invalid('derived host requires a finite group set')
201
+ for (const group of groups) {
202
+ const writes = literalValue(fieldsOf(group, invalid).get('writes'), 'section writes', invalid)
203
+ if (writes !== 'parent' && writes !== 'none') return invalid('derived host group declares a secondary write')
204
+ }
205
+ const routeNode = options.get('route')
206
+ const binding = routeNode && ts.isIdentifier(routeNode) && importedNamedBinding(source, routeNode.text)
207
+ if (!binding || !/^\.\/api(?:\/[A-Za-z0-9_.[\]-]+)*\/route(?:\.[jt]sx?)?$/.test(binding.specifier)) {
208
+ return invalid('derived host route must import the original named makeCrudRoute result from its module API route')
209
+ }
210
+ const relative = binding.specifier.slice(2)
211
+ const routeFile = module.resolve(relative)
212
+ if (!routeFile || routeFile.fromApp !== declaration.fromApp) return invalid('derived host route is missing or shadowed')
213
+ const mirror = routeFile.fromApp ? null : resolveStandaloneSourceMirrorBase(module.roots.pkgBase)
214
+ const mirrorFile = mirror && MODULE_CODE_EXTENSIONS.map((extension) =>
215
+ path.join(mirror, stripModuleCodeExtension(relative) + extension),
216
+ ).find((candidate) => fs.existsSync(candidate))
217
+ const fileName = mirrorFile || routeFile.absolutePath
218
+ const routeSource = ts.createSourceFile(fileName, fs.readFileSync(fileName, 'utf8'), ts.ScriptTarget.Latest, true)
219
+ const routeInitializer = exportedDeclaration(routeSource, binding.exported)
220
+ const routeCall = routeInitializer && unwrap(routeInitializer)
221
+ const factory = routeCall && ts.isCallExpression(routeCall) && ts.isIdentifier(routeCall.expression)
222
+ && importedNamedBinding(routeSource, routeCall.expression.text)
223
+ if (!routeCall || !ts.isCallExpression(routeCall) || routeCall.arguments.length !== 1
224
+ || !factory || factory.exported !== 'makeCrudRoute'
225
+ || !['@open-mercato/shared/lib/crud/factory', '@open-mercato/shared/lib/crud'].includes(factory.specifier)) {
226
+ return invalid('derived host requires a named original makeCrudRoute declaration')
227
+ }
228
+ const routeDeclaration = routeInitializer?.parent
229
+ if (!routeDeclaration || !ts.isVariableDeclaration(routeDeclaration) || !ts.isIdentifier(routeDeclaration.name)
230
+ || !exportsFactoryBinding(routeSource, routeDeclaration.name.text, 'metadata')) {
231
+ return invalid('derived route metadata must come directly from the named factory result')
232
+ }
233
+ const factoryName = routeDeclaration.name.text
234
+ const factoryOptions = fieldsOf(routeCall.arguments[0], invalid)
235
+ const actionNode = factoryOptions.get('actions')
236
+ const metadataNode = factoryOptions.get('metadata')
237
+ if (!actionNode || !metadataNode) return invalid('derived route requires literal factory actions and method metadata')
238
+ if (factoryOptions.has('resolveIdentifiers')) return invalid('derived route declares custom identifier mapping')
239
+ const hooks = factoryOptions.get('hooks')
240
+ if (hooks && [...fieldsOf(hooks, invalid).keys()].some((key) => /^(before|after)(Create|Update|Delete)$/.test(key))) {
241
+ return invalid('derived route declares custom write hooks')
242
+ }
243
+ const actions = fieldsOf(actionNode, invalid)
244
+ const metadata = fieldsOf(metadataNode, invalid)
245
+ const operations: DerivedRouteDeclaration['operations'] = [formOperation, ...(options.has('delete') ? ['delete' as const] : [])]
246
+ for (const operation of operations) {
247
+ const action = actions.get(operation)
248
+ const method = derivedRouteMethods[operation]
249
+ if (!action || !metadata.has(method) || !exportsFactoryBinding(routeSource, factoryName, method)) {
250
+ return invalid(`derived route has no direct ${method} factory export, command or metadata`)
251
+ }
252
+ const command = fieldsOf(action, invalid)
253
+ if (!hasIdentityMapper(command.get('mapInput')) || command.has('metadata')) {
254
+ return invalid(`derived ${method} route requires direct command input without custom metadata`)
255
+ }
256
+ const commandId = literalValue(command.get('commandId'), 'commandId', invalid)
257
+ if (!commandId.endsWith(`.${operation}`)) return invalid(`derived ${method} route command does not match its operation`)
258
+ const methodMetadata = fieldsOf(metadata.get(method)!, invalid)
259
+ if (methodMetadata.get('requireAuth')?.kind !== ts.SyntaxKind.TrueKeyword
260
+ || methodMetadata.has('requireRoles')) {
261
+ return invalid(`derived ${method} route must require authentication`)
262
+ }
263
+ for (const feature of arrayField(methodMetadata, 'requireFeatures', invalid)) literalValue(feature, 'required feature', invalid)
264
+ }
265
+ const configuredPath = metadata.get('path')
266
+ const basePath = configuredPath ? literalValue(configuredPath, 'route path', invalid)
267
+ : `/${[module.modId, ...relative.split('/').slice(1, -1)].join('/')}`
268
+ if (!/^\/(?:[A-Za-z0-9_.-]+|\[[A-Za-z0-9_-]+\])(?:\/(?:[A-Za-z0-9_.-]+|\[[A-Za-z0-9_-]+\]))*$/.test(basePath)) {
269
+ return invalid('derived route path must be a regular named API path')
270
+ }
271
+ const outboxRetry = options.has('outboxRetry')
272
+ if (outboxRetry && (formOperation !== 'update' || options.get('outboxRetry')?.kind !== ts.SyntaxKind.TrueKeyword)) {
273
+ return invalid('derived outbox retry must literally opt in on an update host')
274
+ }
275
+ const versioned = options.has('expectedVersionField')
276
+ if (versioned) literalValue(options.get('expectedVersionField'), 'expectedVersionField', invalid)
277
+ return { index, routePath: `${basePath}/section-policy`, hostDescriptorId, operations, versioned, outboxRetry }
278
+ })
279
+ }
280
+
281
+ function parseModuleSections(module: ModuleSource, checkRevisions = false): ModuleSections | null {
282
+ const declaration = module.resolve('form-sections.ts')
283
+ if (!declaration) return null
284
+ const mirror = declaration.fromApp ? null : resolveStandaloneSourceMirrorBase(module.roots.pkgBase)
285
+ const sourceFile = mirror && fs.existsSync(path.join(mirror, 'form-sections.ts'))
286
+ ? path.join(mirror, 'form-sections.ts')
287
+ : declaration.absolutePath
288
+ const source = ts.createSourceFile(sourceFile, fs.readFileSync(sourceFile, 'utf8'), ts.ScriptTarget.Latest, true)
289
+ const invalid = (reason: string): never => {
290
+ throw new Error(`[generate] form-sections for "${module.modId}" (${sourceFile}): ${reason}`)
291
+ }
292
+ for (const statement of source.statements) {
293
+ if (!ts.isImportDeclaration(statement) || statement.importClause?.isTypeOnly || !ts.isStringLiteralLike(statement.moduleSpecifier)) continue
294
+ const specifier = statement.moduleSpecifier.text
295
+ if (/^(?:react(?:-dom)?|next)(?:\/|$)/.test(specifier) || /(?:\.client(?:\.[jt]sx?)?|\/page(?:\.[jt]sx?)?)$/.test(specifier)) {
296
+ invalid(`server declaration statically imports "${specifier}"`)
297
+ }
298
+ }
299
+ const initializer = exportedDeclaration(source, 'crudFormSections')
300
+ const extensionExport = exportedDeclaration(source, 'crudFormExtensions')
301
+ if (!initializer && !extensionExport) return invalid('expected a named crudFormSections or crudFormExtensions declaration')
302
+ const moduleBase = path.dirname(sourceFile)
303
+ const extensions = parseSectionExtensionSources(extensionExport, moduleBase, declaration.importPath, invalid)
304
+ const fields = initializer ? fieldsOf(helperArgument(initializer, 'defineCrudFormSections', invalid), invalid) : new Map<string, ts.Expression>()
305
+
306
+ const derivedRoutes = parseDerivedRoutes(fields, module, declaration, source, invalid)
307
+ const runtimes = new Map<string, { roundTripId: string; runtimePath: string; source: ts.SourceFile }>()
308
+ for (const runtime of arrayField(fields, 'runtimes', invalid)) {
309
+ const properties = fieldsOf(runtime, invalid)
310
+ const { id, roundTripId } = readIdentity(properties, invalid)
311
+ if (runtimes.has(id)) invalid(`duplicate runtime loader id "${id}"`)
312
+ runtimes.set(id, { roundTripId, ...readRuntimePath(properties.get('load'), declaration, sourceFile, { id, roundTripId }, invalid) })
313
+ }
314
+
315
+ const leafDefaultProviderIds = arrayField(fields, 'leafDefaultProviders', invalid).map((entry) => {
316
+ const provider = unwrap(entry)
317
+ if (!ts.isObjectLiteralExpression(provider)) return invalid('expected a leaf default provider object')
318
+ const factProperty = provider.properties.find((property): property is ts.PropertyAssignment =>
319
+ ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name))
320
+ && property.name.text === 'fact')
321
+ if (!factProperty) return invalid('missing literal leaf default provider fact')
322
+ literalData(factProperty.initializer, invalid)
323
+ return readIdentity(fieldsOf(factProperty.initializer, invalid), invalid).id
324
+ }).sort(compareIds)
325
+ const sinkIds = arrayField(fields, 'sinks', invalid).map((entry) => {
326
+ const call = unwrap(entry)
327
+ const isOutboxBuilder = ts.isCallExpression(call) && ts.isIdentifier(call.expression)
328
+ && call.expression.text === 'defineCrudFormSectionOutboxSink'
329
+ const declaration = unwrap(helperArgument(entry, isOutboxBuilder ? 'defineCrudFormSectionOutboxSink' : 'defineCrudFormSectionSink', invalid))
330
+ if (!ts.isObjectLiteralExpression(declaration)) return invalid('expected a sink declaration object')
331
+ const fact = declaration.properties.find((property): property is ts.PropertyAssignment =>
332
+ ts.isPropertyAssignment(property) && (ts.isIdentifier(property.name) || ts.isStringLiteralLike(property.name))
333
+ && property.name.text === 'fact')
334
+ if (!fact) return invalid('missing literal sink fact')
335
+ const properties = fieldsOf(fact.initializer, invalid)
336
+ const { id } = readIdentity(properties, invalid)
337
+ literalData(fact.initializer, invalid)
338
+ if (literalValue(properties.get('ownerModuleId'), 'ownerModuleId', invalid) !== module.modId) {
339
+ return invalid(`sink "${id}" must be declared in its owning module`)
340
+ }
341
+ const atomicity = literalValue(properties.get('atomicity'), 'atomicity', invalid)
342
+ const externalDelivery = properties.get('externalDelivery')
343
+ if (atomicity === 'outbox') {
344
+ if (!externalDelivery) return invalid(`outbox sink "${id}" requires a literal externalDelivery contract`)
345
+ const external = fieldsOf(externalDelivery, invalid)
346
+ const maxAttempts = external.get('maxAttempts')
347
+ const attempts = maxAttempts && literalData(maxAttempts, invalid)
348
+ const target = literalValue(properties.get('targetEntityId'), 'targetEntityId', invalid)
349
+ const contract = literalValue(external.get('contractId'), 'contractId', invalid)
350
+ if (!contract.startsWith(`${target}@v`) || !/^[1-9][0-9]*$/.test(contract.slice(target.length + 2))) {
351
+ return invalid(`outbox sink "${id}" requires contractId "${target}@v<positive-integer>"`)
352
+ }
353
+ if (external.size !== 6
354
+ || literalValue(external.get('fencing'), 'fencing', invalid) !== 'remote-monotonic-revision/v1'
355
+ || literalValue(external.get('coalesce'), 'coalesce', invalid) !== 'latest-state'
356
+ || !['none', 'read-only'].includes(literalValue(external.get('preCommitValidation'), 'preCommitValidation', invalid))
357
+ || !literalValue(external.get('integrationId'), 'integrationId', invalid)
358
+ || typeof attempts !== 'number' || !Number.isSafeInteger(attempts) || attempts < 1) {
359
+ return invalid(`outbox sink "${id}" requires the remote-monotonic-revision/v1 fencing contract`)
360
+ }
361
+ } else if (!['host-transaction', 'after-commit'].includes(atomicity) || externalDelivery || isOutboxBuilder) {
362
+ return invalid(`invalid atomicity or externalDelivery for sink "${id}"`)
363
+ }
364
+ return id
365
+ }).sort(compareIds)
366
+ const descriptors: Descriptor[] = []
367
+ const primitiveContributions: CompilerModule['primitiveContributions'][number][] = []
368
+ const authoredSource = !moduleBase.split(path.sep).includes('node_modules')
369
+ && (declaration.fromApp || !moduleBase.split(path.sep).includes('dist'))
370
+ const revisions: Array<{ id: string; roundTripId: string; sourceHash: string }> = []
371
+ const clientHosts: CrudFormSectionClientHostFact[] = []
372
+ const customFieldSeedEntities = new Map<string, Readonly<Record<string, string>>>()
373
+ const factIds = new Set<string>()
374
+ for (const [kind, field] of factFields) {
375
+ const facts = arrayField(fields, field, invalid)
376
+ for (const [index, fact] of facts.entries()) {
377
+ const properties = fieldsOf(fact, invalid)
378
+ const { id, roundTripId } = readIdentity(properties, invalid)
379
+ if (kind === 'host') {
380
+ const seeds = properties.get('customFieldSeedEntities')
381
+ if (seeds) {
382
+ customFieldSeedEntities.set(id, Object.fromEntries([...fieldsOf(seeds, invalid)].map(([setId, value]) => {
383
+ const entityId = literalValue(value, 'custom-field seed entity', invalid)
384
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(setId) || !/^[a-z0-9_]+:[a-z0-9_]+$/.test(entityId)) {
385
+ return invalid('customFieldSeedEntities requires literal definition-set and entity ids')
386
+ }
387
+ return [setId, entityId]
388
+ })))
389
+ }
390
+ const hostResourceKind = properties.has('hostResourceKind')
391
+ ? literalValue(properties.get('hostResourceKind'), 'hostResourceKind', invalid)
392
+ : undefined
393
+ const alternatives = arrayField(properties, 'alternatives', invalid).map((entry) => {
394
+ const alternative = fieldsOf(entry, invalid)
395
+ const surface = alternative.get('surface')
396
+ if (!surface) return invalid('missing finite surface alternative')
397
+ const fact = literalData(surface, invalid)
398
+ if (!fact || typeof fact !== 'object' || Array.isArray(fact)) return invalid('expected finite surface facts')
399
+ const derived = derivedRoutes.find(({ hostDescriptorId }) => hostDescriptorId === id)
400
+ if (Object.hasOwn(fact, 'clientMutationSurfaces')) return invalid('client mutation surface projection is generated')
401
+ if ('allowNoopSubmit' in fact && typeof fact.allowNoopSubmit !== 'boolean') return invalid('allowNoopSubmit must be a boolean')
402
+ const authoredIds = (fact as { mutationSurfaceIds?: unknown }).mutationSurfaceIds
403
+ if (!Array.isArray(authoredIds) || authoredIds.some((surfaceId) => typeof surfaceId !== 'string')) {
404
+ return invalid('mutationSurfaceIds must be a literal ID array')
405
+ }
406
+ const rows = derived ? derived.operations.map((operation) => derivedCrudFormSectionClientMutationFact({
407
+ operation, hostDescriptorId: id, route: derived.routePath,
408
+ versioned: derived.versioned, resourceKind: hostResourceKind ?? '',
409
+ })) : arrayField(alternative, 'mutationSurfaces', invalid).map((mutation) => {
410
+ const declaration = fieldsOf(mutation, invalid)
411
+ return Object.fromEntries(Object.keys(crudFormSectionClientMutationFactSchema.shape).flatMap((key) => {
412
+ const value = declaration.get(key)
413
+ return value ? [[key, literalData(value, invalid)]] : []
414
+ }))
415
+ })
416
+ const mutationSurfaceIds = derived ? derived.operations.map((operation) => `${id}.${operation}`) : authoredIds
417
+ const clientMutationSurfaces = parseCrudFormSectionClientMutationFacts(mutationSurfaceIds, rows)
418
+ if (!clientMutationSurfaces || clientMutationSurfaces.some((row) => row.hostResourceKind !== hostResourceKind)) {
419
+ return invalid('mutation surface projection does not match its host alternative')
420
+ }
421
+ return {
422
+ ...fact, mutationSurfaceIds,
423
+ ...(clientMutationSurfaces.length ? { clientMutationSurfaces } : {}),
424
+ }
425
+ })
426
+ if (alternatives.length && !hostResourceKind) return invalid('host alternatives require a hostResourceKind')
427
+ clientHosts.push({ id, roundTripId, hostResourceKind, alternatives: alternatives as unknown as CrudFormSectionClientHostFact['alternatives'] })
428
+ }
429
+ const addressNode = properties.get('address')
430
+ const operationNode = properties.get('operation')
431
+ if (kind === 'contribution' && addressNode && operationNode && ts.isObjectLiteralExpression(unwrap(addressNode))) {
432
+ const operation = unwrap(operationNode)
433
+ const literalAddress = unwrap(addressNode) as ts.ObjectLiteralExpression
434
+ const address = Object.fromEntries(literalAddress.properties.flatMap((property) => {
435
+ if (!ts.isPropertyAssignment(property) || (!ts.isIdentifier(property.name) && !ts.isStringLiteralLike(property.name))) return []
436
+ const value = unwrap(property.initializer)
437
+ return ts.isStringLiteralLike(value) ? [[property.name.text, value.text]] : []
438
+ }))
439
+ const { hostId, formVariant, formOperation, sectionId } = address
440
+ if (hostId && formVariant && sectionId && (formOperation === 'create' || formOperation === 'update')
441
+ && ts.isStringLiteralLike(operation) && (operation.text === 'add' || operation.text === 'replace' || operation.text === 'hide')) {
442
+ primitiveContributions.push({ id, address: { hostId, formVariant, formOperation, sectionId }, operation: operation.text })
443
+ }
444
+ }
445
+ if (factIds.has(id)) invalid(`duplicate fact id "${id}"`)
446
+ factIds.add(id)
447
+ const runtime = runtimes.get(id)
448
+ if (!runtime) return invalid(`fact "${id}" has no matching runtime loader`)
449
+ if (runtime.roundTripId !== roundTripId) {
450
+ invalid(`fact and runtime roundTripId differ for "${id}"`)
451
+ }
452
+ descriptors.push({ id, roundTripId, kind, field, index, runtimePath: runtime.runtimePath })
453
+ if (checkRevisions && authoredSource) {
454
+ revisions.push({ id, roundTripId, sourceHash: hashHandwrittenSectionRuntime(runtime.source, fact, moduleBase) })
455
+ }
456
+ }
457
+ }
458
+ for (const id of runtimes.keys()) {
459
+ if (!factIds.has(id)) invalid(`runtime loader "${id}" has no matching fact`)
460
+ }
461
+ return {
462
+ moduleId: module.modId,
463
+ importPath: declaration.importPath,
464
+ hasHandwrittenSections: Boolean(initializer),
465
+ sourceFileName: path.basename(sourceFile),
466
+ sourceBase: moduleBase,
467
+ authoredSource,
468
+ extensionSources: extensions,
469
+ runtimeSources: runtimes,
470
+ customFieldSeedEntities,
471
+ primitiveContributions,
472
+ derivedRoutes,
473
+ clientHosts: clientHosts.sort((left, right) => compareIds(left.id, right.id)),
474
+ contributedOverrides: fields.has('contributedOverrides')
475
+ ? literalData(fields.get('contributedOverrides')!, invalid) as FormSectionOverridesMap
476
+ : {},
477
+ leafDefaultProviderIds,
478
+ sinkIds,
479
+ revisionWrite: planHandwrittenSectionRevisionWrite(moduleBase, revisions, invalid),
480
+ descriptors: descriptors.sort((left, right) => compareIds(left.id, right.id)),
481
+ }
482
+ }
483
+
484
+ function orderedSectionModules(
485
+ sections: ReadonlyMap<string, ModuleSections>,
486
+ identities: readonly ModuleIdentity[],
487
+ requiresByModule: ReadonlyMap<string, readonly string[]>,
488
+ ): ModuleSections[] {
489
+ const done = new Set<string>()
490
+ const visiting = new Set<string>()
491
+ const ordered: ModuleSections[] = []
492
+ function visit(moduleId: string): void {
493
+ if (done.has(moduleId)) return
494
+ if (visiting.has(moduleId)) {
495
+ throw new Error(`[generate] Cannot order form-sections through a module dependency cycle at "${moduleId}"`)
496
+ }
497
+ visiting.add(moduleId)
498
+ const dependencies = (requiresByModule.get(moduleId) ?? [])
499
+ .map((requirement) => resolveModuleRequirement(requirement, identities))
500
+ .filter((dependency): dependency is string => dependency !== undefined)
501
+ .sort(compareIds)
502
+ for (const dependency of dependencies) visit(dependency)
503
+ visiting.delete(moduleId)
504
+ done.add(moduleId)
505
+ const module = sections.get(moduleId)
506
+ if (module) ordered.push(module)
507
+ }
508
+ const sectionModules = [...sections.values()].sort((left, right) => compareIds(left.importPath, right.importPath))
509
+ for (const module of sectionModules) visit(module.moduleId)
510
+ return ordered
511
+ }
512
+
513
+ const generatedHeader = '// Auto-generated by yarn generate. Do not edit.'
514
+ const injectionPositionTypeImport = "import type { InjectionPosition } from '@open-mercato/shared/modules/widgets/injection-position'"
515
+
516
+ function renderSectionOverrides(overrides: Readonly<FormSectionOverridesMap>): string {
517
+ return escapeGeneratedJsonLiteral(JSON.stringify(overrides, null, 2))
518
+ .replace(/^( +"position": "(?:first|last|before|after)")/gm, '$1 as InjectionPosition')
519
+ }
520
+
521
+ function renderFactRegistry(modules: readonly ModuleSections[], compiled: CompiledSectionExtensions): string {
522
+ const hasGenericSinks = [...compiled.contributionsByModule.values()].some((entries) => entries.some(({ sinks }) =>
523
+ sinks.some(({ fields }) => fields.some(({ field }) => field.store?.kind === 'table' || field.store?.kind === 'external'))))
524
+ const moduleIndexes = new Map(modules.map(({ moduleId }, index) => [moduleId, index]))
525
+ const imports = modules.flatMap(({ importPath, hasHandwrittenSections, extensionSources }, index) => [
526
+ ...(hasHandwrittenSections ? [`import { crudFormSections as sections${index} } from ${JSON.stringify(importPath)}`] : []),
527
+ ...(extensionSources.length ? [`import { crudFormExtensions as extensions${index} } from ${JSON.stringify(importPath)}`] : []),
528
+ ])
529
+ const authoredSection = ({ module, extension, change }: {
530
+ module: CompilerModule; extension: CompilerModule['extensionSources'][number]; change: CompilerModule['extensionSources'][number]['changes'][number]
531
+ }) => `extensions${moduleIndexes.get(module.moduleId)}[${extension.index}].sections[${JSON.stringify(change.id)}]`
532
+ const compiledDeclarations = modules.flatMap(({ moduleId }, index) => {
533
+ const candidates = compiled.contributionsByModule.get(moduleId)
534
+ if (!candidates?.length) return []
535
+ const lines = candidates.map(({ contribution, fields, defaults, sinks }) => {
536
+ const compiledFields = fields.flatMap(({ field, authored, payloadPath }) => {
537
+ if (!payloadPath || (!field.server && !field.rules.some(({ enforce }) => enforce === 'client-and-server'))) return []
538
+ const source = `${authoredSection(authored)}.options.fields[${JSON.stringify(field.id)}].${field.operation === 'add' ? 'definition' : 'patch'}`
539
+ const data = JSON.stringify({ fieldId: field.id, payloadPath, rules: field.rules })
540
+ return [`{ ...${data}${field.server ? `, server: ${source}.validate.server` : ''} }`]
541
+ })
542
+ function fieldStore({ field, authored, payloadPath }: (typeof fields)[number]): string {
543
+ const source = authoredSection(authored)
544
+ if (field.store?.fieldOverride) return `${source}.options.fields[${JSON.stringify(field.id)}].definition.store`
545
+ if (authored.change.operation === 'add' && field.store?.kind !== 'customField') return `${source}.options.store`
546
+ return `{ kind: 'customField', key: ${JSON.stringify(payloadPath?.slice('customFields.'.length))} }`
547
+ }
548
+ const stores = fields.flatMap((item) => {
549
+ const { field, authored, payloadPath, customField } = item
550
+ if (!payloadPath || !field.store) return []
551
+ const data = JSON.stringify({ ownerModuleId: authored.module.moduleId, fieldId: field.id, payloadPath, customField })
552
+ return [`{ ...${data}, store: ${fieldStore(item)} }`]
553
+ })
554
+ const sinkAssociations = sinks.map(({ fields: owned, ...keys }) => {
555
+ const [{ authored }] = owned
556
+ const plan = {
557
+ ...keys, ownerModuleId: authored.module.moduleId, payloadPaths: owned.map(({ payloadPath }) => payloadPath!),
558
+ fields: owned.map(({ field }) => ({
559
+ key: field.id, kind: field.browser.type, required: field.browser.required,
560
+ options: Array.isArray(field.browser.options) ? field.browser.options.map(({ value }) => value) : undefined,
561
+ })),
562
+ }
563
+ const kind = owned[0].field.store?.kind
564
+ const entityProof = kind === 'table' || kind === 'external'
565
+ ? `, entityExports: lookupCompiledOrmExports(${JSON.stringify(authored.module.moduleId)})` : ''
566
+ return `{ ...${JSON.stringify(plan)}, store: ${fieldStore(owned[0])}${entityProof} }`
567
+ })
568
+ const providers = defaults.map(({ owner, id, payloadPath, readsPayloadPaths, scoped }) => {
569
+ const { hostId, formVariant, formOperation } = contribution.address
570
+ const fact = { id, roundTripId: `${id}@v${contribution.roundTripId.split('@v')[1]}`, hostId, formVariant, formOperation, payloadPath, readsPayloadPaths }
571
+ return `{ fact: ${JSON.stringify(fact)}, resolve: extensions${moduleIndexes.get(owner.module.moduleId)}[${owner.extension.index}].defaults[${JSON.stringify(payloadPath)}]${scoped ? ".resolve" : ""} }`
572
+ })
573
+ return ` { contribution: ${JSON.stringify(contribution)}, fieldRules: [${compiledFields.join(', ')}], defaults: [${providers.join(', ')}], stores: [${stores.join(', ')}], sinkAssociations: [${sinkAssociations.join(', ')}] },`
574
+ })
575
+ const overrides = Object.fromEntries(Object.entries(compiled.fallbacks).filter(([, override]) => candidates.some(({ id }) => id === override?.contributionId)))
576
+ return [`const compiled${index} = [`, ...lines, '] as const satisfies readonly CompiledCrudFormContribution[]',
577
+ `const compiledOverrides${index} = ${renderSectionOverrides(overrides)} as const`]
578
+ })
579
+ const entries = modules.flatMap(({ moduleId, descriptors }, index) => [
580
+ ...descriptors.map((descriptor) =>
581
+ ` { kind: ${JSON.stringify(descriptor.kind)}, moduleId: ${JSON.stringify(moduleId)}, fact: sections${index}.${descriptor.field}[${descriptor.index}] },`,
582
+ ),
583
+ ...(compiled.contributionsByModule.get(moduleId) ?? []).map((_, contribution) =>
584
+ ` { kind: "contribution", moduleId: ${JSON.stringify(moduleId)}, fact: compiled${index}[${contribution}].contribution },`),
585
+ ])
586
+ return [
587
+ generatedHeader,
588
+ "import type { CrudFormSectionFactEntry, CrudFormSectionServerModule } from '@open-mercato/shared/modules/form-sections'",
589
+ ...imports,
590
+ ...(hasGenericSinks ? ["import { ormEntityExportNamespaces } from './entities.generated'"] : []),
591
+ ...(compiledDeclarations.length ? [
592
+ "import { bindCompiledCrudFormAlternatives, bindCompiledCrudFormContributions, type CompiledCrudFormContribution } from '@open-mercato/shared/lib/crud/form-sections/compiled-extensions'",
593
+ ] : []),
594
+ ...(compiledDeclarations.some((line) => line.includes(' as InjectionPosition')) ? [injectionPositionTypeImport] : []),
595
+ ...(modules.some(({ derivedRoutes }) => derivedRoutes.length)
596
+ ? ["import { bindDerivedCrudRouteSectionHosts } from '@open-mercato/shared/lib/crud/form-sections/derived-route-host'"] : []),
597
+ '',
598
+ ...(hasGenericSinks ? [
599
+ "export { entities as crudFormSectionOrmEntities } from './entities.generated'",
600
+ 'const lookupCompiledOrmExports = (moduleId: string) => ormEntityExportNamespaces.find((entry) => entry.moduleId === moduleId)?.entities',
601
+ ] : []),
602
+ ...compiledDeclarations,
603
+ 'export const crudFormSectionFactEntries = [',
604
+ ...entries,
605
+ '] as const satisfies readonly CrudFormSectionFactEntry[]',
606
+ '',
607
+ 'export const crudFormSectionServerModules = [',
608
+ ...modules.map(({ moduleId, derivedRoutes, hasHandwrittenSections }, index) => {
609
+ const alternatives = compiled.alternativesByModule.get(moduleId)
610
+ const bindings = derivedRoutes.map((route) => {
611
+ const retrySinks = [...new Set(alternatives?.flatMap((alternative) => alternative.hostDescriptorId === route.hostDescriptorId
612
+ ? alternative.outboxRetrySinkIds ?? [] : []))].sort(compareIds)
613
+ return `{ declaration: sections${index}.derivedHosts[${route.index}], route: ${JSON.stringify(route.routePath)}, outboxRetrySinkIds: ${JSON.stringify(retrySinks)} }`
614
+ })
615
+ const primitive = bindings.length ? `bindDerivedCrudRouteSectionHosts(sections${index}, [${bindings.join(', ')}])`
616
+ : hasHandwrittenSections ? `sections${index}` : '{}'
617
+ const sections = compiled.contributionsByModule.has(moduleId)
618
+ ? `bindCompiledCrudFormContributions(${primitive}, compiled${index}, compiledOverrides${index})` : primitive
619
+ const entry = `{ moduleId: ${JSON.stringify(moduleId)}, sections: ${sections} }`
620
+ return ` ${alternatives?.length ? `bindCompiledCrudFormAlternatives(${entry}, ${JSON.stringify(alternatives)})` : entry},`
621
+ }),
622
+ '] as const satisfies readonly CrudFormSectionServerModule[]',
623
+ '',
624
+ ].join('\n')
625
+ }
626
+
627
+ function renderRuntimeRegistry(modules: readonly ModuleSections[], compiled: CompiledSectionExtensions): string {
628
+ const overrides = renderSectionOverrides(Object.assign({}, ...modules.map((module) => module.contributedOverrides), compiled.fallbacks))
629
+ const entries = modules.flatMap(({ moduleId, descriptors }) => [
630
+ ...descriptors.map(({ id, roundTripId, kind, runtimePath }) =>
631
+ ` { id: ${stringLiteral(id)}, roundTripId: ${stringLiteral(roundTripId)}, kind: ${stringLiteral(kind)}, moduleId: ${stringLiteral(moduleId)}, load: () => import(${stringLiteral(runtimePath)}) },`,
632
+ ),
633
+ ...(compiled.contributionsByModule.get(moduleId) ?? []).map(({ contribution: { id, roundTripId }, file }) =>
634
+ ` { id: ${stringLiteral(id)}, roundTripId: ${stringLiteral(roundTripId)}, kind: "contribution", moduleId: ${stringLiteral(moduleId)}, load: () => import(${stringLiteral('./' + stripModuleCodeExtension(file))}) },`),
635
+ ])
636
+ const versionedSinks = [...compiled.contributionsByModule.values()].flatMap((entries) =>
637
+ entries.flatMap(({ contribution, sinks }) => sinks.flatMap(({ id, fields }) => {
638
+ const first = fields[0]
639
+ const kind = first.field.store?.kind
640
+ const { hostId, formVariant, formOperation } = contribution.address
641
+ return kind === 'table' || kind === 'external'
642
+ ? [{ id, hostId, formVariant, formOperation, kind, ownerModuleId: first.authored.module.moduleId,
643
+ payloadPaths: fields.map(({ payloadPath }) => payloadPath!) }]
644
+ : []
645
+ })))
646
+ return [
647
+ generatedHeader,
648
+ "import type { CrudFormSectionClientHostFact, CrudFormSectionRuntimeEntry } from '@open-mercato/shared/modules/form-sections'",
649
+ "import type { CrudFormSectionClientVersionedSink } from '@open-mercato/shared/lib/crud/form-sections/client-registry'",
650
+ "import type { FormSectionOverridesMap } from '@open-mercato/shared/modules/overrides'",
651
+ ...(overrides.includes(' as InjectionPosition') ? [injectionPositionTypeImport] : []),
652
+ '',
653
+ `export const crudFormSectionClientHostFacts = ${escapeGeneratedJsonLiteral(JSON.stringify(modules.flatMap((module) => module.clientHosts), null, 2))} as const satisfies readonly CrudFormSectionClientHostFact[]`,
654
+ `export const crudFormSectionClientVersionedSinks = ${escapeGeneratedJsonLiteral(JSON.stringify(versionedSinks))} as const satisfies readonly CrudFormSectionClientVersionedSink[]`,
655
+ `export const crudFormSectionContributedOverrides = ${overrides} as const satisfies Readonly<FormSectionOverridesMap>`,
656
+ '',
657
+ 'export const crudFormSectionRuntimeEntries: readonly CrudFormSectionRuntimeEntry[] = [',
658
+ ...entries,
659
+ ']',
660
+ '',
661
+ 'const runtimesById = new Map(crudFormSectionRuntimeEntries.map((entry) => [entry.id, entry]))',
662
+ '',
663
+ 'export function getCrudFormSectionRuntime(id: string): CrudFormSectionRuntimeEntry | undefined {',
664
+ ' return runtimesById.get(id)',
665
+ '}',
666
+ '',
667
+ ].join('\n')
668
+ }
669
+
670
+ type SectionRegistryDiscoveryOptions = {
671
+ modules: readonly ModuleSource[]
672
+ identities: readonly ModuleIdentity[]
673
+ requiresByModule: ReadonlyMap<string, readonly string[]>
674
+ }
675
+
676
+ export function prepareCrudFormSectionRegistries(options: SectionRegistryDiscoveryOptions) {
677
+ const sections = new Map<string, ModuleSections>()
678
+ for (const module of options.modules) {
679
+ const declaration = parseModuleSections(module, true)
680
+ if (declaration) sections.set(module.modId, declaration)
681
+ }
682
+ const modules = orderedSectionModules(sections, options.identities, options.requiresByModule)
683
+ const modulesById = new Map<string, string>()
684
+ const defaultModulesById = new Map<string, string>()
685
+ const sinkModulesById = new Map<string, string>()
686
+ for (const module of modules) {
687
+ for (const id of module.sinkIds) {
688
+ const owner = sinkModulesById.get(id)
689
+ if (owner) throw new Error(`[generate] Duplicate CrudForm section sink id "${id}" in "${owner}" and "${module.moduleId}"`)
690
+ sinkModulesById.set(id, module.moduleId)
691
+ }
692
+ for (const id of module.leafDefaultProviderIds) {
693
+ const owner = defaultModulesById.get(id)
694
+ if (owner) {
695
+ throw new Error(`[generate] Duplicate leaf default provider id "${id}" in "${owner}" and "${module.moduleId}"`)
696
+ }
697
+ defaultModulesById.set(id, module.moduleId)
698
+ }
699
+ for (const { id } of module.descriptors) {
700
+ const owner = modulesById.get(id)
701
+ if (owner) {
702
+ throw new Error(`[generate] Duplicate form-sections descriptor id "${id}" in "${owner}" and "${module.moduleId}"`)
703
+ }
704
+ modulesById.set(id, module.moduleId)
705
+ }
706
+ }
707
+
708
+ const compiled = compileCrudFormSectionExtensions(modules, Object.assign({}, ...options.modules.map(({ formSectionOverrides }) => formSectionOverrides)))
709
+ for (const [moduleId, candidates] of compiled.contributionsByModule) for (const { id } of candidates) {
710
+ const owner = modulesById.get(id)
711
+ if (owner) throw new Error(`[generate] Duplicate form-sections descriptor id "${id}" in "${owner}" and "${moduleId}"`)
712
+ modulesById.set(id, moduleId)
713
+ }
714
+ return { modules, compiled }
715
+ }
716
+
717
+ export type CrudFormSectionContributionProjection = {
718
+ id: string
719
+ key: string
720
+ operation: 'add' | 'hide' | 'replace'
721
+ sourceFileName: string
722
+ exportName: 'crudFormSections' | 'crudFormExtensions'
723
+ }
724
+
725
+ export function projectCrudFormSectionContributions(
726
+ { modules, compiled }: ReturnType<typeof prepareCrudFormSectionRegistries>,
727
+ ): ReadonlyMap<string, readonly CrudFormSectionContributionProjection[]> {
728
+ return new Map(modules.map((module) => {
729
+ const rows: CrudFormSectionContributionProjection[] = []
730
+ for (const { id, address, operation } of module.primitiveContributions) {
731
+ rows.push({ id, key: crudFormSectionOverrideKey(address), operation,
732
+ sourceFileName: module.sourceFileName, exportName: 'crudFormSections' })
733
+ }
734
+ for (const { contribution: { id, address, operation } } of compiled.contributionsByModule.get(module.moduleId) ?? []) {
735
+ rows.push({ id, key: crudFormSectionOverrideKey(address), operation,
736
+ sourceFileName: module.sourceFileName, exportName: 'crudFormExtensions' })
737
+ }
738
+ return [module.moduleId, rows.sort((left, right) => compareIds(left.id, right.id))]
739
+ }))
740
+ }
741
+
742
+ export function writeCrudFormSectionRegistries(options: SectionRegistryDiscoveryOptions & {
743
+ outputDir: string
744
+ structureChecksum: string
745
+ result: GeneratorResult
746
+ quiet: boolean
747
+ prepared?: ReturnType<typeof prepareCrudFormSectionRegistries>
748
+ }): void {
749
+ const { modules, compiled } = options.prepared ?? prepareCrudFormSectionRegistries(options)
750
+ const revisions = [...modules.flatMap(({ revisionWrite }) => revisionWrite ? [revisionWrite] : []), ...compiled.revisionWrites]
751
+ for (const revisionWrite of revisions) {
752
+ const temporary = `${revisionWrite.filename}.${randomUUID()}.tmp`
753
+ try {
754
+ fs.writeFileSync(temporary, revisionWrite.content, { flag: 'wx' })
755
+ fs.renameSync(temporary, revisionWrite.filename)
756
+ } finally {
757
+ fs.rmSync(temporary, { force: true })
758
+ }
759
+ options.result.filesWritten.push(revisionWrite.filename)
760
+ }
761
+ const outputs = [
762
+ ['crud-form-section-facts', renderFactRegistry(modules, compiled)],
763
+ ['crud-form-section-runtime', renderRuntimeRegistry(modules, compiled)],
764
+ ...compiled.runtimeFiles.map(({ name, content }) => [name.slice(0, -'.generated.ts'.length), content]),
765
+ ]
766
+ const retainedRuntimeFiles = new Set(compiled.runtimeFiles.map(({ name }) => name))
767
+ if (fs.existsSync(options.outputDir)) for (const filename of fs.readdirSync(options.outputDir)) {
768
+ if (!/^crud-form-section-extension-[0-9a-f]{20}\.generated\.(?:checksum|ts)$/.test(filename)
769
+ || retainedRuntimeFiles.has(filename.replace(/\.checksum$/, '.ts'))) continue
770
+ fs.rmSync(path.join(options.outputDir, filename), { force: true })
771
+ }
772
+ if (!options.quiet) for (const [moduleId, candidates] of compiled.contributionsByModule) {
773
+ for (const candidate of candidates) {
774
+ const owned = candidate.ownership?.payloadPaths.join(', ') || 'none'
775
+ const stores = candidate.fields.filter(({ field }) => field.store).map(({ field }) => `${field.id}/${field.store!.kind}`).join(', ') || 'none'
776
+ console.log(`[generate] CrudForm extension ${moduleId}/${candidate.id} ${candidate.override.operation}; fields: ${candidate.fields.length}, payload leaves: ${owned}, defaults: ${candidate.defaults.length}, stores: ${stores}, field rules: ${candidate.fields.filter(({ field }) => field.server || field.rules.length).length}`)
777
+ }
778
+ }
779
+ for (const [name, content] of outputs) {
780
+ writeGeneratedFile({
781
+ outFile: path.join(options.outputDir, `${name}.generated.ts`),
782
+ checksumFile: path.join(options.outputDir, `${name}.generated.checksum`),
783
+ content,
784
+ structureChecksum: options.structureChecksum,
785
+ result: options.result,
786
+ quiet: options.quiet,
787
+ })
788
+ }
789
+ }
790
+
791
+ const derivedRouteFilePattern = /^crud-form-section-route-[a-f0-9]{16}\.generated\.ts$/
792
+
793
+ export function writeDerivedCrudFormSectionRoutes(
794
+ options: Parameters<typeof writeCrudFormSectionRegistries>[0],
795
+ ): GeneratedDerivedCrudRoute[] {
796
+ const routes = new Map<string, {
797
+ moduleId: string
798
+ importPath: string
799
+ entries: DerivedRouteDeclaration[]
800
+ }>()
801
+ for (const module of options.modules) {
802
+ const source = parseModuleSections(module)
803
+ if (!source) continue
804
+ const hostIds = new Set(source.descriptors.filter(({ kind }) => kind === 'host').map(({ id }) => id))
805
+ const bound = new Set<string>()
806
+ for (const entry of source.derivedRoutes) {
807
+ if (!hostIds.has(entry.hostDescriptorId) || bound.has(entry.hostDescriptorId)) {
808
+ throw new Error(`[generate] Derived CrudForm route requires one matching host fact in "${module.modId}"`)
809
+ }
810
+ bound.add(entry.hostDescriptorId)
811
+ const existing = routes.get(entry.routePath)
812
+ if (existing && existing.moduleId !== module.modId) {
813
+ throw new Error(`[generate] Duplicate derived CrudForm route "${entry.routePath}"`)
814
+ }
815
+ const route = existing ?? { moduleId: module.modId, importPath: source.importPath, entries: [] }
816
+ route.entries.push(entry)
817
+ routes.set(entry.routePath, route)
818
+ }
819
+ }
820
+
821
+ const generated: GeneratedDerivedCrudRoute[] = []
822
+ function emit(routePath: string, moduleId: string, methods: GeneratedDerivedCrudRoute['methods'], content: string) {
823
+ if (generated.some((route) => route.routePath === routePath)) {
824
+ throw new Error(`[generate] Duplicate derived CrudForm route "${routePath}"`)
825
+ }
826
+ const suffix = createHash('sha256').update(`${moduleId}:${routePath}`).digest('hex').slice(0, 16)
827
+ const fileName = `crud-form-section-route-${suffix}.generated.ts`
828
+ generated.push({ moduleId, routePath, fileName, methods })
829
+ writeGeneratedFile({
830
+ outFile: path.join(options.outputDir, fileName),
831
+ checksumFile: path.join(options.outputDir, fileName.replace(/\.ts$/, '.checksum')),
832
+ content, structureChecksum: options.structureChecksum, result: options.result, quiet: options.quiet,
833
+ })
834
+ }
835
+ for (const [routePath, { moduleId, importPath, entries }] of [...routes].sort(([left], [right]) => compareIds(left, right))) {
836
+ const methods = [...new Set(entries.flatMap(({ operations }) => operations.map((operation) => derivedRouteMethods[operation])))].sort(compareIds)
837
+ const routeImport = `import { crudFormSections } from ${JSON.stringify(importPath)}`
838
+ const declarations = (binding: readonly DerivedRouteDeclaration[]) =>
839
+ `[${binding.map(({ index }) => `crudFormSections.derivedHosts[${index}]`).join(', ')}]`
840
+ const content = [
841
+ generatedHeader,
842
+ "import { createDerivedCrudFormSectionFacade } from '@open-mercato/shared/lib/crud/form-sections/derived-route-host'",
843
+ routeImport,
844
+ `const facade = createDerivedCrudFormSectionFacade(${declarations(entries)}, ${JSON.stringify(routePath)}, ${JSON.stringify(methods)})`,
845
+ 'export const metadata = facade.metadata',
846
+ 'export const openApi = facade.openApi',
847
+ ...methods.map((method) => `export const ${method} = facade.handlers.${method}!`),
848
+ '',
849
+ ].join('\n')
850
+ emit(routePath, moduleId, methods, content)
851
+ const retry = entries.filter(({ outboxRetry }) => outboxRetry)
852
+ if (retry.length) {
853
+ emit(derivedCrudFormSectionRetryPath(routePath), moduleId, ['POST'], [
854
+ generatedHeader,
855
+ "import { createDerivedCrudFormSectionOutboxRetryRoute } from '@open-mercato/shared/lib/crud/form-sections/derived-route-host'",
856
+ routeImport,
857
+ `export const { metadata, openApi, POST } = createDerivedCrudFormSectionOutboxRetryRoute(${declarations(retry)}, ${JSON.stringify(routePath)})`,
858
+ '',
859
+ ].join('\n'))
860
+ }
861
+ }
862
+
863
+ const indexPath = path.join(options.outputDir, generatedDerivedCrudRouteIndex)
864
+ if (generated.length || fs.existsSync(indexPath)) {
865
+ writeGeneratedFile({
866
+ outFile: indexPath,
867
+ checksumFile: indexPath.replace(/\.json$/, '.checksum'),
868
+ content: JSON.stringify(generated, null, 2) + '\n',
869
+ structureChecksum: options.structureChecksum, result: options.result, quiet: options.quiet,
870
+ })
871
+ }
872
+ const current = new Set(generated.map(({ fileName }) => fileName))
873
+ if (fs.existsSync(options.outputDir)) {
874
+ for (const fileName of fs.readdirSync(options.outputDir)) {
875
+ if (!derivedRouteFilePattern.test(fileName) || current.has(fileName)) continue
876
+ fs.rmSync(path.join(options.outputDir, fileName), { force: true })
877
+ fs.rmSync(path.join(options.outputDir, fileName.replace(/\.ts$/, '.checksum')), { force: true })
878
+ }
879
+ }
880
+ return generated
881
+ }
882
+
883
+ export function readDerivedCrudFormSectionRouteIndex(outputDir: string): GeneratedDerivedCrudRoute[] {
884
+ const filePath = path.join(outputDir, generatedDerivedCrudRouteIndex)
885
+ if (!fs.existsSync(filePath)) return []
886
+ const entries: unknown = JSON.parse(fs.readFileSync(filePath, 'utf8'))
887
+ if (!Array.isArray(entries)) throw new Error('[generate] Invalid generated derived route index')
888
+ return entries.map((entry: Partial<GeneratedDerivedCrudRoute>) => {
889
+ if (typeof entry.moduleId !== 'string' || typeof entry.routePath !== 'string' || !/\/section-policy(?:\/retry)?$/.test(entry.routePath)
890
+ || typeof entry.fileName !== 'string' || !derivedRouteFilePattern.test(entry.fileName)
891
+ || !Array.isArray(entry.methods) || !entry.methods.every((method) => ['POST', 'PUT', 'DELETE'].includes(method))) {
892
+ throw new Error('[generate] Invalid derived route index entry')
893
+ }
894
+ return { moduleId: entry.moduleId, routePath: entry.routePath, fileName: entry.fileName, methods: entry.methods }
895
+ })
896
+ }